q:
I'm looking into integrating jBPM with my current project, so far so good just including the  jpdl jar in my ear and using the spring modules 0.8 jbpm module, however I've got to have a reasonable way of going from my changes to to the process definition in the designer to deployment in production.

The path has to be repeatable in a number of environments (dev, many test, staging and then prod) and ideally should be done while the system itself is not running.

I'd Ideally package the entire definition as an SQL script, however I haven't seen any tool to translate from processdefinition.xml to sql and assembling it all manually seems too fiddly and error prone.

Has anyone else out there had any experiences here?

The system is running on websphere 6.1 and it's my preference to avoid executing java code at migration time (running java code to generate artifacts that can then be used during migration is ok though)

[A]
Why not use the ant task extensions provided by JBPM specifically
```
DeployProcessTask
```
. You can deploy to different environments having just a single
```
.par
```
file and the corresponding
```
jbpm-cfg.xml
```
for the various dev/test/staging/prod environments. The only change you might have to do is to configure your hibernate config to directly connect to the database instead of using the datasource.


q:
I've come across the problem where Excel will not play nice with UTF-8 encoded CSV files. See this related question on Stack Overflow.

I've followed the solution of exporting as UTF-16, however it seems that with UTF-16, the comma character doesn't work as a delimiter, only the tab character.

However I can't find anywhere what the correct filename and mime-type should be for tab-delimited files. I found somewhere stating that it was application/vnd.ms-excel and xls. This works ok for Excel 2003 but 2007 does not approve.

So what should it be?

[A]
For tab-delimited files,
http://www.rfc-editor.org/rfc/rfc4180.txt
mentions 'text/tab-separated-values'.
That format is (sparsely) described at
http://www.iana.org/assignments/media-types/text/tab-separated-values
.
More info can be found at :
http://www.cs.tut.fi/~jkorpela/TSV.html
I hope this helps?

s: huggingface

c: devops

d: intermediate


q:
I figure this problem is easier than just a regular spell checker since the list of U.S cities is small compared to all known English words.

Anyhow, here's the problem:
I have text files with full of city names; some of which are spelled correctly and some which aren't.

What kind of algorithm can I use to correct all the misspellings of city names?

[A]
Do you actually need to correct the misspellings or just flag them as with a normal spell checker?  If the latter, you just need to obtain a list of correct spellings and make sure each name is the same as one in your list.
If you want to actually correct them, you probably want to use the concept of
edit distance
to compare the similarity of misspelled strings to those in your reference list.  Then you can replace the misspelled word with the closest match.  You may also want to handle the possibility that the intended city is not in your list.
The
Levenshtein distance
Wikipedia article is another good resource.


q:
Is there a way (in C#) to access the systray?
I am not talking about making a notify icon.
I want to iterate through the items in the tray (I would guess through the processes but I don't know how to determine what is actually in the tray and what is just a process) and also represent the items with their icons in my own ui.

[A]
Mathias Rauen's madCollection (for Delphi not c#) can list
Tray Icons
.
And there is a commandline tool:
Windows System Tray Scan Utility
I have also written (not released) my own program in Delphi (not Delphi.NET), not using madCollection, which shows tray icons, process names, tooltips and other info but it's not perfect. There are a few icons it can't display (even though it lists other info), and it can't display any icons under windows 9x. I haven't tested it at all under Vista.


q:
Sometimes I need to access some servers running Linux (or maybe another Unix-like SO), but I don't know how to verify which distribution is in use on the server (there are times that even the "responsible" person for the server doesn't know).

Is there an easy and reliable way to discover that, one that is uniform and consistent across all of them?

[A]
Try
```
uname -a
```


q:
I am calling an unmanaged C++ dll that expects a char* as one of its parameters and I want to push a byte[] into it.  The project is written in VB.NET.

What type of marshalling will work for this?

[A]
I'm not a .net expert, but I've needed to do something similar recently.
It is not just a matter of serialization, you also have to stop the garbage collector from cleaning up your byte array while it is being used in C++ land...
The below snippet of C# should help.
```
// pin the byte[] (byteArray)
GCHandle handle = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();
// Do your C++ stuff, using the address pointer.

// Cleanup
handle.Free();
```


q: Is there a way to delete a folder, lets call it FolderX from an SVN trunk recursively? A quick search on google only tells me how to recursively delete all .svn folders and this is not what I want to do

[A]
Try something like the following on a posix system:
```
```
find ./ -name "FolderX" | xargs svn delete --force
```
```
This will find all matching files/folders starting in the current directory and perform the action on them i.e. svn delete. I'm not sure how to do this in windows though without cygwin.
For win32, the commenter below suggests a similar solution (cmd):
```
```
for /R . %1 in (*.EXT) do svn delete %1
```
```


q:
I'm not sure how to describe this problem, so I think an example is the best way to ask my question:

I have two tables with a manyToMany relationship:

DriversLicence <-> LicenceClass

LicenceClass is things like "Car", "Motorbike", and "Medium Rigid".

Using Hibernate Criteria, how can I find all licences that have both "Car" and "Motorbike" LicenceClasses?

UPDATE 12/11/2008
I have discovered that this can easily be achieved by using a custom ResultTransformer. However the problem is that a result transformer only gets applied AFTER the query returns its results, it does not actually become part of the SQL. So I guess my question is now "Can you do what I initially described in SQL - and is there a Hibernate Criteria analog?"

[A]
You can still use dot notation to work across the relations.  For example, assuming you have a DriversLicence.licenceClass property and LicenceClass.type property, then:
```
```
session.createCriteria(DriversLicence.class)
   .add(Expression.or(
     Expression.eq("licenceClass.type", "Car"),
     Expression.eq("licenceClass.type", "Motorbike")
   )
).list();
```
```
Personally though, I'd simply avoid using criteria in this case because it's not a dynamic query, but instead use:
```
```
session.createQuery("from DriversLicence where licenceClass.type in (:types)")
  .setParameterList("types", myListOfTypes)
  .list();
```
```


q:
let us have a situation in which the following program prints some 10 lines of #

for(i=0;i<10;i++)
prinf("\n#");

now how to go back to 5 th line and edit that # and change the color of it without clearing the screen or clearing the below 5 lines?

I have tried

window(5,0,20,20);
textcolor(GREEN);
cprintf("#");

but it is not editing that one but it is printing on the side of the original one.why?

is there any other way of doing it and changing the color of the already printed text dynamically?
please help me..my environment is turbo c on windows

[A]
maybe-
```
```
cprintf("\b#");
```
```
'b' is for backspace


q: Is there a reason to sort MultiMap in Java and how to do that?

[A]
Assuming you're talking about
```
org.apache.commons.collections.MultiMap
```
, then you can't; since it returns a
```
Collection
```
and not a
```
List
```
, it doesn't support the concept of order.
If you are talking about
```
org.apache.commons.collections.MultiHashMap
```
, then all you need to do is iterate over the keys, take the
```
ArrayList
```
returned and sort it using
```
Collections.sort()
```
.
That's assuming you are using
that implementation though
.
There is nothing stopping you from implementing your own
```
MultiMap
```
fairly easily though, that supports sorting lists. It may be as easy as
```
HashMap<K, Collection<V>>
```
, I'm not familiar with how MultiMaps work.


q:
I'm doing some searching of tags, and some users like "cat" while others like "Cat"  Go figure...

Anyways, is there a way to force a particular find to be case sensitive?  Such as:

Tag.find(:some-special-option-here)

Any ideas?

[A]
In the mysql database, set your text's data type to utf_collate_bin. For example:
```
```
ALTER TABLE `sets` CHANGE `set_name` `set_name` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL
```
```
Where 'sets' is the table, 'set_name' is the column of type VARCHAR(64). You can also do this in PhpMyAdmin..
Any binary collate will do the job; but utf8 is preferable.
If you were wondering what the _ci at the end of your current collate is, it means "Case Insensitive" :p


q:
I'm building my app in vc2008 and testing it on a network of machines.

Is there any way, other than installing Visual Studio 2008, to run a debug build of a C++ program on another machine? (i.e. that doesn't have vc2008 installed)

Installing the redist package only installs the release mode support DLL's for vc2008 programs. Currently it complains that "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.", which I assume is code for "I'm missing DLL's".

[A]
You can't, because there's no installer redist for the debug runtime (and in fact the software license forbids distributing it, so you'd be breaking the EULA even if you did get something put together). However, a "debug build" generally involves 4 separate options, and the other 3 don't affect distributing the app.
Generating a .pdb file (cl /Zi and link /DEBUG), which allows symbolic debugging. You probably want to add /OPT:ref to the linker options; the linker drops unreferenced functions when not making a .pdb file, but with /DEBUG mode it keeps them all (since the debug symbols reference them) unless you add this expicitly.
I generally do this with all my builds, even production ones. As long as you turn the linker optimizations back on with /OPT:ref it doesn't really cost anything, and having the symbols can be handy if you end up wanting to read a crash dump.
Using a debug version of the C runtime library (probably MSVCR*D.dll, but it depends on what runtime you're using). This boils down to /MT or /MTd (or something else if not using the dll runtime).
This is the one that means you can't redistribute things anymore. It also has a huge impact in the performance of some libraty functions, particularly memory allocation. The debug runtime versions are careful to "poison" the memory they touch with values to make uninitialized data bugs clear, the release ones generally leave the old data round to save the time touching it. I believe with the MSVCP* STL implementations the debug verions also omit all the allocation pooling that is usually done, so that a leak checker can show exactly the block you'd think and not some larger chunk of memory that it's been sub-allocating, but that means it makes more calls to malloc on top of them being much slower. If you have pointer or iterator handling bugs, this could affect what sort of misbehavior you get.
Turning off the compiler optimizations (/Od).
This one does lots of things (
this question
has some good discussion of the subject), but basically it hurts performance. A lot. Unfortunately, it's needed if you want single-stepping to work smoothly.
setting the preprocessor #defines DEBUG or NDEBUG.
This affects lots of libraries in various ways, but most notable it compiles in or eliminates assert() and friends.
So you might consider making a build with some lesser combination of these selections. I make a lot of use of builds that use have symbols (/Zi and link /DEBUG) and asserts (/DDEBUG), but are still optimized (/O1 or /O2 or whatever flags you use) but with stack frame pointers kept for clear backtraces (/Oy-) and using the normal runtime library (/MT). This performs close to my release build and is semi-debuggable (backtraces are fine, single-stepping is a bit wacky at the source level; assembly level works fine of course). You can have however many configurations you want; just clone your release one and turn on whatever parts of the debugging seem useful.
The only one that should impact trying to redistribute the app is 2.
If you're trying to debug on another machine, you might also be interested in
msvsmon
.


q:
I've found the "open" command in Mac OS X very handy in the command line. From "man open":

The open command opens a file (or a directory or URL), just as if you had
      double-clicked the file's icon. If no application name is specified, the
      default application as determined via LaunchServices is used to open the
      specified files.

That is, if I want to open a PDF file with the default PDF viewer (happens to be Preview), I only need to do:

open my.pdf

In Linux, however, to open a PDF file from the command line, I had to dig around to find the default PDF viewer is, for instance, "evince" (who'd have guessed??), and then

evince my.pdf

So, is there a simple equivalent of the 'open' command in the Linux command line?

Thanks!

[A]
You could try
```
xdg-open
```
, most Linux distros have it. It will open default associated app for your file.
FYI
https://portland.freedesktop.org/doc/xdg-open.html


q:
I have used this in my HTML:

<q> Hai How r u </q>

Which shows the text in quotes, like "Hai How r u", for example.

This is working fine in FF but not in IE 6.0.

Please let me know why this happens, and any solutions you might know of.

I don't want to use the quote (") character in my HTML or a separate css file for this.

[A]
Why don't you just use the
```
"
```
characters? Unlike
```
<b>
```
and
```
<i>
```
which should be replaced by strong and emphasis respectively, as appropriate, the quote tag has a direct match in meaning to the quote character. There should be no need to use
```
<q>
```
.
Edit
: Thanks for clarifying the question Yan.
OP: Is there a specific reason you don't want to use the quotes? The stuff I said earlier still holds, but perhaps we can help with the problem preventing you from using quotes.
Edit 2
: :|


q: I am using BSD style pty/tty pairs to implement running a sub shell.  When the user exits the sub shell, how do I detect in the master process that this has occurred?  I am using select(nfds, &read_fds, NULL, NULL, &timeout); with the master pty file descriptor set in the read_fds on the master side.

[A]
The subshell is typically created by a
```
fork()
```
of some sort.  The PID of the child is returned to the master, which can check (with
```
waitpid()
```
, perhaps) if it's still running.


q:
I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur.

For what it is worth, these objects are usually retrieved from the server as JSON and typically are no more than a handful of layers deep (i.e. it may be an array of objects that themselves have data and then arrays with other data objects).

I want to not only see the changes to basic properties, but differences in the number of members of an array, etc. etc.

If I don't get an answer, I will probably end up writing this myself, but hope someone has already done this work or know of someone who has.

EDIT: These objects will typically be very close in structure to one another, so we are not talking about objects that are utterly different from one another, but may have 3 or 4 deltas.

[A]
Here is a partial, naïve solution to my problem - I will update this as I further develop it.
```
```
function findDifferences(objectA, objectB) {
   var propertyChanges = [];
   var objectGraphPath = ["this"];
   (function(a, b) {
      if(a.constructor == Array) {
         // BIG assumptions here: That both arrays are same length, that
         // the members of those arrays are _essentially_ the same, and
         // that those array members are in the same order...
         for(var i = 0; i < a.length; i++) {
            objectGraphPath.push("[" + i.toString() + "]");
            arguments.callee(a[i], b[i]);
            objectGraphPath.pop();
         }
      } else if(a.constructor == Object || (a.constructor != Number &&
                a.constructor != String && a.constructor != Date &&
                a.constructor != RegExp && a.constructor != Function &&
                a.constructor != Boolean)) {
         // we can safely assume that the objects have the
         // same property lists, else why compare them?
         for(var property in a) {
            objectGraphPath.push(("." + property));
            if(a[property].constructor != Function) {
               arguments.callee(a[property], b[property]);
            }
            objectGraphPath.pop();
         }
      } else if(a.constructor != Function) { // filter out functions
         if(a != b) {
            propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b });
         }
      }
   })(objectA, objectB);
   return propertyChanges;
}
```
```
And here is a sample of how it would be used and the data it would provide (please excuse the long example, but I want to use something relatively non-trivial):
```
```
var person1 = {
   FirstName : "John",
   LastName : "Doh",
   Age : 30,
   EMailAddresses : [
      "john.doe@gmail.com",
      "jd@initials.com"
   ],
   Children : [
      {
         FirstName : "Sara",
         LastName : "Doe",
         Age : 2
      }, {
         FirstName : "Beth",
         LastName : "Doe",
         Age : 5
      }
   ]
};

var person2 = {
   FirstName : "John",
   LastName : "Doe",
   Age : 33,
   EMailAddresses : [
      "john.doe@gmail.com",
      "jdoe@hotmail.com"
   ],
   Children : [
      {
         FirstName : "Sara",
         LastName : "Doe",
         Age : 3
      }, {
         FirstName : "Bethany",
         LastName : "Doe",
         Age : 5
      }
   ]
};

var differences = findDifferences(person1, person2);
```
```
At this point, here is what the
```
differences
```
array would look like if you serialized it to JSON:
```
```
[
   {
      "Property":"this.LastName",
      "ObjectA":"Doh",
      "ObjectB":"Doe"
   }, {
      "Property":"this.Age",
      "ObjectA":30,
      "ObjectB":33
   }, {
      "Property":"this.EMailAddresses[1]",
      "ObjectA":"jd@initials.com",
      "ObjectB":"jdoe@hotmail.com"
   }, {
      "Property":"this.Children[0].Age",
      "ObjectA":2,
      "ObjectB":3
   }, {
      "Property":"this.Children[1].FirstName",
      "ObjectA":"Beth",
      "ObjectB":"Bethany"
   }
]
```
```
The
```
this
```
in the
```
Property
```
value refers to the root of the object that was compared. So, this solution is not yet
exactly
what I need, but it is pretty darn close.
Hope this is useful to someone out there, and if you have any suggestions for improvement, I am all-ears; I wrote this very late last night (i.e. early this morning) and there may be things I am completely overlooking.
Thanks.


q:
Apple strongly recommends using the binary plist format when reading large XML-based data sets into iPhone apps. Among their reasoning is the fact that XML parsing is very taxing on the iPhone. However, this requires that files residing on the remote web server be converted first.

For frequently-changing content, it is not acceptable to do this manually. If at all possible, I'd like to avoid having a web based app call the command line to perform the conversion (i.e., plutil).

Are there publicly available algorithms to perform this conversion?

[A]
It's not clear if you want to do the conversion on the iPhone or on the server. If it's on the server and you can use the Cocoa frameworks, the
```
NSPropertyListSerialization
```
provides services to convert between the supported plist types (string, XML, and binary) on OS X (since 10.2). There are also analogous methods in the Core Foundation library if you'd prefer to use that instead.
To convert an XML plist to a binary one:
```
```
NSString *xmlPlistPath; // already set
NSString *outPath; // already set

NSData *plistData;
NSString *error;
NSPropertyListFormat format;
id plist;
plistData = [NSData dataWithContentsOfFile:xmlPlistPath];

plist = [NSPropertyListSerialization propertyListFromData:plistData
                                         mutabilityOption:NSPropertyListImmutable
                                                   format:&format
                                         errorDescription:&error];

if(plist == nil) { // unable to parse plist
    //deal with failure -- error gives description of the error
} else {
    binaryPlistData = [NSPropertyListSerialization dataFromPropertyList:plist
                                                                 format:NSPropertyListBinaryFormat_v1_0
                                                       errorDescription:&error];
    if(binaryPlistData == nil) {//unable to create serialized plist
         // deal with failure -- error gives description of the error
    }

    if(![binaryPlistData writeToFile:outPath atomically:YES]) {
        // unable to write file
    }
}
```
```
See
Property List Pramming Guide
page on developer.apple.com for more information.


q:
function array_value_from_key($array,$key)
{
     return !empty($array[$key]) ? $array[$key] : null;
}

The reason I ask is because I have a class function that returns an array.

Instead of having to do

$myArray = myClass::giveMeArray();
$myValue = $myArray[$myKey];

I'd like to do something along the lines of

$myValue = array_value_from_key(myClass::giveMeArray(),$myKey);

When an object is returned, you can chain the object such as

$myValue = myClass::giveMeObject()->aValue;

Voila, nice and clean..  not being able to find what seems to be a simple and trivial function is driving me crazy...

PS.. one more example of how I'd like to use such a function

if(arrayKeyVal(aClass::giveMeArray(),$myKey)) {
    do_something();
}

[A]
I haven't tried it, but:
```
```
$myValue = @$myArray[$myKey];
```
```
might work, though i honestly think you would be better off using
```
```
$myValue = (array_key_exists($myKey, $myArray)) ? $myArray[$myKey] : null;
```
```


q: After much googling I have been wondering what the benefits/differences are between mysql and sqlite3. I am primarily hoping for a speed bump when moving my development database to my production database, although I imagine this will primarily happen in my code. Does any know what the major differences are in performance? ARE there? Or would you be able to point me in the direction of some literature comparing the two?

[A]
I'm hoping that from your question, you aren't talking about using a different database system in development and production.
If you are using a different DB in development and production, DON'T. Different database engines behave differently and will cause unexpected bugs to appear. Try to get your development system as close to production as you possibly can (hint: run it in a VM)
SQLite and MySQL are both fine products in the right context. Understand what their capabilities are.
SQLite:
Runs in-process with the client application
No network capability
Very low query overhead because of this
Potentially rather fast for easy queries because there is less IPC, system calls and data copying to do.
Very limited concurrency (I think it's either one writer or multiple readers, per database file)
MySQL:
Far more features
Choice of engines (InnoDB provides good features for many workloads)
Much more control of storage, backup, restore etc
Network-capable - which allows its use in large scale applications
Better concurrency - the InnoDB engine has MVCC which means that readers do not block writers, nor do writers block readers. Even the old MyISAM engine has table-level locking rather than for the whole database as sqlite.
Probably a better optimiser for complicated queries
In short, you can't really compare them like-for-like. SQLite is quite popular as an embedded database - Firefox 3 has one inside it.
In SQLite, you're stuck on storing your database on a local disc (or of course, network disc, if one is available). If you want to scale your web application, you'll probably have to use a server-based database such as MySQL.


q:
Does anyone know of a good Java API for controlling RS-232 devices in a WIN32 enviroment?
I've tried RXTX but they don't support RS232, only RS-485.

[A]
What about
J/CoMM
?
OS independent RS232 remote control. Java-based server (console), easy adjustable HTML GUI, local/internet use, incl. device driver API and drivers (e.g. EIKI LC-XM1/SM1/VM1!!)


q:
My php is weak and I'm trying to change this string:

http://www.example.com/backend.php?/c=crud&m=index&t=care
                                   ^

to be:

http://www.example.com/backend.php?c=crud&m=index&t=care
                                  ^

removing the / after the backend.php?. Any ideas on the best way to do this?

Thanks!

[A]
```
```
$str = preg_replace('/\?\//', '?', $str);
```
```
Edit: See CMS' answer. It's late, I should know better.


q:
I am not able to access localhost https pages in firefox3. It gave the error

'Can't connect securely because the SSL protocol has been disabled.
  (Error code: ssl_error_ssl_disabled)'

I enabled all the SSL2 related preferences through about:config and the error changed to

'Data Transfer Error
  The browser connected successfully, but the connection was interrupted while transferring information.  Please try again.'

The first error seems most likely due to a invalid certificate but can't figure out the second...


q:
I've got an application that's using string.compare(string,string) to sort some values.  The thing I can't figure out is why "1022" compares as less than "10-23" and "10-23" compares as less than "1024".

Is there something specific to the value of "-" that causes this result?  Will that overload of string.compare give the same result with different culture settings for the same type of data (numbers with dashes)?

[A]
Well, ignoring the dashes is fairly innocent. If you want to include them, perhaps use
```
StringComparison.Ordinal
```
in the overload.
Reading the
docs for
```
string.Compare
```
, it uses word sort rules, which from
here
means :
Word sort performs a culture-sensitive
  comparison of strings. Certain
  nonalphanumeric characters might have
  special weights assigned to them. For
  example, the hyphen ("-") might have a
  very small weight assigned to it so
  that "coop" and "co-op" appear next to
  each other in a sorted list.
At least it is transitive: I logged a
bug
with "connect" about something very similar involving dashes - where A < B, B < C
and
C < A. since a non-transitive comparison essentially breaks the rules of sorting. It was closed "will not fix". Here it is:
```
```
string s1 = "-0.67:-0.33:0.33";
string s2 = "0.67:-0.33:0.33";
string s3 = "-0.67:0.33:-0.33";
Console.WriteLine(s1.CompareTo(s2));
Console.WriteLine(s2.CompareTo(s3));
Console.WriteLine(s1.CompareTo(s3));
```
```
(returns 1,1,-1 on my machine)


q:
When running an integration test (Web Service talking to JDBC, in this case) how do you force the database to throw an error so that the resulting soap fault can be inspected?

I'm using Spring's Transactional Test Framework, so would be unreasonable to just issue a DROP TABLE whatever; to break it? :D

[A]
In my experience, this is an excellent use for mock objects. Specifically cases where you need to cause a specific failure in order to test how your object, in the case of a unit test, or set of objects, in the case of integration tests, will handle a particular failure. It is better to be in complete control of the failure rather than forcing a specific case of the failure in your integration tests.
I recently worked with an entity framework where I encountered a similar dilemma. By creating mock objects for the entities I was able to force an exception to be thrown during on method calls while running certain tests in order to test failure conditions interacting with the database. This isn't an answer that deals with Spring's Transactional Framework, but I am sure the same principles apply.


q:
Is there such a thing?

I'm talking about something like a C++ new command i.e. allocation of memory which necessitates explicit releasing of the memory (or risk memory leaks).

I ask because I remember having to solve some GDI leak problems previously by setting forms/controls/other objects to Nothing but can't remember what or why now...

Do we ever have to worry about memory management when developing in VB6?

[A]
I'd like to say you never have to worry about memory management, but it's not quite true.  It depends to some extent on the execution environment that your VB6 code is running in.  I have certainly seen VB6 classes running under COM+ that would leak memory if they didn't explicitly set object references to Nothing when finished with them.
Environmental issues aside, memory that you allocate within the VB6 type system will generally be cleaned up for you.  I'm talking about things you allocate with the New keyword.  But there is a significant exception, pointed out by rpetrich and others: -
Because of the reference-counting mechanism that VB uses to manage the lifetime of allocated objects, it is possible to leak memory if you have any cyclic references.  For example, A->B->C->A.  If you have that kind of scenario you'll probably need to spot it yourself and cure it by explicitly setting references to Nothing.  I am not aware of any tools that help much with identifying this kind of problem.
Further problems come in when you're using libraries written in other languages.  You might New-up a COM object written in C++ that allocates some memory internally, and find that you have to call a particular method (such as Close) to free that memory.  Maybe such a COM object would be badly-written, but plenty of them exist.
So there are no rules to follow, except perhaps: -
Try to know as much as possible about the behaviour of any libraries you use, and
Always run your code while watching a memory trace in Performance Monitor to make sure its memory usage isn't growing in an unbounded fashion.
Try to be aware of cyclic references ;-)


q: How to move a sub directory from one directory to another, given that both are inside the same SVN repository? I am using tortoise SVN.

[A]
Select the folder/files that you want to move, then RIGHT-CLICK them and drag them to where you want to move them.  A menu will come up with an option "
SVN Move versioned files here
"
As clarified by
phenry
, the destination folder must be recognized as an SVN folder.  The folder should already be committed to the repository or you can choose Add to set it to be added.
If the destination folder isn't part of an SVN repository, use the SVN Export command after your right-click and drag to copy the files to any destination folder.


q:
i.e. as I compose my test suites to include other suites as well as test cases,
is there a global count of how many tests the TestRunner has executed, will be executing?

Any way I can progammatically access that count?

[A]
not sure about how many it has executed, but couldn't you check how many total tests using
```
self.methods.grep(/test_/)
```
?


q: I know there is a WeakHashMap in java.util, but since it uses WeakReferences for everything, which is only referenced by this Map, referenced objects will get lost on the next GC cycle. So it's nearly useless if you want to cache random data, which is very likely to be requested again without being Hard-linked the rest of the time. The best solution would be a map, which uses SoftReferences instead, but I didn't find one in the Java RT Package.

[A]
Edit (Aug. 2012):
It turns out that currently the best solution are probably Guava 13.0's
```
Cache
```
classes, explained on
Guava's Wiki
- that's what I'm going to use.
It even supports building a
```
SoftHashMap
```
(see
```
CacheBuilder.newBuilder().softKeys()
```
), but it is probably not what you want, as Java expert Jeremy Manson explains (below you'll find the link).
Not that
I know of
(Nov. 2008), but you kind find some implementation of
```
SoftHashMap
```
on the net.
Like this one:
```
SoftHashMap
```
or
this one
.
Edit (Nov. 2009)
As
Matthias
mentions in the comments, the
Google Guava
MapMaker
does use SoftReferences:
A
```
ConcurrentMap
```
builder, providing any combination of these features:
soft or weak keys,
soft or weak values,
timed expiration, and
on-demand computation of values.
As mentioned in
this thread
, another JSR166y candidate:
jsr166y.ConcurrentReferenceHashMap
It provides an alternative concurrent reference map to the Google implementation (which relies on a background thread to evict entries)
Edit (August 2012)
The Google implementation uses a background thread only when timed expiration of entries is requested. In particular, it simply uses
```
java.util.Timer
```
, which is not so intrusive as having a separate background thread.
Jeremy Manson recommends, for any cache, using this feature to avoid the dangers of SoftReference:
http://jeremymanson.blogspot.de/2009/07/how-hotspot-decides-to-clear_07.html
There's another implementation from
Apache Commons
, namely
org.apache.commons.collections.map.ReferenceMap
; it does not support timed removal, but it does support choosing whether keys should be compared by identity or by equality. Moreover, this implementation is not concurrent - it can be made synchronized, but that works less well under accesses from multiple threads.


q:
I'm trying to deserialize an xml structure that looks like this:

<somecontainer>
    <key1>Value1</key1>
    <key1>Value2</key1>
    <key2>Value3</key2>
    <key2>Value4</key2>
</somecontainer>

I can basically choose what kind if element to deserialize to, maybe something like a List of Pair or something. The essence here is that the element names are the keys.

And no, I cannot change the xml structure. Anyone know how to do this with xstream ?


q:
A few months ago I was introduced to the new DateTimeOffset type and was glad DateTime's flaws with regard to time zones were finally taken care of.

However, I was left wondering if there were any overhead or problems that could occur from using this new type.

I work on a multi-locale web application. Does anyone know of anything that could sway me from just using it for all my date/time work? Is there a window for abuse here?

Reference: DateTimeOffset: A New DateTime Structure in .NET 3.5 by Justin Van Patten

[A]
Sometimes you really just want to represent a "local" (timezone unaware) date and time rather than an
instant
in time. To be honest it's more often useful to represent just a time - e.g. "wake me up at 8am, regardless of timezone" - but date and time could be useful too.
I agree that for the vast majority of cases,
```
DateTimeOffset
```
is a better fit. It does strike me as odd that there isn't a
```
DateTimeTimeZone
```
struct which has both the instant and its timezone though... an offset doesn't actually give you all the information you need. (For instance, given a
```
DateTimeOffset
```
, you don't know what the time will be 24 hours later, because you don't know when DST might kick in.)
If you want that kind of structure, I have a
very crude implementation in another answer
. I'm sure it could be improved very easily :)


q: Does anyone know how to use CruiseControl.Net to publish to an FTP server?

[A]
I don't think there's a specific way to do this. You can of course always run the commandline ftp client in window from cruise control.net
One tip:
I found that stuff like this can be hard to set up and maintain in cc.net. There's a lot of trial and error involved and because you're working on a server every trial and every error can take a long time to debug. I usually have a very generic cc.net build setup that i can copy for all my projects that just gets the source from version-control and starts a nant build script. Because you can run the nant build-script on your local machine as well debugging it is far easier.


q:
I can't seem to get Javascript debugging working for my ASP.NET MVC application even though I can for a traditional ASP.NET WebForm app.

I have followed the steps for unchecking the 'Disable Script Debugging' boxes for both IE and other.

when I add a simple function to display an alert in both the site.master and any content view the breakpoint will not fire.

Have i missed something obvious or do I need to use an outside tool for debugging like FireBug?

By the way, I'm using Visual Studio Web Developer Express 2008.

thx

[A]
I don't use VS.Net Express, but in VS.Net Standard you can go to the Debug menu in your solution and choose "Attach to process". You will then get to choose the debug type: Native, Managed, or Script. Select Script, then select your process from the list. A list of scripts will now come up in your IDE. Click on script one you want to debug, throw in a breakpoint or two, and you should be ready to go.
If MS has nerfed the Express version so that you can't attach to a process, then I guess you're stuck and will need the $$$ upgrade (which wouldn't entirely surprise me). Hey, what do you want for free? :)


q:
I'd like to create a text field with a dropdown list that lets the user choose some predefined values. The user should also be able to type a new value or select a predefined one from a dropdown list. I know that I can use two widgets for that but in my app it would be more ergonomnic if it was unified in a one widget.

Is there a standard widget or do I have to use a third party javascript?

How about browser portability?

[A]
I am not sure there is a way to do it automatically without javascript.
What you need is something which runs on the browser side to submit your form back to the server when they user makes a selection - hence, javascript.
Also, ensure you have an alternate means (i.e. a submit button) for those who have javascript turned off.
A good example:
Combo-Box Viewer
I had even a more sophisticated combo-box yesterday, with this
dhtmlxCombo
, using ajax to retrieve pertinent values amongst large quantity of data.


q:
In CSS, with:

@page { @top-right { content: "Page " counter(page) " of " counter(pages); } }

I can have page numbers displayed at the top of every page when the page is printed. This works great. But now, how can I make it so the page number starts with 2 instead of 1? Can I do that by modifying the CSS rule above?

[A]
Don't know if this works, but why don't you try
```
counter(page+1)
```
?


q:
You launch a java program from a console (maybe using a .bat script).
I don't want the console to remain visible, I want to hide it.

Is there a simple way to do this ? Without JNI ?

[A]
Use javaw.
http://java.sun.com/javase/6/docs/tooldocs/windows/java.html
The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear. The javaw launcher will, however, display a dialog box with error information if a launch fails for some reason.


q:
I have built an application that uses SQL Express 2005 and I want to deploy it, but the problem is that anyone who has SQL Management Studio(or something like that) installed on his computer, can connect to my database and change it.
Is there anyway to prevent end-users from seeing or editing the content of my database, even those with the Administrator privileges?

[A]
I suppose this is not the answer you hoped for but it is unavoidable that anyone with administrative rights will be able to browse and edit information in the database.
You cannot change this.
Perhaps you could consider WHY you want to prevent this kind of access?
I expect you want to prevent tampering or accidental corruption of the data?
If that is the reason then you can go a long way to prevent corruption by adding constraints to your database.  Add foreign key constraints, uniqueness constraints, everything that will help prevent data corruption.
Then an administrator would need to deliberately undo these constraints before they tamper, which would prevent most accidental corruption but of course not prevent malicious vandalism.
If you are concerned about protection of your intellectual property, you could encrypt the programmatic components (stored procedures and views and functions).  This kind of encryption is not very strong but prevents casual inspection.
Encryption is added by using the
```
```
WITH ENCRYPTION
```
```
clause in your CREATE or ALTER statements.


q:
We are developing a web application which is available in 3 languages.

There are these key-value pairs to translate everything. At this moment we use Excel (key, german, french, english) for this. But this does not work well ... if there is more than 1 person editing this file, you have no chance to automatically merge the different files.

Is there a good (and free) tool which can handle this job?

--- additional information ---

(This is a STRUTS application) But the question is how to manage these kinds of information in general (or at least in an conveinient way, which also supports multiple users editing this single file ("mergeable" filetypes))

[A]
If you can store this information in plain text then you will be able to use a version control system like subversion to help you with merging changes.  Subversion is free.
The free guide (the "Red Book") to subversion gives a fairly good explanation of how this kind of merging works.
http://svnbook.red-bean.com/en/1.5/svn.basic.vsn-models.html#svn.basic.vsn-models.copy-merge
EDIT: Another thought - if you really want to stay using a spreadsheet - Google Docs supports simultaneous editing of a spreadsheet.  You could import your existing spreadsheet and get your multi-user merging wishes for free with very little change to how you work.


q:
How can I set Resharper to wrap, say, the generated equality members with regions when selected from the Alt+Insert menu?

Thanks

[A]
it doesn't really answer your question, but I just can't resist to try to convince you NOT to use regions. Why would you want to do it? The obvious disadvantages of regions are:
they don't compile, so you can never know if the name of the region really describes what is inside
regions are often used to hide rubbish code. The thinking here is: you can't see the rubbish bits, so it is as if they didn't exist. But guess what, they still exist...
regions are just textual, they don't have any semantic meaning. That means that the code inside the region can change the state of another region - which doesn't help to figure out what is happening in the class at all
if you structure your code correctly, it should be obvious what it is doing anyway
I believe using regions makes sense pretty much only for automatically generated parts, e.g. WinForms designer stuff. In most (all?) other cases it is much better to refactor the code, extract some extra classes or methods, etc. to make it clear.


q:
What is the best way to structure a VB.NET Windows Forms application so that code can be reused and the application can be extended easily?

I used to create lots of new forms. This lead to lots of repeated code and forms which did similar things.

Now, for forms which do similar jobs, such as view/edit/delete items from a specific database table, I create a form with the required controls, have the form create an instance of a class with parameters such as a collection of the controls and a string containing the database table name. Then the individual controls call functions of the class.

Advanced forms will inherit and extend this basic form class.

Has there already been work done in this area?

Are there books / articles available which discuss the options available on this topic?

[A]
I had great success with this
Passive Screen
pattern.
In my opinion, the big problem of the traditional MVC architecture is that people stuff way too much into the form classes. This increases the amount of manual testing you have to do.
The more automated testing you can do after you compile, the more bugs you will catch at your desk. In a complex application, the side effects from even minor changes occur all too often.
The trick to solving this is making a controller assembly that the form assembly (or EXE) references. Every form has a corresponding class in the assembly. Clicking a button will call
```
ThisForm.ThisButton(<args>)
```
which will then fire objects lower in your framework. Each form implements an interface so that, if the controller class needs additional information from the form, it has a interface to retrieve it.
Then for your
unit testing
you simulate an operator performing complex operations by implementing dummy classes to fire events and feed information to the controller classes. The controller classes don't know any different as the dummy classes implement all the expected interfaces.
There is an important exception and that is for trivial dialogs. For dialogs that have a few check boxes I feel this organization is overkill. I use the
command pattern
a lot. So in the assembly where I define the Command objects, I put the SIMPLE dialog associated with that command. How simple a dialog has to be to get this treatment is up to you.
I like to structure my applications as follows.
Utility - This is an assembly that has stuff I use all the time - Math functions, file function, etc.
Objects - This has the specific objects I am using for this application.
UIFramework - This defines all form and controller interfaces.
Commands - This has all the Command objects that manipulate my application objects.
UI - Objects that implement the controller interfaces
EXE - Forms that implement the form interface and calls the controller objects.


q:
Imagine the following

A type T has a field Company.
When executing the following method it works perfectly:

Type t = typeof(T);
t.GetProperty("Company")

Whith the following call I get null though

Type t = typeof(T);
t.GetProperty("company", BindingFlags.IgnoreCase)

Anybody got an idea?

[A]
You need to add
```
BindingFlags.Public | BindingFlags.Instance
```


q:
Is there any way to find out what exceptions might be thrown by any method in .NET code? Ideally I want to see what might be thrown and choose which ones I want to handle. I guess I want the information you'd get from the throws clause in java.

The situation is I'm doing a linq query on an xml document from the network and want to know what could go wrong. I could open up the assembly in reflector and have a look but I thought there might be an easier way.

[A]
.NET does not have enforced ("checked") exceptions like java. The intellisense
might
show this information, if the developer has added a
```
/// <exception.../>
```
block - but ultimately more exceptions can happen than you expect (
```
OutOfMemoryException
```
,
```
ThreadAbortException
```
,
```
TypeLoadException
```
, etc can all happen fairly unpredictably).
In general, you should have an idea of what things are likely to go wrong, and which ones you can actually do something useful about. In most cases, the correct behaviour is to let the exception bubble up (just running any "finally" code to release resources).
Eric Lippert has a good blog on this subject
here
.


q:
I'm currently working on a WebSphere 6.1 Web Project.

In my java code, how can i get the current running application port?

[A]
The servlet API gives you the local port in HttpServletRequest.
```
```
protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    writer.write("" + request.getLocalPort());
    writer.close();
}
```
```
The ports are defined in the node's
serverindex.xml
(e.g. [WAS]/profiles/AppSrv01/config/cells/localhostNode01Cell/nodes/localhostNode01/serverindex.xml).
```
```
<specialEndpoints xmi:id="NamedEndPoint_1214751102556" endPointName="WC_defaulthost">
  <endPoint xmi:id="EndPoint_1214751102556" host="*" port="9080"/>
```
```
I'm not sure if the WAS JMX support exposes this information - you'd have to check the doc.


q: How to put a File path control in VBA front panel? I want the user to be able to select the browse button and select the file path rather than putting up dialog boxes all over the place. I need the user to select three or more file paths.

[A]
Do you mean VBA for Microsoft Office or just general VBA?
In Office,
```
Application.FileDialog(msoFileDialogOpen)
```
.
Otherwise, look at the Win32 API function
```
SHBrowseForFolder
```
(in shell32.dll). You can import it for use into VBA using the
```
Declare Function
```
keywords.


q:
How do you stop race conditions in MySQL? the problem at hand is caused by a simple algorithm:

select a row from table

if it doesn't exist, insert it

and then either you get a duplicate row, or if you prevent it via unique/primary keys, an error.

Now normally I'd think transactions help here, but because the row doesn't exist, the transaction don't actually help (or am I missing something?).

LOCK TABLE sounds like an overkill, especially if the table is updated multiple times per second.

The only other solution I can think of is GET_LOCK() for every different id, but isn't there a better way? Are there no scalability issues here as well? And also, doing it for every table sounds a bit unnatural, as it sounds like a very common problem in high-concurrency databases to me.

[A]
what you want is
LOCK TABLES
or if that seems excessive how about
INSERT IGNORE
with a check that the row was actually inserted.
If you use the IGNORE keyword, errors
  that occur while executing the INSERT
  statement are treated as warnings
  instead.


q:
I have code similar to the following in many places:

var dbParams = db.ReadParams(memberID, product, GetSubscriptionFields());
Debug.Assert(dbParams.Count == 4);

_memberCode = dbParams[0];
_password = dbParams[1];
_userName = dbParams[2];
_reasonCode = dbParams[3];

ReadParams() returns an array of strings, the number of strings depending on the GetSubscriptionFields() function. I could use dbParams[] directly in my code, but I find it more helpful to give meaningful names to each of the values in the array. Is there a way I can get all the results directly, without going through the array?

I am looking for something like:

db.ReadParams(memberID, product, out _memberCode, out _password, out _userName, out _reasonCode);

or

Tuple<_memberCode, _password, _userName, _reasonCode> = db.ReadParams(memberID, product);

Of course, it has to be legal C# code :)

[A]
Why not use constants instead?
Then in your code you could have
```
```
dbParams[MEMBER_CODE]
dbParams[PASSWORD]
dbParams[USERNAME]
dbParams[REASON_CODE]
```
```
which meets your goal of meaningful names without changing the way the method works.


q: I have a gradient image as a background for a table header(9x18pix). This image is called through a selector class. When the header content grows to 2 lines(vertical height increases), the bg image is tiling vertically and looks ugly. How can I stretch the bg image vertically without tiling?

[A]
You can't stretch it. Well not without some nasty CSS hacks, that will not really work in all available browsers. I wouldn't use them (unless your HTML code only targets a single browser, e.g. if it's a page for internal use and the browser being used is known). You can make it repeat in just one direction, though. This is what you usually want when having a gradient.
```
```
background-repeat: repeat-x;
```
```
Here's an example image:
Here's HTML code that uses it
```
```

<title>Gradient Test</title>

            One line
            Three
lines
of text

            Data
            Data

```
```
It will repeat, but only within one direction. Usually a gradient can be safely repeated within one direction, there is no need to stretch it.


q: There is a console Java application which is supposed to run until it is stopped by Ctrl+C or closing the console window. How that application can be programmed to execute a clean up code before exit?

[A]
You could use a
Shutdown Hook
.
Basically you need to create a Thread which will perform your shutdown actions, and then
add it as a shutdown hook
. For example:
```
```
class ShutdownHook extends Thread
{
    public void run()
    {
        // perform shutdown actions
    }
}

// Then, somewhere in your code

Runtime.getRuntime().addShutdownHook(new ShutdownHook())
```
```


q:
I have an App that will send authenticated emails using System.Net.Mail and System.Net.NetworkCredential my question is how should I store the password that is needed to create a NetworkCrednetial object?

The application doesn't have a login but I could setup an option that allows the user to enter their email credentials (in almost all cases this will be their windows login). I can't use Active Directory because not every customer uses it.

I could get the password from the user and then persist it to the users registry, a file or a database. Obviously i'd have to encrypt it. I'm not very familiar with encryption so some pointers would be appreciated if people think thats the best mechanism.

My preference would be to avoid having to store anything, so is there anyway I can get around having to store the credentials myself, perhaps I can get it from the current login or somewhere else?

[A]
To store a username and password (in Windows) use the
DPAPI
. The .Net interface to it is the
ProtectedData
and ProtectedMemory classes.
But first, you could try if the
UseDefaultCredentials
or DefaultNetworkCredentials is working for your environment.


q: I am running a Solr instance on Jetty and when I search using the Solr admin panel, it returns the entire document. What should I do to get only specified fields from each Solr document returned by the search?

[A]
```
```
/?q=query&fl=field1,field2,field3
```
```


q:
As a team we are using Visual Studio 2005 with framework 3.0. I am thinking if it will be nice for us to switch to Visual Studio 2008 with framework 3.5 ? Is it worth it ?

Thanks.

[A] Yes, it is 100% worth it. Visual Studio 2008 supports 2005 code (.net 2.0) completely. There are also a lot of improvements that you'll enjoy as you use 2008.


q:
I am designing a windows service and now deploying it.

I have the code:

ServiceInstaller serviceInstaller1 = new ServiceInstaller();

This instantiates the object (obviously, but throws the following compile-time error:

Error   1   The type 'System.Configuration.Install.ComponentInstaller' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Configuration.Install, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.    C:\Users\firstname.lastnameDocuments\Visual Studio 20

How do I fix this? I'm thinking I need an app config file in my Windows Service?

[A]
System.Configuration.Install should be in the GAC. Is it not there? Does the target machine only have .NET 1.0 or 1.1? Or does the app.config (which you say you might not have present) stipulate one of those earlier .NET Framework versions should be used?
Ah, it is on the dev machine. Then you should go with Marc's answer and just add a reference to the System.Configuration.Install assembly to your project.


q:
I am using a machine on which I do not have root access and would like to access files on a Samba server in random access mode. I know I can transfer the files in their entirety using smbclient but the files are very large (>1GB) and I would rather just treat them as remote files on which I can do random access.

The problem as noted is that I don't have root access to this machine (a Linux box) so I can't mount the remote Samba file system.

Is there a user-level solution that will let me randomly access the contents of a file on a Samba server? Seems it should be possible to do everything that the kernel file system client is doing but from a user-level application.

I only need read-only access btw and the remote file is guaranteed not to change.

[A]
Try to use
```
smbmount
```
to mount the filesystem without root permissions:
```
```
mkdir ~/temp
smbmount //{server}/{share} ~/temp -o username=username={username},password={password}
```
```
Edit: Updated to use
```
smbmount
```
instead of
```
mount
```
.


q:
I'm just in the middle of revisiting maven. Our team had a bad experience when we last looked at this, as it was during the period when maven was rearchitecting from 1.x to 2.x, so a lot of the dependencies we needed hadn't been moved across to the new repositories. However, I have the time to reconsider now.

I am interested in using maven and either LaTeX or DocBook for creating documentation, and I was wondering if anyone had any experiences to share, project/module structure, good plugins to use, etc...

Many thanks :-)

Edit:

Just to clarify, I was looking to write a technical article/book, and my desired artifact would probably be a PDF.

[A]
You can easily create a site (that contains documentation) with Maven using the mvn site command (i.e. using the
plugin site
).
This plugin creates technical reports (such as Javadoc, Unit tests reports, code coverage...) but can be also used to create a "real site".
You have more details about that in
this page
.
Basically, you write your page using
APT
(
Almost Plain Text
which is quite simple to understand), or a XML-based format,
Xdoc
.
2 years ago, I create a complete user guide for one application I developed, using the XDoc format and the Site Maven plugin. Globally, it was quite easy to create!
I hope this will help you!


q:
I need to search a string in the string array. I dont want to use any for looping in it

string [] arr = {"One","Two","Three"};

string theString = "One"

I need to check whether theString variable is present in arr.

[A]
Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:
```
```
bool has = arr.Contains(var); // .NET 3.5
```
```
or
```
```
bool has = Array.IndexOf(arr, var) >= 0;
```
```
For info:
avoid names like var
- this is a keyword in C# 3.0.


q:
I'm having real difficulties with XAML files in Silverlight since they get very big very fast when using Blend. It just becomes a wall of text after only a handful of controls are added and animated.

I'm hoping a better vesion of Blend will come out soon, so that our designers will never even have to see XAML. For now, though, that is not a solution - XAML still needs to be managed manually and it is a depressing task.

Has anyone found a solution to this? How do you keep your XAML files in order? How do you understand them when they get big?

Edit: I am especially interested in Silverlight solutions, since the most obvious WPF solution - splitting things up into resource dictionaries - is not supported in Silverlight.

[A]
It does require a little bit of work to maintain XAML files, but basically, what you need to do is split them up in resource files  (XAML Resource Dictionaries) using a scheme that makes sense to you.
For example we use a scheme where we have a folder structure like this:
Resources (contains XAML Files that represent the user controls and pages)
Stencils (XAML files with Shapes)
Styles ( XAML Files with styles)
Brushes ( ... )
Shared
Templates ( ... )
Your structure might vary but, separating all resources in different files really makes maintenance more easy in the long run.


q: Is it safe to have 2 or more threads call the Win32 API's SetEvent on the same event handler not being protected by a critical section?

[A]
Assuming you have multiple threads waiting on the same event, running the same code.
If your code doesnt clear the event until its done processing, you effectively have a CS.  Since the event remains signaled until it is cleared(aka not autoreset), having multiple threads signal the does nothing except spin the CPU.
If your code clears it at the begining of processing or the event is autorset, then you would have multiple threads running the same function, which is unsafe if these threads share anything.


q: I'm looking for an example of how to load an image from file and print it on a page using WPF.  I'm having a hard time finding good information about WPF printing.

[A]
Just load the image and apply it to a visual.  Then use the PrintDialog to do the work.
```
```
...
PrintDialog printer = new PrintDialog();

if (printer.ShowDialog()) {
  printer.PrintVisual(myVisual, "A Page Title");
}
```
```


q:
I'm using event delegation to listen for events lower in the DOM, but it's not working for an onchange event on a select box.  Does the onchange event propagate or bubble up the DOM?

Googling has failed in finding a conclusive answer.

[A]
Not sure if I get the question, but if you mean this, then NO.
```
```
<div id="foo">
  <select onchange="alert('hi');">
    <option>Hello</option>
    <option>World</option>
  </select>
</foo>
```
```
Where the div id="foo" would have an onchange event... bubbling up from the select list?
on a related note, just an FYI you can't attach an event to the options within the select list in IE (well, you can but it won't fire)


q:
I have to read CSV files line by line which can be 10 to 20 Meg. file() is useless and I have to find the quickest way.

I have tried with fgets(), which runs fine, but I don't know if it reads a small block each time I call it, or if it caches a bigger one and optimize file I/O.
Do I have to try the fread() way, parsing EOL by myself?

[A]
```
fgets()
```
should be perfectly fine for your needs.  Even
```
file()
```
should be ok - 20mb isn't very big unless you're doing this a lot of times concurrently.
Don't forget you can tune
```
fgets()
```
with its second parameter.


q: What is the best way to implement connection pooling in hsqldb, without compromising on the speed?

[A]
If you used Hibernate's own connection pooler, you could consider using
c3p0
? (If you're already using c3p0, I can't help further) I haven't used HSQLDB myself but I think that could be worth trying.


q:
I currently have a 32 bit dll that was created with Visual Studio 2003 in C++ using Managed Extensions. I'm now trying to compile a 64 bit version without having to upgrade to C++/CLI. I've been following the tutorial at this location. I'm getting the following error:

 fatal error C1197:
  cannot reference
  'c:\windows\microsoft.net\framework\v1.1.4322\mscorlib.dll'
  as the progam has already referenced
  'c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll'

I can't figure out what is referencing the .NET 2.0 version of the dll.

[A]
Do you manually call the .dll file in the code? Like in this?
```
```
#using "C:\Windows\Microsoft.NET\Framework\v1.1.4322\mscorlib.dll
```
```
If so, you can change this line to just:
```
```
#using "mscorlib.dll"
```
```


q: I need a java api, that cannot use JMF, to play video interpreted by the SO codecs but i want to retrieve the each frames in java code. Somebody know some?

[A]
Have a look at
FMJ
.  It does
not
require the
Java Media Framework
(JMF).
They have an
example
at the bottom of the page that writes out the first 5 frames of the video to files, so you should be able to get to the individual frames.


q:
I need to pause for maybe 500 miliseconds before I submit a form.  Here is what I have so far:

 $(".rowqty input").bind("keyup", function() { $("#ViewCartPage form").animate({ opacity: 1.0 }, 3000).submit() });

so when someone changes the quantity of the input field it submits the form, but I want it to wait for a slight amount of time incase they need a moment to type 2 or 3 numbers.

As you can see I tried the animate function to try and delay things but with no luck.

I know I could use this: http://blog.mythin.net/projects/jquery.php

I'd rather not add another JS to my site if there is a way around it.

EDIT: Actually the pause plugin above is not working for me either.

[A]
Give this a shot:
```
```
$(".rowqty input").bind("keyup", function() { setTimeout("$('#ViewCartPage form').submit()", 500 });
```
```


q:
Any idea anyone? Is it possible that we specify the name of the form input field?
How to go about doing that?

[A]
It's generated as formId:fieldId
So, if you had the following:
```
```
<h:form id="searchForm">
   <h:inputText id="searchField" ... />
</h:form>
```
```
The name (and HTML ID) of the search field would be:
searchForm:searchField


q: Is there any security issue if let say in one application we do a hidden post to another application to make use of that application functionality?


q:
I have a list of integers in C#. I wish to remove duplicates.
In C++ I would run it through the std::sort and then std::unique algorithms for a very efficient way of obtaining the unique list.

What's the best way to do the same thing in C#? In other words, I'm looking for a more elegant way to do the following code:

    private static int[] unique(int[] ids)
    {
        IDictionary<int, object> d = new Dictionary<int, object>();
        foreach(int i in ids)
            d[i] = null;

        int[] results = new int[d.Count];
        int j = 0;
        foreach(int id in d.Keys)
            results[j++] = id;

        return results;
    }

[A]
What version of .NET are you using?
In .NET 3.5 that's as simple as calling the
Distinct()
extension method and then
ToArray()
if you really need an array again.
For example:
```
```
int[] x = new[] { 1, 4, 23, 4, 1 };
int[] distinct = x.Distinct().ToArray();
// distinct is now { 1, 4, 23 } (but not necessarily in that order)
```
```


q:
I have some function to find a value:

struct FindPredicate
{

    FindPredicate(const SomeType& t) : _t(t) {
    }
    bool operator()(SomeType& t) {
      return t == _t;
    }

private:
    const SomeType& _t;
};

bool ContainsValue(std::vector<SomeType>& v, SomeType& valueToFind) {
    return find_if(v.begin(), v.end(), FindPredicate(valueToFind)) != v.end();
}

Now I would like to write a function that checks if all members of a vector satisfy that predicate:

bool AllSatisfy(std::vector<SomeType>& v) {
    /* ... */
}

One solution is to use the std::count_if algorithm.

Does anyone know a solution that involves negating the predicate?

[A]
The best solution is to use the
STL functional library
. By deriving your predicate from
```
unary_function<SomeType, bool>
```
, you'll then be able to use the
```
not1
```
function, which does precisely what you need (i.e. negating a unary predicate).
Here is how you could do that :
```
```
struct FindPredicate : public unary_function<SomeType, bool>
{
    FindPredicate(const SomeType& t) : _t(t) {}

    bool operator()(const SomeType& t) const {
      return t == _t;
    }

private:
    const SomeType& _t;
};

bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
    return find_if(v.begin(),
                   v.end(),
                   not1(FindPredicate(valueToFind))) == v.end();
}
```
```
If you want to roll your own solution (which is, IMHO, not the best option...), well, you could write another predicate that is the negation of the first one :
```
```
struct NotFindPredicate
{

    NotFindPredicate(const SomeType& t) : _t(t) {
    }
    bool operator()(SomeType& t) {
      return t != _t;
    }

private:
    const SomeType& _t;
};

bool AllSatisfy(std::vector<SomeType>& v) {
    return find_if(v.begin(),
                   v.end(),
                   NotFindPredicate(valueToFind)) == v.end();
}
```
```
Or you could do better and write a template functor negator, like :
```
```
template <class Functor>
struct Not
{
    Not(Functor & f) : func(f) {}

    template <typename ArgType>
    bool operator()(ArgType & arg) { return ! func(arg); }

  private:
    Functor & func;
};
```
```
that you could use as follow :
```
```
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
    FindPredicate f(valueToFind);
    return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();
}
```
```
Of course, the latter solution is better because you can reuse the
Not
struct with every functor you want.


q:
I've found an issue with ASP.NET that I know at least has stumped one other person out there.  We were trying to use an HttpModule to handle wildcard
requests to a web application.  The generated url is dynamic and could
potentially be several hundred characters long.  Unfortunately there
appears to be a limitation in the aspnet_isapi.dll file that limits
the length of the path in the url to MAX_PATH which is hardcoded at
260 chars.

Has anyone else ran into this and found a way around this limit?
Query string parameters are not an option.

Thanks,
Greg Ballard

[A]
The problem actually lies within Windows, not ASP.NET.  Windows has set MAX_PATH at 260 and when IIS takes a request for a longer filename, it will fail.  You've probably found is this KBase article already, but for anyone else:
http://support.microsoft.com/kb/q177665/
.  The Applies To: Section shows this is expected behavior from NT 3.51 all the way to Vista and Server 2003.
As for a workaround, I had a similar situation, but we would up abandoning our attempts to avoid a query string parameter and did it anyway.


q:
I am doing 2^1000 and I am getting this:

1.07151e+301

Is there any way to actually turn this into a proper number without the e+301, or at least can anyone show me where I can see how to turn this in to a real number, by some way working with the e+301 part?


q: I want to be able to launch a third party process from within an Adobe AIR application (actually a command line process). Is there a security context that AIR apps run in that prevents this?

[A]
Two of the most requested features for Adobe AIR have been the ability to launch native executables from an AIR application, and the ability to integrate native libraries into an AIR application. Unfortunately, neither feature is included in Adobe AIR 1.0.
However. Check out:
This blog post
Airaveer
Shu-player
Shu enables you to increase the power and reach of Adobe AIR. With Shu your AIR applications can quickly be converted into standalone applications to run on PC or Mac machines without the AIR runtime installed! Shu applications can also be run from a CD or network share and do not require installation.
  In addition Shu provides you the developer with a toolkit of commands to extend the system capabilities of your AIR application, features include,
controlling external applications, opening external files, database connectivity and control, system path retrieval and screen capture functionality.
Using any of these methods will however break some of the intentions with AIR, which is cross-platform development. And as far as i know that's the main reason why Adobe won't let you execute native code at the moment.


q:
I have an ASP.Net MVC Ajax.BeginForm that submits and updates my page properly when I click the submit button.

The problem is I need additional events to do the same thing, like when they change the text of an input.  The additonal events do properly submit the form but they circumvent the onsubmit javascript generated on the form tag by the Ajax.BeginForm.

Here is the form tag generated by Ajax.BeingForm:

<form action="/Store/UpdateCart" method="post" onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'updatedContent' });">

And here is the jQuery to bind my other events that need to submit the form via Ajax:

 $("#ShippingType, #ViewCart .ddl").bind("change", function() { $("#ViewCartPage form").submit() });

Any ideas on how to get these additional events to trigger onsubmit like I need it too?

[A]
This is a bit of a tricky issue in the current Beta of MVC.  You can't use the "submit()" function because it won't trigger the onsubmit handler.  Instead, you should call the onsubmit handler directly.  The only trick is you need to pass an argument to onsubmit() when you call it.  This argument is what becomes the "event" parameter in the handler (see the "new Sys.UI.DomEvent(event)" part).  The "event" parameter is used by the MVC Ajax scripts to cancel the default behaviour, when you click the Submit button so that the Ajax stuff can happen uninterrupted.
So, if you change your code to this:
```
```
$("#ShippingType, #ViewCart .ddl").bind("change", function() { $("#ViewCartPage form").onsubmit({ preventDefault: function() {} }) });
```
```
The onsubmit() event will be triggered when the form fields change.  The code creates a "fake" event object that implements the preventDefault() method (which is the only one the MVC Ajax helpers use) so you don't get errors.


q:
I was looking into the best encryption for a license key for an application, and someone said that someone can easily decompile the application and then just skip the test for the license key.

how would someone go about doing that practically speaking?  So they have my .dll, they have to decompile it somehow, then comment out the function call to check the license, then recompile it?  The decompiler has to be really good such that the code still compiles!

[A]
Try opening your application with
Reflector
. You will probably be surprised :-)
And once a cracker has located the right location in your code, they can use a combination of
ildasm
/
ilasm
to remove the check from your application - even if the code Reflector generates won't compile.


q:
I want to implement Scrum, but I can't decide on a Sprint length. Ken Schwaber seems to relate that 30 days it the defacto... but I can't imagine waiting 30 days without the possibility of changing direction or reprioritizing.

Our projects usually only last 1-3 months using the waterfall method and moving to Scrum would probably mean less opportunity to fine tune.

I was thinking about 1 week sprints, but this seems like Scrum Micro Management.

Having 2 week sprints would probably be ideal, but I want to know if others out there were able to implement this successfully. What are the downsides? Is it more work/less work/same about of work to manage a team with shorter sprints?

BTW... 3 week sprints seem odd to me, who does a 3 week sprint? Why not just make it 4 weeks. ;)

[A]
2 weeks (10 standard working days, if you are a M-F outfit or 12 if you are a M-S outfit) is half a month (a month typically has roughly 20 working days in it, give or take). Also, week is more vague than day but less vague than month, so it makes the unit of measurement in weeks better for more agile (more give/take) development projects.
However, the last time I did anything like scrum, it was on a school project and it wasn't truly scrum. So it was 7 day weeks in a 10 week quarter. I really liked the 2 week block for that situation. I felt that I could get a lot done but we could adjust timelines and plans frequently.


q:
My table has the following schema:

id, parent_id, text

Given the following data I would like to return an xml hierarchy:

Data: (1,null,'x'), (2,1,'y'), (3,1,'z'), (4,2,'a')

XML:

[row text="x"]

 [row text="y"]

  [row text="a"/]

 [/row]

 [row text="z"/]

[/row]

Added: the hierachy has no maximum depth

[A]
This requires a "transitive closure".  You need to process the data recursively to find all children under a given parent.
Roughly the algorithm looks like this.
```
```
for top in cursor( nodes where  each parent==null ):
    build_tree( top )

def build_tree( parent ):
    emit opening tag
    for child in cursor( nodes where parent == parent ):
        build_tree( child )
    emit closing tag
```
```
Note that some SQL interpreters may have trouble with the recursion -- they may not open a fresh, new cursor as necessary.  Each cursor, however, must be distinct, since you will have as many open cursors as your tree has levels.


q:
I'm using System.Windows.SplashScreen to add a splash screen to my WinForms app (it has a lot of WPF controls, but the 'main window' is still a System.Windows.Forms.Form object). When the splash screen closes the whole app goes as well.

Can I stop it taking the whole app with it?

[A]
I was a bit too quick with that question - it looks like the problem here was down to how I was starting to app. If you do:
```
```
form.ShowDialog();
```
```
Then the form's parent gets set to the splash screen, so when that closes it also closes the child window (in this case 'form'), but if you use:
```
```
System.Windows.Forms.Application.Run(form)
```
```
to start the app, then 'form' is not a child of the splash screen so doesn't close with the splash screen.


q:
Is there any way to create - manipulate calendar events in Exchange Server 2003 ?
I'm using VB.NET 2005. I don't want to use MAPI because everytime I will have to type user name and passwords. Is there any other way ? I used redemption.dll but everytime I want to add for eg. a calendar event it displays the login screen.

Any suggestions ?

Appreciate your help

Thank you

[A]
I'm a bit confused by your configuration file. What exactly are you trying to do?
You've defined 2 endpoints for using MINA (which won't use ActiveMQ at all); then you are using a route from an ActievMQ queue listener_A to listener_B then listener_B to listener_A (which is a recursive loop).
Maybe if you start describing what you want to do we can figure out what the XML should look  like.
Incidentally if you just want to refer to endpoints you've defined, use the
ref="name"
attribute rather than
uri="..."
.
e.g.
```
```
<route>
  <from ref="listener_A"/>
  <to ref="listener_B"/>
</route>
```
```
All that being said - you tend to get better & faster support on Camel via the
Camel User Forum


q: Am I allowed to redistribute only parts of the DirectX package? (e.g. only the DirectDraw DLLs, without Show/3D/etc.)

[A]
No. From the DirectX SDK Redist EULA:
DirectX Software Development Kit Redistributable Code
Redistributable Code is identified as
  all of the files in the following
  "Redist" directory on the DirectX SDK
  CD/Download:
redist/
The following files in the above
  directory must be included in any
  distribution of  the DirectX Runtime.
DSetup32.dll
  DSetup.dll
  DXSetup.exe
  DXupdate.cab
  dxdllreg_x86.cab


q:
I have long been wondering why lazy evaluation is useful. I have yet to have anyone explain to me in a way that makes sense; mostly it ends up boiling down to "trust me".

Note: I do not mean memoization.

[A]
Consider this:
```
```
if (conditionOne && conditionTwo) {
  doSomething();
}
```
```
The method doSomething() will be executed only if conditionOne is true
and
conditionTwo is true.
In the case where conditionOne is false, why do you need to compute the result of the conditionTwo? The evaluation of conditionTwo will be a waste of time in this case, especially if your condition is the result of some method process.
That's one example of the lazy evaluation interest...


q:
An XML attribute declared as xs:boolean can acceptable be "true", "false", "0" or "1".  However, in .NET, Boolean.Parse() will only accept "true" or "false". If it sees a "0" or "1", it throws a "Bad Format" exception.

So, given that, what's the best way to parse such a value into a Boolean?

(Unfortunately, I'm limited to .NET 2.0 solutions, but if v3.5 offers something, I'd love to hear about it.)

[A]
Using
```
CBool
```
instead of
```
Boolean.Parse
```
should do the trick: although you'll have to embed it in a
```
try/catch
```
block (which wouldn't be required when using
```
Boolean.TryParse
```
), it will successfully convert most 'sensible' boolean values, including true/false and 0/1.
Edit: as pointed out in a comment, this answer is kinda useless for C# programmers, as
```
CBool
```
is a VB-ism. It maps to
```
Microsoft.VisualBasic.CompilerServices.Conversions::ToBoolean
```
, which is not suitable for general consumption. Which makes the XMLConvert class pointed out in the accepted answer an even better alternative.


q: Is there any BNF grammar for regular expression?

[A]
You can see one for
Perl regexp
(displayed
a little more in detail here
, as posted by
edg
)


q:
I can't seem to find any GUI framework's for as3 that are as good as any the applications I already see out on the web; Is this something most people code themselves or am I missing something in flash itself?

I'm looking for dialogs/windows, buttons, text boxes, combos, drop downs, menus, etc etc and the ability to extend the components to make new ones.

I'd also prefer it to be as3 but any others will do also.

May need to elaborate a little.. I'm actually looking for a framework to allow me to create my own GUIs in flash, custom skins, colors, styles, etc.

[A]
Short answer:
Here is the
list of base controls
.
Long answer:
Yes, there are many controls (such as
buttons
,
text boxes
,
combo boxes
, etc) already built into Flash / Flex.
Here is
one tutorial
I've found helpful that gives a brief intro to using some components (buttons) without using Flex Builder.
If you use something like Flex Builder, you will get full access to these objects in a friendly drag-and-drop environment, however, it is not necessary to purchase Adobe tools to develop with these, so long as you're comfortable using something like FlashDevelop or the free command-line mxmlc compiler.
Check out the
fl.controls namespace
in Adobe Live Docs for a complete list of these base controls included in Flash / Flex.


q:
I have some HTML and jQuery that slides a div up and down to show or hide` it when a link is clicked:

<ul class="product-info">
  <li>
    <a href="#">YOU CLICK THIS TO SHOW/HIDE</a>
    <div class="toggle">
      <p>CONTENT TO SHOW/HIDE</p>
    </div>
  </li>
</ul>

$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
  $(this).next('div').slideToggle(200);
}

My question is: How do I use preventDefault() to stop the link acting as a link and adding "#" to the end of my URL & jumping to the top of the page?

I can't figure out the right syntax, I just keep getting an error saying

preventDefault() is not a function.

[A]
Try something like:
```
```
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
    event.preventDefault();
    $(this).next('div').slideToggle(200);
});
```
```
Here is the page about that in the
jQuery documentation


q:
how do you go about saving images and displaying them from a SQL Server Image field when using ASP.NET MVC?

Many thanks
Nick

[A]
The MvcFutures
http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18459
project has a FileResult which is a type of ActionResult. You could probably use that to return a binary stream to the browser.


q:
I need a dropdown list on my page that will allow a user to select their state.  Since this is probably a control that will be used elsewhere, I thought it would be a good idea to create an MVC View User Control that could be reused.

I was thinking the control would look something like this:

<select name="" id="">
   <option value="AL">Alabama</option>
   <option value="AK">Alaska</option>
</select>

And the code in my view would be something like:

<%= Html.RenderPartial("StateDropdownControl") %>

My question is, what's the best way to set the name and id on the control?  I'd want to make sure I could have multiple instances of this control on one page, if needed.  Also, I'd want to be able to send in the state that should be selected by default.

Would I do it with ViewData somehow?

[A]
Well you can pass object data to the RenderPartial method in conjunction to the User Control to render, so you could easily do the following:
```
```
```
```
<%= Html.RenderPartial("/someDirectory/SomeControl.ascx", "MyID") %>
```
```
and in the UserControl do the following:
```
```
<select name="<%=ViewData.Model%>" id="<%=ViewData.Model%>">

....
```
```
Just to be sure, a better way to handle it is to make a simple DTO (data transfer object) to hold that information so you can pass more information to your user control, that you will inevitably need.
Example:
```
```
class ComboData
{
   string ID {get;set;}
   string CssClass {get;set;}
   //Other stuff here
}
```
```
```
```
<%
var comboData = new ComboData {ID = "myID", CssClass = "comboStyle" }

%>

<%= Html.RenderPartial("/someDirectory/SomeControl.ascx", comboData) %>
```
```
```
<select name="<%=ViewData.Model.ID%>" id="<%=ViewData.Model.ID%>" class="<%=ViewData.Model.CssClass%>">

....
```
Make sure you set the Code behind for the user control to be a generic of type ComboData for this example.


q:
Just wondering what people think is the best practice when implementing an IValueConverter which does not have a meaningfull ConvertBack implementation (or one that is only to be used as OneWay)?

Should it throw (and in that case what exception), return null or return some default value.

Thoughts?

[A]
The documentation for
```
IValueConverter.ConvertBack
```
recommends returning
```
DependencyProperty.UnsetValue
```
.
The data binding engine does not catch
  exceptions that are thrown by a
  user-supplied converter. Any exception
  that is thrown by the ConvertBack
  method, or any uncaught exceptions
  that are thrown by methods that the
  ConvertBack method calls, are treated
  as run-time errors. Handle anticipated
  problems by returning
  DependencyProperty.UnsetValue.


q: Are hints really necessary for every sql statement? We have a dba who is anal about it and asks us to put hints on every select and update statements in our stored procs. Is this really necessary?

[A]
Not usually.  Putting them on everything sounds like overkill.
The
documentation
says
Because the SQL Server query optimizer typically selects the best execution plan for a query, we recommend that join_hint, query_hint, and table_hint be used only as a last resort by experienced developers and database administrators


q: We have a few applications that use the same Linq 2 SQL DataContext.  One of those Apps wil do massive inserts (it's a convertor from an old system).  Is it possible to change the UpdateCheck of the TimeStamp column of each table at runtime ?  Only for this one app we'd like to set it to Never, all the other apps should have Always.

[A]
AFAIK you can not change it (at least with simple means) at runtime, because it is auto-generated as attribute in the properties of the domain classes. E.g.
```
```
[Column(Name="ITM_CREATE_DATE", Storage="_ITM_CREATE_DATE", DbType="DateTime NOT NULL", UpdateCheck=UpdateCheck.Never)]
public System.DateTime CreationDate
```
```
A possible workaround (that I have never tried, so I don't know if it works) is to copy the
```
<DataContext>.designer.cs
```
code in your single project, make the changes in the copy and use it without the designer.


q: Not wanting to re-invent the wheel or anything, I was wondering if there's a plugin out there a field or form validation plugin that works with Prototype that you can recommend from your own experience and why?

[A]
I like Ben Keen's Really Simple Validation component.
Features I like:
All the validation rules can be kept within javascript so you're not adding class="required" to your HTML code.
You can display error messages in a javascript alert box or with HTML text.
Adding your own extensions is easy.
http://www.benjaminkeen.com/software/rsv/
Note that I've only used the jQuery version, but a Prototype version is also available.


q:
I'm using Windows CE Platform Builder and my code is written in C++ . For each of the folders in the project I'm creating a lib ( the code is statically linked ) . However , there are about 20 libs so far . Is there a way to reduce their number ? I was thinking of creating a lib from other libs , but I don't know if that's even possible . Is it ?

EDIT: how could I do it ?

[A]
I haven't tried it in a while, but traditionally you could use the librarian tool (LIB.EXE) to do this sort of thing.
```
$ lib /?
Microsoft (R) Library Manager Version 8.00.50727.762
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: LIB [options] [files]

   options:

      /DEF[:filename]
      /ERRORREPORT:{NONE|PROMPT|QUEUE|SEND}
      /EXPORT:symbol
      /EXTRACT:membername
      /INCLUDE:symbol
      /LIBPATH:dir
      /LIST[:filename]
      /LTCG
      /MACHINE:{ARM|EBC|IA64|MIPS|MIPS16|MIPSFPU|MIPSFPU16|
                SH4|THUMB|X64|X86}
      /NAME:filename
      /NODEFAULTLIB[:library]
      /NOLOGO
      /OUT:filename
      /REMOVE:membername
      /SUBSYSTEM:{BOOT_APPLICATION|CONSOLE|EFI_APPLICATION|
                  EFI_BOOT_SERVICE_DRIVER|EFI_ROM|EFI_RUNTIME_DRIVER|
                  NATIVE|POSIX|WINDOWS|WINDOWSCE}[,#[.##]]
      /VERBOSE
      /WX[:NO]
```
Normally the librarian takes .OBJ files and combines them into a .LIB, but I think it will also read .LIB files as input.


q:
For example:

public class A : A.B
{
    public class B { }
}

Which generates this error from the compiler:

Circular base class dependency
  involving 'A' and 'A.B'

I always figured a nested class behaved just like a regular class except with special rules concerning accessing the outer class's private members, but I guess there's some implicit inheritance occurring between the two classes?

[A]
There's no implicit inheritance involved as far as I can tell. I would have expected this to be okay - although I can imagine weirdness if A and B were generic.
It's specified in section 10.1.4 of the spec:
When a class B derives from a class A,
  it is a compile-time error for A to
  depend on B. A class directly depends
  on its direct base class (if any) and
directly depends on the class within
  which it is immediately nested
(if
  any). Given this definition, the
  complete set of classes upon which a
  class depends is the transitive
  closure of the directly depends on
  relationship.
I've highlighted the relevant section.
That explains why the compiler is rejecting it, but not why the language prohibits it. I wonder if there's a CLI restriction...
EDIT: Okay, I've had a response from Eric Lippert. Basically, it would be technically possible (there's nothing in the CLI to prohibit it), but:
Allowing it would be difficult in the compiler, invalidating various current assumptions around ordering and cycles
It's a pretty odd design decision which is easier to prohibit than to support
It was also noted on the email thread that it would make this kind of thing valid:
```
```
A.B x = new A.B.B.B.B.B.B.B.B.B.B.B.B();
```
```
... but that would already (as noted by Tinister) be valid if B derived from A.
Nesting + inheritance = oddness...


q:
I have a stored procedure that creates and opens some cursors.  It closes them at the end, but if it hits an error those cursors are left open!  Then subsequent runs fail when it tries to create cursors since a cursor with the name already exists.

Is there a way I can query which cursors exists and if they are open or not so I can close and deallocate them?  I feel like this is better than blindly trying to close and swallow errors.

[A]
Look here
for info on how to find cursors. I have never used any of them because I could figure out a way to get it done without going Row By Agonizing Row.
You should rebuild the sp to either
not use cursors ( we can help -
there is almost always a way to
avoid RBAR)
build it in a transaction and roll it back if there is a failure or if you detect an error. Here are some excellent articles on this.
part 1
and
part 2
If you have SQL2005, you can also use
try catch
EDIT (in response to your post):Ideally, data generation is best handled at the application level as they are better suited for non set based operations.
Red Gate has a
SQL Data generator
that I have used before (its great for single tables, but takes some configuring if you have lots of FK or a wide [normalized] database).


q:
How can I add new application mapping in IIS using vbscript?

Thanks,

[A]
Use a combination of ADSI with VBScript. There are several examples here:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/library/IIS/4b976f46-3751-4f6b-ab68-5e19fa73a7b1.mspx


q:
I added the columns in the select list to the order by list, but it is still giving me the error:

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

Here is the stored proc:

CREATE PROCEDURE [dbo].[GetRadioServiceCodesINGroup]
@RadioServiceGroup nvarchar(1000) = NULL
AS
BEGIN
SET NOCOUNT ON;

SELECT DISTINCT rsc.RadioServiceCodeId,
                rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg
ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
(select val from dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService

END

[A]
While they are not the same thing, in one sense
```
DISTINCT
```
implies a
```
GROUP BY
```
, because every
```
DISTINCT
```
could be re-written using
```
GROUP BY
```
instead. With that in mind, it doesn't make sense to order by something that's not in the aggregate group.
For example, if you have a table like this:
```
col1  col2
----  ----
 1     1
 1     2
 2     1
 2     2
 2     3
 3     1
```
and then try to query it like this:
```
```
SELECT DISTINCT col1 FROM [table] WHERE col2 > 2 ORDER BY col1, col2
```
```
That would make no sense, because there
could
end up being multiple
```
col2
```
values per row. Which one should it use for the order? Of course, in this query you know the results wouldn't be that way, but the database server can't know that in advance.
Now, your case is a little different. You included all the columns from the
```
order by
```
clause in the
```
select
```
clause, and therefore it would seem at first glance that they were all grouped. However, some of those columns were included in a calculated field.  When you do that in combination with distinct, the
```
distinct
```
directive can
only
be applied to the
final results
of the calculation: it doesn't know anything about the source of the calculation any more.
This means the server doesn't really know it can count on those columns any more.  It knows that they were used, but it doesn't know if the calculation operation might cause an effect similar to my first simple example above.
So now you need to do something else to tell the server that the columns are okay to use for ordering. There are several ways to do that, but this approach should work okay:
```
```
SELECT rsc.RadioServiceCodeId,
            rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg
    ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
    (SELECT val FROM dbo.fnParseArray(@RadioServiceGroup,','))
    OR @RadioServiceGroup IS NULL
GROUP BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
```
```


q: What is the best way to build a dynamic Threaded ASP.net radio button list?  I am not that familiar with RadioButtonLists and it is my understanding that ASP.net doesn't like the application of individual styling of ListItems.

[A]
Well, why not use the
```
RadioButtonList
```
control, with a
```
ReapeatDirection="Horizontal"
```
?


q:
Is it possible to use WSE 2.0 SP2 under VS 2008?

I realise that the add-in (that generates the proxy classes/configuration) is not compatible but there are work-arounds to this (copying over the files from a VS 2003 solution). Our web services are relatively static so would not be making too many changes anwyay.

We may at a future date move to WCF but taking baby-steps at the moment and want to get our existing services running under all the .NET 3.5 goodness.

[A]
I have been able to use WSE2 under VS2005/.NET 2.0 with no problems, but I dont know specifically about 2008. I needed Dime attachments (java web service - ugh.. what a headache) which are only in WSE2.
To get the functionality in VS, I actually installed WSE3 and then just changed the dll referenced in the application to the WebServices2 file and all of the Imports (VB - using c#) statements. After that, it worked like a charm.


q:
I have some code that opens a word document using VBScript on an ASP.net page:

set objWord = CreateObject("Word.Application")

objWord.Visible = True

objWord.Documents.Open "c:\inetpub\wwwroot\JSWordTest\test.doc", False, False, False

This works great but opens the word doc in another window. Ideally I would like to make this look as if it is contained in the current page perhaps in an IFrame. I have some other buttons which paste text into the word document when clicked.

I cannot just set the src of the iframe to the word document as need a reference to the word document (objWord) to allow me to paste text into it in real time again using Vbscript to do this.

Not sure if this is possible but any ideas/alternatives welcome?

Requirements:
The word doc needs to be displayed from web browser

At the side of the word document will be some buttons which when clicked paste text into it

[A]
You can use this technique to get the contents of the Word document without displaying any windows at all.
```
```
' Declare an object for the word application '
Set objWord = CreateObject("Word.Application")

objWord.Visible = False                 ' Don''t show word '
objWord.Documents.open("C:\test.doc")   ' Open document '
objWord.Selection.WholeStory            ' Select everything in the doc '
strText = objWord.Selection.Text        ' Assign document contents to var'
objWord.Quit False                      ' Close Word, don't save '
```
```
Once you've got the contents of the document in the variable you can do what you want with it as far as writing it out with a document.write or whatever method you want to use.
You can find more detail on the MS Word application object and its methods here:
http://msdn.microsoft.com/en-us/library/aa221371(office.11).aspx