Question:
In SEO people talk a lot about Google PageRank. It's kind of a catch 22 because until your site is actually big and you don't really need search engines as much, it's unlikely that big sites will link to you and increase your PageRank!

I've been told that it's easiest to simply get a couple high quality links to point to a site to raise it's PageRank. I've also been told that there are certain Open Directories like dmoz.org that Google pays special attention to (since they're human managed links). Can anyone speak to the validity of this or suggest another site/technique to increase a site's PageRank?

Answer:
Have great content
Nothing helps your google rank more than having
content
or offering a service people are interested in. If your web site is better than the competition and solves a real need you will naturally generate more traffic and inbound links.
Keep your content fresh
Use friendly url's that contain keywords
Good
:
http://cars.com/products/cars/ford/focus/
Bad
:
http://cars.com/p?id=1232
Make sure the page title is relevant and well constructed
For example
: Buy A House In France :. Property Purchasing in France
Use a domain name that describes your site
Good
:
http://cars.com/
Bad
:
http://somerandomunrelateddomainname.com/
Example
Type car into Google, out of the top 5 links all 4 have car in the domain:
http://www.google.co.uk/search?q=car
Make it accessible
Make sure people can read your content. This includes a variety of different audiences
People with disabilities: Sight, motor, cognitive disabilities etc..
Search bots
In particular make sure search bots can read every single relevant page on your site. Quite often search bots get blocked by the use of
javascript
to link between pages or the use of frames /
flash
/
silverlight
. One easy way to do this is have a site map page that gives access to the whole site, dividing it into categories / sub categories etc..
Down level browsers
Submit your site map automatically
Most search engines allow you to submit a list of pages on your site including when they were last updated.
Google:
https://www.google.com/webmasters/tools/docs/en/about.html
Inbound links
Generate as much buzz about your website as possible, to increase the likely hood of people linking to you. Blog / podcast about your website if appropriate. List it in online directories (if appropriate).
References
Google Search Engine Ranking Factors, by an SEO company
Creating a Google-friendly site: Best practices
Wikipedia - Search engine optimization


Question: I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to this question only in .Net.

Answer:
In Urlmon.dll, there's a function called
```
FindMimeFromData
```
.
From the documentation
MIME type detection, or "data sniffing," refers to the process of determining an appropriate MIME type from binary data. The final result depends on a combination of server-supplied MIME type headers, file extension, and/or the data itself. Usually, only the first 256 bytes of data are significant.
So, read the first (up to) 256 bytes from the file and pass it to
```
FindMimeFromData
```
.


Question: Is there a way to combine Enums in VB.net?

Answer:
If you taking about using enum flags() there is a good article
here
.


Question:
I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation.

Does anyone know the best way to do this using the WiX framework.

Answer:
Wix has out-of-the-box support for creating event log sources.
Assuming you use Wix 3, you first need to add a reference to WixUtilExtension to either your Votive project or the command line. You can then add an EventSource element under a component :
```
```
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
    xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

    <Component ...>
        ...
        <util:EventSource Log="Application" Name="*source name*"
           EventMessageFile="*path to message file*"/>
        ...
    </Component>
```
```
If this is a .NET project, you can use EventLogMessages.dll in the framework directory as the message file.


Question:
When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error:

Parameters cannot be extracted from the SQL command. The provider might not help to parse parameter information from the command. In that case, use the "SQL command from variable" access mode, in which the entire SQL command is stored in a variable.

  ADDITIONAL INFORMATION:

  Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle)

I have tried following the suggestion here but don't quite understand what is required:Parameterized queries against Oracle

Any ideas?

Answer:
To expand on the link given in the question:
Create a package variable
Double click on the package variable name. (This allows you to access the properties of the variable)
Set the property 'EvaluateAsExpression' to true
Enter the query in the expression builder.
Set the OLE DB source query to SQL Command from Variable
The expression builder can dynamically create expressions using variable to create 'parametised queries'.
So the following 'normal' query:
```
```
select * from book where book.BOOK_ID = ?
```
```
Can be written in the expression builder as:
```
```
"select * from book where book.BOOK_ID = " + @[User::BookID]
```
```
You can then do null handling and data conversion using the expression builder.


Question:
In C++ we acquiring a resource in a constructor and release it in a destructor.

So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever.

AFAIK java classes don't have destructors. So how does one do the resource management in Java.

For example:

public int foo() {
    Resource f = new Resource();
    DoSomething(f);
    f.Release();
}

How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we?

Answer:
Yes you can and should put try/catch/finally block around your code. In C# there is a shorthand "using" statement, but in Java you are stuck with:
```
```
public int foo() {
    Resource f = new Resource();
    try {
        DoSomething(f);
    }
    finally {
        f.Release();
    }
}
```
```


Question:
I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?

An example :

final StringBuilder hql = new StringBuilder();
hql.append( "select bob.id from " )
    .append( bob.class.getName() ).append( " bob " )
    .append( "where bob.id > 10");

final Query query = session.createQuery( hql.toString() );
return query.list();

Answer:
I think you could do that with Projections, something like
```
```
Criteria.forClass(bob.class.getName())
        .add(Restrictions.gt("id", 10))
        .setProjection(Projections.property("id"))
        );
```
```


Question: I have a core dump file from a process that has probably a file descriptor leak (it opens files and sockets but apparently sometimes forgets to close some of them). Is there a way to find out which files and sockets the process had opened before crashing? I can't easily reproduce the crash, so analyzing the core file seems to be the only way to get a hint on the bug.

Answer:
A core dump is a copy of the memory the process had access to when crashed. Depending on how the leak is occurring, it might have lost the reference to the handles, so it may prove to be useless.
lsof lists all currently open files in the system, you could check its output to find leaked sockets or files. Yes, you'd need to have the process running. You could run it with a specific username to easily discern which are the open files from the process you are debugging.
I hope somebody else has better information :-)


Question:
Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse?

I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions?

And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs?

Answer:
Use the visual block command v (or V for whole lines and
C
-
V
for rectangular blocks). While in visual block mode, you can use any motion commands including search; I use } frequently to skip to the next blank line. Once the block is marked, you can :w it to a file, delete, yank, or whatever. If you execute a command and the visual block goes away, re-select the same block with gv. See :help visual-change for more.
I think there are language-specific scripts that come with vim that do things like comment out blocks of code in a way that fits your language of choice.


Question:
I'm developing a multi-threaded app for a Linux embedded platform.

At the moment I'm setting the stack size for each thread (via pthread_set_attr) to a fairly large default value. I would like to fine tune that value for each thread to something smaller to reduce my application's memory usage. I could go through the trial and error route of setting each thread's stack size to progressively smaller values until the program crashed, but the application uses ~15 threads each with completely different functionality/attributes so that approach would be extremely time consuming.

I would much rather prefer being able to directly measure each thread's stack usage. Is there some utility people can recommend to do this? (For example, I come from a vxWorks background and using the 'ti' command from the vxWorks shell directly gives stats on the stack usage as well as other useful info on the task status.)

Thanks

Answer:
I do not know any good tools but as last resort you could include some code in your application to check it, similar to the following:
```
```
__thread void* stack_start;
__thread long stack_max_size = 0L;

void check_stack_size() {
  // address of 'nowhere' approximates end of stack
  char nowhere;
  void* stack_end = (void*)&nowhere;
  // may want to double check stack grows downward on your platform
  long stack_size = (long)stack_start - (long)stack_end;
  // update max_stack_size for this thread
  if (stack_size > stack_max_size)
    stack_max_size = stack_size;
}
```
```
The check_stack_size() function would have to be called in some of the functions that are most deeply nested.
Then as last statement in the thread you could output stack_max_size to somewhere.
The stack_start variable would have to be initialized at start of your thread:
```
```
void thread_proc() {
  char nowhere;
  stack_start = (void*)&nowhere;
  // do stuff including calls to check_stack_size()
  // in deeply nested functions
  // output stack_max_size here
}
```
```


Question:
I have a classic client/server (fat client and database) program written in Delphi 2006. When certain conditions are met in the client, I need to notify all the other clients very quickly. Up until now this has been done using UDP broadcasts, but this is no longer viable as clients now connect from outside the LAN and the UDP broadcast is limited to the local network.

I'm aware of the Indy libraries but am not really sure of which components to use and how to structure it. I'm guessing I'll need to have a server that the clients connect to which will receive and distribute the messages...? Any samples out there to get me started?

Are there any other component sets or technologies I should look at instead/as well?

Answer:
You should be able to use Multicast UDP for the same purpose. The only difference will be to join the multicast group from every client.
http://en.wikipedia.org/wiki/IP_Multicast
http://en.wikipedia.org/wiki/Internet_Group_Management_Protocol
Edit:
Just to clarify, multicast let you join a given "group" associated to a multicast ip address. Any packet sent to that address will reach every client who has join the group


Question:
How do I create a button control (with CreateWindow of a BUTTON window class) that has a standard system-wide size (especially height) that's consistent with the rest of Windows applications?
I should of course take DPI into account and probably other settings.

Remark: Using USE_CW_DEFAULT for width and height results in a 0, 0 size button, so that's not a solution.

Answer:
This is what MSDN has to say:
Design Specifications and Guidelines - Visual Design: Layout
.
The default size of a button is 50x14 DLUs, which can be calculated to pixels using the examples shown for
GetDialogBaseUnits
.
The
MapDialogRect
function seems to do the calculation for you.


Question: How do I make an MD5 hash of a string with Delphi?

Answer:
If you want an MD5 digest and have the
Indy
components installed, you can do this:
```
```
uses SysUtils, IdGlobal, IdHash, IdHashMessageDigest;

with TIdHashMessageDigest5.Create do
try
    Result := TIdHash128.AsHex(HashValue('Hello, world'));
finally
    Free;
end;
```
```
Most popular algorithms are supported in the
Delphi Cryptography Package
:
Haval
MD4, MD5
RipeMD-128, RipeMD-160
SHA-1, SHA-256, SHA-384, SHA-512,
Tiger
Update
```
DCPCrypt
```
is now maintained by
Warren Postma
and source can be found
here
.


Question:
I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have /* .. */ comments, and also has its own self-documentation facility which seems to be the pythonic way to document.

Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of?

Answer:
This is
documented on the doxygen website
, but to summarize here:
You can use doxygen to document your Python code. You can either use the Python documentation string syntax:
```
```
"""@package docstring
Documentation for this module.

More details.
"""

def func():
    """Documentation for a function.

    More details.
    """
    pass
```
```
In which case the comments will be extracted by doxygen, but you won't be able to use any of the
special doxygen commands
.
Or
you can (similar to C-style languages under doxygen) double up the comment marker (
```
#
```
) on the first line before the member:
```
```
## @package pyexample
#  Documentation for this module.
#
#  More details.

## Documentation for a function.
#
#  More details.
def func():
    pass
```
```
In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting
```
OPTMIZE_OUTPUT_JAVA
```
to
```
YES
```
.
Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?


Question:
I have written some code in my VB.NET application to send an HTML e-mail (in this case, a lost password reminder).

When I test the e-mail, it gets eaten by my spam filter.  One of the things that it's scoring badly on is because of the following problem:

MIME_QP_LONG_LINE  RAW: Quoted-printable line longer than 76 chars

I've been through the source of the e-mail, and I've broken each line longer than 76 characters into two lines with a CR+LF in between, but that hasn't fixed the problem.

Can anyone point me in the right direction?

Thanks!

Answer:
Quoted printable expands 8 bit characters to "={HEX-Code}", thus making the messages longer. Maybe you are just hitting this limit?
Have you tried to break the message at, say, 70 characters? That should provide space for a couple of characters per line.
Or you just encode the email with Base64 - all mail client can handle that.
Or you just set Content-Transfer-Encoding to 8bit and send the data unencoded. I know of no mail server unable to handle 8bit bytes these days.


Question:
I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...).

Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically?
Thanks!

Answer:
Getting EXIF data from a JPEG image involves:
Seeking to the JPEG markers which mentions the beginning of the EXIF data,. e.g. normally oxFFE1 is the marker inserted while encoding EXIF data, which is a APPlication segment, where EXIF data goes.
Parse all the data from say 0xFFE1 to 0xFFE2 . This data would be stream of bytes, in the JPEG encoded file.
ASCII equivalent of these bytes would contain various information related to Image Date, Camera Model Name, Exposure etc...


Question:
The situation: I have a pieceofcrapuous laptop. One of the things that make it pieceofcrapuous is that the battery is dead, and the power cable pulls out of the back with little effort.

I recently received a non-pieceofcrapuous laptop, and I am in the process of copying everything from old to new. I'm trying to xcopy c:*.* from the old machine to an external hard drive, but because the cord pulls out so frequently, the xcopy is interrupted fairly often.

What I need is a switch in XCopy that will copy eveything except for files that already exist in the destination folder -- the exact opposite of the behavior of the /U switch.

Does anyone know of a way to do this?

Answer:
I find RoboCopy is a good alternative to xcopy. It supports high latency connections much better and supports resuming a copy.
References
Wikipedia - robocopy
Downloads
Edit
Robocopy was introduced as a standard feature of Windows Vista and Windows Server 2008.
Robocopy is shipped as part of the Windows Server 2003 resource kit and can be download from the
Microsoft download site
.
A very simple GUI has also been release for RoboCopy on technet
http://technet.microsoft.com/en-us/magazine/cc160891.aspx


Question:
I want to copy the entire contents of a directory from one location to another in C#.

There doesn't appear to be a way to do this using System.IO classes without lots of recursion.

There is a method in VB that we can use if we add a reference to Microsoft.VisualBasic:

new Microsoft.VisualBasic.Devices.Computer().
    FileSystem.CopyDirectory( sourceFolder, outputFolder );

This seems like a rather ugly hack. Is there a better way?

Answer:
Or, if you want to go the hard way, add a reference to your project for Microsoft.VisualBasic and then use the following:
```
```
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory);
```
```
However, using one of the recursive functions is a better way to go since it won't have to load the VB dll.


Question:
I need to copy files using Windows command-line (available on XP Pro or later by default) and show progress during the process.

The progress indicator could be in a terminal or a GUI window. It is intended to be used during batch file scripting.

Answer:
robocopy
:
Robocopy
, or "Robust File Copy", is a
command-line
directory and/or file replication
command
. Robocopy functionally replaces
Xcopy
, with more options. It has been available as part of the
Windows Resource Kit
starting with Windows NT 4.0, and was first introduced as a standard feature in
Windows Vista
and
Windows Server 2008
. The command is
```
robocopy
```
...


Question:
How can I get precompiled headers working with GCC?

I have had no luck in my attempts and I haven't seen many good examples for how to set it up.  I've tried on Cygwin GCC 3.4.4 and using 4.0 on Ubuntu.

Answer:
I have managed to get precompiled headers working under gcc once in the past, and I recall having problems then as well. The thing to remember is that gcc will ignore the file (header.h.gch or similar) if certain conditions are not met, a list of which can be found on the
gcc precompiled header documentation page
.
Generally it's safest to have your build system compile the .gch file as a first step, with the same command line options and executable as the rest of your source. This ensures the file is up to date and that there are no subtle differences.
It's probably also a good idea to get it working with a contrived example first, just to remove the possibility that your problems are specific to source code in your project.


Question: I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.

Answer:
I just tried the following:
```
```
$ cat gdbtest.c
 int abc = 43;

 int main()
 {
   abc = 10;
 }
 $ gcc -g -o gdbtest gdbtest.c
 $ gdb gdbtest
 ...
 (gdb) watch abc
 Hardware watchpoint 1: abc
 (gdb) r
 Starting program: /home/mweerden/gdbtest
 ...

 Old value = 43
 New value = 10
 main () at gdbtest.c:6
 6       }
 (gdb) quit
```
```
So it seems possible, but you do appear to need some hardware support.


Question:
Suppose I have a table called Companies that has a DepartmentID column. There's also a Departaments table that has as EmployeeID column. Of course I have an Employee table as well. The problem is that I want to delete a company, so first i have to delete all the employees for every departament and then all the departaments in the company.
Cascade Delete is not an option, therefore i wish to use nested transactions. I'm new to SQL so I would appreciate your help.

Answer:
I'm not answering your question, but foreign Keys
is
the way to go, why is it not an option?
As for nested transactions they are:
```
```
BEGIN
  delete from Employee where departmentId = 1;
  BEGIN
     delete from Department where companyId = 2;
     BEGIN
        delete from Company where companyId = 2;
     END
  END
END
```
```
Programmatically it looks different of course, but that'd depend on the platform you are using


Question: I have any ASP.NET control.  I want the HTML string how to do I get the HTML string of the control?

Answer:
This appears to work.
```
```
public string RenderControlToHtml(Control ControlToRender)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
    System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
    ControlToRender.RenderControl(htmlWriter);
    return sb.ToString();
}
```
```


Question: Using VB.NET, how do I toggle the state of Caps Lock?

Answer:
From:
http://www.vbforums.com/showthread.php?referrerid=61394&t=537891
```
```
Imports System.Runtime.InteropServices

Public Class Form2

    Private Declare Sub keybd_event Lib "user32" ( _
        ByVal bVk As Byte, _
        ByVal bScan As Byte, _
        ByVal dwFlags As Integer, _
        ByVal dwExtraInfo As Integer _
    )
    Private Const VK_CAPITAL As Integer = &H14
    Private Const KEYEVENTF_EXTENDEDKEY As Integer = &H1
    Private Const KEYEVENTF_KEYUP As Integer = &H2

    Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs _
    ) Handles Button1.Click

        ' Toggle CapsLock

        ' Simulate the Key Press
        keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)

        ' Simulate the Key Release
        keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
    End Sub

End Class
```
```


Question:
I'm trying to get an event to fire whenever a choice is made from a JComboBox.

The problem I'm having is that there is no obvious addSelectionListener() method.

I've tried to use actionPerformed(), but it never fires.

Short of overriding the model for the JComboBox, I'm out of ideas.

How do I get notified of a selection change on a JComboBox?**

Edit: I have to apologize. It turns out I was using a misbehaving subclass of JComboBox, but I'll leave the question up since your answer is good.

Answer:
It should respond to
ActionListeners
, like this:
```
```
combo.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        doSomething();
    }
});
```
```
@John Calsbeek
rightly points out that
```
addItemListener()
```
will work, too.  You may get 2
```
ItemEvents
```
, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!


Question:
I'm starting to learn how to use PHPUnit to test the website I'm working on.  The problem I'm running into is that I have five different user types defined and I need to be able to test every class with the different types.  I currently have a user class and I would like to pass this to each function but I can't figure out how to pass this or test the different errors that could come back as being correct or not.

Edit: I should have said.  I have a user class and I want to pass a different instance of this class to each unit test.

Answer:
If you're looking to test the actual UI, you could try using something like Selenium (www.openqa.org). It lets you write the code in PHP (which I'm assuming would work with phpUnit) to drive the browser..
Another approach would be to have a common method that could be called by each test for your different user type. ie, something like 'ValidatePage', which you could then call from TestAdminUser or TestRegularUser and have the method simply perform the same basic validation of what you're expecting..


Question:
How do I find out whether or not Caps Lock is activated, using VB.NET?

This is a follow-up to my earlier question.

Answer:
I'm not an expert in VB.NET so only PInvoke comes to my mind:
```
```
Declare Function GetKeyState Lib "user32"
   Alias "GetKeyState" (ByValnVirtKey As Int32) As Int16

Private Const VK_CAPSLOCK = &H14

If GetKeyState(VK_CAPSLOCK) = 1 Then ...
```
```


Question: The Interface Segregation Principle (ISP) says that many client specific interfaces are better than one general purpose interface. Why is this important?

Answer:
ISP states that:
Clients should not be forced to depend
  on methods that they do not use.
ISP relates to important characteristics -
cohesion
and
coupling
.
Ideally your components must be highly tailored. It improves code robustness and maintainability.
Enforcing ISP gives you following bonuses:
High
cohesion
- better understandability, robustness
Low
coupling
- better maintainability, high resistance to changes
If you want to learn more about software design principles, get a copy
of
Agile Software Development, Principles, Patterns, and Practices
book.


Question:
I'd like to automate TortoiseSVN as part of a commit process.
Specifically I'd like to dynamically create a log entry for the commit dialog.

I know that I can launch the commit dialog either from the commandline or by right clicking on a folder and selecting svncommit.

I'd like to use the start commit hook to setup a log entry.
I thought this worked by passing an entry file name in the MESSAGEFILE variable but when I add a hook script it cannot see this variable (hook launched successfully after right clicking and choosing svncommit).

When I try using the commandline I use the /logmsgfile parameter but it seems to have no effect.

I'm using tortoisesvn 1.5.3.

Answer:
Looks like it was my own misunderstanding of the the API that caused by a problem.
Solution:
1)  I've added a start commit hook script to TortoiseSVN using the hooks gui in the settings area of the right click menu.
2) The script receive 3 pieces of information:      PATH  MESSAGEFILE  CWD
For details see:
Manual
These are passed as command line arguements to the script - for some reason I had thought they were set as temporary environmental variables.
My script then simply opens the file specified by the second arguement and adds in the custom text.
When the commit dialog comes up the custom text is there.
3) Best of all if tortoisesvn is launched from a script directly into the commit dialog:
e.g. [ tortoiseproc /command:commit /path:. /closeonend:1 ]
The hooks are still called.


Question: Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)

Answer:
The following query replace each and every
```
a
```
character with a
```
b
```
character.
```
```
UPDATE
    YourTable
SET
    Column1 = REPLACE(Column1,'a','b')
WHERE
    Column1 LIKE '%a%'
```
```
This will not work on SQL server 2003.


Question:
How do I save each sheet in an Excel workbook to separate CSV files with a macro?

I have an excel with multiple sheets and I was looking for a macro that will save each sheet to a separate CSV (comma separated file). Excel will not allow you to save all sheets to different CSV files.

Answer:
And here's my solution should work with Excel > 2000, but tested only on 2007:
```
```
Private Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' ask the user where to save
OutputPath = InputBox("Enter a directory to save to", "Save to directory", Path)

If OutputPath <> "" Then

    ' save for each sheet
    For Each Sheet In Sheets

        OutputFile = OutputPath & "\" & Sheet.Name & ".csv"

        ' make a copy to create a new book with this sheet
        ' otherwise you will always only get the first sheet
        Sheet.Copy
        ' this copy will now become active
        ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close
    Next

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub
```
```
(OT: I wonder if SO will replace some of my minor blogging)


Question:
I am stress testing a .NET web application.  I did this for 2 reasons: I wanted to see what performance was like under real world conditions and also to make sure we hadn't missed any problems during testing. We had 30 concurrent users in the application using it as they would during the normal course of their jobs. Most users had multiple windows of the application open.

10 Users: Not bad

20 Users: Slowing down

30 Users: Very, very slow but no timeouts

It was loaded on the production server. It is a virtual server with a 2.66G Hz Xeon processor and 2 GB of RAM. We are using Win2K3 SP2. We have .NET 1.1 and 2.0 loaded and are using SQLExpress SP1.

We rechecked the indexes on all of the tables afterword and they were all as they should be.

How can we improve our application's performance?

Answer:
You may be running into concurrency issues, depending on how your application runs. Try performing your reads with the "nolock" keyword.
Try adding in table aliases for your columns (and avoid the use of SELECT *), this helps out MSSQL, as it doesn't have to "guess" which table the columns come from.
If you aren't already, move to SPROCs, this allows MSSQL to index your data better for a given query's normal result set.
Try following the execution plan of your SPROCS to ensure they are using the indexes you think they are.
Run a trace against your database to see what the incoming requests look like. You may notice a particular SPROC is being run over and over: generally a good sign to cache the responses on the client if possible. (lookup lists, etc.)


Question:
Visually both of the following snippets produce the same UI. So why are there 2 controls..

Snippet1

<TextBlock>Name:</TextBlock>
<TextBox Name="nameTextBox" />

Snippet2

<Label>Name:</Label>
<TextBox Name="nameTextBox" />

(Well I am gonna answer this myself... thought this is a useful tidbit I learnt today from Programming WPF)

Answer:
Label has an important
focus handling
responsibility.Its purpose is to allow you to place a caption with an access key. It has a
Target
property, which indicates the target of the access key. Like this...
```
```
<Label Target="{Binding ElementName=nameTextBox}">_Name:</Label>
<TextBox x:Name="nameTextBox" />
```
```
In the absence of the Target property, the Label control does nothing useful. You'll just hear a beep if you press the access key indicating 'unable to process request'


Question:
Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter?

Example 1 - separate parameters:
function convertTemperature("celsius", "fahrenheit", 22)

Example 2 - combined parameter:
function convertTemperature("c-f", 22)

The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow.

Thoughts?

Answer:
Go with the first option, but rather than allow literal strings (which are error prone), take constant values or an enumeration if your language supports it, like this:
```
```
convertTemperature (TempScale.CELSIUS, TempScale.FAHRENHEIT, 22)
```
```


Question:
I am getting this error now that I hit version number 1.256.0:
Error   4   Invalid product version '1.256.0'. Must be of format '##.##.####'

The installer was fine with 1.255.0 but something with 256 (2^8) it doesn't like.  I found this stated on msdn.com:
The Version property must be formatted as N.N.N, where each N represents at least one and no more than four digits. (http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx)

Which would make me believe there is nothing wrong 1.256.0 because it meets the rules stated above.

Does anyone have any ideas on why this would be failing now?

Answer:
Change it to:
```
```
protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) {
```
```
You need that because Comparable is itself a generic type.


Question:
Is there any way to enforce a template in Bugzilla to guide users fill in bugs descriptions ?

Actually, i'd like to put some markup texts in the bug description field and avoid the creation of custom fields.

I've installed version 3.2rc1.

Answer:
The mechansism described under
6.2.5 Particular Templates
(under the section called bug/create/create.html.tmpl and bug/create/comment.txt.tmpl) works pretty well for us.  Even though you say you don't want to create custom fields, adding some arbitrary HTML is easy enough.


Question:
Which standalone Windows GUI application do you recommend for use for accessing a Subversion repository?

Edit: A lot of people are mentioning Tortoise, however I am looking for an application not a shell extension.  Also people are questioning my reasoning behind not wanting to use a shell extension.  In our environment we rather interact with the repository (when not using an IDE plugin) through a management application and not navigate the files through Windows Explorer.

Answer:
TortoiseSVN
From their website:
A Subversion client, implemented as a windows shell extension.
TortoiseSVN is a really easy to use Revision control / version control
  / source control software for Windows. Since it's not an integration
  for a specific IDE you can use it with whatever development tools you
  like. TortoiseSVN is free to use. You don't need to get a loan or pay
  a full years salary to use it.


Question: When I press F5 in Visual Studio 2008, I want Google Chrome launched as the browser that my ASP.NET app runs in. May I know how this can be done?

Answer:
Right click on an .aspx file and click "Browse with..." then select Chrome and click "Set as Default." You can select more than one browser in the list if you want.
There's also this really great
WoVS Default Browser Switcher Visual Studio extension
.


Question:
So I have an object which has some fields, doesn't really matter what.
I have a generic list of these objects.

List<MyObject> myObjects = new List<MyObject>();
myObjects.Add(myObject1);
myObjects.Add(myObject2);
myObjects.Add(myObject3);

So I want to remove objects from my list based on some criteria.
For instance, myObject.X >= 10.
I would like to use the RemoveAll(Predicate<T> match) method for to do this.

I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.

Answer:
There's two options, an explicit delegate or a delegate disguised as a lamba construct:
explicit delegate
```
```
myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; });
```
```
lambda
```
```
myObjects.RemoveAll(m => m.X >= 10);
```
```
Performance wise both are equal. As a matter of fact, both language constructs generate the same IL when compiled. This is because C# 3.0 is basically an extension on C# 2.0, so it compiles to C# 2.0 constructs


Question:
What's the difference between the inner workings of Java's JVM and .NET's CLR?

Perhaps a starting point would be, are they basically the same thing in their respective environments (Java > JVM > Machine code) (C# > CLR > IL).

Update:  Several people have alluded to the points I was trying to cover:

Garbage Collection

Boxing/Unboxing

JIT debugging

Generics/Templates

Please feel free to suggest other good topics that differentiate the two.

@George Mauer - this sounds very interesting:

Already posted this once but here is a series of interviews with c# chief language designer Anders Hejlsberg.

Answer:
From
here
. I couldn't have said it better (Well, with the exception of a flame war, this is a flameless place :-) ).
Hello,
Responding to your question seems
  fraught with peril by starting a flame
  war, so I'll proceed cautiously.
There are a number of fundamental
  technical similarities between the
  Java Runtime and the Common Language
  Runtime, including garbage collected
  memory, an intermediate language
  (Microsoft IL versus Java ByteCode),
  core system libraries, and support for
  fairly high level languages, code
  security, and deployment.
However, each of these 'similar' areas
  also have a number of sizable and
  small differences, and it's beyond the
  scope of a simple Forum post to
  describe most of them.
I would suggest asking a more
  targetted question about any of the
  various runtime features and component
  areas (e.g. memory management,
  compilation, system libraries,
  security, etc.) and then we can
  provide a more targetted response
  (e.g. a blog, a technical article, or
  some books).


Question:
I have a WCF service that gets called from client side JavaScript. The call fails with a Service is null JavaScript error. WebDevelopment helper trace shows that the calls to load the jsdebug support file results in a 404 (file not found) error.

Restarting IIS or clearing out the Temp ASP.Net files or setting batch="false" on the compilation tag in web.config does not resolve the problem

From the browser

https://Myserver/MyApp/Services/MyService.svc displays the service metadata

however

https://Myserver/MyApp/Services/MyService.svc/jsdebug results in a 404.

The issue seems to be with the https protocol. With http /jsdebug downloads the supporting JS file.

Any ideas?

TIA

Answer:
Figured it out!
Here is the services configuration section from web.config
Look at the bindingConfiguration attribute on the endpoint. The value "webBinding" points to the binding name="webBinding" tag in the bindings and that is what tells the service to use Transport level security it HTTPS. In my case the attribute value was empty causing the webservice request to the /js or /jsdebug file over HTTPS to fail and throw a 404 error.
```
```
<services>
      <service name="MyService">
        <endpoint address="" behaviorConfiguration="MyServiceAspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="Services.MyService" />
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="webBinding">
          <security mode="Transport">
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
```
```
Note that the bindingConfiguration attribute should be empty ("") if the service is accessed via http instead of https (when testing on local machine with no certs)
Hope this helps someone.


Question:
What is the best way to keep an asp:button from displaying it's URL on the status bar of the browser?  The button is currently defines like this:

<asp:button id="btnFind"
            runat="server"
            Text="Find Info"
            onclick="btnFind_Click">
</asp:button>

Update:

This appears to be specific to IE7,  IE6 and FF do not show the URL in the status bar.

Answer:
I use FF so never noticed this, but the link does in fact appear in the status bar in IE..
I dont think you can overwrite it :( I initially thought maybe setting the ToolTip (al la "title") property might do it.. Seems it does not..
Looking at the source, what appears is nowhere to be found, so I would say this is a
browser
issue, I don't think you can do anything in code.. :(
Update
Yeah, Looks like IE always posts whatever the form action is.. Can't see a way to override it, as yet..
Perhaps try explicitly setting it via JS?
Update II
Done some more Googleing. Don't think there really is a "nice" way of doing it.. Unless you remove the form all together and post data some other way..
Is it really worth that much? Generally this just tends to be the page name?


Question:
I am using ActiveScaffold in a Ruby on Rails app, and to save space in the table I have replaced the default "actions" text in the table (ie. "edit", "delete", "show") with icons using CSS. I have also added a couple of custom actions with action_link.add ("move" and "copy").

For clarity, I would like to have a tooltip pop up with the related action (ie. "edit", "copy") when I hover the mouse over the icon.

I thought I could do this by adding a simple "alt" definition to the  tag, but that doesn't appear to work.

Can somebody point me in the right direction?

Answer:
Tooltips in HTML are the contents of the
```
alt
```
text for image tags, but if you're setting this using CSS you probably have a
```
background:url(...);
```
style instead of an image.


Question:
What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table?

For example: I have a JOBS table with the column JOB_NUMBER.  How can I find out if I have any duplicate JOB_NUMBERs, and how many times they're duplicated?

Answer:
Aggregate the column by COUNT, then use a HAVING clause to find values that appear greater than one time.
```
```
SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name
HAVING COUNT(column_name) > 1;
```
```


Question:
Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no  longer supported.

The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases.

Answer:
Just write
```
<input type="button" ... />
```
into your html.  There's nothing special at all with the html controls.


Question:
I'm trying to create a standard way of rolling out web applications for our company.  Currently we do it with zip files, vbscript/javascript, and manual some steps.

For thick client installs we generate MSI installers using Wise/Wix.  We don't create installers currently for websites as in general they are just xcopy deploy.  However we have some config files that need to be changed, verify that certain handlers are registered in IIS...  The list goes on.

Do most people use MSI installers for web applications as well, or some other tool/scripting language?

Answer:
You may want to look at:
How do I get a deployable output from a build script with ASP.NET
Step by Step ASP.NET Automated Build/Deploy
We use MSI to create basic installers for our web projects too, often using the Web Setup Projects in VS and sometimes completely custom installers. You may also want to look at
MSDeploy
.


Question:
I need to update a combobox with a new value so it changes the reflected text in it. The cleanest way to do this is after the comboboxhas been initialised and with a message.

So I am trying to craft a postmessage to the hwnd that contains the combobox.

So if I want to send a message to it, changing the currently selected item to the nth item, what would the postmessage look like?

I am guessing that it would involve ON_CBN_SELCHANGE, but I can't get it to work right.

Answer:
You want
ComboBox_SetCurSel
:
```
```
ComboBox_SetCurSel(hWndCombo, n);
```
```
or if it's an MFC CComboBox control you can probably do:
```
```
m_combo.SetCurSel(2);
```
```
I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN_SELCHANGE is the notification that the control sends
back to you
when the selection is changed.
Finally, you might want to add the c++ tag to this question.


Question:
I have the following query:

select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;

What would be the difference if I replaced all calls to count(column_name) to count(*)?

This question was inspired by How do I find duplicate values in a table in Oracle?.

To clarify the accepted answer (and maybe my question), replacing count(column_name) with count(*) would return an extra row in the result that contains a null and the count of null values in the column.

Answer:
```
count(*)
```
counts NULLs and
```
count(column)
```
does not
[edit] added this code so that people can run it
```
```
create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,null)

select count(*),count(id),count(id2)
from #bla
```
```
results
7   3   2


Question:
I'm migrating a Hibernate application's cache from EHCache to JBoss TreeCache.
I'm trying to find how to configure the equivalent to maxElementsOnDisk to limit the cache size on disk, but I couldn't find anything similar to configure in a FileCacheLoader with passivation activated.

Thanks

Answer:
This page
seems to imply that the correct configuration element is:
```
```
<attribute name="MaxCapacity">20000</attribute>
```
```
However, I've only ever used EHCache myself.


Question: What is the best way to vertically center the content of a div when the height of the content is variable.  In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.

Answer:
This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks.  When we get browser support for css 3 you'll get your vertical centering without sinning.
For a better explanation of the technique you can look
the article I adapted it from
, but basically it involves adding an extra element and applying different styles in IE and browsers that support
```
position:table\table-cell
```
on non-table elements.
```
```

            Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.

```
```
There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.
Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases.  If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.
Update:
We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See
this other question
for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.


Question:
I have the following code:

SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;

Is there any difference to the results or performance if I replace the COUNT(*) with COUNT('x')?

(This question is related to a previous one)

Answer:
The major performance difference is that COUNT(*) can be satisfied by examining the primary key on the table.
i.e. in the simple case below, the query will return immediately, without needing to examine any rows.
```
```
select count(*) from table
```
```
I'm not sure if the query optimizer in SQL Server will do so, but in the example above, if the column you are grouping on has an index the server should be able to satisfy the query without hitting the actual table at all.
To clarify: this answer refers specifically to SQL Server.  I don't know how other DBMS products handle this.


Question:
Suppose I have fileA.h which declares a class classA with template function SomeFunc<T>(). This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of SomeFunc() (like for SomeFunc<int>()) in fileA.C (ie. not in the header file).

If I now call SomeFunc<int>() from some other code (maybe also from another library), would it call the generic version, or the specialization?

I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.

Answer:
Unless the specialized template function is also listed in the header file, the other application will have no knowledge of the specialized version.  The solution is the add
```
SomeFunc<int>()
```
to the header as well.


Question:
In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?

Am I going to get myself into trouble if I change this:

<cfcomponent>
    <cfset variables.foo = "a private instance variable">

    <cffunction name = "doSomething">
        <cfset var bar = "a function local variable">
        <cfreturn "I have #variables.foo# and #bar#.">
    </cffunction>
</cfcomponent>

to this?

<cfcomponent>
    <cfset foo = "a private instance variable">

    <cffunction name = "doSomething">
        <cfset var bar = "a function local variable">
        <cfreturn "I have #foo# and #bar#.">
    </cffunction>
</cfcomponent>

Answer:
It won't matter to specify "variables" when you create the variable, because foo will be placed in the variables scope by default; but it will matter when you access the variable.
```
```
<cfcomponent>
    <cfset foo = "a private instance variable">

    <cffunction name="doSomething">
        <cfargument name="foo" required="yes"/>
        <cfset var bar = "a function local variable">
        <cfreturn "I have #foo# and #bar#.">
    </cffunction>

    <cffunction name="doAnotherThing">
        <cfargument name="foo" required="yes"/>
        <cfset var bar = "a function local variable">
        <cfreturn "I have #variables.foo# and #bar#.">
    </cffunction>

</cfcomponent>
```
```
doSomething("args") returns "I have
args
and a
function local variable
"
doAnotherThing("args") returns "I have
a private instance of a variable
and a
function local variable
."


Question:
Those of you who have used Pex, what do you think its advantages and disadvantages are of Pex as a tool?

Also, what do you think are the advantages and disadvantages of "Automated Exploratory Testing" in general, as a supplement to TDD/Unit Testing?

Answer:
I think Pex as an exploratory testing tool is really intriguing. In that regard, I see it as something I'd want to hand off to QA to use.
As a TDD tool, it needs some work, as TDD is a design activity. However, I do like the direction that Peli is heading. There's something to be said for automated assisted design. For example, just because TDD is a design tool, there's no reason I can't have an automated tool point out potential edge cases while I'm designing, right? Build quality in from the start.
Check out this post in which Peli uses Pex in a TDD style workflow.
http://blog.dotnetwiki.org/TDDingABinaryHeapWithPexPart1.aspx


Question:
Is accessing a bool field atomic in C#? In particular, do I need to put a lock around:

class Foo
{
   private bool _bar;

   //... in some function on any thread (or many threads)
   _bar = true;

   //... same for a read
   if (_bar) { ... }
}

Answer:
Yes.
Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.
as found in
C# Language Spec
.
Edit: It's probably also worthwhile understanding the
volatile
keyword.


Question:
I've got the following in my .css file creating a little image next to each link on my site:

div.post .text a[href^="http:"]
{
    background: url(../../pics/remote.gif) right top no-repeat;
    padding-right: 10px;
    white-space: nowrap;
}

How do I modify this snippet (or add something new) to exclude the link icon next to images that are links themselves?

Answer:
It might be worth it to add a class to those
```
<a>
```
tags and then add another declaration to remove the background:
```
```
div.post .text a.noimage{
   background:none;
}
```
```


Question:
I'm using MySQL in particular, but I'm hoping for a cross-vendor solution.  I'm using the NOW() function to add a timestamp as a column for each record.

INSERT INTO messages
(typeId, messageTime, stationId, message)
VALUES
(?, NOW(), ?, ?)

Answer:
```
```
SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= messageTime
```
```


Question:
How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.

Edit: Here's the code I'm now using this for, based on the answer from Santiago below.

public DataTemplate Create(Type type)
{
  return (DataTemplate)XamlReader.Load(
          @"<DataTemplate
            xmlns=""http://schemas.microsoft.com/client/2007"">
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
            </DataTemplate>"
   );
}

This works really nicely and allows me to change the binding on the fly.

Answer:
citation from MSDN
:
The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element.


Question:
I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item.

Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, _File

However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following?

<Menu>
<MenuItem>
    <MenuItem.Header>
    <UserControl>
        <Image Source="..." />
        <Label Text="_Open" />
    </UserControl>
    </MenuItem.Header>
</MenuItem>
...

Answer:
The problem is you placed the image inside of the content of the MenuHeader which means that you'll lose the accelerator key. If you're just trying to have an image in the menu header, do the following.
```
```
<MenuItem Header="_Open">
  <MenuItem.Icon>
    <Image Source="images/Open.png"/>
  </MenuItem.Icon>
</MenuItem>
```
```
If you want to customize the look and feel even further, modify the
controltemplate
and style for the menu. From experience, styling the menus and menuitems are much more difficult then styling the other WPF controls.


Question:
By default the webjump hotlist has the following which I use quite often:

M-x webjump RET Google
M-x webjump RET Wikipedia

How can I add 'Stackoverflow' to my list?

Answer:
Here's some example code in
a webjump.el file on a site run by Apple:
```
```
;;   (require 'webjump)
;;   (global-set-key "\C-cj" 'webjump)
;;   (setq webjump-sites
;;         (append '(
;;                   ("My Home Page" . "www.someisp.net/users/joebobjr/")
;;                   ("Pop's Site"   . "www.joebob-and-son.com/")
;;                   )
;;                 webjump-sample-sites))
```
```


Question: I have a Windows Form that takes quite a bit of time to load initially.  However, each subsequent request to load the Form doesn't take as long.  Is there a way to optimize a Form's load time?

Answer:
You can use
ngen
.
I also use this tip to reduce the
Memory footprint on startup
.
The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. The runtime can use native images from the cache instead using the just-in-time (JIT) compiler to compile the original assembly.


Question: What's a good program to record videos or screencasts being played on screen?

Answer:
I've had success with Camtasia / CamStudio.  Check out
http://showmedo.com
for tutorials.  It's a little recursive though - it would be better to capture it from source.


Question:
is there an easy way to transform HTML into markdown with JAVA?

I am currently using the Java MarkdownJ library to transform markdown to html.

import com.petebevin.markdown.MarkdownProcessor;
...
public static String getHTML(String markdown) {
    MarkdownProcessor markdown_processor = new MarkdownProcessor();
    return markdown_processor.markdown(markdown);
}

public static String getMarkdown(String html) {
/* TODO Ask stackoverflow */
}

Answer:
I am working on the same issue, and experimenting with a couple different techniques.
The answer above could work. You could use the
jTidy library
to do the initial cleanup work and convert from HTML to XHTML. You use the
XSLT stylesheet
linked above.
Unfortunately there is no library that has a one-stop function to do this in Java. You could try using the Python script
html2text
with Jython, but I haven't yet tried this!


Question:
I understand the main function of the lock key word from MSDN

lock Statement (C# Reference)

The lock keyword marks a statement
  block as a critical section by
  obtaining the mutual-exclusion lock
  for a given object, executing a
  statement, and then releasing the
  lock.

When should the lock be used?

For instance it makes sense with multi-threaded applications because it protects the data.  But is it necessary when the application does not spin off any other threads?

Is there performance issues with using lock?

I have just inherited an application that is using lock everywhere, and it is single threaded and I want to know should I leave them in, are they even necessary?

Please note this is more of a general knowledge question, the application speed is fine, I want to know if that is a good design pattern to follow in the future or should this be avoided unless absolutely needed.

Answer:
Generally speaking if your application is single threaded, you're not going to get much use out of the lock statement. Not knowing your application exactly, I don't know if they're useful or not - but I suspect not. Further, if you're application is using lock everywhere I don't know that I would feel all that confident about it working in a multi-threaded  environment anyways - did the original developer
actually
know how to develop multi-threaded code, or did they just add lock statements everywhere in the vague hope that that would do the trick?


Question:
I have a page results page (you get there after submitting your search query elsewhere) whit a whole bunch of gridviews for different type of data objects.

Obviously, some of the queries take longer than the others. How can I make each gridview render as soon as it has the data it needs?

This has been tricky for me because it must work on a postback as well as a pageload. Also, the object data sources just fire automatically on page load/postback; I'm not calling any methods programatically to get the data. Will I have to change this?

Answer:
Could you put the DataGrids inside panels that have their visibility set to false, then call a client-side javascript function from the body's onload event that calls a server side function that sets the visibility of the panels to true?
If you combined this with an asp:updateProgress control and wrapped the whole thing in an UpdatePanel, you should get something close to what you're looking for - especially if you rigged the js function called in onload to only show one panel and call a return function that showed the next etc.


Question: What's the best way to determine which version of the .NET Compact Frameworks (including Service Packs) is installed on a device through a .NET application.

Answer:
I have battled this problem myself last week and consider myself somewhat of an expert now ;)
I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put
```
```
#define _BIND_TO_CURRENT_MFC_VERSION 1
#define _BIND_TO_CURRENT_CRT_VERSION 1
```
```
into
every
project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled.
There are more flags that define what versions to bind to; it's documented on
http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx
. As an alternative to the lines above, you can also put
```
```
#define _BIND_TO_CURRENT_VCLIBS_VERSION 1
```
```
which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP).
Then, check what the embedded manifest says. Download XM Resource Editor:
http://www.wilsonc.demon.co.uk/d10resourceeditor.htm
. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version.
What I found is that in many cases,
both
versions were included in the manifest. This means that some libraries use the sp1 version and others don't.
A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the
```
_BIND_TO_CURRENT_CRT_VERSION
```
preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere.
Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.


Question:
I have a web page that I have hooked up to a stored procedure. In this SQL data source, I have a parameter that I'm passing back to the stored procedure of type int.

ASP.NET seems to want to default to int32, but the number won't get higher than 6.  Is it ok to override the ASP.NET default and put in 16 or will there be a conflict somewhere down the road?

specification: the database field has a length of 4 and precision of 10, if that makes a difference in the answer.

Answer:
Are you talking about doing this?
```
```
>>> a = [ ['a', 'b'], ['c', 'd'] ]
>>> a[1]
['c', 'd']
>>> a[1][1]
'd'
```
```


Question:
Is there a way to get at the ItemContaner of a selected item in a listbox?  In Silverlight 2.0 Beta 1 I could, but the container is hidden in Beta 2 of Silverlight 2.0.

I'm trying to resize the listbox item when it is unselected to a specific size and when selected to a variable size.  I also want to get the relative position of the selected item for animations.   Growing to a variable size and getting the relative pasition is why i need to get to the listbox item.

I should clarify i'm not adding items to the listbox explicitly.  I am using data binding in xaml and DataTemplates.  What I have trouble accessing is the ItemContainer of the selected item's DataTemplate.

Answer:
If you are adding non-UI elements to the listbox (such as strings or non-UI data objects), then this is probably pretty difficult.  However if you wrap your items in some sort of FrameworkElement-derived object before adding them to the listbox, you can use TransformToVisual to get the relative size and use Height and Width to set the size of the item.
In general you can wrap your objects in a ContentControl like the following.  Instead of:
```
```
_ListBox.Items.Add(obj0);
_ListBox.Items.Add(obj1);
```
```
Do this:
```
```
_ListBox.Items.Add(new ContentControl { Content = obj0 });
_ListBox.Items.Add(new ContentControl { Content = obj1 });
```
```
Now when you get _ListBox.SelectedItem you can cast it to ContentControl and set the size and get the relative position.  If you need the original object, simply get the value of the item's Content property.


Question:
Given a controller method like:

def show
  @model = Model.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml => model }
  end
end

What's the best way to write an integration test that asserts that the return has the expected XML?

Answer:
Set the request objects accept header:
```
```
@request.accept = 'text/xml' # or 'application/xml' I forget which
```
```
Then you can assert the response body is equal to what you were expecting
```
```
assert_equal '<some>xml</some>', @response.body
```
```


Question:
Erasing programs such as Eraser recommend overwriting data maybe 36 times.

As I understand it all data is stored on a hard drive as 1s or 0s.

If an overwrite of random 1s and 0s is carried out once over the whole file then why isn't that enough to remove all traces of the original file?

Answer:
There are "disk repair" type applications and services that can still read data off a hard drive even after it's been formatted, so simply overwriting with random 1s and 0s one time isn't sufficient if you really need to securely erase something.
I would say that for the average user, this is more than sufficient, but if you are in a high-security environment (government, military, etc.) then you need a much higher level of "delete" that can pretty effectively guarantee that no data will be recoverable from the drive.


Question: In a LotusScript Agent that is being run via WebQueryOpen, how do you get the name of the current server?

Answer:
```
```
Set s = New NotesSession
Set db = s.CurrentDatabase

If db.Server <> "" Then
  Set sName = New NotesName(db.Server)
Else
  Set sName = New NotesName(s.Username)
End If
```
```


Question: Is there an equivalent operator to Haskell's list difference operator \\ in F#?

Answer:
Nope... Just write it and make it an infix operator --using the set of special characters. Backslash (
```
\
```
) is not in the list below, so it will not work as an infix operator. See the
manual
:
infix-op :=
```
```
or || & && <OP >OP $OP = |OP &OP ^OP :: -OP +OP *OP /OP %OP

**OP
```
```
prefix-op :=
```
```
!OP ?OP ~OP -OP +OP % %% & &&
```
```


Question:
The most common method for corrupting compressed files is to inadvertently do an ASCII-mode FTP transfer, which causes a many-to-one trashing of CR and/or LF characters.

Obviously, there is information loss, and the best way to fix this problem is to transfer again, in FTP binary mode.

However, if the original is lost, and it's important, how recoverable is the data?

[Actually, I already know what I think is the best answer (it's very difficult but sometimes possible - I'll post more later), and the common non-answers (lots of off-the-shelf programs for repairing CRCs without repairing data), but I thought it would be interesting to try out this question during the stackoverflow beta period, and see if anyone else has gone down the successful-recovery path or discovered tools I don't know about.]

Answer:
You could try writing a little script to replace all of the CRs with CRLFs (assuming the direction of trashing was CRLF to CR), swapping them randomly per block until you had the correct crc.  Assuming that the data wasn't particularly large, I guess that might not use all of your CPU until the heat death of the universe to complete.
As there is definite information loss, I don't know that there is a better way.  Loss in the CR to CRLF direction might be slightly easier to roll back.


Question: With text-recognition improving and CAPTCHA-breakers using Mechanical Turks to break otherwise unbreakable keys, what's the next technology to keep scripts from spam-botting a site that relies on user input?

Answer:
I am a fan of limiting logins by using a credit card or cell phone SMS (like Craigslist and Gmail). These methods don't cost much (<$1), but can be highly effective in keeping spam accounts under control.
However, this is tricky on a site like SO because one of the founding goals is to have minimum friction and allow anonymous users to contribute. I guess that's where the throttling and voting comes into play.


Question: I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong?

Answer:
At the top of your external JavaScript file, add the following:
```
```
/// <reference path="jQuery.js"/>
```
```
Make sure the path is correct, relative to the file's position in the folder structure, etc.
Also, any references need to be at the top of the file, before
any
other text, including comments - literally, the very first thing in the file. Hopefully future version of Visual Studio will work regardless of where it is in the file, or maybe they will do something altogether different...
Once you have done that and
saved the file
, hit
Ctrl
+
Shift
+
J
to force Visual Studio to update Intellisense.


Question:
I have been hearing the podcast blog for a while, I hope I dont break this.
The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp_xml_preparedocument that is used to get transfer XMLs to an object and throught code.

I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes.

Answer:
If your XML conforms to a particular XSD schema, you can look into using the "xsd.exe" command line tool to generate C# object classes that you can bind the XML to, and then form your insert statements using the properties of those objects:
MSDN XSD Doc


Question:
I'm trying to get the GWTShell mode to load my context.xml file in which my database is described.

The only usable info can be found here, but this doesn't seem to work for the context.xml part.

Answer:
As of version 1.4, I have been running all my server side code, in my container of choice (Glassfish) and hooking up the GWTShell to that. Are you using Netbeans, Eclipse or something else? The Netbeans plugin gwt4nb does this for you out of the box, you just have to start your web project in debug mode. I'm sure the GWT plugin for Eclipse does the same thing.
I realise this doesn't directly answer your question -> but my question is, is there a reason you're trying to get GWT to pick up your database settings and not just running your project as normal instead. I find this much better and robust way of running the GWTShell.
Edit: Sorry I don't really use Eclipse, so I can't help you with plugins for it. I find Netbeans far superior for J2EE/web type projects. It's a bit slower, but far more functional. The plugin for that is called 'GWT4NB', it's free and it will set up your ant script in such a way that you just have to right-click on your web project and choose debug. I can understand if you don't want to switch IDEs though.


Question:
I am getting the following error in an MS Access ADP when trying to add a record on a form linked to a MS SQL Server 2000 table:

Run-time error '31004':

The value of an (AutoNumber) field
  cannot be retrived prior to being
  saved.

Please save the record that contains
  the (AutoNumber) field prior to
  performing this action.
  note: retrieved is actually spelled wrong in the error.

Does anyone know what this means?

I've done a web search and was only able to find the answer at a certain site that only experts have access to.

Answer:
Are you trying to assign the value of an Identity field to a variable or something else before you have saved the record?
For whatever reason, your app is trying to read the value of the identity field before the record has been saved, which is what generates that identity field.  In other words, no value exists for the Autonumber field until the row is saved.
I think we'd need to see more code or know more about the steps that lead up to this error to resolve it in more detail.


Question:
I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure:

Contact
{
    string First
    string Last
    string Phone
}

How would I go about creating this so that I could use it in function like the following:

function PrintContact
{
    param( [Contact]$contact )
    "Customer Name is " + $contact.First + " " + $contact.Last
    "Customer Phone is " + $contact.Phone
}

Is something like this possible, or even recommended in PowerShell?

Answer:
There is the concept of PSObject and Add-Member that you could use.
```
```
$contact = New-Object PSObject

$contact | Add-Member -memberType NoteProperty -name "First" -value "John"
$contact | Add-Member -memberType NoteProperty -name "Last" -value "Doe"
$contact | Add-Member -memberType NoteProperty -name "Phone" -value "123-4567"
```
```
This outputs like:
```
```
[8] » $contact

First                                       Last                                       Phone
-----                                       ----                                       -----
John                                        Doe                                        123-4567
```
```
The other alternative (that I'm aware of) is to define a type in C#/VB.NET and load that assembly into PowerShell for use directly.
This behavior is definitely encouraged because it allows other scripts or sections of your script work with an actual object.


Question:
Suppose the following:

>>> s = set([1, 2, 3])

How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.

Quick and dirty:

>>> elem = s.pop()
>>> s.add(elem)

But do you know of a better way? Ideally in constant time.

Answer:
Two options that don't require copying the whole set:
```
```
for e in s:
    break
# e is now an element from s
```
```
Or...
```
```
e = next(iter(s))
```
```
But in general, sets don't support indexing or slicing.


Question:
I have a page that uses

$(id).show("highlight", {}, 2000);

to highlight an element when I start a ajax request, that might fail so that I want to use something like

$(id).show("highlight", {color: "#FF0000"}, 2000);

in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect?

Answer:
From the jQuery docs:
http://docs.jquery.com/Effects/stop
Stop the currently-running animation on the matched elements.
...
When
```
.stop()
```
is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with
```
.slideUp()
```
when
```
.stop()
```
is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.
If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When
```
.stop()
```
is called, the next animation in the queue begins immediately. If the
```
clearQueue
```
parameter is provided with a value of
```
true
```
, then the rest of the animations in the queue are removed and never run.
If the
```
jumpToEnd
```
argument is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our above
```
.slideUp()
```
example, the element would be immediately hidden. The callback function is then immediately called, if provided...


Question:
I am working on an application for college music majors. A feature i am considering is slowing down music playback without changing its pitch. I have seen this done in commercial software, but cannot find any libraries or open source apps that do anything like this.

Are there libraries out there?

How could this be done from scratch from various file formats?

Note: I am working in java but am not oppossed to changing languages.

Answer:
Timestretching is quite hard. The more you slow down or speed up the sound the more artifacts you get. If you want to know what they sound like listen to "The Rockafeller Skank" by Fat Boy Slim. There are a lot of ways to do it that all have their own strengths and weaknesses. The math can get really complex. That's why there are so many proprietary algorithms.
This page explains things a bit clearer than I can and links to the Dirac library.
http://www.dspdimension.com/admin/time-pitch-overview/
I found this link for java code to do pitch shifting/timestretching
http://www.adetorres.com/keychanger/KeyChangerReadme.html


Question: I started a project a long time ago and created a Data Access Layer project in my solution but have never developed anything in it.  What is the purpose of a data access layer?  Are there any good sources that I could learn more about the Data Access Layer?

Answer:
I recommend you read up here:
http://msdn.microsoft.com/en-us/practices/default.aspx
Using a DAL will help you isolate your data access from your presentation and business logic. I use it a lot so that I can easily swap out (through reflection and dynamically loading assemblies) data providers.
Read up, lots of good info there.
Also, look into the
Data Access Block
if you are planning on using .NET. It can be a big help.


Question: We can successfully consume a .NET 2.0 web service from a Flex/AS3 application. Aside from SSL, how else can we make the security more robust (i.e., authentication)?

Answer:
If you're talking about
securing the information
going over the wire, you can use Web Service Extensions (WSE) to encrypt the body of the soap message so that you don't have to secure the channel. This way the message can get passed around from more than one endpoint (ie. it can get forwarded) and you don't need multiple https certs.
If you're talking abut
autentication
then you could do forms auth with either a password in the body or in the soap headers (once again either encrypt the body or the channel). Or one of the easiest ways to secure a webservice (if it's an internal set of services) is have IIS do it, turn on NTLM and do authentication there. You can do authorization later on in the pipeline with an HTTPModule that checks peoples credential against the code they're trying to call.


Question: I'm working on a simple ASP.Net page (handler, actually) where I check the value of the LOGON_USER server variable.  This works using Visual Studio's built-in web server and it works in other sites deployed to the live intranet site.  But it doesn't work on the IIS instance on my local XP machine.  How can I fix it, or what's going on if I can't?

Answer:
What authentication do you have enabled in IIS?  Anonmyous, Basic, Digest, Integrated Windows?  Sounds to me like anonymous access is enabled/allowed, and nothing else.  This would means that LOGON_USER is not populated.
When you access your local IIS, trying using
http://127.0.0.1
in particular if you use IE.  IE will recognize "localhost" as being in your local trusted zone and will automatically pass your XP login credentials through when Integrated Windows auth is enabled.


Question: I've been playing with RSS feeds this week, and for my next trick I want to build one for our internal application log.  We have a centralized database table that our myriad batch and intranet apps use for posting log messages.  I want to create an RSS feed off of this table, but I'm not sure how to handle the volume- there could be hundreds of entries per day even on a normal day.  An exceptional make-you-want-to-quit kind of day might see a few thousand.  Any thoughts?

Answer:
Without knowing your application, I can't offer specific advice.
That said, it's common in these sorts of systems to have a level of severity. You could have a query string parameter that you tack on to the end of the URL that specifies the severity. If set to "DEBUG" you would see every event, no matter how trivial. If you set it to "FATAL" you'd only see the events that that were "System Failure" in magnitude.
If there are still too many events, you may want to sub-divide your events in to some sort of category system. Again, I would have this as a query string parameter.
You can then have multiple RSS feeds for the various categories and severities. This should allow you to tune the level of alerts you get an acceptable level.


Question:
I am wanting to use ActiveScaffold to create assignment records for several students in a single step.  The records will all contain identical data, with the exception of the student_id.

I was able to override the default form and replace the dropdown box for selecting the student name with a multi-select box - which is what I want.  That change however, was only cosmetic, as the underlying code only grabs the first selected name from that box, and creates a single record.

Can somebody suggest a good way to accomplish this in a way that doesn't require my deciphering and rewriting too much of the underlying ActiveScaffold code?

Update: I still haven't found a good answer to this problem.

Answer:
if your assingnments have
```
has_many :students
```
or
```
has_and_belongs_to_many :students
```
, then you can change the id of the multi-select box to assignment_student_ids[], and it should work.


Question:
In Firefox you can enter the following into the awesome bar and hit enter:

javascript:self.resizeTo(1024,768);

How do you do the same thing in IE?

Answer:
Try:
```
```
javascript:resizeTo(1024,768);
```
```
This works in IE7 at least.


Question: I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?

Answer:
I don't think there's a way to do it with any built-in commands. I would suggest you download something like
Gnuwin32
or
UnxUtils
and use the
```
sed
```
command (or download only
```
sed
```
):
```
```
sed -c s/FOO/BAR/g filename
```
```


Question:
I am currently working on (or at least planning) a couple of projects that work with large amounts of repetitive data. The kind of data that works well in a spreadsheet or database, but is nasty in XML. :)

NetCDF seems like a great option for a file format. However, my work is in C# and there is no "official" NetCDF implementation available. There is an "official" Python version that I could potentially use with IronPython. Another option is the "NetCDF Library for .Net" on CodePlex but it seems pretty quiet (http://www.codeplex.com/netcdf).

Has anyone worked with either of these libraries? Can you provide any recommendations?

Answer:
First, are you sure that NetCDF is the right choice?  If you want to interact with other programs that need to read in large amounts of data and they already support NetCDF, then it's probably a great choice.  There aren't that many standard and well-supported file formats that support large multidimensional arrays.  But if you're only going to be reading and writing files from C#, it may not be such a good choice.
I'm a big fan of the "classic" NetCDF file format.  It's compact and extremely simple, but flexible enough to support lots of common kinds of multidimensional well-structured data.  It only took me one day to write a complete parser for classic NetCDF, and it only took an hour to write a program to output a well-formed special case of a classic NetCDF file.  You could implement a pure C# NetCDF library yourself and it wouldn't be much trouble.  You could easily start by implementing only the features you need.
Here's the specification.
Unfortunately, NetCDF-4 chose to use HDF-5 as its data format.  It adds a lot of complexity and makes it much more difficult to write a complete NetCDF parser in another language.  HDF-5 is very general-purpose and in my opinion, it was overengineered - it tries to be too many things to too many people.  I would not recommend trying to work with it directly unless you plan to spend a month writing unit tests.  If you must use netCDF-4 / HDF-5 from C#, your only realistic option would be to wrap the C library using SWIG or something like that.
Note that NetCDF for Python is just a wrapper around the C code, so it's not really all that helpful; if you're going to use a wrapped C library you may as well just write a C# wrapper rather than use Python as a middle layer.


Question:
I wrote a simple web service in C# using SharpDevelop (which I just got and I love).

The client wanted it in VB, and fortunately there's a Convert To VB.NET feature.  It's great.  Translated all the code, and it builds.  (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.)

But I get this error when I try to load the service now.

Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'.

Source Error:

Line 1:  <%@ WebService Class="flightinfo.Soap,flightinfo" %>

I have deleted the bins and rebuilt, and I have searched google (and stackoverflow).  I have scoured the project files for any remnants of C#.

Any ideas?

Answer:
```
```
<%@ WebService Class="flightinfo.Soap,flightinfo" %>
```
```
What is the name of your class?


Question:
What is a good challenge to improve your skills in object oriented programming?

The idea behind this poll is to provide an idea of which exercises are useful for learning OOP.

The challenge should be as language agnostic as possible, requiring either little or no use of specific libraries, or only the most common of libraries. Try to include only one challenge per answer, so that a vote will correspond to the merits of that challenge alone. Would also be nice if a level of skill required was indicated, and also the rationale behind why it is a useful exercise.

Solutions to the challenges could then be posted as answers to a "How to..." question and linked to from here.

For example:

Challenge - implement a last-in-first-out stack

Skill level - beginner

Rationale - gives experience of how to reference objects

Answer: Certainly a good challenge, although less accessible than a "start from scratch" assignment, is to refactor some existing code that either doesn't use inheritance or doesn't use very much of it to make greater use of inheritance.  The process of refactoring will expose a lot of the benefits and gotchas of oop, as it certainly has for me on my most recent project.  It also pushed me to understand the concepts better than past projects have where I've created my own object oriented designs.


Question: Is there a way to access Visual Studio's built-in ASP.NET Development Server over HTTPS?

Answer:
Cassini does not support HTTPS.
However, you can use IIS to do this, if your using IIS 5.1, download the MS IIS toolpack for IIS 6.0, it comes with a tool to create self signed SSL certificates. This works on IIS 5.1
http://www.microsoft.com/downloads/details.aspx?FamilyID=56fc92ee-a71a-4c73-b628-ade629c89499&DisplayLang=en
The one tool you need (SelfSSL.exe) works just fine with IIS 5.1. Unfortunately, it comes bundled with a bunch of other stuff.
Steps:
Install the IIS Tools File. If you want, you can click Custom and tell it to only install SelfSSL.
Activate the site in IIS that you want to install a SSL certificate too.
Go to Start / Programs / IIS Resources / SelfSSL
This will launch a command prompt in the SelfSSL directory.
Using the provided help, run SelfSSL. The command I used was: selfssl.exe /N:cn=[MACHINENAME] /K:1024 /V:90
/S:5 /P:443
The /S switch indicates which site to install the certificate. You can figure out the number by looking at your sites in IIS and counting (Starting at 1 for the first site, not 0), to the site you want.
Once this has ran, browse to your localhost over HTTPS
You should receive an error message stating that this certificate is from a untrusted source. You can either add your machinename to the browsers “Trusted Authorities” list, or you can tell the browser to ignore this.
At this point, you will be able to run your localhost over HTTPS.


Question:
Silverlight v2.0 is getting closer and closer to RTM but I have yet to hear any stats as to how many browsers are running Silverlight. If I ask Adobe (by googling "Flash install base") they're only too happy to tell me that 97.7% of browsers are running Flash player 9 or better.

Not that I believe everything I read, but where are these statistics from Microsoft or some other vendor about Silverlight? I'm going to be making a technology choice soon and a little bit of empirical evidence would be an asset at this point...

All you Silverlight developers out there, show me your stats!

Answer:
If you are developing something for a general audience, I would highly recommend against Silverlight as you immediately cut out Linux users.
I went to watch videos for the Olympics (and I run exclusively Linux), and I couldn't watch the video on their site because they were in Silverlight.  On top of that, they actively removed all videos from YouTube, so I had no alternative but to try and scrounge up a Windows boot.  This only served to give me a very negative opinion of NBC, and consider them quite amateurish to pick such a restricting technology for something that should be available for everyone.
While Flash has it's problems, it works fine in Linux, so I would say (at this point), it is a much superior technology choice.
If you KNOW your audience is entirely on Windows (maybe Mac).... then you can consider Silverlight with knowing you won't be cutting out part of your audience.


Question:
How much traffic can one web server handle? What's the best way to see if we're beyond that?

I have an ASP.Net application that has a couple hundred users. Aspects of it are fairly processor intensive, but thus far we have done fine with only one server to run both SqlServer and the site. It's running Windows Server 2003, 3.4 GHz with 3.5 GB of RAM.

But lately I've started to notice slows at various times, and I was wondering what's the best way to determine if the server is overloaded by the usage of the application or if I need to do something to fix the application (I don't really want to spend a lot of time hunting down little optimizations if I'm just expecting too much from the box).

Answer:
What you need is some info on
Capacity Planning
..
Capacity planning is the process of planning for growth and forecasting peak usage periods in order to meet system and application capacity requirements. It involves extensive performance testing to establish the application's resource utilization and transaction throughput under load. First, you measure the number of visitors the site currently receives and how much demand each user places on the server, and then you calculate the computing resources (CPU, RAM, disk space, and network bandwidth) that are necessary to support current and future usage levels.


Question: Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.

Answer:
Since
Java 1.5, yes
:
```
```
Pattern.quote("$5");
```
```


Question:
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:

$unsafe_variable = $_POST['user_input'];

mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");

That's because the user can input something like value'); DROP TABLE table;--, and the query becomes:

INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')

What can be done to prevent this from happening?

Answer:
I'd recommend using
PDO
(PHP Data Objects) to run parameterized SQL queries.
Not only does this protect against SQL injection, but it also speeds up queries.
And by using PDO rather than
```
mysql_
```
,
```
mysqli_
```
, and
```
pgsql_
```
functions, you make your application a little more abstracted from the database, in the rare occurrence that you have to switch database providers.


Question:
I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement.  What are the recommended Python solutions in this scenario?

Answer:
The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the
```
match
```
-
```
case
```
statement which provides a first-class implementation of a "switch" for Python. For example:
```
```
def f(x):
    match x:
        case 'a':
            return 1
        case 'b':
            return 2
        case _:
            return 0   # 0 is the default case if x is not found
```
```
The
```
match
```
-
```
case
```
statement is considerably more powerful than this simple example.
You could use a dictionary:
```
```
def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]
```
```


Question:
I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:

[======>                    ] 37%

and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?

Answer:
There are two ways I know of to do this:
Use the backspace escape character ('\b') to erase your line
Use the
```
curses
```
package, if your programming language of choice has bindings for it.
And a Google revealed
ANSI Escape Codes
, which appear to be a good way. For reference, here is a function in C++ to do this:
```
```
void DrawProgressBar(int len, double percent) {
  cout << "\x1B[2K"; // Erase the entire current line.
  cout << "\x1B[0E"; // Move to the beginning of the current line.
  string progress;
  for (int i = 0; i < len; ++i) {
    if (i < static_cast<int>(len * percent)) {
      progress += "=";
    } else {
      progress += " ";
    }
  }
  cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
  flush(cout); // Required.
}
```
```


Question:
I need to join two binary files with a *.bat script on Windows.

How can I achieve that?

Answer:
You can use
```
copy /b
```
like this:
```
```
copy /b file1+file2 destfile
```
```


Question:
Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding.
Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI.

Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source?

Code snippets would be great.

Update: To make it more clear,
Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls.

Answer:
using your webservice get your XML and create an XML Document from it, You can then set the Source of your xmlDataProvider to the XMLDocument you got from the service.
I'm not at a pc with visual studio to test it but it should be possible for you to do this.
The steps are as you mentioned in your question:
```
1. Get XML from webservice
2. Convert XML String to XML Document
3. Set the XMLDataProvider.Document value to your XML Document
4. Bind that to your controls
```