q:
I am re-factoring some code and am wondering about the use of a lock in the instance constructor.

public class MyClass {

    private static Int32 counter = 0;
    private Int32 myCount;

    public MyClass() {

        lock(this) {
            counter++;
            myCount = counter;
        }
    }
}

Please confirm

Instance constructors are thread-safe.

The lock statement prevents access to that code block, not to the static 'counter' member.

If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a MyClass and changing the count before this one sets its count?

FYI - This class is not a singleton. Instances must simply be aware of their number.

[A]
I'm guessing this is for a singleton pattern or something like it. What you want to do is not lock your object, but lock the counter while your are modifying it.
```
```
private static int counter = 0;
private static object counterLock = new Object();

lock(counterLock) {
    counter++;
    myCounter = counter;
}
```
```
Because your current code is sort of redundant. Especially being in the constructor where there is only one thread that can call a constructor, unlike with methods where it could be shared across threads and be accessed from any thread that is shared.
From the little I can tell from you code, you are trying to give the object the current count at the time of it being created. So with the above code the counter will be locked while the counter is updated and set locally. So all other constructors will have to wait for the counter to be released.


q:
I'm using Microsoft AjaxControlToolkit for modal popup window.

And on a modal popup window, when a postback occurred, the window was closing. How do I prevent from the closing action of the modal popup?

[A]
You can call
```
Show()
```
method during postback to prevent the modal popup window from closing
```
```
MyModalPopoupExtender.Show()
```
```

s: huggingface

c: devops

d: intermediate


q:
When should I include PDB files for a production release? Should I use the Optimize code flag and how would that affect the information I get from an exception?

If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app?

[A]
When you want to see source filenames and line numbers in your stacktraces, generate PDBs using the pdb-only option. Optimization is separate from PDB generation, i.e. you can optimize
and
generate PDBs without a performance hit.
From
the C# Language Reference
If you use /debug:full, be aware that there is some impact on the speed and size of JIT optimized code and a small impact on code quality with /debug:full. We recommend /debug:pdbonly or no PDB for generating release code.


q:
I'm about to start testing an intranet web application. Specifically, I've to determine the application's performance.

Please could someone suggest formal/informal standards for how I can judge the application's performance.

[A]
To test the front-end then YSlow is great for getting statistics for how long your pages take to load from a user perspective. It breaks down into stats for each specfic HTTP request, the time it took, etc. Get it at
http://developer.yahoo.com/yslow/
Firebug, of course, also is essential. You can profile your JS explicitly or in real time by hitting the profile button. Making optimisations where necessary and seeing how long all your functions take to run. This changed the way I measure the performance of my JS code.
http://getfirebug.com/js.html


q: I am using the ODBC connector to access a MySQL db from Visual Studio 2008 and I'm facing performance problems when dealing with crystal reports and to solve this I need a native connector to visual studio. If someone has had a similar problem and knows a solution or tools (freeware preferable), I would be really grateful.

[A]
You want
Connector/Net
Update:
This link should take you to a more recent version:
http://dev.mysql.com/downloads/connector/net/5.2.html


q: Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.

[A]
Try this:
```
```
StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
    StackTraceElement main = stack[stack.length - 1];
    String mainClass = main.getClassName ();
```
```
Of course, this only works if you're running from the main thread.  Unfortunately I don't think there's a system property you can query to find this out.
Edit:
Pulling in @John Meagher's comment, which is a great idea:
To expand on @jodonnell you can also
  get all stack traces in the system
  using Thread.getAllStackTraces(). From
  this you can search all the stack
  traces for the "main" Thread to
  determine what the main class is. This
  will work even if your class is not
  running in the main thread.


q: I'm a software engineer, not a lawyer, and my university doesn't offer any courses geared toward licensing software. In fact, their law-related courses are lacking (but slowly growing in number). Where can I go to learn about open-source licenses and how to choose them?

[A]
There are lots described here:
http://www.gnu.org/licenses/license-list.html#SoftwareLicenses
The decision of which one to use can be political, but should ultimately be determined by your plans/desires for the software. If you want to ensure it is always free then choose GPL or another "Copyleft" license.  If you don't mind some commercial use, choose another one that's compatible with that.


q: I'm creating an application which lets you define events with a time frame.  I want to automatically fill in the end date when the user selects or changes the start date.  I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.

[A]
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the
```
getTime()
```
method
or
just using the date in a numeric expression.
So to get the difference, just subtract the two dates.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
```
```
var oldBegin = ...
var oldEnd = ...
var newBegin = ...

var newEnd = new Date(newBegin + oldEnd - oldBegin);
```
```
This should just work
EDIT
: Fixed bug pointed by @bdukes
EDIT
:
For an explanation of the behavior,
```
oldBegin
```
,
```
oldEnd
```
, and
```
newBegin
```
are
```
Date
```
instances. Calling operators
```
+
```
and
```
-
```
will trigger Javascript auto casting and will automatically call the
```
valueOf()
```
prototype method of those objects. It happens that the
```
valueOf()
```
method is implemented in the
```
Date
```
object as a call to
```
getTime()
```
.
So basically:
```
date.getTime() === date.valueOf() === (0 + date) === (+date)
```


q: What is the fastest method of parsing an XML file in C#? I'm using .Net 2.0

[A]
If you're using .Net 2 then the XmlReader and XmlDocument are about it.
If you can use .Net 3.5 then the new Linq to Xml methods are a big improvement.


q: As per this comment in a related thread, I'd like to know why Levenshtein distance based methods are better than Soundex.

[A]
Soundex is rather primitive - it was originally developed to be hand calculated. It results in a key that can be compared.
Soundex works well with western names, as it was originally developed for US census data. It's intended for phonetic comparison.
Levenshtein distance looks at two values and produces a value based on their similarity. It's looking for missing or substituted letters.
Basically Soundex is better for finding that "Schmidt" and "Smith" might be the same surname.
Levenshtein distance is better for spotting that the user has mistyped "Levnshtein" ;-)


q: I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net.  Does anybody has experience with this?

[A]
I like
Atalasoft's DotImage Photo
, but its a closed source solution and costs about 600 per dev license.
You can also check out
DTools at Codeplex
, which is an open source framework designed to supplement the standard Fx.  It includes some Exif related classes.


q:
I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:

var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');

This gives me an error:

unterminated string literal

With JSON.parse(data), I see similar error messages: "Unexpected token ↵" in Chrome, and "unterminated string literal" in Firefox and IE.

When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail.

[A]
This is what you want:
```
```
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
```
```
You need to escape the
```
\
```
in your string (turning it into a double-
```
\
```
), otherwise it will become a newline in the JSON source, not the JSON data.


q:
Following my question regarding a .NET YAML Library... as there doesn't seem to be great support for YAML in .NET, are there and good open source really simple .NET XML libraries.  I just want something where I can pass it a section name and a key and it gives me the value as well as being able to give me a list of all the current sections and keys.

Also, preferably something with a license that allows it to be used commercially.

[A] Can you use the 3.5 framework? Linq to XML is fantastic, and simple.


q:
I have a library I created,

File mylib.c:

#include <mylib.h>

int
testlib() {
    printf("Hello, World!\n");
    return (0);
}

File mylib.h:

#include <stdio.h>
extern int testlib();

In my program, I've attempted to call this library function:

File myprogram.c:

#include <mylib.h>

int
main (int argc, char *argv[]) {
    testlib();
    return (0);
}

When I attempt to compile this program I get the following error:

In file included from myprogram.c:1
mylib.h:2 warning: function declaration isn't a prototype

I'm using: gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)

What is the proper way to declare a function prototype?

[A]
Try:
```
```
extern int testlib(void);
```
```


q:
.NET Framework: 2.0
Preferred Language: C#

I am new to TDD (Test Driven Development).

First of all, is it even possible to unit test Windows Service?

Windows service class is derived from ServiceBase, which has overridable methods,

OnStart

OnStop

How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order?

At this point, am I even doing a Unit testing? or an Integration test?

I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.

[A]
I would start
here
.  It shows how to start and stop services in C#
A sample to start is is
```
```
public static void StartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
    // ...
  }
}
```
```
I have also tested services mostly through console app, simulating what the service would do.  That way my unit test is completely automated.


q:
The company I work for makes hardware that communicates to the computer though a serial port. Third party companies write software that communicates with our hardware.

There are times when I need to diagnose our hardware. However, a third party software app connects to the serial port when Windows starts up, blocking any other connection. I don't know the name of this application/service and it's not always the same one.

Is there any way to either:

Find the name/pid of the app/service that is currently using a given serial port or

Steal the serial port connection from another app.

vb.net preferably, but I'll take a language agnostic answer as well.

[A]
Sysinternals
has a slew of utilities I find very useful and educational for tracking down what processes are doing to the system.
They have a utility that does exactly what you need called
Portmon
, and give some information on how it works near the bottom of the page.  That info and a few well-asked questions will probably give you everything you need to implement it yourself if the utility isn't enough.
-Adam


q:
I'm looking to use SQL to format a number with commas in the thousands, but no decimal (so can't use Money) - any suggestions?

I'm using SQL Server 2005, but feel free to answer for others as well (like MySQL)

[A]
In MySQL, the
```
FORMAT()
```
function will do the trick.


q:
We're doing an "Amazing Race" kind of event, and thought it would be cool to have CDs that could only play once... like a "this message will self destruct in 5 seconds..."

Any thoughts on how to do this?  I was thinking it could be a compiled HTML website that would write a cookie and only play once.  I don't want to write to the registry (don't want to depend on windows, don't want to install anything, etc).

I also don't care if it's hackable... This is a one-time fun event, and I don't really care too much if people could remove the cookie or something.

Any other ideas?

[A]
If the content is HTML and run inside a normal browser window, then a cookie may work but there are caveats:
User runs the CD once when IE is the default browser. User runs at a later time, when Firefox is the default browser so cookie cannot be checked.
The browser's security settings may be locked down to prevent use of script so the cookie cannot be set (more of an IE problem).
An alternative might be Flash's equivalent of cookies, but if script was locked down then the same may be true for Flash.


q:
The following code illustrates an object literal being assigned, but with no semicolon afterwards:

var literal = {
    say: function(msg) { alert(msg); }
}
literal.say("hello world!");

This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?

I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.

[A]
Not technically, JavaScript has semicolons as optional in many situations.
But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.
Automatic semicolon insertion is performed by the interpreter, so you
can
leave them out if you so choose. In the comments, someone claimed that
Semicolons are not optional with statements like break/continue/throw
but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference.
Here is the rest of the standard on semicolon insertion:
For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.


q:
I would like to flash a success message on my page.

I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.

What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.

How can you animate this using jQuery?

[A]
use
```
setTimeout(function(){$elem.hide();}, 5000);
```
Where
```
$elem
```
is the element you wish to hide, and
```
5000
```
is the delay in milliseconds. You can actually use any function within the call to
```
setTimeout()
```
, that code just defines a small anonymous function for simplicity.


q:
It seems that IE6 ignores any form of cache invalidation sent via http headers, I've tried setting Pragma to No Cache and setting Cache Expiration to the current time, yet in IE6, hitting back will always pull up a cached version of a page I am working on.

Is there a specific HTTP Header that IE6 does listen too?

[A]
Have you tried setting an ETag in the header?  They're a pretty reliable way to indicate that content has changed
w3c Spec
&
Wikipedia
Beyond that, a little more crude way is to append a random query string parameter to the request, such as the current unix timestamp.  As I said, crude, but then IE6 is not the most subtle of beasts


q: I have a simple 2-column layout with a footer that clears both the right and left div in my markup.  My problem is that I can't get the footer to stay at the bottom of the page in all browsers.  It works if the content pushes the footer down, but that's not always the case.

[A]
To get a sticky footer:
Have a
```
<div>
```
with
```
class="wrapper"
```
for your content.
Right
before
the closing
```
</div>
```
of the
```
wrapper
```
place the
```
<div class="push"></div>
```
.
Right
after
the closing
```
</div>
```
of the
```
wrapper
```
place the
```
<div class="footer"></div>
```
.
```
```
* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}
```
```


q: Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.

[A]
For a heavy weight solution, you should check out
doxygen
.  It scans through your code base and comes up with a website, effectively, that documents your code.  One of the many things it shows is include trees.
If you were looking to be able to plug the output of this tool into some other process, then this may not work for you (although doxygen does output to other formats, I'm not real familiar with that feature).  If you simply want to eyeball the dependencies, though, it should work great.


q:
I have the next function:

function setImagesWidth(id,width) {
    var images = document.getElementById(id).getElementsByTagName("img");
    for(var i = 0; i < images.length;i++) {
        // If the real width is bigger than width parameter
            images[i].style.width=width;
        //}
    }
}

I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework.

images[i].offsetWidth returns 111 for an image of 109px width. Is this because 1px each side border?

[A]
Here is, hopefully, enough sample code to give you what you want:
```
```
var myImage = document.getElementById("myImagesId");
var imageWidth = myImage.offsetWidth;
var imageHeight = myImage.offsetHeight;
```
```
That should give you the numbers you need to derive the solution you want. I think you can write the rest of the code yourself. :)
EDIT: Here, I couldn't help myself - is this what you are after?
```
```
function setImagesWidth(id,width) {
   var images = document.getElementById(id).getElementsByTagName("img");
   for(var i = 0; i < images.length;i++) {
      if(images[i].offsetWidth > width) {
         images[i].style.width= (width + "px");
      }
   }
}
```
```


q:
Sometimes IE6 will render the text of a <ul> list the same color as the background color. If you select it, they show back up, or if you scroll the page up and back down.

It is obviously a rendering bug, but I was wondering if anyone knows of a workaround to make it reliable?

[A]
Have you tried explicitly setting a line-height? For some reason this seems to be the solution to a great many IE6 rendering bugs!
e.g.
```
```
.mylist {
    line-height: 1.6em;
}
```
```


q:
How can I determine if a string is an IP address? Either IPv4 or IPv6?

What is the least and most number of characters?

I assume this would be a regex answer.


q: We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE.  We aren't sure what the EXE file is used for because we are able to install without the EXE.

[A]
It's a bootstrapper that checks to make sure that the .NET Framework is installed, before launching the MSI. It's pretty handy.
I suggest using something like SFX Compiler to package the two together into one self-extracting .exe and then launch the extracted setup.exe. This way you retain the benefits of the bootstrapper, but your users only download a single thing.
Edit
: also see
The official line:
MSDN documentation
Some bootstrapper customization:
some guy's blog post about what he did


q:
Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?

//pseudo-codeish
string s = Coalesce(string1, string2, string3);

or, more generally,

object obj = Coalesce(obj1, obj2, obj3, ...objx);

[A]
the
??
operator.
```
```
string a = nullstring ?? "empty!";
```
```


q:
Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong.  Will it cause a memory leak.

EG:

try

dim mySQL as new sqlcommand(sSQL, cnInput)

// do a sql execute and read the data

mySQL = new sqlcommand(sSQLdifferent, cnInput)

// do sql execute and read the data
catch ...

finally

if mysql isnot nothing then
   mysql.dispose
   mysql = nothing
end if

EDIT: put try catch in to avoid the comments about not using them

[A]
Garbage collection will gather up the first new when it is run.
Only the second one you purposely dispose in the Finally block.  The first one will be disposed of the next time the garbage collection is run.
I do not think this is a good idea.  If the first command is not closed correctly it is possible you would have an open connection to the database and it will not be disposed.
A better way would be to dispose the first command after you are done using it, and then to reuse it.


q:
X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions.

Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X?

I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.


q:
I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key presses that contain the card swipe sentinel characters.

Is there a better way to deal with this sort of input?

Edit: The device does simply present the data as keystrokes and doesn't interface through some other driver. Also We use a wide range of these types of devices so ideally a method should work independent of the specific model of wedge being used. However if there is no other option I'll have to make do.

[A]
One thing you can do is that you should be able to configure your wedge reader so that it presents one or many escape characters before or after the string.  You would use these escape characters to know that you are about to have (or just had) a magcard input.
This same technique is used by barcode reader devices so you application knows to get focus or handle the data input from the device.
The negative to this approach is that you have to properly configure your external devices.  This can be a deployment issue.
This assumes that your devices simply present the data as keystrokes and don't interface through some other driver.


q:
I have some code that uses SMO to populate a list of available SQL Servers and databases.  While we no longer support SQL Server 2000, it's possible that the code could get run on a machine that SQL Server 2000 and not have the SMO library installed.  I would perfer to check for SMO first and degrade the functionality gracefully instead of blowing up in the user's face.  What is best way to detect whether or not SMO is available on a machine?

Every example that I have seen through a quick Google scan was a variation of "look for C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll".  The problem with that approach is that it only works with SQL Server 2005.  If SQL Server 2008 is the only SQL Server installed then the path will be different.

[A]
This is kind of clunky, but a quick check of the registry seems to work.  Under HKEY_CLASSES_ROOT, a large number of classes from the SMO assemblies will be registered.  All I needed to do was to pick one of the SMO classes and check for the existence of the key with the same name.  The following function will return true if SMO has been installed, false if otherwise.
```
```
private bool CheckForSmo()
{
    string RegKeyName = @"Microsoft.SqlServer.Management.Smo.Database";
    bool result = false;
    Microsoft.Win32.RegistryKey hkcr = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(RegKeyName);
    result = hkcr != null;

    if (hkcr != null)
    {
        hkcr.Close();
    }

    return result;
}
```
```


q:
class Foo
{
   static bool Bar(Stream^ stream);
};

class FooWrapper
{
   bool Bar(LPCWSTR szUnicodeString)
   {
       return Foo::Bar(??);
   }
};

MemoryStream will take a byte[] but I'd like to do this without copying the data if possible.

[A]
If I had to copy the memory, I think the following would work:
```
```
static Stream^ UnicodeStringToStream(LPCWSTR szUnicodeString)
{
   //validate the input parameter
   if (szUnicodeString == NULL)
   {
      return nullptr;
   }

   //get the length of the string
   size_t lengthInWChars = wcslen(szUnicodeString);
   size_t lengthInBytes = lengthInWChars * sizeof(wchar_t);

   //allocate the .Net byte array
   array^ byteArray = gcnew array(lengthInBytes);

   //copy the unmanaged memory into the byte array
   Marshal::Copy((IntPtr)(void*)szUnicodeString, byteArray, 0, lengthInBytes);

   //create a memory stream from the byte array
   return gcnew MemoryStream(byteArray);
}
```
```


q:
We have a client that has Oracle Standard, and a project that would be ten times easier addressed using OLAP. However, Oracle only supports OLAP in the Enterprise version.

Migration to enterprise is not possible

I'm thinking of doing some manual simulation of OLAP, creating relational tables to simulate the technology.

Do you know of some other way I could do this? Maybe an open-source tool for OLAP? Any ideas?

[A]
I find that it's the schema that causes most of the issues people have with querying a database.  OLAP forces you to either a flat table or a Star/snowflake schema which is easy to query and comparably faster to the source oltp tables.   So if you ETL your source to a flat table or star schema you should get 80% of what you get from OLAP, the 20% being MDX and analytic functions and performance.
Note that you should get a perf boost with a star schema in relational database as well and Oracle probably has analytic functions in PL/SQL anyways.


q:
I've started working with ASP.net AJAX (finally ☺). and I've got an update panel together with a asp:UpdateProgress. My Problem: The UpdateProgress always forces a line-break, because it renders out as a div-tag.

Is there any way to force it being a span instead? I want to display it on the same line as some other controls without having to use a table or even shudders absolute positioning in CSS.

I'm stuck with ASP.net AJAX 1.0 and .net 3.0 if that makes a difference.

[A]
You can make a div inline like this:
```
```

stuff

```
```
I'm skeptical of it rendering the div for you though...  I don't remember having this problem on my pages...


q:
I have a C# singleton class that multiple classes use. Is access through Instance to the Toggle() method thread-safe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it?

public class MyClass
{
    private static readonly MyClass instance = new MyClass();

    public static MyClass Instance
    {
        get { return instance; }
    }

    private int value = 0;

    public int Toggle()
    {
        if(value == 0)
        {
            value = 1;
        }
        else if(value == 1)
        {
            value = 0;
        }

        return value;
    }
}

[A]
Quote:
```
```
if(value == 0) { value = 1; }
if(value == 1) { value = 0; }
return value;
```
```
```
value
```
will always be 0...


q:
Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.

[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]

Becomes:

[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]

Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?

[A]
Here it is in C#
```
```
int[,] array = new int[4,4] {
    { 1,2,3,4 },
    { 5,6,7,8 },
    { 9,0,1,2 },
    { 3,4,5,6 }
};

int[,] rotated = RotateMatrix(array, 4);

static int[,] RotateMatrix(int[,] matrix, int n) {
    int[,] ret = new int[n, n];

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            ret[i, j] = matrix[n - j - 1, i];
        }
    }

    return ret;
}
```
```


q:
Looking for an example that:

Launches an EXE

Waits for the EXE to finish.

Properly closes all the handles when the executable finishes.

[A]
There is an example at
http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx
Just replace the
```
argv[1]
```
with your constant or variable containing the program.
```
```
#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }

    // Start the child process.
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    )
    {
        printf( "CreateProcess failed (%d).\n", GetLastError() );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles.
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}
```
```


q:
I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?

Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):

The [below] code does NOT make a
  connection or send any packets (to
  64.233.187.99 which is google). Since UDP is a stateless protocol connect()
  merely makes a system call which
  figures out how to route the packets
  based on the address and what
  interface (and therefore IP address)
  it should bind to. addr() returns an
  array containing the family (AF_INET),
  local port, and local address (which
  is what we want) of the socket.

[A]
try:
Request.remote_ip
remote_ip()
Determine originating IP address. REMOTE_ADDR is the standard but will
  fail if the user is behind a proxy. HTTP_CLIENT_IP and/or
  HTTP_X_FORWARDED_FOR are set by proxies so check for these if
  REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma- delimited
  list in the case of multiple chained proxies; the last address which
  is not trusted is the originating IP.
Update:
Oops, sorry I misread the documentation.


q:
The Python docs say:

re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...

So what's going on when I get the following unexpected result?

>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'

[A]
Look at the definition of
```
re.sub
```
:
```
```
re.sub(pattern, repl, string[, count, flags])
```
```
The 4th argument is the count, you are using
```
re.MULTILINE
```
(which is 8) as the count, not as a flag.
Either use a named argument:
```
```
re.sub('^//', '', s, flags=re.MULTILINE)
```
```
Or compile the regex first:
```
```
re.sub(re.compile('^//', re.MULTILINE), '', s)
```
```


q:
I know you can use several different view engines with ASP.NET MVC:

ASPX, obviously

NVelocity

Brail

NHaml

et al...

The default ASPX view engine seems to make the most sense to me, coming from an ASP.NET WebForms background.

But, I wanted to get an idea of the pros and cons of each and see what most people are using.

Which does StackOverflow use?

[A]
Most people on the planet will just use ASPX because that's what they know.  Another excellent benefit is the compiled-nature... so you not only get type-safety and intellisense, but you can get the perf benefit as well.
The drawback that I see is that it's so flippin' verbose.  I converted an app to NVelocity and was astounded at how clean it looked.  The problem is that there were a lot of things that didn't work with NVelocity (like your own custom view helpers) and there was a severe lack of documentation.
I added a feature to MvcContrib where you can register your own HtmlExtension types to it, but it's more of a bandaid until a better solution comes out.


q:
I have heard/read the term but don't quite understand what it means.

When should I use this technique and how would I use it? Can anyone provide a good code sample?

[A]
The visitor pattern is a way of doing double-dispatch in an object-oriented way.
It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time.
Double dispatch is a special case of
multiple dispatch
.
When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object.
For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time.
In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.
Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters.
To do double-dispatch in C#
, you can declare a method with a sole object argument and then specific methods with specific types:
```
```
using System.Linq;

class DoubleDispatch
{
    public T Foo<T>(object arg)
    {
        var method = from m in GetType().GetMethods()
                   where    m.Name == "Foo"
                         && m.GetParameters().Length==1
                         && arg.GetType().IsAssignableFrom
                                           (m.GetParameters()[0].GetType())
                         && m.ReturnType == typeof(T)
                   select m;

        return (T) method.Single().Invoke(this,new object[]{arg});
    }

    public int Foo(int arg) { /* ... */ }

    static void Test()
    {
        object x = 5;
        Foo<int>(x); //should call Foo(int) via Foo<T>(object).
    }
}
```
```


q:
How am I supposed to get the IDENTITY of an inserted row?

I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY, but don't understand the implications or impacts attached to each.

Can someone please explain the differences and when I would be using each?

[A]
From MSDN
@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.
@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.
IDENT_CURRENT is a function which takes a table as a argument.
@@IDENTITY may return confusing result when you have an trigger on the table
SCOPE_IDENTITY is your hero most of the time.


q: Generally the database server is the biggest, most expensive box we have to buy as scaling vertically is the only option.  Are there any databases that scale well horizontally (i.e. across multiple commodity machines) and what are the limitations in this approach?

[A]
There are storage techniques such as JavaSpaces (or a commercial implementation such as Gigaspaces) which provide highly scalable, fast & secure access to objects.
There are also distributed cacheing systems such as memcached, which offer a similar approach.
Of course, neither of these are true databases, but they are things that can work in conjunction with databases to offer a large amount of horizontal scalability, given a suitable architecture.  The real problem is that if you want all of the ACID goodness that comes with a database, there are certain unavoidable performance penalties. The only way out is to figure out the bits where you don't need ACID, and use other technologies to service those bits.


q:
What would be the best way to do an scp or sftp copy in a Unix environment using C?

I'm interested in knowing the best library to use and an example if at all possible. I'm working on a Solaris server with the Sun tools installed.

[A]
In the past, I've simply called a shell script that contained the file transfer code.
```
```
int transferFile()
{
  // Declare the transfer command
  char transferCommand[50] = "/home/tyler/transferFile.shl";
  // Execute the command
  return system(transferCommand);
}
```
```
This will return 1 if the transfer command returns successfully.


q:
What's the best way to get user input in a C program where the choices are of a limited number?

Say for example the choices are:

A) Print the list.
B) Add 99 to the end of the list.
C) Delete all duplicates.
5) Reset 5 times.

Entering "A" and then Enter is OK.
Or, just a single keystroke would work as well.

[A]
I have used something simple like the following:
```
```
int intput()
{
    char input = 0;
    int ret_val = 0;

    read(0, &input, 1);

    switch(input) {
        case 'c':
            // Do c
            break;

        case 'p':
            // Do p
            break;

        case 'd':
            // Do d
            break;

        case 'q':
            quit = 1;
            break;

        case '?':
            PRINT(ENABLE, "c - connect\n");
            PRINT(ENABLE, "p - ping\n");
            PRINT(ENABLE, "d - disconnect\n");
            PRINT(ENABLE, "q - quit\n");
            PRINT(ENABLE, "? - this message\n");
            break;
    }

    return 0;
}
```
```


q:
Here is some code I could not get to format properly in markdown, this is straight C code, pasted into the text box with the '4 spaces' format to denote code:

#define PRINT(x, format, ...) \
if ( x ) { \
    if ( debug_fd != NULL ) { \
        fprintf(debug_fd, format, ##__VA_ARGS__); \
    } \
    else { \
        fprintf(stdout, format, ##__VA_ARGS__); \
    } \
}

It seems as though the '\' causes the newlines to be ignored.  Ok fine, I am used to this in bash, but if I put '\' the second one doesn't show up.  As if the second one is absorbed.   Am I missing something?

[A]
Add at least four spaces or a hard tab before each line of the code. Like this:
```
```
#define PRINT(x, format, ...) \
if ( x ) { \
    if ( debug_fd != NULL ) { \
        fprintf(debug_fd, format, ##VA_ARGS); \
} \
else { \
    fprintf(stdout, format, ##VA_ARGS); \
} \
}
```
```


q: Does anyone know how many options a drop down list can have? Is it unlimited?  How many before performance degrades?

[A]
Does anyone know how many options a drop down list can have? Is it unlimited?
I imagine it is unlimited in theory, obviously not in practice as a computer's RAM and the specific browser's limitations come into play.
How many before performance degrades?
Again, this would depend on a few factors, at the least the specific browser, the computer's memory and processing power.
EDIT: From experience, I have had drop down lists with thousands of options. It wasn't ideal though because who wants to scroll through all of those? This is why an auto-complete of some type is more desirable for numerous reasons, especially the end user's experience.


q: I'm using Ctrl+Left / Ctrl+Right in a GreaseMonkey script as a hotkey to turn back / forward pages. It seems to works fine, but I want to disable this behavior if I'm in a text edit area. I'm trying to use document.activeElement to get the page active element and test if it's an editable area, but it always returns "undefined".

[A]
document.activeElement works for me in FF3 but the following also works
```
```
(function() {

var myActiveElement;
document.onkeypress = function(event) {
    if ((myActiveElement || document.activeElement || {}).tagName != 'INPUT')
        // do your magic
};
if (!document.activeElement) {
    var elements = document.getElementsByTagName('input');
    for(var i=0; i<elements.length; i++) {
        elements[i].addEventListener('focus',function() {
            myActiveElement = this;
        },false);
        elements[i].addEventListener('blur',function() {
            myActiveElement = null;
        },false);
    }
}

})();
```
```


q: Do you have any strategies for retrofitting unit tests onto a code base that currently has no unit tests ?

[A]
Read
Working Effectively With Legacy Code by Feathers
.
Jimmy Bogard has a
good blog series on SOC
.


q: How can I get the MAC Address using only the compact framework?

[A]
Add a reference to System.Management.dll and use something like:
```
```
Dim mc As System.Management.ManagementClass
Dim mo As ManagementObject
mc = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim moc As ManagementObjectCollection = mc.GetInstances()
For Each mo In moc
    If mo.Item("IPEnabled") = True Then
        ListBox1.Items.Add("MAC address " & mo.Item("MacAddress").ToString())
    End If
Next
```
```


q: Anyone know a good book or post about how to start in EF? I have seen the DnrTV any other place?

[A]
Mike Taulty's Blog:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/category/1024.aspx
A great EF intro deck:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/03/13/10235.aspx
And these ADO.NET Data Services screencasts are nice too:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/01/25/10152.aspx
ADO.NET Entity Framework MSDN:
http://msdn.microsoft.com/en-us/library/bb399572.aspx
ADO.NET Entity Framework forums:
http://forums.microsoft.com/msdn/ShowForum.aspx?ForumID=533&SiteID=1
ADO.NET team blog:
http://blogs.msdn.com/adonet/archive/tags/Entity+Framework/default.aspx
Programming LINQ and the ADO.NET Entity Framework Webcast:
http://blogs.msdn.com/adonet/archive/2008/01/28/programming-linq-and-the-ado-net-entity-framework-webcast.aspx


q:
I'm using the AutoComplete control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox.

I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work.  If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click.

Is there a special place I need to set the focus or something else I need to do to make this work?  Thanks.

[A]
We had exactly the same problem.  What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox.  You can have a look at the (terribly hacky) solution here:
http://www.drive.com.au
The textbox id is
```
MainSearchBox_SearchTextBox
```
.  Have a look at about line 586 & you can see where I'm wiring up all the events (I'm actually using prototype for this bit.
Basically on the focus event of the textbox I set a global var called
```
textBoxHasFocus
```
to true and on the blur event I set it to false.  The on the load event of the page I call this script:
```
```
if (textBoxHasFocus) {
    $get("MainSearchBox_SearchTextBox").blur();
    $get("MainSearchBox_SearchTextBox").focus();
}
```
```
This resets the textbox.  It's really dodgy, but it's the only solution I could find


q:
Of course the best metric would be a happiness of your users.

But what metrics do you know for GUI usability measurements?

For example, one of the common metrics is a average click count to perform action.
What other metrics do you know?

[A]
Jakob Nielsen has several articles regarding usability metrics, including one that is entitled, well,
Usability Metrics
:
The most basic measures are based on the definition of usability as a quality metric:
success rate (whether users can perform the task at all),
the time a task requires,
the error rate, and
users' subjective satisfaction.


q:
Is there any benefit in using a <blockquote> element over a <div>? I was looking at a website's markup to learn CSS and I couldn't figure out why the <blockquote> was being used.

EDIT: Yeah sorry I didn't clarify, it was used to hold the <div> tag with username as 'text' and an input tag. There was clearly no quote.

[A]
Semantically, a
```
blockquote
```
tag makes sense when you're quoting something.  Sure, a stylized div can do the same thing, but why not use the right tag for the job?
Additionally, the blockquote tag allows you to include a citation with the
```
cite
```
attribute.


q:
What database should a beginner use in the C language?

Can I use MySQL?

Thanks

[A]
You can use SQLite, MySQL, PostgreSQL, or any other DBMS with a C language binding.
SQLite In 5 Minutes Or Less
MySQL C API
PostgreSQL C API


q:
In one of my applications I have a 1gb database table that is used for reference data. It has a huge amounts of reads coming off that table but there are no writes ever. I was wondering if there's any way that data could be loaded into RAM so that it doesn't have to be accessed from disk?

I'm using SQL Server 2005

[A]
You're going to want to take a look at memcached. It's what a lot of huge (and well-scaled) sites used to handle problems just like this. If you have a few spare servers, you can easily set them up to keep most of your data in memory.
http://en.wikipedia.org/wiki/Memcached
http://www.danga.com/memcached/
http://www.socialtext.net/memcached/


q:
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn't support that, does the dateutil package support this?

[A]
EDIT: See @Blair Conrad's answer for a cleaner solution
```
```
>>> import datetime
>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
datetime.date(2000, 1, 31)
```
```


q: What would be the best way to develop a text box that remembers the last x number of entries that were put into it.  This is a standalone app written with C#.

[A]
This is actually fairly easy, especially in terms of showing the "AutoComplete" part of it.  In terms of remembering the last x number of entries, you are just going to have to decide on a particular event (or events) that you consider as an entry being completed and write that entry off to a list... an AutoCompleteStringCollection to be precise.
The TextBox class has the 3 following properties that you will need:
AutoCompleteCustomSource
AutoCompleteMode
AutoCompleteSource
Set AutoCompleteMode to SuggestAppend and AutoCompleteSource to CustomSource.
Then at runtime, every time a new entry is made, use the Add() method of AutoCompleteStringCollection to add that entry to the list (and pop off any old ones if you want).  You can actually do this operation directly on the AutoCompleteCustomSource property of the TextBox as long as you've already initialized it.
Now, every time you type in the TextBox it will suggest previous entries :)
See this article for a more complete example:
http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx
AutoComplete also has some built in features like FileSystem and URLs (though it only does stuff that was typed into IE...)


q: Does anyone know how to setup Mercurial to use p4merge as the merge/diff tool on OS X 10.5?

[A]
I'm guessing there's a CLI tool for p4merge (which I know nothing about).
I wrote a blog post about using Changes.app, and some other GUI tools with Mercurial:
Using Mercurial with GUI Tools.
Basically, you need to know the calling expectations of the CLI tool that loads up the diff tool.  IE, how to make it load data from a particular file, and how to make it wait for exit.  There should be enough info on the post to give you some ideas.


q:
I'm behind a firewall at work at the moment and I was testing something that I had deployed to my website, and the work proxy seems to be blocking it somewhat.

Basically I am getting a message of:

Operation is not valid due to the current state of the object

I've got it down to my proxy interferring, but I can't see any advanced settings or anything I can set up to go through my proxy to get to my service.

I did a quick google for it, but no joy.

Anyone found a quick way to get around it?

[A]
Edit, I forgot to write this part in the answer: You may need to add the web reference url to the safe list for your proxy.  I am not sure what proxy you are using or if you have control of it, but this should solve your problem.  If you don't have access to change the proxy, then I put a quick work around right below.
Here's a quick work around, just use the browser to navigate to the WSDL.  Grab the xml and save it as a .wsdl file on your computer you would like to generate the client on.  Then use the
wsdl.exe
to generate the client pointing it to the path you saved the wsdl file.


q:
I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.

Example:

// Updated to be correct, thanks @Apocalisp
^foo.*(?<!bar)$

Should match anything that starts with "foo" and doesn't end with "bar".  I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters.

I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too.

Thanks to @Kibbee for verifying that this works in C# as well.

[A]
I'm not familiar with Java regex but documentation for the
Pattern Class
would suggest you could use (?!X) for a non-capturing zero-width negative lookahead (it looks for something that is not X at that postision, without capturing it as a backreference). So you could do:
```
```
foo.*(?!bar) // not correct
```
```
Update
: Apocalisp's right, you want negative lookbehind. (you're checking that what the .* matches doesn't end with bar)


q:
Starting a new project and would like to use one of the MVC framworks.  ASP.NET MVC is still in preview but Spring.net is in production and has a history with Java.  I'd like to know the general lowdown between the two.

Current questions..

What are the major feature differences?

What about deployment/hosting issues?

Future support? Do you think Spring.net will fade once ASP.NET MVC is in production.

Current Support?  I saw the Jeff twitting about a breaking change in the next preview.

Thanks!

[A]
I am a little confused by the question.  Spring.Net is a dependency injection framework that you can use in ASP.NET MVC.  I kind of based my answer off what you are actually asking though.  The difference between ASP.NET MVC and another MVC framework that runs in ASP.NET.
If you are worried about using ASP.NET MVC in production since it is not even in beta yet, then you may want to check out
MonoRail
as an alternate.  There are some differences in features, but the two are pretty close in terminology and how MVC is implemented.  To learn differences,
here is a question
that was posted, that you might want to monitor.  I think once ASP.NET hits release, that most Microsoft shops will switch to it.  With ASP.NET MVC still being developed, you will run into breaking changes that you will have to change when you upgrade to the next release.  That goes with the territory of living on the edge.  You just need to read the release notes before jumping to the latest release.


q:
I have upgraded a MS Visual Studio Application from VS 2003 to VS 2008 (Targeting .NET 2.0). As part of the conversion process the wizard said I needed to take the additional step of Converting my Project to a Website by Right-Clicking and blah blah blah...

I didn't follow directions and the web application seems to be working fine.

My question is, should I be concerned about pushing this to a production system? What exactly is going on here?

[A]
There are two types of web applications in ASP.NET: The Web Site and Web Application Project. The difference between the two are discussed here:
Difference between web site and web applications in Visual Studio 2005
Convert to Website allows you to convert a Web Application Project to a Web Site.
Visual Studio 2003 used the Web Application Project style, but initially VS2005 only supported web sites. VS2005 SP1 brought back Web Applications.
If you don't want to convert your project to a web site, apply SP1 if you're using VS2005. VS2008 can support either.


q:
I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc.

I've found solutions to this problem but they rely on alternative color palettes than RGB.
I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors.

Any ideas would be great.

[A]
you could have them be within a certain brightness. that would control the ammount of "neon" colors a bit. for instance, if the "brightness"
```
```
brightness = sqrt(R^2+G^2+B^2)
```
```
was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black.


q:
I have a self referencing Categories table. Each Category has a CategoryID, ParentCategoryID, CategoryName, etc. And each category can have any number of sub categories, and each of those sub categories can have any number of sub categories, and so and and so forth. So basically the tree can be X levels deep.

Then Products are associated to leaf (sub) Categories. Is there a way to get all the Products for any given Category (which would be all the products associated to all its leaf descendants) using LINQ to SQL?

This feels like a recursive problem. Is it better to used a Stored Procedure instead?

[A]
Well here is a terrible rushed implementation using LINQ.
Don't use this :-)
```
```
public IQueryable GetCategories(Category parent)
{
    var cats = (parent.Categories);
    foreach (Category c in cats )
    {
        cats  = cats .Concat(GetCategories(c));
    }
    return a;
}
```
```


q:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

[A]
I think
```
```
var castList = list.Cast<typeof(T)>();
```
```
should be
```
```
var castList = list.Cast<T>();
```
```
@Jon Limjap The most glaring error I can see is
  that an
```
IList
```
is definitely different from an
```
IList<T>
```
. An
```
IList
```
is non-generic
  (e.g.,
```
ArrayList
```
).
The original question was already using an
```
IList<T>
```
. It was removed when someone edited the formatting. Probably a problem with Markdown.
Fixed now.


q:
Simple question, but one that I've been curious about...is there a functional difference between the following two commands?

String::class
String.class

They both do what I expect -- that is to say they return Class -- but what is the difference between using the :: and the .?

I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after :: but not after ., but I don't know what the reason for this is...

[A]
The
```
.
```
operator basically says "send this message to the object". In your example it is calling that particular member. The
```
::
```
operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator.
When you use
```
::
```
you have to be referencing members that are defined. When using
```
.
```
you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for
```
.
```
while it does for
```
::
```
.


q:
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).

So, given an InputStream in and an OutputStream out, is there a simpler way to write the following?

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}

[A]
I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.
```
```
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}
```
```


q:
I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.

However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.

Does anybody have any ideas for resolving this?

[A]
If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work.
You could also do this in your Page_Load (In your masterpage):
```
```
Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js"))
```
```


q: Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)

[A]
OK, here's my best pseudo math:
The equation for your line is:
Y = a + bX
Where:
b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)
a = sum(y)/n - b(sum(x)/n)
Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)
... and now with added Sigma
b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n)
a = (Σy)/n - b((Σx)/n)
Where Σ(xy) is the sum of all x*y etc. and n is the number of points


q:
Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure?

For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it.

SQL Server 2005 is my only applicable limitation I think.

create procedure getDepartments
  @DepartmentIds varchar(max)
as
  declare @Sql varchar(max)
  select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')'
  exec(@Sql)

[A]
Yeah, your current solution is prone to SQL injection attacks.
The best solution that I've found is to use a function that splits text into words (there are a few posted here, or you can use
this one from my blog
) and then join that to your table. Something like:
```
```
SELECT d.[Name]
FROM Department d
    JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId
```
```


q: Can we have the database and transaction logs on the same drive? What will be its consequences if it is not recommended?

[A]
The only downside is that it causes more thrashing on the disk, so worse performance.
A single write will require 2 seeks (between: write transaction log, write data, commit log). Having the transaction log on a separate disk means as few as zero seeks, because the drive heads can remain on the transaction log and the data.


q:
How can I do this fast?

Sure I can do this:

static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
    if (a1.Length != a2.Length)
        return false;

    for (int i=0; i<a1.Length; i++)
        if (a1[i]!=a2[i])
            return false;

    return true;
}

But I'm looking for either a BCL function or some highly optimized proven way to do this.

java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2);

works nicely, but it doesn't look like that would work for x64.

Note my super-fast answer here.

[A]
I would use unsafe code and run the
```
for
```
loop comparing Int32 pointers.
Maybe you should also consider checking the arrays to be non-null.


q:
In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?

What I need is to create a list of menu items where each item has name, URL, and an active flag  (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.

[A]
If you need to use something similar to the
```
{% url %}
```
template tag in your code, Django provides the
```
django.core.urlresolvers.reverse()
```
. The
```
reverse
```
function has the following signature:
```
```
reverse(viewname, urlconf=None, args=None, kwargs=None)
```
```
https://docs.djangoproject.com/en/dev/ref/urlresolvers/
At the time of this edit the import is
```
django.urls import reverse
```


q:
I know that I can do something like

$int = (int)99; //(int) has a maximum or 99

To set the variable $int to an integer and give it a value of 99.

Is there a way to set the type to something like LongBlob in MySQL for LARGE Integers in PHP?

[A]
No. PHP does what is called automatic type conversion.
In your example
```
```
$int = (int)123;
```
```
the "(int)" just assures that at that exact moment 123 will be handled as an int.
I think your best bet would be to use a class to provide some sort of type safety.


q: Using PyObjC, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?

[A]
Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift.
There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term.
That said, Objective-C and Swift really are not too scary...
2016 edit
Javascript with NativeScript framework is available to use now.


q:
I know that default cron's behavior is to send normal and error output to cron's owner local email box.

Is there other ways to get theses results (for example to send it by email to a bunch of people, to store them somewhere, and so on) ?

[A]
The cron line is just like any other unix command line so you can redirect output to another program. Ie.
```
```
* * * * * /path/my/command > /my/email/script 2&>1
```
```


q: For example, I issued an ALTER TABLE statement to create an index on a MEDIUMTEXT field in an InnoDB table that has 134k rows where the size of the index was 255 bytes and the average size of the data in the field is 30k.  This command has been running for the last 15 minutes or so (and is the only thing running on the database).  Is there any way for me to determine if it is going to finish in closer to 5 minutes, 5 hours, or 5 days?

[A]
This is a pretty common request apparently - requested as far back as 2005 on
bugs.mysql.com
.
It exists in Oracle already, and is listed as useful, but
"it is not a simple thing to do, so don't expect it to be
implemented soon."
. Although that was 2005 :)
That said, the chap who asked the original question later released a
patch
for MySQL 5.0, backported to 4.1, which might help you out.


q:
Say I have a site on http://example.com. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words

http://example.com & http://example.com/ should be allowed, but
http://example.com/anything and http://example.com/someendpoint.aspx should be blocked.

Further it would be great if I can allow certain query strings to passthrough to the home page:
http://example.com?okparam=true

but not
http://example.com?anythingbutokparam=true

[A]
Basic robots.txt:
```
```
Disallow: /subdir/
```
```
I don't think that you can create an expression saying 'everything but the root', you have to fill in all sub directories.
The query string limitation is also not possible from robots.txt. You have to do it in the background code (the processing part), or maybe with server rewrite-rules.


q:
I know 'best' is subjective, so according to you, what is the best solution for the following problem:

Given a string of length n (say "abc"), generate all proper subsets of the string. So, for our example, the output would be {}, {a}, {b}, {c}, {ab}, {bc}, {ac}. {abc}.

What do you think?

[A]
```
```
def subsets(s):
    r = []
    a = [False] * len(s)
    while True:
        r.append("".join([s[i] for i in range(len(s)) if a[i]]))
        j = 0
        while a[j]:
            a[j] = False
            j += 1
            if j >= len(s):
                return r
        a[j] = True

print subsets("abc")
```
```


q:
When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during wm_close - is DestroyHandle the .net equivalent?

I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg:

void Dispose(bool disposing) {
    otherObject.Event -= myEventHandler;
}

[A]
Normally
```
DestroyHandle
```
is being called in
```
Dispose
```
method. So you need to make sure that all controls are disposed to avoid resource leaks.


q:
Is there a way to detect if a flash movie contains any sound or is playing any music?

It would be nice if this could be done inside a webbrowser (actionscript from another flash object, javascript,..) and could be done before the flash movie starts playing.

However, I have my doubts this will be possible altogether, so any other (programmable) solution is also appreciated

[A]
Yes, on the server side for sure.  Client side?  I don't know.  (I'm a serverside kind of guy.)
On the server side, one would have to parse the file, read the header and/or look for audio frames.  (I've ported a haskel FLV parser to Java for indexing purposes myself, and there are other parsing utilities out there.  It is possible.)
osflash.org's FLV page
has the gory details.  Check out the FLV Format sections's FLV Header table.
```
```
FIELD       DATA TYPE      EXAMPLE                  DESCRIPTION
 Signature   byte[3]        “FLV”                    Always “FLV”
 Version     uint8          “\x01” (1)               Currently 1 for known FLV files
 Flags       uint8 bitmask  “\x05” (5, audio+video)  Bitmask: 4 is audio, 1 is video
 Offset      uint32-be      “\x00\x00\x00\x09” (9)   Total size of header (always 9 for known FLV files)
```
```
EDIT: My client side coding with Flash is non-existent, but I believe there is an onMetaDataLoad event that your code could catch.  That might be happening a bit late for you, but maybe it is good enough?


q:
In the business I work for we are discussion methods to reduce the read load on our primary database.

One option that has been suggested is to have live one-way replication from our primary database to a slave database. Applications would then read from the slave database and write directly to the primary database. So...

Application Reads From Slave

Application Writes to Primary

Primary Updates Slave Automatically

What are the major pros and cons for this method?

[A]
A few cons:
2 points of failure
Application logic will have to take into account the delay between writing something and then reading it, since it won't be available immediately from the secondary database
A strategy I have used is to send key reporting data to a secondary database nightly, de-normalizing it on the way, so that beefy queries can run on that database instead of locking up tables and stealing resources from the OLTP server.  I'm not using any formal data warehousing or replication tools, rather I identify problem queries that are Ok without up-to-the-minute data and create data structures on the secondary server specifically for those queries.
There are definitely pros to the "replicate everything" approach:
You can run any ad-hoc query on the secondary, since it has all of your data
If your primary server dies, you can re-purpose the secondary quickly to take over


q: Older versions of the .Net Framework used to install "Microsoft .NET Framework v1.0 / v1.1 / v2.0 Configuration" in the Control Panel, under Administrative Tools. I just noticed that there isn't a v3.0 or v3.5 version of this. Is this functionality now hiding somewhere else, or do I have to use the command-line tools instead?

[A]
Both 3 and 3.5 still use the
Common Language Runtime of .NET Framework 2.0
. So no control panel is needed, as you can still use the 2.0 control panel.


q:
I have some classes layed out like this

class A
{
    public virtual void Render()
    {
    }
}
class B : A
{
    public override void Render()
    {
        // Prepare the object for rendering
        SpecialRender();
        // Do some cleanup
    }

    protected virtual void SpecialRender()
    {
    }
}
class C : B
{
    protected override void SpecialRender()
    {
        // Do some cool stuff
    }
}

Is it possible to prevent the C class from overriding the Render method, without breaking the following code?

A obj = new C();
obj.Render();       // calls B.Render -> c.SpecialRender

[A]
You can seal individual methods to prevent them from being overridable:
```
```
public sealed override void Render()
{
    // Prepare the object for rendering
    SpecialRender();
    // Do some cleanup
}
```
```


q:
Using C# 2.0 what is the best way to implement dynamic form controls?

I need to provide a set of controls per data object, so should i just do it manually and lay them out while increment the top value or is there a better way?

[A]
What do you mean by “dynamic”? A new, fixed set of controls for each data row in the data set? Then use a
```
UserControl
```
that contains your controls.
Or do you mean that, depending on your data layout, you want to provide the user with a customized set of controls, say, one
```
TextBox
```
for each column?


q: How to restrict the maximum number of characters that can be entered into an HTML <textarea>? I'm looking for a cross-browser solution.

[A]
The
```
TEXTAREA
```
tag does not have a
```
MAXLENGTH
```
attribute the way that an
```
INPUT
```
tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be
typed
into a
```
TEXTAREA
```
tag is:
```
```
<textarea onKeyPress="return ( this.value.length < 50 );"></textarea>
```
```
Note:
```
onKeyPress
```
, is going to prevent any button press,
any button
including
the backspace key.
This works because the Boolean expression compares the field's length
before the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more,
```
false
```
if not. Returning false from most events cancels the default action.
So if the current length is already 50 (or more), the handler returns false,
the
```
KeyPress
```
action is cancelled, and the character is not added.
One fly in the ointment is the possibility of pasting into a
```
TEXTAREA
```
,
which does not cause the
```
KeyPress
```
event to fire, circumventing this check.
Internet Explorer 5+ contains an
```
onPaste
```
event whose handler can contain the
check. However, note that you must also take into account how many
characters are waiting in the clipboard to know if the total is going to
take you over the limit or not. Fortunately, IE also contains a clipboard
object from the window object.
1
Thus:
```
```
<textarea onKeyPress="return ( this.value.length < 50 );"
onPaste="return (( this.value.length +
window.clipboardData.getData('Text').length) < 50 );"></textarea>
```
```
Again, the
```
onPaste
```
event and
```
clipboardData
```
object are IE 5+ only. For a cross-browser solution, you will just have to use an
```
OnChange
```
or
```
OnBlur
```
handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly.
Source
Also, there is another way here, including a finished script you could include in your page:
http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html


q:
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.

Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.

Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.

How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows.

Does the browser add this information when posting the file to the web page?

Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?

[A]
The
mimetypes module
in the standard library will determine/guess the MIME type from a file extension.
If users are uploading files the HTTP post will contain the MIME type of the file alongside the data.  For example, Django makes this data available as an attribute of the
UploadedFile
object.


q:
A very niche problem:

I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js).

Now on this page I have a Google Map and I use the Prototype Window library.

The problem occurs in IE7 and FF3.

This is the info FireBug gives:

handler is undefined
? in prototype.js@3871()prototype.js (line 3877)
handler.call(element, event);

I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error...

I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :).

[A]
I switched to a local version of prototypejs and added some debugging
  in the offending method (createWraper) but the debugging never appears
  before the error...
Actually the offending function being called when the error occurs is "wrapper" which is created inside createWrapper (but not called there). Basically what is happening is that you've attached a function as the event handler for an element, and the function doesn't actually exist.
If you're trying to put any debug information in to try and pinpoint which function "doesn't exist" then add your alert messages or firebug console output inside the wrapper function between lines 3871 and 3878.


q: I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?

[A]
First day is always YYYY-MM-01, isn't it? Example:
```
date("Y-M-d", mktime(0, 0, 0, 8, 1, 2008))
```
Last day is the previous day of the next month's first day:
```
```
$date = new DateTime("2008-09-01");
$date->modify("-1 day");
echo $date->format("Y-m-d");
```
```


q: I understand that there are several ways to blend XNA and WPF within the same application. I find it enticing to use WPF for all GUI and HUD stuff in my XNA games. Does anyone have any practical experience on how well this approach works in real life using .NET 3.5 SP1 ? Any pitfalls (such as the "airspace problem")? Any hint on what appoach works best?

[A]
There is an addition in 3.5 SP1 that allows better interaction between DirectX and WPF (D3DImage), and one way to get to that is through XNA.
Here are some details:
http://jmorrill.hjtcentral.com/Default.aspx?tabid=428&EntryID=259


q: I need to select data when a page is viewed and update the 'views' column is there a way to do this in one query, or do I have to use to distinct queries?

[A]
You would have to do this in two statements in one transaction
```
```
Begin Tran

Update Pages Set Views = Views + 1 Where ID = @ID
Select Columns From Pages Where ID = @ID

Commit Tran
```
```


q:
I have a line color property in my custom grid control. I want it to default to Drawing.SystemColors.InactiveBorder. I tried:

[DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")]
public Color LineColor { get; set; }

But it doesn't seem to work. How do I do that with the default value attribute?

[A]
You need to change first argument from
```
SystemColors
```
to
```
Color
```
.
It seems that there is no type converter for the
```
SystemColors
```
type, only for the
```
Color
```
type.
```
```
[DefaultValue(typeof(Color),"InactiveBorder")]
```
```


q: I have a String representation of a date that I need to create a Date or Calendar object from. I've looked through Date and Calendar APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?

[A]
Try this:
```
```
DateFormat.parse(String)
```
```


q:
This is probably a really simple jQuery question, but I couldn't answer it after 10 minutes in the documentation so...

I have a list of checkboxes, and I can get them with the selector 'input[type=checkbox]'. I want the user to be able to shift-click and select a range of checkboxes. To accomplish this, I need to get the index of a checkbox in the list, so I can pass that index to .slice(start, end). How do I get the index when the user clicks a box?

[A]
The following selector should also work in jQuery:
```
input:checkbox
```
.
You can then string the
```
:gt(index)
```
and
```
:lt(index)
```
filters together, so if you want the 5th to 7th checkboxes, you'd use
```
input:checkbox:gt(4):lt(2)
```
.
To get the index of the currently clicked checkbox, just use
```
$("input:checkbox").index($(this))
```
.


q:
We are now using NHibernate to connect to different database base on where our software is installed.  So I am porting many SQL Procedures to Oracle.

SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate.

Date parts examples are day, week, month, year, etc. . .

What is the Oracle equivalent?

I have not found one do I have to create my own version of it?

(update by Mark Harrison) there are several nice answers that explain Oracle date arithmetic.  If you need an Oracle datediff() see Einstein's answer.  (I need this to keep spme SQL scripts compatible between Sybase and Oracle.)  Note that this question applies equally to Sybase.

[A]
Tom's article is very old.  It only discusses the DATE type.  If you use TIMESTAMP types then date arithmetic is built into PL/SQL.
http://www.akadia.com/services/ora_date_time.html
```
```
DECLARE
ts_a timestamp;
ts_b timestamp;
diff interval day to second;
BEGIN
  ts_a := systimestamp;
  ts_b := systimestamp-1/24;
  diff := ts_a - ts_b;
  dbms_output.put_line(diff);
END;
+00 01:00:00.462000
```
```
or
```
```
DECLARE
ts_b timestamp;
ts_a timestamp;
date_part interval day to second;

BEGIN
  ts_a := systimestamp;
  date_part := to_dsinterval('0 01:23:45.678');
  ts_b := ts_a + date_part;
  dbms_output.put_line(ts_b);
END;

04-SEP-08 05.00.38.108000 PM
```
```


q: Why do I need two of them? When I have to use one or another?

[A]
Please see:
http://www.sap-img.com/oracle-database/finding-oracle-sid-of-a-database.htm
What is the difference between Oracle
  SIDs and Oracle SERVICE NAMES. One
  config tool looks for SERVICE NAME and
  then the next looks for SIDs! What's
  going on?!
Oracle SID is the unique name that
  uniquely identifies your
  instance/database where as Service
  name is the TNS alias that you give
  when you remotely connect to your
  database and this Service name is
  recorded in Tnsnames.ora file on your
  clients and it can be the same as SID
  and you can also give it any other
  name you want.
SERVICE_NAME is the new feature from
  oracle 8i onwards in which database
  can register itself with listener. If
  database is registered with listener
  in this way then you can use
  SERVICE_NAME parameter in tnsnames.ora
  otherwise - use SID in tnsnames.ora.
Also if you have OPS (RAC) you will
  have different SERVICE_NAME for each
  instance.
SERVICE_NAMES specifies one or more
  names for the database service to
  which this instance connects. You can
  specify multiple services names in
  order to distinguish among different
  uses of the same database. For
  example:
SERVICE_NAMES = sales.acme.com,
  widgetsales.acme.com
You can also use service names to
  identify a single service that is
  available from two different databases
  through the use of replication.
In an Oracle Parallel Server
  environment, you must set this
  parameter for every instance.
In short: SID = the unique name of your DB instance, ServiceName = the alias used when connecting


q:
I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:

ID   COMPANY_ID   EMPLOYEE
1    1            Anna
2    1            Bill
3    2            Carol
4    2            Dave

and I wanted to group by company_id to get something like:

COMPANY_ID   EMPLOYEE
1            Anna, Bill
2            Carol, Dave

There is a built-in function in mySQL to do this group_concat

[A]
I claim no credit for the answer because I found it after some searching:
What I didn't know is that PostgreSQL allows you to define your own aggregate functions with
CREATE AGGREGATE
This post
on the PostgreSQL list shows how trivial it is to create a function to do what's required:
```
```
CREATE AGGREGATE textcat_all(
  basetype    = text,
  sfunc       = textcat,
  stype       = text,
  initcond    = ''
);

SELECT company_id, textcat_all(employee || ', ')
FROM mytable
GROUP BY company_id;
```
```


q:
I have a multiple selection SELECT field which I don't want the end user to be able to change the value of.

For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success.

Can this be done or am I trying to do the impossible?

[A]
Could you do it with an
```
onchange
```
event?
```
```
<select onfocus="this.oldIndex=this.selectedIndex" onchange="this.selectedIndex=this.oldIndex">
```
```


q:
A .container can contain many .components, and .components themselves can contain .containers (which in turn can contain .components etc. etc.)

Given code like this:

$(".container .component").each(function(){
  $(".container", this).css('border', '1px solid #f00');
});

What do I need to add to the line within the braces to select only the nested .containers that have their width in CSS set to auto?  I'm sure it's something simple, but I haven't really used jQuery all that much.

[A]
```
```
$(".container .component").each(function() {
    if ($(".container", this).css('width') === "auto")
        $(".container", this).css('border', '1px solid #f00');
});
```
```


q:
Suppose I have some code that would, in theory, compile against any version of the .net framework. Think "Hello World", if you like.

If I actually compile the code, though, I'll get an executable that runs against one particular version.

Is there any way to arrange things so that the compiled exe will just run against whatever version it finds? I strongly suspect that the answer is no, but I'd be happy to be proven wrong...

Edit: Well, I'll go to the foot of our stairs. I had no idea that later frameworks would happily run exe's compiled under earlier versions. Thanks for all the responses!

[A]
Read ScuttGu's post about
VS 2008 Multi-Targeting Support
One of the big changes we are making
  starting with the VS 2008 release is
  to support what we call
  "Multi-Targeting" - which means that
  Visual Studio will now support
  targeting multiple versions of the
  .NET Framework, and developers will be
  able to start taking advantage of the
  new features Visual Studio provides
  without having to always upgrade their
  existing projects and deployed
  applications to use a new version of
  the .NET Framework library.
Now when you open an existing project
  or create a new one with VS 2008, you
  can pick which version of the .NET
  Framework to work with - and the IDE
  will update its compilers and
  feature-set to match this.  Among
  other things, this means that
  features, controls, projects,
  item-templates, and assembly
  references that don't work with that
  version of the framework will be
  hidden, and when you build your
  application you'll be able to take the
  compiled output and copy it onto a
  machine that only has an older version
  of the .NET Framework installed, and
  you'll know that the application will
  work.
That way you can use VS2008 to develop .NET 2.0 projects that will work on both .NET 2.0, 3.0 and 3.5


q:
Caveat: I'm relatively new to coding as well as TextMate, so apologies if there is an obvious answer I'm missing here.

I do a lot of HTML/CSS markup, there are certain patterns that I use a lot, for example, forms, navigation menus etc. What I would like is a way to store those patterns and insert them quickly when I need them.

Is there a way to do this using TextMate?

[A]
You can do this very easily in TextMate using
Snippets
. Just add a new snippet in the bundle editor, and set up how you want to trigger it. You can set a key shortcut, or have it pop up when you hit
```
Tab
```
after a certain word/pattern.
There are many things you can do with them—in your case, it would probably be very useful to set so-called "placeholders" in your snippets, which are the parts that change every time (e.g. the names of the fields in the form). Then, as soon as you insert the snippet, you can hit
```
Tab
```
to move between these.


q:
I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address.  We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall.

So how do I configure sendmail to send all mail through mailrelay.example.com?  Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying.

[A]
http://www.elandsys.com/resources/sendmail/smarthost.html
Sendmail Smarthost
A smarthost is a host through which
  outgoing mail is relayed. Some ISPs
  block outgoing SMTP traffic (port 25)
  and require their users to send out
  all mail through the ISP's mail
  server. Sendmail can be configured to
  use the ISP's mail server as the smart
  host.
Read the linked article for instruction for how to set this up.


q:
Handling multiple merges onto branches in Subversion or CVS is just one of those things that has to be experienced. It is inordinately easier to keep track of branches and merges in Mercurial (and probably any other distributed system) but I don't know why. Does anyone else know?

My question stems from the fact that with Mercurial you can adopt a working practice similar to that of Subversions/CVSs central repository and everything will work just fine. You can do multiple merges on the same branch and you won't need endless scraps of paper with commit numbers and tag names.

I know the latest version of Subversion has the ability to track merges to branches so you don't get quite the same degree of hassle but it was a huge and major development on their side and it still doesn't do everything the development team would like it to do.

There must be a fundamental difference in the way it all works.

[A]
I only have experience with Subversion but I can tell you that the merge screen in TortoiseSVN is horribly complicated.  Luckily they include a dry run button so that you can see if you are doing it right.  The complication is in the configuration of what you want to merge to where.  Once you get that set up for the merge the merge generally goes fine.  Then you need to resolve any and all conflicts and then commit your merged in working copy to the repository.
If Mercurial can make the configuration of the merge easier then I can say that would make merging 100% easier then Subversion.


q:
I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding.  For example:

declare @value decimal(18,2)

set @value = 123.456

This will automatically round @value to be 123.46, which is good in most cases.  However, for this project, I don't need that.  Is there a simple way to truncate the decimals I don't need?  I know I can use the left() function and convert back to a decimal.  Are there any other ways?

[A]
```
```
select convert(int,@value)
```
```


q:
Is it possible to pass a reference to a function to another function in F#?  Specifically, I'd like to pass lambda functions like

foo(fun x -> x ** 3)

More specifically, I need to know how I would refer to the passed function in a function that I wrote myself.

[A]
Yes, it is possible. The
manual
has this example:
```
```
> List.map (fun x -> x % 2 = 0) [1 .. 5];;

val it : bool list
= [false; true; false; true; false]
```
```


q:
We've been using "Drip" to try and identify why pages with UpdatePanels in them tend to use a lot of client-side memory.  With a page with a regular postback, we are seeing 0 leaks detected by Drip.  However, when we add an update panel to the mix, every single DOM object that is inside of the update panel appears to leak (according to Drip).

I am not certain is Drip is reliable enough to report these kinds of things - the reported leaks do seem to indicate Drip is modifying the page slightly.

Does anyone have any experience with this?  Should I panic and stop using Microsoft Ajax?  I'm not above doubting Microsoft, but it seems fishy to me that it could be this bad.

Also, if you know of a tool that is better than Drip, that would be helpful as well.

[A]
According to
ASP.NET AJAX in Action
, p. 257
Just before the old markup is replaced with the updated HTML, all the DOM elements in the panel are examined for Microsoft Ajax behaviours or controls attached to them. To avoid memory leaks, the components associated with DOM elements are disposed, and then destroyed when the HTMl is replaced.
So as far as I know, any asp.net ajax components within the update panel are disposed to prevent memory leaks, but anything else in there will just be replaced with the html received.
So if you don't have any asp.net ajax components in the target container for the response, it would be basically the same as an inner html replacement with any other js framework / ajax request, so i would say that it's just the how the browser handles this, rather than asp.net ajax causing this.
Also, while it may be "leaking", it may be by design, meaning that the browser might not have reclaimed the dom elements yet and released them. Also, drip might be causing those to leak, as it is attaching to those dom elements.


q:
I am working on a site where users can login to get more private information.
 My client has another site else where that uses nt authentication for accessing it.

What they want to do is have a button on the site I am working on under the private area that will send them to the nt authenticated site, but not require them to log on to that site instead passing the username and password that they used to log into my site to the other site for them.

Is it possible to do this? and how would I accomplish it? Is there a better way to do this?

[A]
How will the other site validate your username and password?
Ideally your site shouldn't even be remembering the user's password to be able to pass it to another site (you store hashes of the password, not the password itself, and only use the actually password during validation).
What if your site provided a token to the user, who presents that token to the new site, which in turn asks your site to validate the token.  Basically the second site is trusting you to tell them who the user is.
This all breaks down if the second site is actually using the Windows accounts for anything other than just retrieving a user name (for example permissions on the underlying file), since the user is not logged on as the actual Windows user account in this scenario.


q:
What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes).

I've already seen a few ways to do it, but can't decide on which one is the best.

[A]
There is an official recommendation on
storing additional information about users
.
The Django Book also discusses this problem in section
Profiles
.


q:
Does anyone know of a way to alter a computed column without dropping the column in SQL Server. I want to stop using the column as a computed column and start storing data directly in the column, but would like to retain the current values.

Is this even possible?

[A]
Ok, so let me see if I got this straight.  You want to take a column that is currently computed and make it a plain-jane data column.  Normally this would drop the column but you want to keep the data in the column.
Make a new table with the primary key columns from your source table and the generated column.
Copy the data from your source table into the new table.
Change the column on your source table.
Copy the data back.
No matter what you do I am pretty sure changing the column will drop it.  This way is a bit more complex but not that bad and it saves your data.
[Edit: @SqlMenace's answer is much easier. :)  Curse you Menace!! :)]


q:
I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown.

The blinking input caret is confusing. How do I hide it?

[A]
If you disable the text box (set
```
Enable=false
```
), the text in it is still scrollable and selectable. If you don't like the visual presentation of a disabled text box (gray background usually) you can manually override the colors.
Be warned, manually overriding colors is going to make your form/control look weird on systems that do not use the default color/theme settings. Don't assume that because your control is white that everyone's control is going to be white. That's why you should always use the system colors whenever possible (defined in the
```
System.Drawing.SystemColors
```
enumeration) such as
```
SystemColors.ControlLight
```
.