q: I have ASP.NET web pages for which I want to build automated tests (using WatiN & MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS.

[A]
From what I know, you can fire up the dev server from the command prompt with the following path/syntax:
```
```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT]
```
```
...so I could imagine you could easily use Process.Start() to launch the particulars you need through some code.
Naturally you'll want to adjust that version number to whatever is most recent/desired for you.


q:
I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so.

If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0.

Is there a way to bypass this behaviour and get true Windows version?

[A]
WMI QUery:
```
```
"Select * from Win32_OperatingSystem"
```
```
EDIT: Actually better would be:
```
```
"Select Version from Win32_OperatingSystem"
```
```
You could implement this in Delphi like so:
```
```
function OperatingSystemDisplayName: string;

  function GetWMIObject(const objectName: string): IDispatch;
  var
    chEaten: Integer;
    BindCtx: IBindCtx;
    Moniker: IMoniker;
  begin
    OleCheck(CreateBindCtx(0, bindCtx));
    OleCheck(MkParseDisplayName(BindCtx, PChar(objectName), chEaten, Moniker));
    OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result));
  end;

  function VarToString(const Value: OleVariant): string;
  begin
    if VarIsStr(Value) then begin
      Result := Trim(Value);
    end else begin
      Result := '';
    end;
  end;

  function FullVersionString(const Item: OleVariant): string;
  var
    Caption, ServicePack, Version, Architecture: string;
  begin
    Caption := VarToString(Item.Caption);
    ServicePack := VarToString(Item.CSDVersion);
    Version := VarToString(Item.Version);
    Architecture := ArchitectureDisplayName(SystemArchitecture);
    Result := Caption;
    if ServicePack <> '' then begin
      Result := Result + ' ' + ServicePack;
    end;
    Result := Result + ', version ' + Version + ', ' + Architecture;
  end;

var
  objWMIService: OleVariant;
  colItems: OleVariant;
  Item: OleVariant;
  oEnum: IEnumvariant;
  iValue: LongWord;

begin
  Try
    objWMIService := GetWMIObject('winmgmts:\\localhost\root\cimv2');
    colItems := objWMIService.ExecQuery('SELECT Caption, CSDVersion, Version FROM Win32_OperatingSystem', 'WQL', 0);
    oEnum := IUnknown(colItems._NewEnum) as IEnumVariant;
    if oEnum.Next(1, Item, iValue)=0 then begin
      Result := FullVersionString(Item);
      exit;
    end;
  Except
    // yes, I know this is nasty, but come what may I want to use the fallback code below should the WMI code fail
  End;

  (* Fallback, relies on the deprecated function GetVersionEx, reports erroneous values
     when manifest does not contain supportedOS matching the executing system *)
  Result := TOSVersion.ToString;
end;
```
```

s: huggingface

c: devops

d: intermediate


q: I recently upgraded to Subversion 1.5, and now I cannot commit my code to the repository. I get an error message: "403 Forbidden in response to MKACTIVITY". I know the upgrade worked because my fellow developers are not getting this issue. What's going on?

[A]
Answering my own question:
Apparently my SVN URL had the wrong case! A Google search turned up an article (no longer available online) that explained what was going on. My URL was of the form
http://svn.foobar.com/foobar
but the actual repository was called
http://svn.foobar.com/fooBar
.
I use TortoiseSVN, so the fix was to use the Relocate command to correct the path to the repository.
Hopefully this will help someone else.


q:
While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc).

class Foo
{
  ArrayList<Bar> bars = new ArrayList<Bar>(10);
}

A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm?

Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things.

[A]
The overhead is very small. It is possible to write a hybrid array list that has fields for the first few items, and then falls back to using an array for longer list.
You can avoid the overhead of the list object entirely by using an array. To go even further hardcore, you can declare the field as Object, and avoid the array altogether for a single item.
If memory really is a problem, you might want to forget about using object instances at the low-level. Instead use a larger data structure at a larger level of granularity.


q:
Here's the scenario. I'm using myopenid for, among other things, StackOverflow. When I initially set up my openid account with myopenid, I decided to try out Cardspace because they had support.

I later wanted to access Stackoverflow from another machine so I chose to back up my card. I gave it a password and a filename and successfully created a backup file. I was also to able successfully import it to my laptop.

Here is where the problem comes in - I am unable to use the card that I backed up from my laptop. The original card still works great on my desktop. Additional information is that my desktop is running Windows XP SP3 (x86) while my laptop is running Windows Vista (x64).

Any ideas? Am I doing something wrong? I'm seriously considering dropping Cardspace on myopenid and moving to a password solution with them instead.

Thanks!

[A]
It
should
work; however if you have 3.5SP1 on one machine and 3.5 or less on another there was an (unannounced) breaking change with the code to generate the unique ID from the card; which may explain why it doesn't work.
I would try sending a test transaction to
the SharpSTS test page
with only the PPID as the claim, and examine the token sent back; if the PPIDs differ then that's your problem.


q: I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility).

[A]
```
```
SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >
```
```


q:
Has anyone had any luck of using Oracle from .Net on a 64 bit machine, and using the UDT capabilities of Oracle?

I've been able to use an x64 ODP.Net client, but cannot find one with any support for UDTs.

Thanks

Nick

[Edit]
I've posted an answer below. The latest (as of December 2008) release is 11.1.0.7. This has support for 64 bit and UDT.

[A]
UDT capability is only listed in 11g clients and the latest 64 bit client is 10.2.0.3.
Not the answer you wanted, but the one that Oracle seems to be giving.
Actually I'm glad you asked this question.  We're working on migrating to 64 bit server code and I wouldn't have thought to check for this.


q:
How do I get the history of commits that have been made to the repository for a particular user?

I am able to access CVS either through the command line or TortioseCVS, so a solution using either method is sufficient.

[A]
```
```
cvs history -u username
```
```
gives a history of changes the user has made


q:
I have a Windows Form app with a TabControl. One of the TabPages in the TabControl contains a ToolStrip. Frequently, the Windows Form designer will spontaneously set the Visible property of the Toolstrip to False. To get the toolstrip to reappear in my form, I have to manually find the control and set the property back to True. It's really annoying.

Does anyone know why this happens, or how to stop it? I've tried setting the minimum height of the control to a non-zero value, but that has no effect.

I'm using VS2008, VB.NET and the .Net framework 2.0, however I've struggled with this problem in VS2005 too, in several different applications.

[A]
I may have found a workaround for this.
My ToolStrip was placed directly on the TabPage, docked to Top. However, I found
a thread on Microsoft Connect
that described the same problem when the ToolStrip was in a ToolStripContainer on the TabPage. That problem was observed in a release candidate of VS2005, but supposedly fixed by Microsoft in September 2006.
As such, I changed my code to put the ToolStrip inside a ToolStripContainer, and now I am unable to reproduce the problem.


q:
When I'm creating a user for my web application, an SMTP email (using ASP.NET's SmtpClient) is sent to the user with the
automatically generated password. However, sometimes what I notice is that it times out and the new user simply won't receive the email with the password.

Alright, so I'll display a message indicating that the mail did not go through but the user is created.

Therefore, the sys admin has 2 options so far:

Reset the password for the user and hope another SMTP mail is sent with the auto-generated password.

Delete and recreate the user.

I could rollback the user creation if the smtp is not sent but what is the best practice to tackle this problem?

I'm thinking that I should retry sending the email 3 times with a timeout period of 5 seconds each. So 15 seconds would be the worse case scenario.

Is this the way to go?

[A]
Well, depending on your platform, if you can just hand off your mail to a local MTA, it should handle the retries and such.  Your program can just queue the mail and move on, not worry about dealing with timeouts and graylists etc.
If the message still can't be delivered, you could always try resending it (via a password reset feature).  If that fails as well, most likely there was a mistake in the email address, and I would suggest deleting the account, causing the user to re-register.
This, of course, might not be possible on some systems, depending what can be done with an unconfirmed user - that really depends on what you allow people to do before their email is validated.


q:
I have seen this question about deploying to WebSphere using the WAS ant tasks.

Is there a simpler way to do this?  In the past I have deployed to Tomcat by dropping a war file into a directory.  I was hoping there would be a similar mechanism for WebSphere that doesn't involve calling the IBM libraries or rely on RAD to be installed on your workstation.

[A]
One way to do it could be using
Jython or jacl scripts
. See those samples at IBM site.
[EDIT]
Especially the
```
wsadminlib.py.zip
```
download near the bottom of the page contains a huge set of examples and helper functions to get you started.


q:
What could the best strategy for writing validation layer for mid-enterprise level business application built on Spring 2.5

I know that Spring provides facility where we can implement Validator interface and write validation logic in validate method. But this will be restricted to only web requests coming through spring controller.

I would like to develop the validation framework which can be utilized during web-services calls.

In other words, the framework can remain and be called independently without the need of implementing Validator interface and then too it can be automatically integrated into Spring MVC flow.

Hope you get my point.

[A]
The Spring Validation framework can be used outside of Spring MVC. What WebServices Stack are you using? If you are using Spring-WS (Spring's Web Services stack) they have special instructions on how to set up the validator here:
http://static.springframework.org/spring-ws/sites/1.5/reference/html/server.html#d0e2313
If you are using some other stack, it is probably easier to implement something for that stack (or find one) that will use Spring's validation framework.


q: I am forced to use VSS at work, but use SVN for a personal repository.  What is the best way to sync between VSS and sync?

[A]
What I have done in the past is as follows:
Make sure all my changes are committed to svn://trunk
Do a get latest from VSS into my working copy.
Manually merge the changes in my working copy.
Commit the merged code into the svn://trunk
Do a VSS diff and checkout any files with differences (without overwriting files)
Check in those files.


q:
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it?

I am rethrowing the InnerException, but this destroys the stack trace.

Example code:

public void test1()
{
    // Throw an exception for testing purposes
    throw new ArgumentException("test1");
}

void test2()
{
    try
    {
        MethodInfo mi = typeof(Program).GetMethod("test1");
        mi.Invoke(this, null);
    }
    catch (TargetInvocationException tiex)
    {
        // Throw the new exception
        throw tiex.InnerException;
    }
}

[A]
I think your best bet would be to just put this in your catch block:
```
```
throw;
```
```
And then extract the innerexception later.


q:
I would like to make an ajax call to a different server (same domain and box, just a different port.)
e.g.

My page is

http://localhost/index.html

I would like to make a ajax get request to:

http://localhost:7076/?word=foo

I am getting this error:

Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)

I know that you can not make an ajax request to a different domain, but it seem this also included different ports? are there any workarounds?

[A]
Have a certain page on your port 80 server proxy requests to the other port. For example:
```
```
http://localhost/proxy?port=7076&url=%2f%3fword%3dfoo
```
```
Note the url encoding on the last query string argument value.


q: I'd like to use the camera in my Macbook in a program. I'm fairly language agnostic - C, Java, Python etc are all fine. Could anyone suggest the best place to look for documents or "Hello world" type code?

[A]
The ImageKit framework in Leopard has an
```
IKPictureTaker
```
class that will let you run the standard picture-taking sheet or panel that you seen in iChat and other applications.
If you don't want to use the standard picture-taker panel/sheet interface, you an use the
QTKit Capture
functionality to get an image from the iSight.
Both of these will require writing some Cocoa code in Objective-C, but that shouldn't really be an obstacle these days.


q:
No, this is not a question about generics.

I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory).

My problem is that CreateInstance fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter.

Example

// Fails
Activator.CreateInstance(type);

// Works
Activator.CreateInstance(type, true);

I wanted to make the factory generic to make it a little simpler, like this:

public class GenericFactory<T> where T : MyAbstractType
{
    public static T GetInstance()
    {
        return Activator.CreateInstance<T>();
    }
}

However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal).

Did I miss something or it isn't possible?

[A]
To get around this, couldnt you just alter your usage as such:
```
```
public class GenericFactory<T> where T : MyAbstractType
{
    public static T GetInstance()
    {
        return Activator.CreateInstance(typeof(T), true);
    }
}
```
```
Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results.


q:
I'm working on a big .NET 1.1 project, and there exists a wish to upgrade this, majorily to be able to use better tools like Visual Studio 2008, but also because of the new features and smaller amount of bugs in the .NET 2.0 framework.

The project consist for the bigger part of VB.NET, but there are also parts in C#. It is a Windows Forms application, using various third party controls. Using .NET remoting the rich client talks to a server process which interfaces with a MSSQL 2000 database.

What kind of issues can we expect in case we decide to perform the upgrade?

[A]
Nothing, really.  You'll find a couple warnings on compilation about obsolete methods, but often those are trivial to fix.
You should shoot big and go for 3.5.  The water is niiiiiiice in here.


q:
I am currently working on a project that is moving from .NET 2.0 to 3.5 across the board.

I am well aware that 3.5 is basically a set of added functionality (libraries, if you will) on top of what 2.0 offers.

Are there any gotchas that I might hit by simply re-targeting the compiler to 3.5?

[A]
Nope
3.5 is completely compatible with 2.0, not the other way around of course


q:
Is there an equivalent of svn's blame for Perforce on the command line? p4 annotate doesn't display usernames -- only changeset numbers (without ancestor history!).

I currently have to track code back through ancestors and compare against the filelog, and there just has to be an easier way -- maybe a F/OSS utility?

[A]
I'm not overly familiar with the blame command, but I assume that you are looking for who changes a particular line of code.  The easiest way is to use Perforce's 'time lapse view' available from both p4win and p4v.
This tool uses annotate and some other commands to give you a view of the code line over time.  You can see who modified what code, when it was inserted or removed from the codeline, etc.
It's not command line though.  I checked briefly in the help and there doesnt' seem to be a way to launch the time lapse view directly from a p4win or p4v invocation.  There might be though...I'll be checking further...
Edit:  I checked with support, and you can launch the timelapse view through p4v as follows:
```
```
p4v.exe -cmd "annotate //<path/to/file>"
```
```
HTH.


q: Looking for a good approach to keep track of a Breadth-First traversal between two nodes, without knowing anything about the graph. Versus Depth-First (where you can throw away the path if it doesn't pan out) you may have quite a few "open" possibilities during the traversal.

[A] The naive approach is to build a tree with the source node as the root and all its connections as its children. Depending on the amount of space you have, you might need to eliminate cycles as you go. You can do that with a bitmap where each bit corresponds to a distinct node in the graph. When you reach the target node, you can follow the parent links back to the root and that is your path. Since you are going breadth first, you are assured that it is a shortest path even if you don't eliminate cycles.


q: What is the difference between a pointer variable and a reference variable?

[A]
Apart from syntactic sugar, a reference is a
```
const
```
pointer (
not
pointer to a
```
const
```
). You must establish what it refers to when you declare the reference variable, and you cannot change it later.
Update: now that I think about it some more, there is an important difference.
A const pointer's target can be replaced by taking its address and using a const cast.
A reference's target cannot be replaced in any way short of UB.
This should permit the compiler to do more optimization on a reference.


q:
I'm trying to do a basic "OR" on three fields using a hibernate criteria query.

Example

class Whatever{
 string name;
 string address;
 string phoneNumber;
}

I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".

[A]
You want to use
```
Restrictions.disjuntion()
```
. Like so
```
```
session.createCriteria(Whatever.class)
    .add(Restrictions.disjunction()
        .add(Restrictions.eq("name", queryString))
        .add(Restrictions.eq("address", queryString))
        .add(Restrictions.eq("phoneNumber", queryString))
    );
```
```
See the Hibernate doc
here
.


q:
Does anyone know of a way to declare a date constant that is compatible with international dates?

I've tried:

' not international compatible
public const ADate as Date = #12/31/04#

' breaking change if you have an optional parameter that defaults to this value
' because it isnt constant.
public shared readonly ADate As New Date(12, 31, 04)

[A]
OK, I am unsure what you are trying to do here:
The code you are posting is
NOT
.NET, are you trying to port?
DateTime's cannot be declared as constants.
DateTime's are a data type, so once init'ed, the format that they were init'ed from is irrelevant.
If you need a constant value, then just create a method to always return the same DateTime.
For example:
```
```
public static DateTime SadDayForAll()
{
    return new DateTime(2001, 09, 11);
}
```
```
Update
Where the hell are you getting all that from?!
There
are
differences between C# and VB.NET, and this highlights one of them.
Date
is not a
.NET data type
-
DateTime
is.
It looks like you can create DateTime constants in VB.NET but there are limitations
The method was there to try and help you, since you cannot create a const from a
variable
(i.e. optional param). That doesn't even make sense.


q: For those of you familiar with Gallio, what Advantages and Disadvantages have you experienced using this tool, a so-called Test Automation Platform?

[A]
On the advantages front, integration with everything is quite nice :)  Seriously, I'm a huge fan of the experimental integration with Visual Studio Team System (screenshots
here
). I think that really lowers the bar for those new to unit testing.
The only disadvantage from my perspective
so far
is the fact that it isn't released yet.


q:
Is it possible for SelectNodes() called on an XmlDocument to return null?

My predicament is that I am trying to reach 100% unit test code coverage; ReSharper tells me that I need to guard against a null return from the SelectNodes() method, but I can see no way that an XmlDocument can return null (and therefore, no way to test my guard clause and reach 100% unit test coverage!)

[A]
Is it necessary to reach 100% code coverage? Indeed, is it even possible under normal (i.e. controllable, testable) circumstances?
We often find that using "syntactic sugar" constructions like the
```
using {}
```
block, there are "hidden" code paths created (most likely
```
finally {}
```
or
```
catch {}
```
blocks) that can't be exercised unless some environmental condition (like a broken socket or broken disk) gets in the way.


q:
I'm a bit confused here.  Microsoft as far as I can tell claims that parametrization is the best way to protect your database from SQL injection attacks.  But I find two conflicting sources of information here:

This page says to use the ADO command object.  But this page says that the command object isn't safe for scripting.  I seem to recall reading somewhere that the command object shouldn't be used in VBScript or JScript because of security vulnerabilities, but I can't seem to find that article.

Am I missing something here, or do those two articles seem to contradict each other?

[A]
I could be wrong here, but I think this just means that someone could use the Command object to do bad things.  I.e. it's not to be trusted if someone else is scripting it.
See
safe for scripting
in this article.  Every instance that talks about this phrase online, references it as if you are marking an ActiveX control saying "This control does no I/O or only talks back to the server that it came from" but the Command object doesn't do that.  It can be used to do a lot of things which could be unsafe.
The "safe" they are talking about and the "safe" to prevent from SQL injection are two different things.  The article about using the ADO Command object to parametrize your data is spot on.  You should do that.
And, Microsoft further confirms this here:
http://msdn.microsoft.com/en-us/library/ms676585(v=VS.85).aspx


q:
In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying.

It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost.

Does anyone know of a method for getting the context directory so that I can load and write files to disk?

[A]
Do you mean:
```
```
public class MyServlet extends HttpServlet {

    public void init(final ServletConfig config) {
        final String context = config.getServletContext();
        ...
    }

    ...
}
```
```
Or something more complex?


q:
Ok, so I got my extender working on a default.aspx page on my website and it looks good.  I basically copied and pasted the code for it into a user control control.ascx page.  When I do this I completely loose the functionality (just shows the target control label and no dropdown, even upon hover).  Is there any reason why it doesn't work in a custom user control inside a masterpage setup?

Edit:
Didn't quite do the trick.  Any other suggestions?
Its in a master page setup, using eo web tabs (I tried it inside the tabs and outside the tabs but on the same page as the tabs, to no avail), and its in a custom user control.  Think there are dependency issues?

[A]
Check the DocType.  Here is what I have found useful
```
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" >
```
```
Place this in your user control (or the page that uses it) and all should be well.  I had a similar problem with a collapsible extender and this worked for me.
Edit: Here is a
link
to my question for further details.


q: What's the best way in c# to determine is a given QFE/patch has been installed?

[A]
The most reliable way is to determine which files are impacted by the QFE and use
```
System.Diagnostics.FileVersionInfo.GetVersionInfo(path)
```
on each file and compare the version numbers.
edit: I think there's a way to check the uninstall information in the registry as well, but if the QFE ever becomes part of a Service Pack or rollup package that might report false negatives


q:
I get this error on an update panel within a popupControlExtender which is within a dragPanelExtender.

I see that a lot of other people have this issue and have various fixes none of which have worked for me.

I would love to hear a logical explanation for why this is occurring and a foolproof way to avoid such issues in the future.

I have found that like others maintain this error does not occur when the trigger is a LinkButton rather than an ImageButton, still wondering if anyone has an explanation.

[A]
My best guess is that the UpdatePanel is not able to write out the custom "async" property to the postback request properly. This is likely due to blocking from one of the controls wrapping it (my gut feeling is that it's the popupControlExtender - it tends to have odd behavior with updatepanels, as it is intended to manage the events inside it for it's show/hide purposes).
I would recommend either removing the updatepanel and rolling your own solution for your specific business need for having it there, or implementing your own popup script (probably slightly easier to write).
Incidentally, for some background, the "this._postbackSettings.async" is your AJAX.NET framework trying to figure out whether this is an async call or not. You might be able to overcome it by setting this programaticly before the postback is sent (catch the postback event and add the field to the postback request if it is not already there).
Just some thoughts...I do not believe there is a "plug and play" answer for this one!


q:
What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)?

The datediff function doesn't handle year boundaries well, plus getting the months and days separate will be a bear.  I know I can do it on the client side relatively easily, but I'd like to have it done in my stored procedure.

[A]
Are you trying to calculate the total days/months/years of an age? do you have a starting date? Or are you trying to dissect it (ex: 24 years, 1 month, 29 days)?
If you have a start date that you're working with, datediff will output the total days/months/years with the following commands:
```
```
Select DateDiff(d,'1984-07-12','2008-09-11')

Select DateDiff(m,'1984-07-12','2008-09-11')

Select DateDiff(yyyy,'1984-07-12','2008-09-11')
```
```
with the respective outputs being (8827/290/24).
Now, if you wanted to do the dissection method, you'd have to subtract the number of years in days (days - 365*years), and then do further math on that to get the months, etc.


q:
Scenario:

The user has two monitors.

Their browser is open on the secondary monitor.

They click a link in the browser which calls window.open() with a specific top and left window offset.

The popup window always opens on their primary monitor.

Is there any way in JavaScript to get the popup window to open on the same monitor as the initial browser window (the opener)?

[A]
as long as you know the x and y position that falls on the particular monitor you can do:
```
```
var x = 0;
var y = 0;
var myWin = window.open(''+self.location,'mywin','left='+x+',top='+y+',width=500,height=500,toolbar=1,resizable=0');
```
```


q:
I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?

For example:

I get back:

&#x01ce;

which represents an "ǎ" with a tone mark.  In binary, this is represented as the 16 bit 01ce.  I want to convert the html entity into the value  u'\u01ce'

[A]
You could find an answer here --
Getting international characters from a web page?
EDIT
: It seems like
```
BeautifulSoup
```
doesn't convert entities written in hexadecimal form. It can be fixed:
```
```
import copy, re
from BeautifulSoup import BeautifulSoup

hexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
# replace hexadecimal character reference by decimal one
hexentityMassage += [(re.compile('&#x([^;]+);'),
                     lambda m: '&#%d;' % int(m.group(1), 16))]

def convert(html):
    return BeautifulSoup(html,
        convertEntities=BeautifulSoup.HTML_ENTITIES,
        markupMassage=hexentityMassage).contents[0].string

html = '<html>ǎǎ</html>'
print repr(convert(html))
# u'\u01ce\u01ce'
```
```
EDIT
:
```
unescape()
```
function mentioned by
@dF
which uses
```
htmlentitydefs
```
standard module and
```
unichr()
```
might be more appropriate in this case.


q:
I want to find any text in a file that matches a regexp of the form t[A-Z]u (i.e., a match t followed by a capital letter and another match u, and transform the matched text so that the capital letter is lowercase. For example, for the regexp x[A-Z]y

xAy

becomes

xay

and

xZy

becomes

xzy

Emacs' query-replace function allows back-references, but AFAIK not the transformation of the matched text. Is there a built-in function that does this? Does anybody have a short Elisp function I could use?

UPDATE

@Marcel Levy has it: \, in a replacement expression introduces an (arbitrary?) Elisp expression. E.g., the solution to the above is

M-x replace-regexp <RET> x\([A-Z]\)z <RET> x\,(downcase \1)z

[A]
It looks like
Steve Yegge
actually already posted the answer to this a few years back:
"Shiny and New: Emacs 22."
Scroll down to "Changing Case in Replacement Strings" and you'll see his example code using the
```
replace-regexp
```
function.
The general answer is that you use "\," to call any lisp expression as part of the replacement string, as in
```
\,(capitalize \1)
```
. Reading the help text, it looks like it's only in interactive mode, but that seems like the one place where this would be most necessary.


q:
I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.

Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads.

The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?

[A]
EDIT:
My "workaround" below is complete overkill, based on my lack of understanding. Go with Shog9's answer above.
OK so while I was writing the question, I came up with a workaround which will work for now.
I put a global JavaScript variable in act as a boolean on whether or not the icon is being hovered over. Then, I attach events to the image's onmouseover and onmouseout events and write functions that will set this value. Finally, I just code in the function that handles onbeforeunload that will check this value before setting event.returnValue.
Probably not a flawless workaround but it will work for now.


q: Best practices recommend not installing Sql Server to run as SYSTEM.  What is the bare minumum you need to give the user account you create for it?

[A]
Typically I create a Domain User with only the specific rights on the network which I will require the server to have (i.e. to write to the network backup drive), I then add the account to local power users or local administrators depending on what needs to be done on the machine, however this isn't required.  I've installed SQL a number of times using a standard user as a Service Account but you need to ensure that the user has access to write to the resources as listed at
https://web.archive.org/web/20081223155956/http://support.microsoft.com/kb/283811
.  Its probably not as defined an answer as you wanted but I'm only a developer (not a professional DBA / System Engineer).
Mauro
PS dont downmark me for saying "only a developer" :P


q: How do you convert decimal values to their hexadecimal equivalent in JavaScript?

[A]
Convert a number to a hexadecimal string with:
```
```
hexString = yourNumber.toString(16);
```
```
And reverse the process with:
```
```
yourNumber = parseInt(hexString, 16);
```
```


q:
I have a div with id="a" that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works:

$("#a").removeClass("bg*");

[A]
You don't need any jQuery specific code to handle this.  Just use a RegExp to replace them:
```
```
$("#a").className = $("#a").className.replace(/\bbg.*?\b/g, '');
```
```
You can modify this to support any prefix but the faster method is above as the RegExp will be compiled only once:
```
```
function removeClassByPrefix(el, prefix) {
    var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
    el.className = el.className.replace(regx, '');
    return el;
}
```
```


q:
I have a wrapper around a C++ function call which I call from C# code. How do I attach a debugger in Visual Studio to step into the native C++ code?

This is the wrapper that I have which calls GetData() defined in a C++ file:

    [DllImport("Unmanaged.dll", CallingConvention=CallingConvention.Cdecl,
               EntryPoint = "GetData", BestFitMapping = false)]
        public static extern String GetData(String url);

The code is crashing and I want to investigate the root cause.

Thanks,
Nikhil

[A]
Check the Debug tab on your project's properties page. There should be an "Enable unmanaged code debugging" checkbox. This worked for me when we developed a new .NET UI for  our old c++ DLLs.
If your unmanaged DLL is being built from another project (for a while ours were being built using VS6) just make sure you have the DLL's pdb file handy for the debugging.
The other approach is to use the C# exe as the target exe to run from the DLL project, you can then debug your DLL normally.


q:
Is it possible to use BackGroundWorker thread in ASP.NET 2.0 for the following scenario, so that the user at the browser's end does not have to wait for long time?

Scenario

The browser requests a page, say SendEmails.aspx

SendEmails.aspx page creates a BackgroundWorker thread, and supplies the thread with enough context to create and send emails.

The browser receives the response from the ComposeAndSendEmails.aspx, saying that emails are being sent.

Meanwhile, the background thread is engaged in a process of creating and sending emails which could take some considerable time to complete.

My main concern is about keeping the BackgroundWorker thread running, trying to send, say 50 emails while the ASP.NET workerprocess threadpool thread is long gone.

[A]
```
```
ThreadPool.QueueUserWorkItem(delegateThatSendsEmails)
```
```
or on System.Net.Mail.SmtpServer use the SendAsync method.
You want to put the email sending code on another thread, because then it will return the the user immediately, and will just process, no matter how long it takes.


q:
How can I close a browser window without receiving the Do you want to close this window prompt?

The prompt occurs when I use the window.close(); function.

[A]
The best solution I have found is:
```
```
this.focus();
self.opener=this;
self.close();
```
```


q: If I create an index on columns (A, B, C), in that order, my understanding is that the database will be able to use it even if I search only on (A), or (A and B), or (A and B and C), but not if I search only on (B), or (C), or (B and C). Is this correct?

[A]
That is not correct. Always best to come up with a test case that represents your data and see for yourself. If you want to really understand the Oracle SQL Optimizer google Jonathan Lewis, read his books, read his blog, check out his website, the guy is amazing, and he always generates test cases.
```
```
create table mytab nologging as (
select mod(rownum, 3) x, rownum  y, mod(rownum, 3) z from all_objects, (select 'x' from user_tables where rownum < 4)
);

create index i on mytab (x, y, z);

exec dbms_stats.gather_table_stats(ownname=>'DBADMIN',tabname=>'MYTAB', cascade=>true);

set autot trace exp

select * from mytab where y=5000;

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=10)
   1    0   INDEX (SKIP SCAN) OF 'I' (INDEX) (Cost=1 Card=1 Bytes=10)
```
```


q:
My project has some money to spend before the end of the fiscal year and we are considering replacing a Sun-Fire-V490 server we've had for a few years.  One option we are looking at is the CoolThreads technology.  All I know is the Sun marketing, which may not be 100% unbiased.  Has anyone actually played with one of these?

I suspect it will be no value to us, since we don't use threads or virtual machines much and we can't spend a lot of time retrofitting code.  We do spawn a ton of processes, but I doubt CoolThreads will be of help there.

(And yes, the money would be better spent on bonuses or something, but that's not going to happen.)

[A]
IIRC The coolthreads technology is referring to the fact that rather than just ramping up the clock speed ever higher to improve performance they are now looking at multiple core processors with hyperthreading effectively giving you loads of processors on one chip. Overall the processing capacity available is higher but without the additional electrical power and aircon requirements you would expect (hence cool). Its usefulness definitely depends on what you are planning to run on it. If you are running Apache with the multiple threads core it will love it as it can run the individual response threads on the individual cpu cores. If you are simply running single thread processes you will get some performance increases over a single cpu box but not as great (any old fashioned non mod_perl/mod_python CGID processes would still be sharing the the cpu a bit). If your application consists of one single threaded process running maxed out on the box you will get very little improvement on a single core cpu running at the same speed.
Peter
Edit:
Oh and for a benchmark. We compared a T2000 in our server farm to our current V240s (May have been V480's I don't recall) The T2000 took the load of 12-13 of the Older boxes in a live test without any OS tweeking for performance. As I said Apache loves it :-)


q: Grails scaffolding defaults to 10 rows per page.  I would like to increase that number without generating the views and changing the 10 in every file.  Where do I change the default?

[A]
I found this but can't get it to work.  You're supposed to be able (according to
this
) to scaffold and then override the actions you want (say list) in your controller, but like I said, it doesn't work for me...
```
```
class PersonController {
  def scaffold = true

  def list = {
    if(!params.max) params.max = 20
    [ personList: Person.list( params ) ]
  }
}
```
```


q:
We have a whole bunch of queries that "search" for clients, customers, etc. You can search by first name, email, etc. We're using LIKE statements in the following manner:

SELECT *
FROM customer
WHERE fname LIKE '%someName%'

Does full-text indexing help in the scenario? We're using SQL Server 2005.

[A]
It will depend upon your DBMS.  I believe that most systems will not take advantage of the full-text index unless you use the full-text functions.  (e.g.
MATCH/AGAINST
in mySQL or FREETEXT/CONTAINS in MS SQL)
Here is two good articles on when, why, and how to use full-text indexing in SQL Server:
How To Use SQL Server Full-Text Searching
Solving Complex SQL Problems with Full-Text Indexing


q:
I like HtmlControls because there is no HTML magic going on... the asp source looks similar to what the client sees.

I can't argue with the utility of GridView, Repeater, CheckBoxLists, etc, so I use them when I need that functionality.

Also, it looks weird to have code that mixes and matches:

<asp:Button id='btnOK' runat='server' Text='OK' />
<input id='btnCancel' runat='server' type='button' value='Cancel' />

(The above case in the event you wanted to bind a server-side event listener to OK but Cancel just runs a javascript that hides the current div)

Is there some definitive style guide out there? Should HtmlControls just be avoided?

[A]
well... i wouldn't use an html control if you don't need to do anything on it on the server. i would do
```
```
<input id='btnCancel' type='button' value='Cancel' />
```
```
fin.


q: I'm just looking for a simple, concise explanation of the difference between these two. MSDN doesn't go into a hell of a lot of detail here.

[A]
```
__declspec(dllexport)
```
tells the linker that you want this object to be made available for other DLL's to import. It is used when creating a DLL that others can link to.
```
__declspec(dllimport)
```
imports the implementation from a DLL so your application can use it.
I'm only a novice C/C++ developer, so perhaps someone's got a better explanation than I.


q:
I'm trying to provide a link to my company's website from a Windows Form.  I want to be well behaved and launch using the user's preferred browser.

What is the best way to open a URL in the user's default browser from a Windows Forms application?

[A]
```
```
using System.Diagnostics;

Process.Start("http://www.google.com/");
```
```
This approach has worked for me, but I could be missing something important.


q:
Using reflection, I need to load 2 different versions of the same assembly. Can I load the 2 versions in 2 different AppDomains in the same process?

I need to do some data migration from the old version of the app to the new version.
Please let me know if this is possible or should I use 2 separate processes.

[A]
If you are doing it at design time (which you indicate you are not) this should help you:
http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx
If you are doing it dynamically through reflection (looks like the case here) this might help you:
https://www.infosysblogs.com/microsoft/2007/04/loading_multiple_versions_of_s.html


q: I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.

[A]
Here is a solution I found. It doesn't seem very elegant, though:
```
```
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<% pageContext.setAttribute("newLineChar", "\n"); %>

${fn:replace(item.comments, newLineChar, "; ")}
```
```


q:
I'm trying to write a small class library for a C++ course.

I was wondering if it was possible to define a set of classes in my shared object and then using them directly in my main program that demos the library. Are there any tricks involved? I remember reading this long ago (before I started really programming) that C++ classes only worked with MFC .dlls and not plain ones, but that's just the windows side.

[A]
C++ classes work fine in .so shared libraries (they also work in non-MFC DLLs on Windows, but that's not really your question).  It's actually easier than Windows, because you don't have to explicitly export any symbols from the libraries.
This document will answer most of your questions:
http://people.redhat.com/drepper/dsohowto.pdf
The main things to remember are to use the
```
-fPIC
```
option when compiling, and the
```
-shared
```
option when linking.  You can find plenty of examples on the net.


q: I can't tell from the Python documentation whether the re.compile(x) function may throw an exception (assuming you pass in a string). I imagine there is something that could be considered an invalid regular expression. The larger question is, where do I go to find if a given Python library call may throw exception(s) and what those are?

[A]
Well,
```
re.compile
```
certainly may:
```
```
>>> import re
>>> re.compile('he(lo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python25\lib\re.py", line 180, in compile
    return _compile(pattern, flags)
  File "C:\Python25\lib\re.py", line 233, in _compile
    raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis
```
```
The documentation
does support this, in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the
```
error
```
exception.
Unfortunately, I don't have any answer to the general question. I suppose the documentation for the various modules varies in quality and thoroughness. If there were particular modules you were interested in, you might be able to
decompile
them (if written in Python) or even
look at the source
, if they're in the standard library.


q: I am trying to come up with the best way to render some hierarchical data in to a nested unordered list using ASP.NET MVC. Does anyone have any tips on how to do this?

[A]
You mean... you want some sort of tree view?
You can actually get the treeview control to work... but you have to wrap it in server side form tag to function.  You'll get the usual nastiness that that brings (like generated ids and viewstate) but it will work from a rendering perspective.
If you want to just create  tags and nest them, it would be pretty easy to do with foreach() loops.


q:
Is there something special about Safari for Windows and AJAX?

In other words: Are there some common pitfalls I should keep in mind?

[A]
Safari is really standards compliant.  Unless you're using some really esoteric browser features, in general if something works in Firefox, I've found it works without modification in Windows Safari.
Apple has
a developer center for web developers
, but I didn't find anything too useful there.


q:
To create a playlist for all of the music in a folder, I am using the following command in bash:

ls > list.txt

I would like to use the result of the pwd command for the name of the playlist.

Something like:

ls > ${pwd}.txt

That doesn't work though - can anyone tell me what syntax I need to use to do something like this?

Edit: As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!

[A]
The best way to do this is with
```
"$(command substitution)"
```
(thanks,
Landon
):
```
```
ls > "$(pwd).txt"
```
```
You will sometimes also see people use the older backtick notation, but this has
several drawbacks
in terms of nesting and escaping:
```
```
ls > "`pwd`.txt"
```
```
Note that the unprocessed substitution of
```
pwd
```
is an absolute path, so the above command creates a file with the same name in the same directory as the working directory, but with a
```
.txt
```
extension. Thomas Kammeyer pointed out that the
```
basename
```
command strips the leading directory, so this would create a text file in the current directory with the name of that directory:
```
```
ls > "$(basename "$(pwd)").txt"
```
```
Also thanks to erichui for bringing up the problem of spaces in the path.


q:
We have a requirement to increase the functionality of a grid we are using to edit on our webapp, and our manager keeps citing Excel as the perfect example for a data grid :/ He still doesn't really get that a Spreadsheet like control doesn't exist out of the box, but I thought I'd do a bit of searching nonetheless.

I've found a couple of products on Google, but was wondering if anyone else has any feedback around any such controls (obviously the cheaper or ahem freer the better)

EDIT We do currently have the Telerik controls, but what the 'current' requirement is, is a control that can copy and paste (e.g) 3 cells from one row and paste them on another, the row by row editing of Telerik doesn't really cut it. We are currently in competition with an 'Excel' based solution, which is always a nightmare in winning users around, who always prefer flexibility to structure

[A]
Update: with Silverlight fast approaching, maybe you can use a real excel control.
Devexpress
has a powerful grid control for both web and windows. It is not free and I guess nothing really matches Excel. But once the users started using it, they wanted every app with it. Check these
videos
especially the data grouping one.


q: Simple as the title states: Can you use only Java commands to take a screenshot and save it?  Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?

[A]
Believe it or not, you can actually use
```
java.awt.Robot
```
to "create an image containing pixels read from the screen." You can then write that image to a file on disk.
I just tried it, and the whole thing ends up like:
```
```
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));
```
```
NOTE: This will only capture the primary monitor. See
GraphicsConfiguration
for multi-monitor support.


q:
Using win forms with an MVC/MVP architecture, I would normally use a class to wrap a view to test the UI while using mocks for the model and controller/presenter.  The wrapper class would make most everything in the UI an observable property for the test runner through properties and events.

Would this be a viable approach to testing a WPF app?  Is there a better way? Are there any gotchas to watch out for?

[A]
@Matt David,
Please read documentation and take a look at the code samples for Microsoft
CompositeWPF
(aka Prism). It's a project created specifically to teach how to deal with MVP/MVC architecture in test-driven manner. Their sample application contains unit tests for presenters\controllers and very cool acceptance tests for UI (they use
White framework
to simulate user actions)


q:
I have wondered for some time, what a nice, clean solution for joining an array of strings might look like.
Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma".

Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented.
When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string).
I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?).

Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant?

[A]
The most elegant solution i found for problems like this is something like this (in pseudocode)
```
```
separator = ""
foreach(item in stringCollection)
{
    concatenatedString += separator + item
    separator = ","
}
```
```
You just run the loop and only after the second time around the separator is set. So the first time it won't get added. It's not as clean as I'd like it to be so I'd still add comments but it's better than an if statement or adding the first or last item outside the loop.


q:
How do you randomly select a table row in T-SQL based on an applied weight for all candidate rows?

For example, I have a set of rows in a table weighted at 50, 25, and 25 (which adds up to 100 but does not need to), and I want to select one of them randomly with a statistical outcome equivalent to the respective weight.

[A]
You simply need to sum the weights of all candidate rows, then choose a random point within that sum, then select the record that coordinates with that chosen point (each record is incrementally carrying an accumulating weight sum with it).
```
```
DECLARE @id int, @weight_sum int, @weight_point int
DECLARE @table TABLE (id int, weight int)

INSERT INTO @table(id, weight) VALUES(1, 50)
INSERT INTO @table(id, weight) VALUES(2, 25)
INSERT INTO @table(id, weight) VALUES(3, 25)

SELECT @weight_sum = SUM(weight)
FROM @table

SELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)

SELECT TOP 1 @id = t1.id
FROM @table t1, @table t2
WHERE t1.id >= t2.id
GROUP BY t1.id
HAVING SUM(t2.weight) >= @weight_point
ORDER BY t1.id

SELECT @id
```
```


q:
Which OS do you prefer to program on? Client or Server

There is a school of though that if you are doing (mostly) web programming (or other server based code), you should use a server OS for your dev machine, since that's closer to the environment where your app will be running.

Update: I should add, this is really directed to the Windows crowd

[A]
Regardless of the operating system you're actually talking about, it shouldn't matter. Most applications you might write won't need to worry about the differences (if there indeed are any). Only in rare cases might you use some specific functionality that might only be available on a "server" edition of your OS.
There are other considerations, for example Windows server editions are tuned by default to give less priority and attention to desktop programs, and more attention to things like the file cache. Personally, I would always choose a "client" edition of my chosen OS.


q:
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?

[A]
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


q: 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.

[A]
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
```
.


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

[A]
If you taking about using enum flags() there is a good article
here
.


q:
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.

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
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();
    }
}
```
```


q:
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();

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


q: 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.

[A]
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 :-)


q:
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?

[A]
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.


q:
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

[A]
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
}
```
```


q:
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?

[A]
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


q:
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.

[A]
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.


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

[A]
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
.


q:
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?

[A]
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?


q:
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!

[A]
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.


q:
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!

[A]
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...


q:
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?

[A]
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


q:
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?

[A]
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.


q:
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.

[A]
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
```
...


q:
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.

[A]
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.


q: 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.

[A]
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.


q:
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.

[A]
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


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

[A]
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();
}
```
```


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

[A]
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
```
```


q:
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.

[A]
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!


q:
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.

[A]
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..


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

This is a follow-up to my earlier question.

[A]
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 ...
```
```


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

[A]
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.


q:
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.

[A]
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.


q: 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)

[A]
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.


q:
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.

[A]
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)


q:
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?

[A]
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.)


q:
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)

[A]
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'


q:
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?

[A]
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)
```
```


q:
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?

[A]
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.


q:
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.

[A]
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.


q:
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.

[A]
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.


q: 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?

[A]
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
.


q:
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.

[A]
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


q:
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.

[A]
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).


q:
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

[A]
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.


q:
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.

[A]
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?


q:
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?

[A]
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.


q:
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?

[A]
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;
```
```