Question:
We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client.  We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects?

Thanks for your time!

Answer:
I have no Dabo experience at all but this question is on the top of the list fo such a long time that I decided to give it a shot:
Framework selection
Assumptions:
medium-to-big project: we're talking about a team of more than 20 people working on something for about a year for the first phase. This is usually an expensive and very important effort for the client.
this project will have significant amount of users (around a hundred) so performance is essential
it's an ERP project so the application will work with large amounts of information
you have no prior Dabo experience in your team
Considerations:
I could not open Dabo project site right now. There seems to be some server problem. That alone would make me think twice about using it for a big project.
It's not a well-known framework.  Typing Dabo in Google returns almost no useful results, it does not have a Wikipedia page, all-in-all it's quite obscure. It means that when you will have problems with it (and you will have problems with it) you will have almost no place to go. Your question was unanswered for 8 days on SO, this alone would make me re-consider. If you base your project on an obscure technology you have no previous experience with - it's a huge risk.
You don't have people who know that framework in your team. It means that you have to learn it to get any results at all and to master it will require quite significant amount of time. You will have to factor that time into your project plan. Do you really need it?
What does this framework give you that you cannot do yourself? Quite a lot of time my team tried to use some third-party component or tool only to find that building a custom one would be faster than dealing with third-party problems and limitations. There are brilliant tools available to people nowadays and we would be lost without them - but you have to carefully consider if this tool  is one of them
Dabo project version is 0.84. Do you know if they spend time optimising their code for performance at this stage? Did you run any tests to see it will sustain the load you have in your NFRs.
Hope that helps :) Good luck with your project


Question: I've got it configured, but I want more from it...maybe Cygwin isn't the right tool, but I like how it provides a *nix-like environment within Windows.

Answer:
I'm quite interested in this question myself. I've used the
Cygwin Setup guide
to get set up, but it doesn't get you all the way. One thing that I learned from it, though, is that it recommends leaving the setup.exe in the directory with Cygwin so that you can quickly add packages, since apt-get apparently doesn't work that well in Cygwin. The article also talks about cyg-get as an alternative.


Question:
I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (FROM WINDOWS, not fox):

Windows-No disk
Exception Processing Message c0000012 Parameters .....

Any help please
Nelson Marmol

Answer:
Nelson:
"That's how foxpro does it and there is no way around it"?
I'm using FOX since FoxPro 2.5 to Visual FoxPro 9, and you are NEVER forced in any way to hard-code a path, you can use SET PATH TO (sYourPath), you can embed the icons and bitmaps in your EXE / APP file and therefore there's no need of including this resources externally.
You say that you have a "Foxpro App": which version? Old MS-DOS FoxPro o Visual FoxPro?
If you're using VFP 8+, you can use SYS(2450, 1):
```
```
Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on.

You can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.

SYS(2450 [, 0 | 1 ])

Parameters
0
Search along path and default locations before searching in the application. (Default)

1
Search within the application for the specified procedure or UDF before searching the path and default locations.
```
```
One quick workaround could be assign another letter to your USB via the Disk Manager.


Question:
I am looking for a reliable technique for adding Ajax to a working ASP.NET MVC application. I want to use jQuery, and understand how to use the AJAX functionality from jQuery.

What I need to know is how I should write my controller so that I can run the site without JavaScript, but at the same time make AJAX calls possible without the need for a separate view, separate controller, or any kind of route hack. My goal is to have a working application enhanced when JavaScript is enabled without the need to duplicate or recreate elements of the app.

Answer:
Typically you would create your site so that it works without JavaScript being enabled. Then you would add the
unobtrusive JavaScript
needed to enhance your site with Ajax e.g. adding event handlers for links, form submits, etc. to make GET / POST requests and update your UI accordingly.
The only changes you would need in your MVC app would be to handle the Ajax requests and return the data as JSON, XML, etc.


Question:
I'm trying to send messages to Objective-C objects in gdb.

(gdb) p $esi
$2 = (void *) 0x1268160
(gdb) po $esi
<NSArray: 0x1359c0>
(gdb) po [$esi count]
Target does not respond to this message selector.

I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?

Answer:
Is it possible that you need to cast
```
$esi
```
?
```
```
p (NSUInteger)[(NSArray *)$esi count]
```
```


Question:
I am looking for a way to interact with a standalone full version of Windows Media Player.

Mostly I need to know the Path of the currently played track.

The iTunes SDK makes this really easy but unfortunately there really isn't any way to do it with Windows Media Player, at least not in .Net(C#) without any heavy use of pinvoke, which I am not really comfortable with.

Thanks

Just to clearify: I don't want to embedded a new instance of Windows Media Player in my app, but instead control/read the "real" full version of Windows Media Player, started seperatly by the user

Answer:
I had this
https://social.msdn.microsoft.com/Forums/vstudio/en-US/dbd43d7e-f3a6-4087-be06-df17e76b635d/windows-media-player-remoting-in-c?forum=clr
in my bookmarks but have NOT tested it in anyway. Just a pointer in the right direction. It's nothing official and will require a bit of digging, but you should get a fairly simple wrapper (which will still use PInvoke under the hood - but you won't see it) around Windows Media Player.
Hope that helps.
Oh, I misunderstood. I thought you were talking about controlling the currently running Windows Media Player instance. If you are hosting Windows Media Player yourself then WMPLib is certainly the better solution.


Question: In C# are the nullable primitive types (i.e. bool?) just aliases for their corresponding Nullable<T> type or is there a difference between the two?

Answer:
A
```
Nullable<T>
```
is a structure consisting of a T and a bit flag indicating whether or not the T is valid.  A
```
Nullable<bool>
```
has three possible values: true, false and null.
Edit:
Ah, I missed the fact that the question mark after "bool" was actually part of the type name and not an indicator that you were asking a question :).  The answer to your question, then, is "yes, the C#
```
bool?
```
is just an alias for
```
Nullable<bool>
```
".


Question: How do you perform a CROSS JOIN with LINQ to SQL?

Answer:
A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.
```
var combo = from p in people
            from c in cars
            select new
            {
                p.Name,
                c.Make,
                c.Model,
                c.Colour
            };
```


Question: Does a new SessionFactory and Session object have to be created for each database? I have a data store for my application data, and a separate data store for my employee security, which is used to validate users. Do I have to create a new SessionFactory ans Session object for calls to the 2 different databases?

Answer:
ok so this doesn't answer your question directly but it might offer an insight as to why you should create multiple session objects for each datastore.
This article
explains how you can implement a thread safe lazy singleton for each type of Session you need so that you only have one session per datastore but it's shared across the entire application. So at most you're only ever going to have 2 session objects.
To directly answer your question however, you will need 1 session object per database.


Question:
Possible Duplicate:

  Debugging JavaScript in IE7

Firefox has Web Developer plugin and Firebug for troubleshooting html/css/javascript issues. Google Chrome and Safari have a very similar console and right-click options for "Inspect Element".

Does IE7 have anything similar for troubleshooting layout/html/css issues?

Answer:
Web Development Helper
Web Development Helper is a free browser extension for Internet Explorer that provides a set of tools and utilities for the Web developer, esp. Ajax and ASP.NET developers. The tool provides features such as a DOM inspector, an HTTP tracing tool, and script diagnostics and immediate window.
Web Development Helper works against IE6+, and requires the .NET Framework 2.0 or greater to be installed on the machine.
Once installed, the tool can be activated using the Tools | Web Development Helper command. You can also customize your browser's toolbar to add a button for this command to facilitate frequest use. Clicking on the menu command or browser button brings up the tool's console window and set of commands.
Page Features:
DOM inspector allows viewing all elements, selected elements, or elements matching an ID or CSS class, their attributes and styles.
Capturing a screen shot of the current page.
Viewing page information such as metadata, tags, and linked resources.
.......


Question: I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log?

Answer:
Here is a simple and
very inelegant
&
potentially dangerous
way.
Backup DB
Detach DB
Rename Log file
Attach DB
New log file will be recreated
Delete Renamed Log file.
I'm guessing that you are not doing log backups. (Which truncate the log). My advice is to change recovery model from
full
to
simple
. This will prevent log bloat.


Question:
Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments.  It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen.  (To see an example, click here.)

My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down?  I know this will involve a combination of CSS and javascript.  I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?

Answer:
Okay, I figured it out.  I will post it here in case it help anyone else.  This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think.
```
```
var MenuManager = Class.create({
    initialize: function initialize(menuElt) {
        this.menu = $(menuElt);
        this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) };
        registerEvent(document, 'scroll', this.handleScroll.bind(this));
        this.handleScroll();
    },
    handleScroll: function handleScroll() {
        this.scrollOffset = document.viewport.getScrollOffsets().top;
        if (this.scrollOffset > this.homePosn.y) {
            this.menu.style.position = 'fixed';
            this.menu.style.top = 0;
            this.menu.style.left = this.homePosn.x;
        } else {
            this.menu.style.position = 'absolute';
            this.menu.style.top = null;
            this.menu.style.left = null;
        }
    }
});
```
```
Just call the constructor with the id of your menu, and the class will take it from there.


Question:
I want to convert a number that is in PRTime format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a DateTime.

Note that this is slightly different than the usual "number of milliseconds since 1/1/1970".

Answer:
```
```
Dim prTimeInMillis As UInt64
prTimeInMillis = prTime/1000

Dim prDateTime As New DateTime(1970, 1, 1)
prDateTime = prDateTime.AddMilliseconds(prTimeInMillis)
```
```


Question:
I am building on C++ dll, by writing code in C#.

I get an error, saying

LoaderLock was detected Message:
  Attempting managed execution inside OS
  Loader lock. Do not attempt to run
  managed code inside a DllMain or image
  initialization function since doing so
  can cause the application to hang.

I tried seraching what this error exactly means, but I am drawing pointless articles, mostly saying that it's just a warning, and I should switch that off in Visual Studio.
The other solutions seem to be due to ITunes, or this problem occurring when programming with DirectX. My problem is connected to neither.

Can anybody explain, what this actually means?

Answer:
The general idea of loader lock:
The system runs the code in DllMain inside a lock (as in - synchronization lock). Therefore, running non-trivial code inside DllMain is "asking for a deadlock", as described
here
.
The question is, why are you trying to run code inside DllMain? Is it crucial that this code run inside the context of DllMain or can you spawn a new thread and run the code in it, and not wait for the code to finish execution inside DllMain?
I believe that the problem with manged code specifically, is that running managed code might involves loading the CLR and suchlike and there's no knowing what could happen there that would result in a deadlock... I would not heed the advice of "disable this warning" if I were you because most chances are you'll find your applications hangs unexpectedly under some scenarios.


Question:
If you have an NSMutableArray, how do you shuffle the elements randomly?

(I have my own answer for this, which is posted below, but I'm new to Cocoa and I'm interested to know if there is a better way.)

Update: As noted by @Mukesh, as of iOS 10+ and macOS 10.12+, there is an -[NSMutableArray shuffledArray] method that can be used to shuffle. See https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc for details. (But note that this creates a new array, rather than shuffling the elements in place.)

Answer:
I solved this by adding a category to NSMutableArray.
Edit:
Removed unnecessary method thanks to answer by Ladd.
Edit:
Changed
```
(arc4random() % nElements)
```
to
```
arc4random_uniform(nElements)
```
thanks to answer by Gregory Goltsov and comments by miho and blahdiblah
Edit:
Loop improvement, thanks to comment by Ron
Edit:
Added check that array is not empty, thanks to comment by Mahesh Agrawal
```
```
//  NSMutableArray_Shuffling.h

#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#include <Cocoa/Cocoa.h>
#endif

// This category enhances NSMutableArray by providing
// methods to randomly shuffle the elements.
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end

//  NSMutableArray_Shuffling.m

#import "NSMutableArray_Shuffling.h"

@implementation NSMutableArray (Shuffling)

- (void)shuffle
{
    NSUInteger count = [self count];
    if (count <= 1) return;
    for (NSUInteger i = 0; i < count - 1; ++i) {
        NSInteger remainingCount = count - i;
        NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
        [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
    }
}

@end
```
```


Question: I have an application running under Windows XP, and I'm accessing the Processor and Memory performance counters.  When I try to run the same code and access them on XP Embedded, the counters don't seem to be present.  They are present in the image - I can see them all in perfmon.  What's the missing piece here?

Answer:
Have you added all the WMI components? As far as I know, you need all the WMI components to access the counters!
The Performance Counter Windows Management Instrumentation (WMI) Provider component provides a bridge between the performance registry interface and the WMI interface. This component allows WMI clients to access performance counters through WMI scripts, and allows management applications built using WMI to access performance counters. Without this component, applications must directly use the registry interface or the performance data helper interface to access performance counters.
Thank you TimK for the link (
http://msdn.microsoft.com/en-us/library/aa939695.aspx
)


Question:
Summary

What's the best way to ensure a table cell cannot be less than a certain minimum width.

Example

I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space.

Browser compatibility

I possible I would like to find a solution that works in

IE 6-8

FF 2-3

Safari

In order of preference.

Answer:
This CSS should suffice:
```
```
td { min-width: 100px; }
```
```
However, it's not always obeyed correctly (the min-width attribute) by all browsers (for example, IE6 dislikes it a great deal).
Edit:
As for an IE6 (and before) solution, there isn't one that works reliably under all circumstances, as far as I know.  Using the nowrap HTML attribute doesn't really achieve the desired result, as that just prevents line-breaks in the cell, rather than specifying a minimum width.
However, if nowrap is used in conjunction with a regular cell width property (such as using width: 100px), the 100px will act
like
a minimum width and the cell will still expand with the text (due to the nowrap).  This is a less-than-ideal solution, which cannot be fully applied using CSS and, as such, would be tedious to implement if you have many tables you wish to apply this to.  (Of course, this entire alternative solution falls down if you want to have dynamic line-breaks in your cells, anyway).


Question:
I hope not everyone is using Rational Purify.

So what do you do when you want to measure:

time taken by a function

peak memory usage

code coverage

At the moment, we do it manually [using log statements with timestamps and another script to parse the log and output to excel. phew...)

What would you recommend? Pointing to tools or any techniques would be appreciated!

EDIT: Sorry, I didn't specify the environment first, Its plain C on a proprietary mobile platform

Answer:
nProf
- Free, does that for .NET.
Gets the job done, at least enough to see the 80/20. (20% of the code, taking 80% of the time)


Question:
In Windows, is there an easy way to tell if a folder has a subfile that has changed?

I verified, and the last modified date on the folder does not get updated when a subfile changes.

Is there a registry entry I can set that will modify this behavior?

If it matters, I am using an NTFS volume.

I would ultimately like to have this ability from a C++ program.

Scanning an entire directory recursively will not work for me because the folder is much too large.

Update: I really need a way to do this without a process running while the change occurs.  So installing a file system watcher is not optimal for me.

Update2: The archive bit will also not work because it has the same problem as the last modification date.  The file's archive bit will be set, but the folders will not.

Answer:
If you can't run a process when the change occurs, then there's not much you can do except scan the filesystem, and check the modification date/time.  This requires you to store each file's last date/time, though, and compare.
You can speed this up by using the
archive bit
(though it may mess up your backup software, so proceed carefully).
An archive bit is a file attribute
  present in many computer file systems,
  notably FAT, FAT32, and NTFS. The
  purpose of an archive bit is to track
  incremental changes to files for the
  purpose of backup, also called
  archiving.
As the archive bit is a binary bit, it
  is either 1 or 0, or in this case more
  frequently called set (1) and clear
  (0). The operating system sets the
  archive bit any time a file is
  created, moved, renamed, or otherwise
  modified in any way. The archive bit
  therefore represents one of two
  states: "changed" and "not changed"
  since the last backup.
Archive bits are not affected by
  simply reading a file. When a file is
  copied, the original file's archive
  bit is unaffected, however the copy's
  archive bit will be set at the time
  the copy is made.
So the process would be:
Clear the archive bit on all the files
Let the file system change over time
Scan all the files - any with the archive bit set have changed
This will eliminate the need for your program to keep state, and since you're only going over the directory entries (where the bit is stored) and they are clustered, it should be very, very fast.
If you can run a process during the changes, however, then you'll want to look at the
FileSystemWatcher
class.  Here's an
example
of how you might use it.
It also exists in
.NET
(for future searchers of this type of problem)
Perhaps you can leave a process running on the machine watching for changes and creating a file for you to read later.
-Adam


Question:
Just got a request from my boss for an application I'm working on. Basically we're getting an email address setup for an external client to submit excel files to.

What I need is a way to automatically pick up any email sent to this address, so I can take the attachment, process it and save it to a folder.

Any information of even where to start would be helpful.\

Note: We're using a lotus notes server to do this, but a generic way would be more helpful (If possible).

Answer:
Email -> mailserver ->[something] -> file-on-disk.
File on disk is pretty easy to parse, use
JavaMail
.
The [something] could be:
listener for smtp connections (overkill)!
Pop3
/
imap
client
Maildir
/Mailbox


Question: When using an aggregate control in some reports you would prefer to see a blank field instead of 0.  There does not appear to be a way to do this automatically.  Does anyone have a way that this can be done.  Note, you want to maintain the '0' value for the field in cases when you export, but you want to show a blank when rendering to PDF or HTML.

Answer:
There are a number of ways to solve this.  The two primary are to use either visibility rules or highlights to create conditional formatting.  The visibility is particularly attractive since it is easy to only apply the format rules to particular types of output (e.g. HTML).
For this particular case, there are two problems with these approaches.  First, I want a general solutions where I don't have to specify the text color.  In other words, when the condition is true (value of 0) then I want my text color to match the background color.  In that way if someone changes the backgroundColor for the control, the code still works.
The other issue is that in this case I am using dynamic column binding which does not support value lookup.
The solution that I created was to add a JavaScript function called hideMe as shown below.
```
```
function hideText (dataControl){
    if (dataControl.getValue() == 0) {
        var color = dataControl.getStyle().getBackgroundColor();
        var parentItem = dataControl.getParent();
        do {
            if (color == null && parentItem != null) {
                color = parentItem.getStyle().getBackgroundColor();
                parentItem = parentItem.getParent();
            } else {
                break;
            }

        } while (color == null);
        dataControl.getStyle().color = color;
    }
}
```
```
Once this function has been added to the report (in my case an included javascript file) I just call it from the OnCreate method of the control.
```
```
hideText(this);
```
```
This can also be done using Java Event Handlers but this method seems to be easier.


Question:
Is the standard Java 1.6 javax.xml.parsers.DocumentBuilder class thread safe? Is it safe to call the parse() method from several threads in parallel?

The JavaDoc doesn't mention the issue, but the JavaDoc for the same class in Java 1.4 specifically says that it isn't meant to be concurrent; so can I assume that in 1.6 it is?

The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.

Answer:
Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:
```
```
private static final ThreadLocal<DocumentBuilder> builderLocal =
    new ThreadLocal<DocumentBuilder>() {
        @Override protected DocumentBuilder initialValue() {
            try {
                return
                    DocumentBuilderFactory
                        .newInstance(
                            "xx.MyDocumentBuilderFactory",
                            getClass().getClassLoader()
                        ).newDocumentBuilder();
            } catch (ParserConfigurationException exc) {
                throw new IllegalArgumentException(exc);
            }
        }
    };
```
```
(Disclaimer: Not so much as attempted to compile the code.)


Question: Is there a way to access file system info via some type of Windows API? If not what other methods are available to a user mode developer?

Answer:
Not very clean, but you can use
```
DeviceIoControl()
```
Open volume as a file, pass resulting handle to
```
DeviceIoControl()
```
together with control code. Check MSDN for control codes, there is something like "read journal record".


Question:
Is there a difference (performance, overhead) between these two ways of merging data sets?

MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);

and

MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);

Which do you recommend?

Answer:
Those two lines do different things.
The first one creates a new set, and then merges a second set into it.
The second one sets the ds reference to point to the second set, so:
```
```
MyTypedDataSet ds1 = new MyTypedDataSet();
ds1.Merge(anotherDataSet);
//ds1 is a copy of anotherDataSet
ds1.Tables.Add("test")

//anotherDataSet does not contain the new table

MyTypedDataSet ds2 = anotherDataSet;
//ds12 actually points to anotherDataSet
ds2.Tables.Add("test");

//anotherDataSet now contains the new table
```
```
Ok, let's assume that what you meant was:
```
```
MyClass o1 = new MyClass();
o1.LoadFrom( /* some data */ );

//vs

MyClass o2 = new MyClass( /* some data */ );
```
```
Then the latter is better, as the former creates an empty object before populating it.
However unless initialising an empty class has a high cost or is repeated a large number of times the difference is not that important.


Question:
I'm creating an ASP.NET web site where all pages hang off a database-driven tree-hierarchy.  Pages typically present HTML content.  But, some will execute programming.

Examples:

a "contact us" form

a report generator

How should I represent/reference the programming within the database?  Should I have a varchar value of a Web User Control (.ascx) name?  Or a Web Form (.aspx) name?  Something else?  Or should it just be an integer or other such ID in a dictionary within my application?

Can I make an ASP.NET Site Map Provider with this structure?

See more information here: Which is the best database schema for my navigation?

Answer:
Our development team has had success with defining the name of a Web User Control in the database. Upon page load it checks too see what controls to dynamically load from the database.
We use Web User Controls instead of Web Forms in order to ensure we can use the control on any page.
You can also dynamically build a site map using ASP.Net's provider.
CodeProject
has a good example.


Question:
I was reviewing some code that a consultant checked in and notice they were using SQLCLR.  I don't have any experience with it so thought I would research what it was about.  I noticed that they used

Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" & sDb)

instead of

DIM conn As New SqlConnection("context connection=true")

I'm wondering what the difference since it's localhost on the first?

Answer:
The context connection uses the user's already established connection to the server.  So you inherit things like their database context, connection options, etc.
Using localhost will connect to the server using a normal shared memory connection.  This can be useful if you don't want to use the user's connection (i.e. if you want to connect to a different database, or with different options, etc).
In most cases you should use the context connection, since it doesn't create a separate connection to the server.
Also, be warned that using a separate connection means you are not part of the user's transaction and are subject to normal locking semantics.


Question:
The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:

n = 5.59
round(n, 1) # 5.6

But, in actuality, good old floating point weirdness creeps in and you get:

5.5999999999999996

For the purposes of UI, I need to display 5.6. I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. See here also.

Short of creating my own round library, is there any way around this?

Answer:
What about:
```
```
round(n,1)+epsilon
```
```


Question: My application has a need to let the user choose a date from a list of dates conforming to a certain pattern. For instance, they may need to choose a monday from a list Monday's for a month. Is there a way to get a UIDatePicker to limit date choices to a certain subset or should I just use a UIPickerView?

Answer:
You cannot limit which dates are selectable in a
```
UIDatePicker
```
. You could change the date when the value changed event is sent, but since the user cannot tell which dates are "good" and which are not, it's a bad UI choice to do so.
Use a
```
UIPickerView
```
of your own making instead.


Question: I have heard that the Liskov Substitution  Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?

Answer:
Would implementing ThreeDBoard in terms of an array of Board be that useful?
Perhaps you may want to treat slices of ThreeDBoard in various planes as a Board. In that case you may want to abstract out an interface (or abstract class) for Board to allow for multiple implementations.
In terms of external interface, you might want to factor out a Board interface for both TwoDBoard and ThreeDBoard (although none of the above methods fit).


Question:
A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results?

I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like.

(Any sample web service can be chosen as an example.)

Answer:
```
```
import org.restlet.Client;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Response;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.Node;

/**
 * Uses YAHOO!'s RESTful web service with XML.
 */
public class YahooSearch {
    private static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";

    public static void main(final String[] args) {
        if (1 != args.length) {
            System.err.println("You need to pass a search term!");
        } else {
            final String term = Reference.encode(args[0]);
            final String uri = BASE_URI + "?appid=restbook&query=" + term;
            final Response response = new Client(Protocol.HTTP).get(uri);
            final DomRepresentation document = response.getEntityAsDom();

            document.setNamespaceAware(true);
            document.putNamespace("y", "urn:yahoo:srch");

            final String expr = "/y:ResultSet/y:Result/y:Title/text()";
            for (final Node node : document.getNodes(expr)) {
                System.out.println(node.getTextContent());
            }
        }
    }
}
```
```
This code uses
Restlet
to make a request to Yahoo's RESTful search service. Obviously, the details of the web service you are using will dictate what your client for it looks like.


Question:
I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.

if (YesNoDialog.ask("Are you sure?") == true) {
  // yes was chosen
} else {
  // no was chosen
}

Answer:
I dont have programed in Java ME, but i found in it's reference for optional packages the
Advanced Graphics and User Interface API
, and it's used like the Java SE API to create these dialogs with the
JOptionPane Class
```
int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object >message, java.lang.String title, int optionType)
```
Return could be
```
JOptionPane.YES_OPTION
```
,
```
JOptionPane.NO_OPTION
```
,
```
JOptionPane.CANCEL_OPTION
```
...


Question:
Encouraged by SO, I'm trying to write an ASP.NET site that uses OpenID for user authentication.  It's a regular WinForms site (not MVC.NET), using the DotNetOpenId library for authentication.

Is it safe for me to permit/deny administrative functions on the site by simply comparing the current session's "ClaimedID" (as returned in the OpenIdLogin_LoggedIn event, as member DotNetOpenId.RelyingParty,OpenIdEventArgs.Response.ClaimedIdentifier) to a known administrator's OpenID (i.e. mine)?

If so, is it safe for this ID to be visible (e.g. in open source code), or should it be "hidden" in a configuration file or a database row?  (I know it's better design to make it configurable, my question is just about safety.)

Answer:
My solution is to follow the same idea of the Roles table. After you've authenticated the user, look up that user's roles. If the user has role "Administrator" in the UserRoles table, then they can do whatever the Administrator can do.
I don't broadcast open ID's in my app. They're stored in the table. On every action result, I'm hitting the Users table, since I have also modified mine to store various user state information. With the exception of the home page, there is going to be some user information that I need from that table. I'm using LINQ, so I include the .LoadWith() to load the User with his list of roles when it serializes.


Question:
We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...

I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:

Value
----------
   143.55
  3532.13
     1.75

How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".

I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.

Thank you.

Answer:
The
STR function
has an optional length argument as well as a number-of-decimals one.
```
```
SELECT STR(123.45, 6, 1)

------
 123.5

(1 row(s) affected)
```
```


Question:
The code

private SomeClass<Integer> someClass;
someClass = EasyMock.createMock(SomeClass.class);

gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>".

Answer:
The two obvious routes are to suppress the warning or mock a subclass.
```
```
private static class SomeClass_Integer extends SomeClass<Integer>();
private SomeClass<Integer> someClass;
...
    someClass = EasyMock.createMock(SomeClass_Integer.class);
```
```
(Disclaimer: Not even attempted to compile this code, nor have I used EasyMock.)


Question:
In the following snippet:

public class a {
    public void otherMethod(){}
    public void doStuff(String str, InnerClass b){}
    public void method(a){
        doStuff("asd",
            new InnerClass(){
                public void innerMethod(){
                    otherMethod();
                }
            }
        );
    }
}

Is there a keyword to refer to the outer class from the inner class?  Basically what I want to do is outer.otherMethod(), or something of the like, but can't seem to find anything.

Answer:
In general you use
```
OuterClassName.this
```
to refer to the enclosing instance of the outer class.
In your example that would be
```
a.this.otherMethod()
```


Question:
I'm currently looping through a datareader and calling the System.Net.Mail.SmtpClient's Send() method. The problem with this is that it's slow. Each email takes about 5-10 seconds to send (it's possible this is just an issue with my host). I had to override the executionTimeout default in my web.config file (it defaults to 90 seconds) like this:

 <httpRuntime executionTimeout="3000" />

One caveat: I'm on a shared host, so I don't think it is possible for me to send using the PickupDirectoryFromIis option (at least, it gave me errors when I turned it on).

Answer:
You could send the mail asynchronous. That way the timeout should not interrupt your sending.
This article should help you get started with that:
Sending Emails Asynchronously in C#
.
There is another approach here:
http://www.vikramlakhotia.com/Sending_Email_asynchronously_in_AspNet_20.aspx
And off course there are several commercial clients available, but the only one that i have tried and can recommend is
http://www.aspnetemail.com/


Question:
A Sprint cellular modem plugs into a laptop - often the PCMCIA slot. To connect, the user opens a program called the Connection Manager. This program has a menu option to display the serial number and phone number of the modem that's currently inserted.

Does that imply that the serial/phone number of the modem could be available to other programs running on the system? (Note: let's assume this is Windows XP.)

Specifically, could a company's VPN software be configured to pass along information about which modem is being used to connect?

Finally, is there existing VPN software that already does this, or would it have to be custom-programmed?

Answer:
You could send the mail asynchronous. That way the timeout should not interrupt your sending.
This article should help you get started with that:
Sending Emails Asynchronously in C#
.
There is another approach here:
http://www.vikramlakhotia.com/Sending_Email_asynchronously_in_AspNet_20.aspx
And off course there are several commercial clients available, but the only one that i have tried and can recommend is
http://www.aspnetemail.com/


Question:
What CSS should I use to make a cell's border appear even if the cell is empty?

IE 7 specifically.

Answer:
If I recall, the cell dosn't exist in some IE's unless it's filled with something...
If you can put a
```

```
(non-breaking space) to fill the void, that will usually work. Or do you require a pure CSS solution?
Apparently, IE8 shows the cells by default, and you have to hide it with
```
empty-cells:hide
```
But it doesn't work at all in IE7 (which hides by default).


Question: I want to create dynamic content based on this. I know it's somewhere, as web analytics engines can get this data to determine how people got to your site (referrer, search terms used, etc.), but I don't know how to get at it myself.

Answer:
You can use the "referer" part of the request that the user sent to figure out what he searched for. Example from Google:
http://www.google.no/search?q=stack%20overflow
So you must search the string (in ASP(.NET) this can be found be looking in
```
Request.Referer
```
) for "q=" and then URLDecode the contents.
Also, you should take a look at this article that talks more about referrers and also other methods to track your visitors:
http://www.15seconds.com/issue/021119.htm


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

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


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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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


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

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

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

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

Thanks!

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


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

Answer:
```
```
SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >
```
```


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

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

Thanks

Nick

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

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


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

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

Answer:
```
```
cvs history -u username
```
```
gives a history of changes the user has made


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

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

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

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


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

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

Therefore, the sys admin has 2 options so far:

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

Delete and recreate the user.

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

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

Is this the way to go?

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


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

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

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


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

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

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

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

Hope you get my point.

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


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

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


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

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

Example code:

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

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

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


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

My page is

http://localhost/index.html

I would like to make a ajax get request to:

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

I am getting this error:

Access to restricted URI denied (NS_ERROR_DOM_BAD_URI)

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

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


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

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


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

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

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

Example

// Fails
Activator.CreateInstance(type);

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

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

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

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

Did I miss something or it isn't possible?

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


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

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

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

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


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

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

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

Answer:
Nope
3.5 is completely compatible with 2.0, not the other way around of course


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

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

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


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

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


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

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


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

Example

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

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

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


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

I've tried:

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

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

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


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

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


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

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

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


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

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

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

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


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

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

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

Answer:
Do you mean:
```
```
public class MyServlet extends HttpServlet {

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

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


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

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

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


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

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


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

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

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

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

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


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

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

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

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

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


Question:
Scenario:

The user has two monitors.

Their browser is open on the secondary monitor.

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

The popup window always opens on their primary monitor.

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

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


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

For example:

I get back:

&#x01ce;

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

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

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

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

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


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

xAy

becomes

xay

and

xZy

becomes

xzy

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

UPDATE

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

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

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


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

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

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

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


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

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


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

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


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

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

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


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

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

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

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

Thanks,
Nikhil

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


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

Scenario

The browser requests a page, say SendEmails.aspx

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

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

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

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

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


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

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

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


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

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

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

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

set autot trace exp

select * from mytab where y=5000;

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


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

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

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

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


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

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

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


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

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

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

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


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

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

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

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

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

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

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


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

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


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

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

Answer:
```
```
using System.Diagnostics;

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


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

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

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


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

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

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


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

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

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


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

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


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

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


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

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

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


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

ls > list.txt

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

Something like:

ls > ${pwd}.txt

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

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

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


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

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

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

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


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

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


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

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

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


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

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

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

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


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

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

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

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

SELECT @weight_sum = SUM(weight)
FROM @table

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

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

SELECT @id
```
```


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

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

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

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