q:
I would like to use as and is as members of an enumeration. I know that this is possible in VB.NET to write it like this:

Public Enum Test
    [as] = 1
    [is] = 2
End Enum

How do I write the equivalent statement in C#?
The following code does not compile:

public enum Test
{
    as = 1,
    is = 2
}

[A]
Prefixing reserved words in C# is done with @.
```
```
public enum Test
{
    @as = 1,
    @is = 2
}
```
```


q:
I'm looking for an existing library to summarize or paraphrase content (I'm aiming at blog posts) - any experience with existing natural language processing libraries?

I'm open to a variety of languages, so I'm more interested in the abilities & accuracy.

[A]
Your getting into really far out AI type domain. I have done extensive work in text transformation into machine knowledge mainly using Attempto Controlled English (see:
http://attempto.ifi.uzh.ch/site/
), it is a natural language (english) that is completely computer processable into several different ontologies, such as OWLDL.
Seems like that would we way overkill though...
Is there a reason for not just taking the first few sentences of your blog post and then appending an ellipse for your summary?

s: huggingface

c: devops

d: intermediate


q:
I am familiar with nunit for unit testing of the business layer however I am looking now to automate the test of the win forms gui layer.

I have seen watin and the watin recorder for automating tests on web application by accessing the controls and automating them. However I am struggling to find a watin equivalent for windows forms (written in c# or vb.net) preferably that is open source.

Does one exist or are all products based on recording mouse and keyboard presses?

Update: I have looked at this blog post on white and it seems the sort of thing I am looking for. The blog post raises some issues but as white is only in version 0.6 these may be resolved. Be interested if others have used white or any others for comparison.

[A]
AutomatedQA's TestComplete
is a good testing application to automate GUI testing.  It supports more than just Windows Forms also, so you can reuse it for other applications.  It is not open source and this is the best that I have found.  I haven't seen an open source equivalent to WatiN.  It does have a free trial, for you decide if you like it or not.  The main reason I went with it, is that it really is cost effective, compared to other testing applications.


q:
I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma.

What would be, in your opinion, the best way to do this using C#.NET 2.0?

[A]
The best way is the builtin way: Use
```
string.Replace
```
. Why do you need alternatives?


q: Does .NET come with a class capable of representing extremely large integers, such as 100 factorial?  If not, what are some good third party libraries to accomplish this?

[A]
.NET has a BigInteger class, but it is internal, unfortunately. However, several places have their own. You can grab an implementation from IronPython, or the one from CodeProject, or from Visual J#. I have to say, I've not tried these myself, so I don't know which one is the best.
http://www.codeplex.com/IronPython
http://www.codeproject.com/KB/cs/biginteger.aspx
http://msdn.microsoft.com/en-us/magazine/cc163696.aspx


q:
I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions?

They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer?

Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.

[A]
Lambdas bring functional programing to C#.
They are anonymous functions that can be passed as values to certain other functions.  Used most in LINQ.
Here is a contrived example:
```
```
List<int> myInts = GetAll();
IEnumerable<int> evenNumbers = myInts.Where(x => x % 2 == 0);
```
```
Now when you foreach through evenNumbers the lamda
```
```
x=> x % 2 == 0
```
```
is then applied as a filter to myInts.
They become really useful in increasing readability to complicated algorithms that would have many nested IF conditionals and loops.


q:
Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier.

Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc.

Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole?

[A]
What I found works best is to really learn CSS. I mean
really
learn CSS.
It can be a confusing language to learn, but if you read enough about it and practice, eventually you'll learn the best way to do things.
The key is to do it enough that it comes natural. CSS can be very elegant if you know what you want to do before you start and you have enough experience to do it.
Granted, it is also a major PITA to do sometimes, but even cross-browser issues aren't so bad if you
really
practice at it and learn what works and what doesn't, and how to get around problems.
All it takes is practice and in time you can become good at it.


q:
I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering...

For those who have used reflection in applications, have you measured performance hits and, is it really so bad?

[A]
It is. But that depends on what you're trying to do.
I use reflection to dynamically load assemblies (plugins) and its performance "penalty" is not a problem, since the operation is something I do during startup of the application.
However, if you're reflecting inside a series of nested loops with reflection calls on each, I'd say you should revisit your code :)
For "a couple of time" operations, reflection is perfectly acceptable and you won't notice any delay or problem with it. It's a very powerful mechanism and it is even used by .NET, so I don't see why you shouldn't give it a try.


q:
Is it possible to call a stored procedure from another stored procedure asynchronously?

Edit: Specifically I'm working with a DB2 database.

[A]
Executive summary:  Yes, if your database has a message queue service.
You can push a message onto a queue and the queue processor will consume it asynchronously.
Oracle: queues
Sql Server: service broker
DB2: event broker
For "pure" stored procedure languages (PL/Sql or T-Sql) the answer is no, since it works against the fundamental transaction model most databases have.
However, if your database has a queuing mechanism, you can use that to get the same result.


q:
What would be the Master Pages equivalent in the Java web development world?  I've heard of Tiles, Tapestry and Velocity but don't know anything about them.  Are they as easy to use as Master Pages?

I want something as easy as set up one template and subsequent pages derive from the template and override content regions, similar to Master Pages.

Any examples would be great!!

[A]
First, the equivalent of ASP.Net in Java is going to be a web framework, such as the ones you mention (Tiles, Tapestry and Velocity).
Master pages give the ability to define pages in terms of content slotted into a master template.
Master pages are a feature of ASP.Net (the .Net web framework), so you are looking for a feature similar to master pages in a Java web framework.
http://tiles.apache.org/framework/tutorial/basic/pages.html
gives some basic examples using Tiles and JSP to implement something similar with Struts, a Java web framework.  In this case, the Master Pages functionality is a plugin on top of Struts.
Velocity is a generic templating engine, not specialized for web pages and definitely more complicated than you need.  (I've seen it used for code generation.)
Tapestry is more of a full featured web stack than Tile, and is probably good for your purposes.  Its templating functionality involves creating a component and putting all common markup in that.  An example is at
http://www.infoq.com/articles/tapestry5-intro
.
The specifics of this differ based on which Java web framework you choose.


q: Is there a way to shutdown a computer using a built-in Java method?

[A]
Create your own function to execute an OS command through the
command line
?
For the sake of an example. But know where and why you'd want to use this as others note.
```
```
public static void main(String arg[]) throws IOException{
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("shutdown -s -t 0");
    System.exit(0);
}
```
```


q: I want to programatically create an NSTextView. How can I determine the correct frame height so that the view displays one line of text in the current default font?

[A]
The NSFont class has a method that can give you the size of a rectangle that would enclose a specific attributed string.  Get the font used by your text view, create a string that serves as a reasonable example of what will be in the text view, and use that to inform your frame height.  (The frame height will need to be some number of points larger than the actual rectangle the string would be displayed in.)
Alternately, you can get the various metrics from the font and attempt to calculate a reasonable frame from that.  That might or might not work; for example, a font like Apple Chancery has a huge amount of variation depending on the glyphs that are being rendered, where they are in a word, and so on; I don't know that you can calculate what the needed size would be in advance without knowing exactly what you were going to render.


q:
Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column?

For instance, I can currently set the display name of a column like this:

[DisplayName("Last name")]
public object Last_name { get; set; }

Is there a similar way to hide a column?

Edit: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-)

[A]
Had no idea what ASP.NET Dynamic Data was so you promted me to so some research :)
Looks like the property you are looking for is
```
```
[ScaffoldColumn(false)]
```
```
There is also a similar property for tables
```
```
[ScaffoldTable(false)]
```
```
source


q: Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope?

[A]
There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Request. Some are inadvisable to use in certain ways (i.e. using Request or Application scope inside your Custom Tags or CFC's; this is
coupling
, violates encapsulation principles, and is considered a bad practice), and some have special purposes: Cookie is persisted on the client machine as physical cookies, and Session scoped variables are user-specific and expire with the user's session on the website.
If a variable is extremely unlikely to change (constant for all intents and purposes) and can simply be initialized on application startup and never written again, generally you should put it into Application scope because this persists it between every user and every session. When properly implemented it is written once and read N times.
A proper implementation of Application variables in Application.cfm might look like this:
```
```
<cfif not structKeyExists(application, "dsn")>
    <cflock scope="application" type="exclusive" timeout="30">
        <cfif not structKeyExists(application, "dsn")>
            <cfset application.dsn = "MyDSN" />
            <cfset foo = "bar" />
            <cfset x = 5 />
        </cfif>
    </cflock>
</cfif>
```
```
Note that the existence of the variable in the application scope is checked before and after the lock, so that if two users create a race condition at application startup, only one of them will end up setting the application variables.
The benefit of this approach is that it won't constantly refresh these stored variables on every request, wasting the user's time and the server's processing cycles. The trade-off is that it is a little verbose and complex.
This was greatly simplified with the addition of Application.cfc. Now, you can specify which variables are created on application startup and don't have to worry about locking and checking for existence and all of that fun stuff:
```
```
<cfcomponent>
    <cfset this.name = "myApplicationName" />

    <cffunction name="onApplicationStart" returnType="boolean" output="false">
        <cfset application.dsn = "MyDSN" />
        <cfset foo = "bar" />
        <cfset x = 5 />
        <cfreturn true />
    </cffunction>
</cfcomponent>
```
```
For more information on Application.cfc including all of the various special functions available and every little detail about what and how to use it,
I recommend this post on Raymond Camden's blog
.
To summarize, request scope is available everywhere in your code, but that doesn't necessarily make it "right" to use it everywhere. Chances are that your predecessor was using it to break encapsulation, and that can be cumbersome to refactor out. You may be best off leaving it as-is, but understanding which scope is the best tool for the job will definitely make your future code better.


q: In coding a traditional MVC application, what is the best practice for coding server-side form validations? Does the code belong in the controller, or the model layer? And why?

[A]
From Wikipedia:
Model-view-controller
(MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.
Thus, model - it holds the application and the business rules.


q:
I'm learning objective-C and Cocoa and have come across this statement:

The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings.

I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal?

[A]
Let's use C++, since my Objective C is totally non-existent.
If you stash a string into a constant variable:
```
```
const std::string mystring = "my string";
```
```
Now when you call methods, you use my_string, you're using a string constant:
```
```
someMethod(mystring);
```
```
Or, you can call those methods with the string literal directly:
```
```
someMethod("my string");
```
```
The reason, presumably, that they encourage you to use string constants is because Objective C doesn't do "interning"; that is, when you use the same string literal in several places, it's actually a different pointer pointing to a separate copy of the string.
For dictionary keys, this makes a huge difference, because if I can see the two pointers are pointing to the same thing, that's much cheaper than having to do a whole string comparison to make sure the strings have equal value.
Edit:
Mike, in C# strings are immutable, and literal strings with identical values all end pointing at the same string value. I imagine that's true for other languages as well that have immutable strings. In Ruby, which has mutable strings, they offer a new data-type: symbols ("foo" vs. :foo, where the former is a mutable string, and the latter is an immutable identifier often used for Hash keys).


q:
I'm learning objective-c and keep bumping into the @ symbol. It is used in different scenarios, for example at the start of a string or to synthesise accessor methods.

What's does the @ symbol mean in objective-c?

[A]
From
Objective-C Tutorial: The @ Symbol
, the reason it is on the front of various keywords:
Using @ should make it easier to bolt an Objective-C compiler on to an existing C compiler. Because the @ isn't valid in any context in C except a string literal, the tokenizer (an early and simple step in the compiler) could be modified to simply look for the @ character outside of a string constant (the tokenizer understands string literals, so it is in a position to distinguish this). When @ is encountered the tokenizer would put the rest of the compiler in "Objective-C mode." (The Objective-C parser would be responsible for returning the compiler back to regular C mode when it detects the end of the Objective-C code).
Also when seen in front of a string literal, it makes an NSString rather than a 'char *' in C.


q:
In a drop down list, I need to add spaces in front of the options in the list. I am trying

<select>
<option>&#32;&#32;Sample</option>
</select>

for adding two spaces but it displays no spaces. How can I add spaces before option texts?

[A]
```
```

```
```
Can you try that? Or is it the same?


q:
I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential.

Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience...

[A]
If your hardcoded values are just simple key-value pairs, you should look at
java.util.Properties
.  It's a lot simpler than xml, easier to use, and mind-numbingly trivial to implement.
If you are working with Java and the data you are storing or retrieving from disk is modeled as a key value pair (which it sounds like it is in your case), then I really can't imagine a better solution.
I have used properties files for simple configuration of small packages in a bigger project, and as a more global configuration for a whole project, and I have never had problems with it.
Of course this has the huge benefit of not requiring any 3rd party libraries to utilize.


q:
Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory?

To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5.

And just to be clear, there's only one file present, it should never be deleted.

[A]
Remove all but 5 (or whatever number) of the most recent files in a directory.
```
```
rm `ls -t | awk 'NR>5'`
```
```


q:
Without local access to the server, is there any way to duplicate/clone a MySQL db (with content and without content) into another without using mysqldump?

I am currently using MySQL 4.0.

[A]
You can duplicate a table without data by running:
```
```
CREATE TABLE x LIKE y;
```
```
(See the
MySQL CREATE TABLE
Docs)
You could write a script that takes the output from
```
SHOW TABLES
```
from one database and copies the schema to another. You should be able to reference schema+table names like:
```
```
CREATE TABLE x LIKE other_db.y;
```
```
As far as the data goes, you can also do it in MySQL, but it's not necessarily fast. After you've created the references, you can run the following to copy the data:
```
```
INSERT INTO x SELECT * FROM other_db.y;
```
```
If you're using MyISAM, you're better off to copy the table files; it'll be much faster. You should be able to do the same if you're using INNODB with
per table table spaces
.
If you do end up doing an
```
INSERT INTO SELECT
```
, be sure to temporarily
turn off indexes
with
```
ALTER TABLE x DISABLE KEYS
```
!
EDIT
Maatkit
also has some scripts that may be helpful for syncing data. It may not be faster, but you could probably run their syncing scripts on live data without much locking.


q:
If I have Python code

class A():
    pass
class B():
    pass
class C(A, B):
    pass

and I have class C, is there a way to iterate through it's super classed (A and B)? Something like pseudocode:

>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)

One solution seems to be inspect module and getclasstree function.

def magicGetSuperClasses(cls):
    return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]

but is this a "Pythonian" way to achieve the goal?

[A]
```
C.__bases__
```
is an array of the super classes, so you could implement your hypothetical function like so:
```
```
def magicGetSuperClasses(cls):
  return cls.__bases__
```
```
But I imagine it would be easier to just reference
```
cls.__bases__
```
directly in most cases.


q:
I have seen Solutions created in Visual Studio 2008 cannot be opened in Visual Studio 2005 and tried workaround 1. Yet to try the workaround 2.

But as that link was bit old and out of desperation asking here: Is there any convertor available?

I dont have VS2008 yet and i wanted to open an opensource solution which was done in vs2008.

Guess i have to fiddle around or wait till the vs2008 is shipped.

[A]
I'd say you should restore your 2005 version from source control, assuming you have source control and a 2005 copy of the file.
Otherwise, there are plenty of pages on the net that details the changes, but unfortunately no ready-made converter program that will do it for you.
Be aware that as soon as you open the file in 2008 again, it'll be upgraded once more.
Perhaps the solution (no pun intended) is to keep separate copy of the project and solution files for 2005 and 2008?
Why do you want to open it in 2005 anyway?


q: How do you get the maximum number of bytes that can be passed to a sendto(..) call for a socket opened as a UDP port?

[A]
As UDP is not connection oriented there's no way to indicate that two packets belong together. As a result you're limited by the maximum size of a single IP packet (65535). The data you can send is somewhat less that that, because the IP packet size also includes the IP header (usually 20 bytes) and the UDP header (8 bytes).
Note that this IP packet can be fragmented to fit in smaller packets (eg. ~1500 bytes for ethernet).
I'm not aware of any OS restricting this further.
Bonus
```
SO_MAX_MSG_SIZE
```
of UDP packet
IPv4: 65,507 bytes
IPv6: 65,527 bytes


q:
I know that MAC OS X 10.5 comes with Apache installed but I would like to install the latest Apache without touching the OS Defaults incase it causes problems in the future with other udpates. So I have used the details located at: http://diymacserver.com/installing-apache/compiling-apache-on-leopard/ But I'm unsure how to make this the 64 Bit version of Apache as it seems to still install the 32 bit version.

Any help is appreciated

Cheers

[A]
Add this to your ~/.bash_profile which means that your architecture is 64-bit ant you’d like to compile Universal binaries.
```
```
export CFLAGS="-arch x86_64"
```
```


q:
My good friend, Wikipedia, didn't give me a very good response to that question. So:

What are language bindings?

How do they work?

Specifically accessing functions from code written in language X of a library written in language Y.

[A]
In Flex (Actionscript 3).
Source
A data binding copies the value of a property in one object to a property in another object. You can bind the properties of following objects: Flex components, Flex data models, and Flex data services.
The object property that provides the data is known as the source property. The object property that receives the data is known as the destination property.
The following example binds the text property of a TextInput component (the source property) to the text property of a Label component (the destination property) so that text entered in the TextInput component is displayed by the Label component:
```
```
<mx:TextInput id="LNameInput"></mx:TextInput>
...
<mx:Label text="{LNameInput.text}"></mx:Label>
```
```
Data binding is usually a simple way to bind a model to user interface components. For example, you have a class with a FirstName property. In flex you could easily bind that property to a textbox by setting the value of the textbox to {Object.FirstName}. Then, every time that FirstName property changes, the textbox will be updated without requiring you to write any code to monitor that property for changes.
Hope that helps.
Matt


q:
We created several custom web parts for SharePoint 2007. They work fine. However whenever they are loaded, we get an error in the event log saying:

error initializing safe control - Assembly: ...

The assembly actually loads fine. Additionally, it is correctly listed in the web.config and GAC.

Any ideas about how to stop these (Phantom?) errors would be appreciated.

[A]
You need to add a safecontrol entry to the web,config file, have a look at the following:
```
```
<SafeControls>
  <SafeControl
    Assembly = "Text"
    Namespace = "Text"
    Safe = "TRUE" | "FALSE"
    TypeName = "Text"/>
  ...
</SafeControls>
```
```
http://msdn.microsoft.com/en-us/library/ms413697.aspx


q:
Back when I was at school, I remember tinkering with a Mac game where you programmed little robots in a sort of pseudo-assembler language which could then battle each other. They could move themselves around the arena, look for opponents in different directions, and fire some sort of weapon. Pretty basic stuff, but I remember it quite fondly, even if I can't remember the name.

Are there any good modern day equivalents?

[A]
I used to have a lot of fun coding my own robot with
Robocode
in college.
It is Java based, the API is detailled and it's pretty easy to get a challenging robot up and running.
Here is an example :
```
```
public class MyFirstRobot extends Robot {
     public void run() {
         while (true) {
             ahead(100);
             turnGunRight(360);
             back(100);
             turnGunRight(360);
         }
     }

     public void onScannedRobot(ScannedRobotEvent e) {
         fire(1);
     }
 }
```
```


q:
I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day (MySQL, Oracle, SQL Server, Informix, and DB2).

Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92) that would allow me to insert the values without worrying about the underlying database?

[A]
Try:
```
```
INSERT INTO table1 ( column1 )
SELECT  col1
FROM    table2
```
```
This is standard ANSI SQL and should work on any DBMS
It definitely works for:
Oracle
MS SQL Server
MySQL
Postgres
SQLite v3
Teradata
DB2
Sybase
Vertica
HSQLDB
H2
AWS RedShift
SAP HANA
Google Spanner


q:
Is there an easy way to iterate over an associative array of this structure in PHP:

The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two).

Thoughts on doing this in a way that's nice, neat, and understandable?

[A]
You should be able to use a nested foreach statment
from the
php manual
```
```
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}
```
```


q: I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?

[A]
There is a list of Sqlite wrappers for .Net at
http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers
. From what I've heard
http://sqlite.phxsoftware.com/
is quite good. This particular one lets you access Sqlite through ADO.Net just like any other database.


q:
I'm starting to develop a browser-based game (and by this I mean text-based, no Flash or similar stuff on it) and I'm struggling to decide on which development framework to use.

As far as requirements are concerned, the most important thing that I can think of right now is the ability to translate it to several languages. A good object-relational mapping and a way to generate forms from logical objects would also be very good, as I've noticed that I always spend lots of time solving the problems that come up when I change any of those things.

The programming language is kind of unimportant. I have some experience in PHP and C#, but I don't mind, and I would even like to use this as an excuse, learning some new thing like Python or Ruby. What I do want is something with a good and thriving community and lots of samples and tutorials online to help me.

[A]
I would reccomend sticking to what you know - PHP is more than capable.
I used to play a game called
Hyperiums
- a text based browser game like yours - which is created using Java (it's web-based quivalent is JSP?) and servlets. It works fairly well (it has had downtime issues but those were more related to it's running on a pretty crap server).
As for which framework to use - why not create your own? Spend a good amount of time pre-coding deciding how you're going to handle various things - such as langauge support: you could use a phrase system or seperate langauge-specific templates. Third party frameworks are probably better tested than one you make but they're not created for a specific purpose, they're created for a wide range of purposes.


q:
I have an Access database in which I drop the table and then create the table afresh.  However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ).  If I were doing this in the SQL database I would just do:

IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for'))
BEGIN
drop table 'Table-Name-to-look-for'
END

But how do I do that for an Access database?

Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists?

SQL Server 2000


q:
What strategies have you used with Model Based Testing?

Do you use it exclusively for
integration testing, or branch it
out to other areas
(unit/functional/system/spec verification)?

Do you build focused "sealed" models  or do you evolve complex onibus models over time?

When in the product cycle do you invest in creating MBTs?

What sort of base test libraries do you exclusively create for  MBTs?

What difference do you make in your functional base test libraries to better support MBTs?

[A]
We haven't done any/much I&T and use unit testing almost exclusively, seasoned with a bit of system testing. But our focus is clearly on unit testing. I'm pretty strict on the APIs we build/provide, so the assumption is, if it works by itself, it will work in conjunction and there hasn't been much wrong in it yet.
Our models are focused on a single purpose/module with as little dependencies as possible.
The focus is always to start as early as possible (TDD-kinda), but unfortunately we don't always get to it. The problem is, you always have to sell it to management and then it's hard because while testing improves stability (overall QA), the people from the outside (outside of tech) can't really relate to what that means until something bad happened.
Since we use PHP, we employ PHPUnit for the unit tests. All in all, we do CI with various different tools. :)


q:
I have a couple of questions regarding VBScript and ASP Classic:

What is the preferred way to access an MS SQL Server database in VBScript/ASP?

What are best practices in regards to separating model from view from controller?

Any other things I should know about either VBScript or ASP?

If you haven't noticed, I'm new at VBScript coding.  I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.

[A]
ADO is an excellent way to access a database in VBScript/Classic ASP.
```
```
Dim db: Set db = Server.CreateObject("ADODB.Connection")
db.Open "yourconnectionstring -> see connectionstrings.com"
Dim rs: Set rs = db.Execute("SELECT firstName from Employees")
While Not rs.EOF
    Response.Write rs("firstName")
    rs.MoveNext
Wend
rs.Close
```
```
More info here:
http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/
One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query.  Otherwise you will run into problems.
(Reference:
http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html
)


q:
C++ 0x has template aliases (sometimes referred to as template typedefs). See here. Current spec of C++ does not.

What do you like to use as work around ? Container objects or Macros ?
Do you feel its worth it ?

[A]
What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?
The canonical way is to use a metafunction like thus:
```
```
template <typename T>
struct my_string_map {
    typedef std::map<std::string, T> type;
};

// Invoke:

my_string_map<int>::type my_str_int_map;
```
```
This is also used in the STL (
```
allocator::rebind<U>
```
) and in many libraries including Boost. We use it extensively in a
bioinformatical library
.
It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.
(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)


q:
I've always wanted to be able to get a reasonably elegant way of getting vimdiff to work with a CVS controlled file. I've found numerous (somewhat hacky) scripts around the internet (best example here) that basically check out the file you are editing from CVS to a temp file, and vimdiff the two. None of these take into account branches, and always assume you're working from MAIN, which for me is completely useless.

So, my question is this: has anyone out there found a decent solution for this that does more than this script?

Or failing that, does anyone have any ideas of how they would implement this, or suggestions for what features you would consider vital for something that does this? My intention is that, if no one can suggest an already built solution to either use or build from, we start building one from here.

[A]
You could change the call to
```
cvs
```
to take branches into account. That shouldn't be to hard. It bit harder would to change the whole function and make the branch your working a variable (argument, session, global or otherwise).


q:
I am looking for a very fast way to filter down a collection in C#.  I am currently using generic List<object> collections, but am open to using other structures if they perform better.

Currently, I am just creating a new List<object> and looping thru the original list.  If the filtering criteria matches, I put a copy into the new list.

Is there a better way to do this?  Is there a way to filter in place so there is no temporary list required?

[A]
If you're using C# 3.0 you can use linq, which is way better and way more elegant:
```
```
List<int> myList = GetListOfIntsFromSomewhere();

// This will filter ints that are not > 7 out of the list; Where returns an
// IEnumerable<T>, so call ToList to convert back to a List<T>.
List<int> filteredList = myList.Where(x => x > 7).ToList();
```
```
If you can't find the
```
.Where
```
, that means you need to import
```
using System.Linq;
```
at the top of your file.


q:
Do you know if I can use Visio to forward-engineer a sequence diagram into code (c#)?

Can it be done with Visio alone or do I need a plugin?

What about other diagrams?

[A]
To the best of my knowledge, Visio can only forward-engineer code from class models.
As sequence diagrams only really show paths of communication between objects, I suspect that they do not contain the necessary information, except perhaps in trivial cases, for generating code.
Objects with any sort of complex behaviour patterns are likely to involve changing run-time states, of which sequence diagrams aren't really capable of capturing.


q: Over the last few months/years, I have shared a folder or two with numerous people on my domain. How do I easily revoke those shares to keep access to my system nice and tidy?

[A]
On Windows XP, go to:
```
```
Administrative Tools > Computer Management > System Tools > Shared Folders > Shares
```
```
This page lists all shares and lets you remove them easily, in one place.


q: Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.

[A]
System.Net.WebClient
From MSDN:
```
```
using System;
using System.Net;
using System.IO;

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }
        WebClient client = new WebClient ();

        // Add a user agent header in case the
        // requested URI contains a query.

        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }
}
```
```


q: What JavaScript keywords (function names, variables, etc) are reserved?

[A]
We should be linking to the actual sources of info, rather than just the top google hit.
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words
JScript 8.0:
http://msdn.microsoft.com/en-us/library/ttyab5c8.aspx


q: I want to be able to play sound files in my program. Where should I look?

[A]
A bad example:
```
```
import  sun.audio.*;    //import the sun.audio package
import  java.io.*;

//** add this into your application code as appropriate
// Open an input stream  to the audio file.
InputStream in = new FileInputStream(Filename);

// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);

// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);

// Similarly, to stop the audio.
AudioPlayer.player.stop(as);
```
```


q:
C#: What is a good Regex to parse hyperlinks and their description?

Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag.

Please also consider obtaining hyperlinks which have other tags within the <a> tags such as <b> and <i>.

[A]
I found this
but apparently
these guys
had some problems with it.
Edit:
(It works!)
I have now done my own testing and found that it works, I don't know C# so I can't give you a C# answer but I do know PHP and here's the matches array I got back from running it on this:
```
```
Text

array(3) { [0]=> string(52) "Text" [1]=> string(15) "pages/index.php" [2]=> string(4) "Text" }
```
```


q:
I've found an article on this subject by a Microsoft employee, but has anyone implemented a more robust framework for this? Is there a lightweight framework for WinForms that could be ported easily? I'd like to get up to speed fairly quickly and avoid producing a framework/library of my own to handle this when someone smarter has already done this.

I haven't looked at the Mobile Software Factory from the P&P group, but I suspect it's kind of heavy. Is it worth a look?

Edit: I'm not looking for information on the ASP.NET MVC project. I'm asking about the compact framework 'WinForms' implementation, and how to implement MVC with that.

[A]
Edit: The above posters are correct.  I saw MVC and immediately thought of web forms.  My apologies.  Feel free to disregard this.  I'll leave my original message in place just in case anyone who
is
interested in web forms MVC needs the links. :-)
There are a couple MVC frameworks out there, neither of which are very "lightweight", but MVC is a pretty big shift away from web forms so that is expected:
ASP.NET MVC
- This is Microsoft's attempt at an MVC framework.  It is still in preview mode so use it at your own discretion, but several people are already using it in their production applications.  You will find ample documentation on this with a simple Google search as it is becoming very popular amongst the .NET crowd.
Castle MonoRail
- The MonoRail framework is an open-source MVC framework that has been around for quite some time and is in use on several production applications.  It is definitely more flushed out than the ASP.NET MVC framework, but considering the amount of effort Microsoft is throwing at their MVC offering, I think will change relatively soon.


q: Do you know where I could find some useful third party (free) code snippets for VS 2008?

[A]
http://gotcodesnippets.com/
http://www.codekeep.net/
has a VS add-in for their snippets, too


q:
Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?

Doing session.contains(obj) seems to only return true if the session contains that exact object, not another object with the same ID.

Using merge(obj) throws an exception if the object is new

[A]
Have you tried calling .SaveOrUpdateCopy()?
It should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).
Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object.
This should be easy enough to do:
```
```
IPersistable entity = Whatever(); // This is the object we're trying to update
// (IPersistable has an id field)
session.Evict(session.Get(entity.GetType(), entity.Id));
session.SaveOrUpdate(entity);
```
```
Although the above code could probably do with some null checking for the .Get() call.


q:
Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach?

I came across the Design by Contract approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd.

[A]
I can't recommend it highly enough.  It's particularly nice if you have a suite that takes inline documentation contract specifications, like so:
```
```
// @returns null iff x = 0
public foo(int x) {
  ...
}
```
```
and turns them into generated unit tests, like so:
```
```
public test_foo_returns_null_iff_x_equals_0() {
  assertNull foo(0);
}
```
```
That way, you can actually see the tests you're running, but they're auto-generated.  Generated tests shouldn't be checked into source control, by the way.


q:
I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.

How can I do this?

[A]
You can use
```
BindingUtils
```
to get notified when the
```
dataProvider
```
property of the combo box changes:
```
```
BindingUtils.bindSetter(comboBoxDataProviderChanged, comboBox, "dataProvider");
```
```
```
BindingUtils
```
lives in the
```
mx.binding.utils
```
package.
I have a longer description of how to work with
```
BindingUtils
```
here:
Does painless programmatic data binding exist?


q:
I have a habit of keeping my variable usage to a bare minimum.  So I'm wondering if there is any advantage to be gained by the following:

$query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30');

// Example 1
$query = $query->fetch_assoc();

// Example 2
$query_r = $query->fetch_assoc();
$query->free();

Now if I'm right Example 1 should be more efficient as $query is unset when I reassign it  which should free any memory associated with it. However there is a method (MySQLi_Result::free()) which frees associated memory - is this the same thing?

If I don't call ::free() to free any memory associated with the result but unset it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas?

[A]
The
manual
seems to suggest that you should still be using
```
free()
```
to release the memory. I believe the reasoning is that
```
free()
```
is freeing the memory in
MySQL
, not in PHP. Since PHP can't garbage-collect for MySQL, you need to call
```
free()
```
.


q:
My coworker and I have encountered a nasty situation where we have to use an active X control to manipulate a web camera on a page.

Is it possible to assign a javascript event handler to a button in the active x control so that it would fire an action on the page when clicked, or do we have to create a button on the html page itself that manipulates the Active X Control and then can fire any necessary actions on the page?

[A]
Yes! You can throw events in C++/ActiveX land which makes the JavaScript code run an event handler function. I was even able to make an entire invisible ActiveX control (same color as page background) with no buttons or visual feedback that did all of its GUI work through JavaScript and CSS.
edit: Frank's advice is right on.
Here's the link on scripting events.
My strategy was to call a C++ function called MyUpdate (which implements IConnectionPoint) when I wanted to force updates in the browser.
(Also, I made sure to pump Windows messages in the Fire_MyUpdate method because sometimes JavaScript code would call back into C++ land by calling methods on the ActiveX control; this avoids freezing up the browser and ensures that the JavaScript GUI stays responsive, e.g. for a Cancel button.)
On the browser side, the JavaScript code has the global variable referencing the object, followed by "::", followed by the method name:
```
```
function Uploader::MyUpdate()
{
    // ... code to fetch the current state of various
    // properties from the Uploader object and do something with it
    // for example check Uploader.IsActive and show or hide an HTML div
}
```
```


q:
Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it?

Basic detection can be done with the URL itself, such as “http://myblog.blogger.com” etc. But what if it's self hosted?

I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.

[A]
Some blogs provide a Generator meta tag - e.g. Wordpress - you could find out if there's any exceptions to this.
You'll have to be careful how you detect it though, Google surprised me with this line:
```
```
<meta content='blogger' name='generator'/>
```
```
Single quotes are blasphemy.


q:
I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.

Here's what the command line looks like:

test.cmd admin P@55w0rd > test-log.txt

[A]
Yep, and just don't forget to use variables like
```
%%1
```
when using
```
if
```
and
```
for
```
and the gang.
If you forget the double
```
%
```
, then you will be substituting in (possibly null) command line arguments and you will receive some pretty confusing error messages.


q: What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries?

[A]
From SQL BOL:
SET NOCOUNT ON prevents the sending of
  DONE_IN_PROC messages to the client
  for each statement in a stored
  procedure. For stored procedures that
  contain several statements that do not
  return much actual data,
setting SET
  NOCOUNT to ON can provide a
  significant performance boost
, because
  network traffic is greatly reduced.
See
http://msdn.microsoft.com/en-us/library/ms189837.aspx
for more details.
Also, this article on SQLServerCentral is great on this subject:
Performance Effects of NOCOUNT


q: I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems.  But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much.

[A]
I've used mod_rewrite on sites that get millions/hits/month without any significant performance issues. You do have to know which rewrites get applied first depending on your rules.
Using mod_rewrite is most likely faster than parsing the URL with your current language.
If you are really worried about performance, don't use
```
.htaccess
```
files, those are slow. Put all your rewrite rules in your Apache config, which is only read once on startup.
```
.htaccess
```
files get re-parsed on every request, along with
every
```
.htaccess
```
file in parent folders.


q: What libraries/methods do you know of that can do some basic HTML representation in Swing? Can you comment on your experience?

[A]
I haven't tried this in a while, but a quick google search shows some possibilities:
Java Sketchbook: The HTML Renderer Shootout, Part 1
Cobra: Java HTML Renderer & Parser
Are you trying to do this in an applet, or an application?  If it's an application (or signed applet) you could potentially instantiate IE or Firefox within your application.
Webrenderer
acts as a Swing wrapper for this.


q:
Is there any difference between:

if foo is None: pass

and

if foo == None: pass

The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter.  None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right?  Are there any circumstances in which it might?

[A]
```
is
```
always returns
```
True
```
if it compares the same object instance
Whereas
```
==
```
is ultimately determined by the
```
__eq__()
```
method
i.e.
```
```
>>> class Foo(object):
       def __eq__(self, other):
           return True

>>> f = Foo()
>>> f == None
True
>>> f is None
False
```
```


q:
In my web app, I submit some form fields with jQuery's $.getJSON() method. I am having some problems with the encoding. The character-set of my app is charset=ISO-8859-1, but I think these fields are submitted with UTF-8.

How I can set encoding used in $.getJSON calls?

[A]
I think that you'll probably have to use
```
$.ajax()
```
if you want to change the encoding, see the
```
contentType
```
param below (the
```
success
```
and
```
error
```
callbacks assume you have
```
<div id="success"></div>
```
and
```
<div id="error"></div>
```
in the html):
```
```
$.ajax({
    type: "POST",
    url: "SomePage.aspx/GetSomeObjects",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (xhr, textStatus, errorThrown) {
        $("#error").html(xhr.responseText);
    }
});
```
```
I actually just had to do this about an hour ago, what a coincidence!


q: Is there a way to make a TSQL variable constant?

[A]
There are no such thing as "creating a constant" in database literature. Constants exist as they are and often called values. One can declare a variable and assign a value (constant) to it. From a scholastic view:
```
```
DECLARE @two INT
SET @two = 2
```
```
Here @two is a variable and 2 is a value/constant.


q:
I found What are mvp and mvc and what is the difference but it didn't really answer this question.

I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on?

Pros

Display and Processing are seperated

Cons

None so far

[A]
MVC is the separation of
m
odel,
v
iew and
c
ontroller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class.
For example, while a table grid
view
should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the
model
) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the
controller
.
A 'save file' dialog (
view
) ultimately passes the path, once picked by the user, on to the
controller
, which then asks the
model
for the data, and does the actual saving.
This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.


q:
How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example:

--index.aspx
--about.aspx
--contact.aspx
--/feature1
--/feature1/subfeature/action
--/feature2/subfeature/action

I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application.

I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice.

[A]
There isn't any issues with organizing your controllers.  You just need to setup the routes to take the organization into consideration.  The problem you will run into is finding the view for the controller, since you changed the convention.  There isn't any built in functionality for it yet, but it is easy to create a work around yourself with a ActionFilterAttribute and a custom view locator that inherits off ViewLocator.  Then when creating your controller, you just specify what ViewLocator to use, so the controller knows how to find the view.  I can post some code if needed.
This method kind of goes along with some advice I gave another person for separating their views out for a portal using ASP.NET MVC.  Here is the
link to the question
as a reference.


q:
When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed.  Ideally the content would shrink just a bit to make room for the vertical scrollbar.

My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up.  Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all.  But then at least the user doesn't actually need to use the horizontal scrollbar that comes up.

Is there a better way to make this all work?  Some way to keep the unneeded and unwanted scrollbars from showing up at all?

[A]
If your controls are inside a panel, try setting the AutoScroll property of the Panel to False.  This will hide the scrollbars.  I hope this points you in the right direction.
```
```
myPanel.AutoScroll = False
```
```


q:
<servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>workflow.WDispatcher</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>*NEXTEVENT*</url-pattern>
</servlet-mapping>

Above is the snippet from Tomcat's web.xml. The URL pattern *NEXTEVENT* on start up throws

java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping

It will be greatly appreciated if someone can hint at the error.

[A]
```
```
<url-pattern>*NEXTEVENT*</url-pattern>
```
```
The URL pattern is not valid. It can either end in an asterisk or start with one (to denote a file extension mapping).
The url-pattern specification:
A string beginning with a ‘/’ character and ending with a ‘/*’
  suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension
  mapping.
A string containing only the ’/’ character indicates the "default"
  servlet of the application. In this
  case the servlet path is the request
  URI minus the context path and the
  path info is null.
All other strings are used for exact matches only.
See section 12.2 of the
Java Servlet Specification
Version 3.1 for more details.


q:
Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?

This is what I want to re-write:

foreach (Type t in this.GetType().Assembly.GetTypes())
    if (t is IMyInterface)
        ; //do stuff

[A]
loop through all loaded assemblies, loop through all their types, and check if they implement the interface.
something like:
```
```
Type ti = typeof(IYourInterface);
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
    foreach (Type t in asm.GetTypes()) {
        if (ti.IsAssignableFrom(t)) {
            // here's your type in t
        }
    }
}
```
```


q: I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?

[A]
This seems to work, though it is a bit hackish:
```
```
TimeSpan span;

if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))
            MessageBox.Show(span.ToString());
```
```


q: How do you back up your development machine so that in the event of a catastrophic hardware malfunction, you are up and running in the least amount of time possible?

[A]
All important files are in version control (Subversion)
My subversion layout generally matches the file layout on my web server so I can just do a checkout and all of my library files and things are in the correct places.
Twice-daily backups to an external hard drive
Nightly rsync backups to a remote server.
This means that I send stuff on my home server over to my webhost and all files & databases on my webhost back home so I'm not screwed if I lose either my house or my webhost.


q:
I'm using XPath in .NET to parse an XML document, along the lines of:

XmlNodeList lotsOStuff = doc.SelectNodes("//stuff");

foreach (XmlNode stuff in lotsOStuff) {
   XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild");
   // ... etc
}

The issue is that the XPath Query for stuffChild is always returning the child of the first stuff element, never the rest. Can XPath not be used to query against an individual XMLElement?

[A]
```
//
```
at the beginning of an XPath expression starts from the document root.  Try ".//stuffChild".  . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.
So you have:
```
```
XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild");
```
```
which translates to:
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
```
```
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild");
```
```
In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:
```
```
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
```
```
Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild".
```
```
XmlNode stuffChild = stuff.SelectSingleNode("stuffChild");
```
```
The
W3Schools
tutorial has helpful info in an easy to digest format.


q:
I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this:

DataRow row = ds.Tables[0].Rows[0];
string value = (string)row;

What is the best way to deal with DBNull's in this type of situation.

[A]
Nullable types are good, but only for types that are not nullable to begin with.
To make a type "nullable" append a question mark to the type, for example:
```
```
int? value = 5;
```
```
I would also recommend using the "
```
as
```
" keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is
If a type is nullable, the "
```
as
```
" keyword returns
```
null
```
if a value is
```
DBNull
```
.
It's
ever-so-slightly faster than casting
though
only in certain cases
. This on its own is never a good enough reason to use
```
as
```
, but coupled with the reason above it's useful.
I'd recommend doing something like this
```
```
DataRow row = ds.Tables[0].Rows[0];
string value = row as string;
```
```
In the case above, if
```
row
```
comes back as
```
DBNull
```
, then
```
value
```
will become
```
null
```
instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned,
using
```
as
```
will cause your code to silently fail
and make values simple
```
null
```
instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves.


q: I'm currently using the module URI::URL to generate a full URL from a relative URL; however, it isn't running as fast as I'd like it to be. Does anyone know another way to do this that may be faster?

[A]
Perhaps I got the wrong end of the stick but wouldn't,
```
```
$full_url = $base_url . $relative_url
```
```
work? IIRC Perl text processing is pretty quick.
@lennysan
Ah sure yes of course. Sorry I can't help, my Perl is pretty rusty.


q:
Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?

Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a link/button on my site's page that will fill in those values and submit the info without having to copy/paste them across and click the submit button.

Further clarification: How do automated spam bots fill out forms and click the submit button if they were written in C#?

[A]
The code will look something like this:
```
```
WebRequest req = WebRequest.Create("http://mysite/myform.aspx");
string postData = "item1=11111&item2=22222&Item3=33333";

byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;

Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();

WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
```
```


q:
In C#, what is the difference (if any) between these two lines of code?

tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);

and

tmrMain.Elapsed += tmrMain_Tick;

Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?

[A]
I did this
```
```
static void Hook1()
{
    someEvent += new EventHandler( Program_someEvent );
}

static void Hook2()
{
    someEvent += Program_someEvent;
}
```
```
And then ran ildasm over the code.
The generated MSIL was exactly the same.
So to answer your question, yes they are the same thing.
The compiler is just inferring that you want
```
someEvent += new EventHandler( Program_someEvent );
```
-- You can see it creating the new
```
EventHandler
```
object in both cases in the MSIL


q: As someone who hasn't used either technology on real-world projects I wonder if anyone knows how these two complement each other and how much their functionalities overlap?

[A]
Can you clarify what you mean by "LINQ"?
LINQ isn't an data access technology, it's just a language feature which supports querying as a native construct. It can query any object model which supports specific interfaces (e.g. IQueryable).
Many people refer to LINQ To SQL as LINQ, but that's not at all correct. Microsoft has just released LINQ To Entities with .NET 3.5 SP1. Additionally, NHibernate has a LINQ interface, so you could use LINQ and NHibernate to get at your data.


q:
I have been in both situations:

Creating too many custom Exceptions

Using too many general Exception class

In both cases the project started OK but soon became an overhead to maintain (and refactor).

So what is the best practice regarding the creation of your own Exception classes?

[A]
Basically, each job deserves an own exception. When you catch exceptions, you don't distinguish different instances, like you would normally do with objects, therefore you need different subtypes. Using too many custom exceptions is a case which I see hardly occurring.
One advice would be to create exceptions as needed, and if it becomes apparent that one exception type is a duplicate of another, refactor the code by merging the two. Of course it helps if some thought goes into structuring exceptions from the beginning. But generally, use custom exceptions for all cases that have no 1:1 correspondence to existing, situation-specific exceptions.
On the other hand,
```
NullPointerException
```
s and
```
IndexOutofBoundsException
```
s might actually often be appropriate. Don't catch these, though (except for logging) as they're a programming error which means that after throwing them, the program is in an undefined state.


q: When applying the Single Responsibility Principle and looking at a class's reason to change, how do you determine whether that reason too change is too granular, or not granular enough?

[A]
Rewrite your code in a passing style!
Seriously, an old code base will have hundreds of errors - but that's why we have novice/intern programmers. Correcting FxCop violations is a great way to get an overview of the code base and also learn how to write conforming .NET code.
So just bite the bullet, drink lots of caffeine, and just get through it in a couple days!


q:
So you know a lot of Mac apps use "bundles":  It looks like a single file to your application, but it's actually a folder with many files inside.

For a version control system to handle this, it needs to:

check out all the files in a directory, so the app can modify them as necessary

at checkin,

commit files which have been modified

add new files which the application has created

mark as deleted files which are no longer there (since the app deleted them)

manage this as one atomic change

Any ideas on the best way to handle this with existing version control systems?  Are any of the versioning systems more adept in this area?

[A]
Mercurial in particular versions based on file, not directory structure.  Therefore, your working tree, which is a fully-fledged repository, doesn't spit out .svn folders at each level.
It also means that a directory that is replaced, like an Application or other Bundle, will still find it's contents with particular file names under revision control.  File names are monitored, not inodes or anything fancy like that!
Obviously, if a new file is added to the Bundle, you'll need to explicitly add this to your repository.  Similarly, removing a file from a Bundle should be done with an 'hg rm'.
There aren't any decent Mercurial GUIs for OS X yet, but if all you do is add/commit/merge, it isn't that hard to use a command line.


q:
Do any of you know of a tool that will search for .class files and then display their compiled versions?

I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).

[A]
It is easy enough to read the
class file signature
and get these values without a 3rd party API. All you need to do is read the first 8 bytes.
```
```
ClassFile {
    u4 magic;
    u2 minor_version;
    u2 major_version;
```
```
For class file version 51.0 (Java 7), the opening bytes are:
```
```
CA FE BA BE 00 00 00 33
```
```
...where 0xCAFEBABE are the magic bytes, 0x0000 is the minor version and 0x0033 is the major version.
```
```
import java.io.*;

public class Demo {
  public static void main(String[] args) throws IOException {
    ClassLoader loader = Demo.class.getClassLoader();
    try (InputStream in = loader.getResourceAsStream("Demo.class");
        DataInputStream data = new DataInputStream(in)) {
      if (0xCAFEBABE != data.readInt()) {
        throw new IOException("invalid header");
      }
      int minor = data.readUnsignedShort();
      int major = data.readUnsignedShort();
      System.out.println(major + "." + minor);
    }
  }
}
```
```
Walking directories (
File
) and archives (
JarFile
) looking for class files is trivial.
Oracle's
Joe Darcy's blog
lists the
class version to JDK version mappings
up to Java 7:
```
```
Target   Major.minor Hex
1.1      45.3        0x2D
1.2      46.0        0x2E
1.3      47.0        0x2F
1.4      48.0        0x30
5 (1.5)  49.0        0x31
6 (1.6)  50.0        0x32
7 (1.7)  51.0        0x33
8 (1.8)  52.0        0x34
9        53.0        0x35
```
```


q:
I have an old C library with a function that takes a void**:

oldFunction(void** pStuff);

I'm trying to call this function from managed C++ (m_pStuff is a member of the parent ref class of type void*):

oldFunction( static_cast<sqlite3**>(  &m_pStuff ) );

This gives me the following error from Visual Studio:

error C2440: 'static_cast' : cannot convert from 'cli::interior_ptr' to 'void **'

I'm guessing the compiler is converting the void* member pointer to a cli::interior_ptr behind my back.

Any advice on how to do this?

[A]
EDIT: Fixed answer, see below.
Really you need to know what oldFunction is going to be doing with pStuff. If pStuff is a pointer to some unmanaged data you can try wrapping the definition  of m_pStuff with:
```
```
#pragma unmanaged

void* m_pStuff

#pragma managed
```
```
This will make the pointer unmanaged which can then be passed into unmanaged functions. Of course you will not be able to assign any managed objects to this pointer directly.
Fundamentally unmanaged and managed pointers are not the same and can't be converted without some sort of glue code that copies the underlying data. Basically managed pointers point to the managed heap and since this is garbage collected the actual memory address they point to can change over time. Unmanaged pointers do not change the memory address without you explicitly doing so.
Scratch that, you can't define unmanaged / managed inside a class definition. But this test code seems to work just fine:
```
```
// TestSol.cpp : main project file.

#include "stdafx.h"

using namespace System;

#pragma unmanaged

void oldFunction(void** pStuff)
{
    return;
}

#pragma managed

ref class Test
{
public:
    void* m_test;

};

int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");

    Test^ test = gcnew Test();
    void* pStuff = test->m_test;
    oldFunction(&pStuff);
    test->m_test = pStuff;

    return 0;
}
```
```
Here I copy the pointer out of the managed object first and then pass that in by to the oldFunction. Then I copy the result (probably updated by oldFunction) back into the managed object. Since the managed object is on the managed heap, the compiler won't let you pass a reference to the pointer contained in that object as it may move when the garbage collector runs.


q: I have a bunch of perfmon files that have captured information over a period of time. Whats the best tool to crunch this information? Idealy I'd like to be able to see avg stats per hour for the object counters that have been monitored.

[A]
Perhaps look into using
LogParser
.
It depends on how the info was logged (Perfmon doesn't lack flexibility)
If they're CSV you can even use the ODBC Text drivers and run queries against them!
(performance would be 'intriguing')
And here's the obligatory link to a
CodingHorror article
on the topic ;-)


q: Can anyone recommend a library for chart generation (bar charts, pie charts etc.) which runs on both Java and .Net?

[A]
Have you looking into using
JFreeChart
.
I have used it on a few Java projects and its very configurable. Its free but I think you can purchase the developers guide for $50. Its good for quick simple charts too. However performance for real-time data is not quite up to par (Check out the
FAQ
).
They also have a port to
.NET
however I have never used it.
Hope that helps.


q:
I was wondering if I could access the iPhones Core Location framework over a website?

My goal is to build a webapp/website that the iPhone would browse to, then upload its current GPS location. This would be a simple site primary for friends/family so we could locate each other. I can have them manually enter lng/lat but its not the easiest thing to find. If the iPhone could display or upload this automatically it would be great.

I don't own a Mac yet (waiting for the new Mac Book Pro) but would like something a little more automatic right now. Once I have the mac I could download the SDK and build a better version later. For now a webapp version would be great if possible. Thanks.

[A]
I'm pretty sure you can't do what you want directly.
The best idea I can come up with is to "reuse" an iPhone app that records location and makes it accessible on the web. Take Twitter for example. If I'm not mistaken, Tapulous' app Twinkle will grab your location and post it to your Twitter.com user profile. Here's an example of what that looks like:
From your webapp, you could then scrape the user page for each person whose location you're interested in. It's a pain in the butt, but like I said, this is the best I could come up with.
Again, if you don't want to mess with Twitter, there may be other apps out there that do this as well, but I don't personally know of any. Good luck.


q: Can fogbugz track case dependencies?

[A]
Yes and no. Cases can be linked to each other, but if you're looking for a tree of cases (prerequisites and such), you need FogBugz 7 or later.
If you're using FogBugz 7.3 or greater, you can now use the
Case Dependency Plugin
, which was released in April 2011.


q:
I'm comparing between two techniques to create partitioned tables in SQL 2005.

Use partitioned views with a standard version of SQL 2005 (described here)

Use the built in partition in the Enterprise edition of SQL 2005 (described here)

Given that the enterprise edition is much more expensive, I would like to know what are the main benefits of the newer enterprise built-in implementation. Is it just an time saver for the implementation itself. Or will I gain real performance on large DBs?

I know i can adjust the constraints in the first option to keep a sliding window into the partitions. Can I do it with the built in version?


q:
Given a select with multiple option's in jQuery.

$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
       .append("<option>John</option>") //Key = 32
       .append("<option>Paul</option>") //Key = 423

How should the key be stored and retrieved?

The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).

Thanks

and in the spirit of TMTOWTDI.

$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
    $(this).append($("<option/>").val(value).text(text));
};

$select.append($option.val(1).text("Jason").clone())
       .append("<option value=32>John</option>")
       .append($("<option/>").val(423).text("Paul"))
       .addOption("321","Lenny");

[A]
The HTML
```
<option>
```
tag has an attribute called "value", where you can store your key.
e.g.:
```
```
<option value=1>Jason</option>
```
```
I don't know how this will play with jQuery (I don't use it), but I hope this is helpful nonetheless.


q: I'm looking for a method, or a code snippet for converting std::string to LPCWSTR

[A]
If you are in an ATL/MFC environment, You can use the ATL conversion macro:
```
```
#include <atlbase.h>
#include <atlconv.h>

. . .

string myStr("My string");
CA2W unicodeStr(myStr);
```
```
You can then use unicodeStr as an LPCWSTR.  The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.


q:
What kinds of considerations are there for migrating an application from NHibernate 1.2 to 2.0? What are breaking changes vs. recommended changes?

Are there mapping issues?

[A]
Breaking changes in NHibernate 2.0
If you have good test coverage it's busywork.
Edit: We upgraded this morning.  There is nothing major.  You have to Flush() the session after you delete.  The Expression namespace got renamed to Criterion.  All these are covered in the link above.  Mappings need no change.  It's quite transparent.  Oh, and transactions
everywhere
, but you were probably doing that already.
By the way, here's an interesting look at the changes:
http://codebetter.com/blogs/patricksmacchia/archive/2008/08/26/nhibernate-2-0-changes-overview.aspx


q: I know that this should be easy but how do I export/save a DataGridView to excel?

[A] Does it need to be a native XLS file? Your best bet is probably just to export the data to a CSV file, which is plain text and reasonably easy to generate. CSVs open in Excel by default for most users so they won't know the difference.


q: I'm running MAMP 1.7.2 on a Mac and I'd like to install the extension php_gd2.  How do I do this?  I know that on Windows using WAMP I'd simply select the php_gd2 entry in the extensions menu to activate it.  How is it done when using MAMP? I know that I can do it using MacPorts but I'd prefer not to make any changes to my default OS X PHP installation.

[A]
You shouldn't need to install the extension.  I have 1.7.2 installed and running right now and it has GD bundled (2.0.34 compatible).
From the MAMP start page, click on phpinfo and you should see a GD section.


q:
On an 8-bit micro controller I would like to do the following:

16bit_integer = another_16bit_integer * 0.997;

with the least possible number of instructions.

[A]
How about integer arithmetic in 32 bits?
```
```
16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);
```
```
32 bits will be enough to store (INT16_MAX × 997), do the sum on values 1000 times larger then divide back to your 16 bit scale.


q:
I am working on a web application using Python (Django) and would like to know whether MySQL or PostgreSQL would be more suitable when deploying for production.

In one podcast Joel said that he had some problems with MySQL and the data wasn't consistent.

I would like to know whether someone had any such problems. Also when it comes to performance which can be easily tweaked?

[A]
Well, I don't think you should be using a different database brand in anything past development (build, staging, prod) as that will come back to bite you.
From how I understand it PostgreSQL is a more 'correct' database implementation while mySQl is less correct (less compliant) but faster.
So if you are pretty much writing a CRUD application mySQL is the way to go. If you require certain features out of your database (if you're not sure then you don't) then you may want to look into postgreSQL.


q:
I've learned in College that you always have to free your unused Objects but not how you actually do it. For example structuring your code right and so on.
Are there any general rules on how to handle pointers in C++?

I'm currently not allowed to use boost. I have to stick to pure c++ because the framework I'm using forbids any use of generics.

[A]
Rules:
Wherever possible, use a
smart pointer
.  Boost has some
good ones
.
If you
can't use a smart pointer,
null out
your pointer after deleting it
.
Never work anywhere that won't let you use rule 1.
If someone disallows rule 1, remember that if you grab someone else's code, change the variable names and delete the copyright notices, no-one will ever notice.  Unless it's a school project, where they actually check for that kind of shenanigans with quite sophisticated tools.  See also,
this question
.


q: How do I check if an object property in JavaScript is undefined?

[A]
```
```
if (somevariable == undefined) {
  alert('the variable is not defined!');
}
```
```
You can also make it into a function, as shown
here
:
```
```
function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}
```
```


q: Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is this blog entry, but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.

[A]
you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage
p
of the first colour and percentage 1 -
p
of the second:
```
```
R = firstCol.R * p + secondCol.R * (1 - p)
```
```
There's
another question
related to this.
There are other methods of interpolation that sometimes work better. For example, using a
bell-shaped (sigmoidal)
interpolation function makes the transition smoother.
/EDIT: Oops, you mean using a predefined function. OK, even easier. The blog post you linked now has an example code in Python.
In Java, you could use the
```
GradientPaint
```
.


q: The ones that stick out and make life usefull.

[A]
Here is one for a testClass with Nunit support.
```
```
Imports Nunit.FrameWork

    Namespace $NAMESPACE$
    '''
    ''' A TestClass
    '''
    '''
     _
    Public Class $CLASSNAME$

#Region " Setup and TearDown "
        '''
        ''' Sets up the Tests
        '''
        '''
         _
        Public Sub Setup()

            End Sub

        '''
        ''' Tears down the test. Is executed after the Test is Completed
        '''
        '''
         _
        Public Sub TearDown()

        End Sub
#End Region

#Region " Tests "
                '''
        ''' A Test
        '''
        '''
             _
            Public Sub $Test_Name$()

            End Sub
#End Region

    End Class
End Namespace
```
```


q:
I am running oracle and have a query which pulls some results from the database. I would like to write the results as a text file. How would I go about doing this?

My prefered way would be by using UTL_FILE. Would some one have an example of how to do this?

[A]
If you're running the query from
sqlplus
you can use the spool command:
```
spool /tmp/test.spool
```
After executing the spool command within a session, all output is sent to the sqlplus console as well as the /tmp/test.spool text file.


q:
We've been using the 32bit linux version of the JavaServiceWrapper for quite a while now and it's working perfectly. We are now considering also using it on 64bit linux systems. There are downloads for 64bit binaries on the website, but looking into Makefile for the 64bit version I found the following comment, though:
    # This makefile is in progess. It builds, but the resulting libwrapper.so does not yet work.
    # If you know how to fix it then please help out.

Can anyone confirm, that this comment is just outdated and the resulting wrapper will work without flaws?

[A]
From
http://wrapper.tanukisoftware.org/doc/english/introduction.html
:
Binary distributions are provided for
  the following list of platforms and
  are available on the download page.
  Only OS versions which are known to
  work have been listed.
(snip...)
linux - Linux kernels; 2.2.x 2.4.x, 2.6.x. Known to work with Debian and Red Hat, but should work with any
  distribution. Currently supported on
  both 32 and
64-bit
x86, and 64-bit ppc
  systems.


q:
In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?

My instinct is to say that a checked exception would be called for in cases where the caller might be able to recover in some productive way, where as an unchecked exception would be more for unrecoverable cases, but I'd be interested in other's thoughts.

[A]
From
A Java Learner
:
When an exception occurs, you have to
  either catch and handle the exception,
  or tell compiler that you can't handle
  it by declaring that your method
  throws that exception, then the code
  that uses your method will have to
  handle that exception (even it also
  may choose to declare that it throws
  the exception if it can't handle it).
Compiler will check that we have done
  one of the two things (catch, or
  declare).  So these are called Checked
  exceptions.   But Errors, and Runtime
  Exceptions are not checked for by
  compiler (even though you can choose
  to catch, or declare, it is not
  required).  So, these two are called
  Unchecked exceptions.
Errors are used to represent those
  conditions which occur outside the
  application, such as crash of the
  system.  Runtime exceptions are
  usually occur by fault in the
  application logic.  You can't do
  anything in these situations.  When
  runtime exception occur, you have to
  re-write your program code.  So, these
  are not  checked by compiler.  These
  runtime exceptions will uncover in
  development, and testing period.  Then
  we have to refactor our code to remove
  these errors.


q: What issues / pitfalls must be considered when overriding equals and hashCode?

[A]
The theory (for the language lawyers and the mathematically inclined):
```
equals()
```
(
javadoc
) must define an equivalence relation (it must be
reflexive
,
symmetric
, and
transitive
). In addition, it must be
consistent
(if the objects are not modified, then it must keep returning the same value). Furthermore,
```
o.equals(null)
```
must always return false.
```
hashCode()
```
(
javadoc
) must also be
consistent
(if the object is not modified in terms of
```
equals()
```
, it must keep returning the same value).
The
relation
between the two methods is:
Whenever
```
a.equals(b)
```
, then
```
a.hashCode()
```
must be same as
```
b.hashCode()
```
.
In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute
```
equals()
```
to compute
```
hashCode()
```
.
Use the excellent helper classes
EqualsBuilder
and
HashCodeBuilder
from the
Apache Commons Lang
library. An example:
```
```
public class Person {
    private String name;
    private int age;
    // ...

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
            // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}
```
```
Also remember:
When using a hash-based
Collection
or
Map
such as
HashSet
,
LinkedHashSet
,
HashMap
,
Hashtable
, or
WeakHashMap
, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable,
which has also other benefits
.


q:
I've deployed some Managed Beans on WebSphere 6.1 and I've managed to invoke them through a standalone client, but when I try to use the application "jconsole" distributed with the standard JDK can can't make it works.

Has anyone achieved to connect the jconsole with WAS 6.1?

IBM WebSphere 6.1 it's supossed to support JSR 160 JavaTM Management Extensions (JMX) Remote API. Furthermore, it uses the MX4J implementation (http://mx4j.sourceforge.net). But I can't make it works with neither "jconsole" nor "MC4J".

I have the Classpath and the JAVA_HOME correctly setted, so the issue it's not there.

[A]
I have successfully connected to ActiveMQ and ServiceMix using the JConsole. Does WAS 6.1 use Java Management Extension (JMX) technology? JMX is required for JConsole.
If your path is set correctly it should work fine. On windows you go to System Properties -> Advanced Tab -> Environment Variables. Have your JAVA_HOME System variable set to the path of your JDK or JRE and your Path variable with %JAVA_HOME%/bin added somewhere in there. Then all you need to do is go to Start->Run->JConsole. Select the correct Process Name and your done.
Where are you having problems at? I hope this helps.
Edit:
Here is the Java Doc's on
JConsole
.


q:
Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:

find_if(serverNames.begin(), serverNames.end(), ContactServer());

Where ContactServer is a predicate function object.

On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (i.e. the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.

What do you say?

[A]
I think I would go for it.
The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like "Find the first server I can contact", which makes perfect sense.
You might want to rename
```
ContactServer
```
to indicate that it is a predicate;
```
CanContactServer
```
? (But then people would complain about hidden side effects. Hmm...)


q:
On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?

Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.

Example: I need to copy every .txt file in the following hierarchy

/foo/a.txt
/foo/x.jpg
/foo/bar/a.txt
/foo/bar/c.jpg
/foo/bar/b.txt

To a folder named 'dest' and get:

/dest/a.txt
/dest/b.txt

[A]
In bash:
```
```
find /foo -iname '*.txt' -exec cp \{\} /dest/ \;
```
```
```
find
```
will find all the files under the path
```
/foo
```
matching the wildcard
```
*.txt
```
, case insensitively (That's what
```
-iname
```
means). For each file,
```
find
```
will execute
```
cp {} /dest/
```
, with the found file in place of
```
{}
```
.


q:
The TRACE macro can be used to output diagnostic messages to the debugger when the code is compiled in Debug mode. I need the same messages while in Release mode. Is there a way to achieve this?

(Please do not waste your time discussing why I should not be using TRACE in Release mode :-)

[A]
In MFC, TRACE is defined as ATLTRACE. And in release mode that is defined as:
```
```
#define ATLTRACE            __noop
```
```
So, using the out-the-box TRACE from MFC, you won't actually be able to read any TRACE text, because it won't even be written out. You could write your own TRACE function instead, then re-define the TRACE macro. You could do something like this:
```
```
void MyTrace(const CString& text)
{
  ::OutputDebugString(text); // Outputs to console, same as regular TRACE
  // TODO: Do whatever output you need here. Write to event log / write to text file / write to pipe etc.
}
```
```


q:
We currently maintain a suit of MFC applications that are fairly well designed, however the user interface is beginning to look tired and a lot of the code is in need quite a bit of refactoring to tidy up some duplication and/or performance problems.  We make use of quite a few custom controls that handle all their own drawing (all written using MFC).

Recently I've been doing more research into Qt and the benefits it provides (cross-platform and supports what you might call a more "professional" looking framework for UI development).

My question is - what would be the best approach to perhaps moving to the Qt framework?  Does Qt play nice with MFC?  Would it be better to start porting some of our custom controls to Qt and gradually integrate more and more into our existing MFC apps? (is this possible?).

Any advice or previous experience is appreciated.

[A]
(This doesn't really answer your specific questions but...)
I haven't personally used Qt, but it's not free for commercial Windows development.
Have you looked at
wxWindows
which is free? Nice article
here
. Just as an aside, if you wanted a single code base for all platforms, then you may have to migrate away from MFC - I am pretty sure (someone will correct if wrong) that MFC only targets Windows.
One other option would be to look at the
Feature Pack update
to MFC in SP1 of VS2008 - it includes access to new controls, including the Office style ribbon controls.


q:
I'm having a problem obtaining the total row count for items displayed in a Gridview using Paging and with a LinqDataSource as the source of data.

I've tried several approaches:

protected void GridDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
    totalLabel.Text = e.TotalRowCount.ToString();
}

returns -1 every time.

protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
    System.Collections.Generic.List<country> lst  = e.Result as System.Collections.Generic.List<country>;
    int count = lst.Count;
}

only gives me the count for the current page, and not the total.

Any other suggestions?

[A]
The LinqDataSourceEventArgs returned in those events return -1 on these occasions:
-1 if the LinqDataSourceStatusEventArgs object was created during a data modification operation; -1 if you enabled customized paging by setting AutoPage to true and by setting RetrieveTotalRowCount to false.
Check here for more information
- the table towards the bottom, shows different properties to set to get the rowcount back, but it looks like you either have to set AutoPage and AllowPage properties to either both true or both false.
Judging by the table in the link above and the example you provide you have Autopage set to false, but AllowPaging set to true, therefore it is returning the amount of rows in the page.
HTH


q: I completely understand the concept of expression trees, but I am having a hard time trying to find situations in which they are useful. Is there a specific instance in which expression trees can be applied? Or is it only useful as a transport mechanism for code? I feel like I am missing something here. Thanks!

[A]
Some unit test mocking frameworks make use of expression trees in order to set up strongly typed expectations/verifications. Ie:
```
```
myMock.Verify(m => m.SomeMethod(someObject)); // tells moq to verify that the method
                                              // SomeMethod was called with
                                              // someObject as the argument
```
```
Here, the expression is never actually executed, but the expression itself holds the interesting information. The alternative without expression trees would be
```
```
myMock.Verify("SomeMethod", someObject) // we've lost the strong typing
```
```


q:
An app I'm writing always crashes on a clients computer, but I don't get an exception description, or a stack trace.

The only thing I get is a crash report that windows wants to send to Microsoft.

I would like to get that dump file and investigate it myself, but I cannot find it.

When I "View the contents of the error report" I can see the different memory dumps, but I cannot copy it or save it.

[A]
You can use the
Windows debugging tools
to view the crash dump. To get the most use out of it, you'll need an exact copy of the symbols for that application (i.e. same version).
Have a look at
Tess's blog
for tutorials on how to use the Windows debugging tools. I refer to her blog constantly whenever I'm in need of analysing crash dumps.