Example DOM Tree
Image via Wikipedia

jQuery does a wonderful job of traversing the DOM tree, so you might ask why you would like to do this yourself?
I recently encountered a requirement to count the maximum ‘depth’ of a DOM tree. I.e. find the level of the deepest nested element. So, I managed to knock this up in a few minutes:

function Recurse($item, depth) {
    $item.each(function() {
        depth.count++;
        if (depth.count > depth.max) {
            depth.max = depth.count;
        }
        Recurse($(this).children(), depth);
    });
    depth.count--;
    return depth.max;
}

$(document).ready(function() {
    alert(Recurse($("body"), { count: 0, max:0 }));
}

A few points to note about this

  • depth is an object with two members, count and max. We want to keep a count of the current and maximum depth, but want to avoid global variables (it’s better practice, and makes the solution more self-contained).
  • JavaScript doesn’t allow us to pass variables by reference. Using the variables within the passed depth object means we can pass values to lower levels of recursion.
  • We must pass an object in our first call. Technically the function can be improved by including a check for this.
  • The function returns depth.max. Although the return value doesn’t matter when the function is called recursively, its useful for passing our intended value out to the original calling function.

You can test this out on JsFiddle: http://jsfiddle.net/RqHzf/

Enhanced by Zemanta
,

When I starting writing this blog, I was a little unsure as to what to put in it. I knew I wanted it to be mostly programming related, with articles about things that interested me. So I named it my ‘Programming Notebook’ and put into words exactly what I envisaged I’d be putting in it. This is what I put in my About page:

My main intention was for this blog was to be a notebook for myself in a presentable format – an aid to memory of things I’ve found useful on a day-to-day basis, and little snippets I’d like to share. A lot of it won’t be ground-breaking and you’ll almost certainly find it around elsewhere on the net, but it’s presented in a way that I learned it in the hope that others might find it useful.

And later on I started fretting that I was duplicating what already ‘out there’, which is nonsense, because almost everything that anyone writes is already ‘out there’ anyway.

None of this has anything to do with Identity Inserting in SQL Server, but maybe goes some way to explaining why I am writing about something that is well documented ‘out there’.

The reason is that I had to look it up twice. I needed to look it once, and then I forgot, so I needed to look it up again. What I needed was some sort of programming noteb…. hey… I have one!

So here it is:

SET IDENTITY_INSERT [MyTable] ON
INSERT INTO [MyTable] (IDField, Field2, Field3, Field4) values (1,212,2,2)
SET IDENTITY_INSERT [MyTable] OFF

You’ll need to set IDENTITY_INSERT ‘ON’ for the table into which you are inserting, and (for good measure) set it back to ‘OFF’ when you’re done.

You’ll also need to include a field list (which is good practice anyway). The following just won’t work:

INSERT INTO [MyTable] values (1,212,2,2)

So there we are, SQL Server Identity Inserting covered….again.

,

I was wrong today.
A CSS Stylesheet had a style with a backgound-color setting of #fff:

background-color:#fff;

And another style with a color of #aaaaaa:

background-color:#aaaaaa;

My colleague commented that for consistency they should both be a six digit hex-code, to which I agreed. But I was mistaken as to what the six digit hex equivalent of #fff was.

I thought it was #fff000.

I can also see what fold might assume its #000fff.

Or even #f0f0f0;

But actually, it is #ffffff. The same is true for #aaa and #aaaaaa. And #aba is actually #aabbaa.

For a good explanation as to why this might be, refer to the following links:
http://www.fluther.com/13071/whats-the-difference-in-fff-and-ffffff-in-css-and-why/
http://stackoverflow.com/questions/2899197/does-stylecolor-fff-render-as-f0f0f0-or-ffffff

,

And I was out! Dammit!

“We have noticed from our logs that you have been downloading lots of viruses”

My wife took the call, and politely declined, which is more than they deserved. I’ve got a nice counter-scam dreamed up as well (see This Post for my thoughts on this).

So, to all the criminals responsible for perpetrating the scam that are this. Please ring back, I REALLY want technical support, as my event viewer has lots of errors, and my prefetch folder is full of viruses!

Help!

Other Articles

This is one of an ongoing series of articles that I have written following this scam. You can find them under the following tag group:

http://www.jameswiseman.com/blog/tag/windows-support-telephone-scam/

,

Have you ever been working on a bit of code, or writing a document, and then find that you need to jump elsewhere to check something out. You’ll move the cursor away from your edit position, and you’ll lost where you are and have to spend time finding where it was. Maybe not much, but enough to be sufficiently

Well, here is what I do:  control-z then control-y.

What this effectively does is undo your last change, then reapply it, and in the process return to exactly where you were editing originally. Beware, though, to make sure your IDE actually does this. Its pretty standard, but not all will support it. For example, you’ll be disappointed if you’re using VB6 IDE.

Of course, if you’re keyboard-shy, the you can always use the ‘undo’ and ‘redo’ arrow buttons in your editor.

,

One of the reasons I like Stackoverflow as a place for asking and answering programming questions is that I

  1. Almost always get what I am after
  2. Almost always learn something in the process (in answering and asking)

Case in point with a question I asked regarding hierarchy sorting in SQL Server. The question in full can be found on the adjacent link, but, in a nutshell I was looking at how I might sort a variable length hierarchy field in SQL Server 2000.

So, the field value could be 1. Or it could be 1.2.3.4. Or it could be 1.92.333.14.58.62.7.81231.

Given that I needed to sort by the last digit, then the second-last, etc, etc, AND that the length was variable, I found myself a little stumped as to an elegant solution. So I decided to call upon the generosity of the Stackoverflow community

First-up was a number of fixed length solutions, which while good, didn’t quite help. Then I got some help in SQL 2008, which was unfortunate, as I was wanting it in SQL 2000. And then user Vash popped up with an edit to his original post:

Solutions for 2000, 2005, 2008: Solutions to T-SQL Sorting Challenge here.

Marvellous! Here is the solution (modified sightly) that I adopted:

CREATE FUNCTION dbo.ufn_SortByHierarchy(@s as varchar(500), @delimiter as char(1))
  returns VARBINARY(2500)
AS
BEGIN
  DECLARE @pos as int, @r as varbinary(2500), @element as int;

  SET @r = 0x;
  SET @s = @s + @delimiter;
  SET @pos = charindex(@delimiter, @s);
  while @pos > 0
  BEGIN
	SET @element = cast(left(@s, @pos - 1) AS INT);

	SET @r = @r +
	  CASE
		WHEN @element = -2147483648 THEN 0x0000000000
		WHEN sign(@element) = -1
		  THEN 0x01 + cast(2147483647 + @element AS BINARY(4))
		ELSE 0x02 + cast(@element AS BINARY(4))
	  END;

	SET @s = stuff(@s, 1, @pos, '');
	SET @pos = charindex(@delimiter, @s);
  END

  RETURN @r;

END

And, as it turned out, I’d never heard of the varbinary data type, so right there was some extra reading and knowledge for me.

And that, I thought was it. But no! A short while later, user Martin Smith, popped up with a comment.

@James – Not sure what you ended up using. You can also use parsename for this as in this answer: stackoverflow.com/questions/3057532/

A comment! I’d have voted it up if it were an answer. So I followed the link, and voted that up.

So, I also learned about Parsename, which works in lowly SQL 2000 as well. unfortunately, it only works on a four-digit hierarchy, but still useful for me to know about.

So, lots of useful information, new things learned and a permanently documented solution to my problem. That is why I like Stackoverflow.

, , ,

Recently I encountered a business requirement whereby it was stipulated that both radio buttons in a group be left unchecked. In addition to this, a check was required to forcing the user to select one before they can continue.radio button

This struck me as being direct contradiction as to what a Radio button was trying to achieve, and that it was actually more work as you were forcing the user to make a choice without giving them a default.

It just felt wrong.

But I wasn’t sure, so I did a bit of research, and came up with the following.

Firstly (and some could say, lastly) there is the W3 Recommendation at http://www.w3.org/TR/html401/interact/forms.html#radio:

At all times, exactly one of the radio buttons in a set is checked.

And that ought to be it, but for completeness, here is quite a nice set of guidelines regarding this http://www.useit.com/alertbox/20040927.html:

Always offer a default selection for radio button lists. By definition, radio buttons always have exactly one option selected, and you therefore shouldn’t display them without a default selection. (Checkboxes, in contrast, often default to having none of the options selected.)

  • If users might need to refrain from making a selection, you should provide a radio button for this choice, such as one labeled “None.” Offering users an explicit, neutral option to click is better than requiring the implicit act of not selecting from the list, especially because doing the latter violates the rule of always having exactly one option chosen.
  • Personally, it was nice to pin this down and get some good points of reference.
    ,

    Yesterday when wanting to run some commands from the Windows Command Shell, I fired it up on my windows XP desktop, only to find things were a little strange.

    For a start it was slower – pasting something in from the clipboard seemed to take time. And then it didn’t protest too much when I started typing things I felt sure shouldn’t work. Then things I wanted to happen didn’t happen when I expected them to.

    It all left me a bit confused.

    And then I noticed, I’d typed in “command.com” not “cmd.exe”. I rectified the mistake, and everything seemed to be just fine. But I did wonder what the difference was.

    Cmd or Command?

    Well, initially, from the above screenshot we can see that the version information has the text is ‘Windows DOS’ vs ‘Windows XP’. However there are a number of other differences:

    Cmd.exe is a command-line interface, provided so you can run command-line commands. It is not a DOS window.

    Command.com is a stripped-down version of the command processor from DOS. It is a 16-bit application which is used for older DOS compatibility and actually runs inside the NTVDM (NT Virtual DOS Machine) due to its 16-bit nature.

    With Command.com we do not have the long name support. Typing in ‘cd program files‘ yields the error ‘Too many parameters – files‘, whereas this command works fine in Cmd.exe. In fact to get this to work in Command.com, we have to type ‘cd progra~1‘.

    ,