q:
I have been trying to find an easy way to parse a search query and convert it to an SQL query for my DB.

I have found two solutions:

Lucene: Powerful Java-based search engine, contains a query parser but it isn't very configurable and I could find a way to easily hack/adapt it to create SQL queries.

ANTLR: A veteran text lexer-parser. Used for building anything from compilers to sky scrapers. ANTLR is highly configurable but everyone touching the code from now on will have to learn a new language...

Any other ideas?

[A]
Depends a lot on the kind of queries you've got to parse and somewhat on the structure of the data in your database. I'm going to assume that you're not trying to do full text search in a DB (i.e. a search engine across your entire DB) because, as most Information Retrieval people will tell you, the performance for that is terrible. Inverted indexes are most certainly the best way of doing that.
Tell us a bit more about the actual problem: what are the users going to input, what are they expecting as output, and what's the data model like. Design a search solution without those pieces of information, and you'll get a far from optimal result.


q: When I've registered an object foo to receive KVO notifications from another object bar (using addObserver:...), if I then deallocate foo do I need to send a removeObserver:forKeyPath: message to bar in -dealloc?

[A]
You need to use
```
-removeObserver:forKeyPath:
```
to remove the observer before
```
-[NSObject dealloc]
```
runs, so yes, doing it in the
```
-dealloc
```
method of your class would work.
Better than that though would be to have a deterministic point where whatever owns the object that's doing the observing could tell it it's done and will (eventually) be deallocated.  That way, you can stop observing immediately when the thing doing the observing is no longer needed, regardless of when it's actually deallocated.
This is important to keep in mind because the lifetime of objects in Cocoa isn't as deterministic as some people seem to think it is.  The various Mac OS X frameworks themselves
will
send your objects
```
-retain
```
and
```
-autorelease
```
, extending their lifetime beyond what you might otherwise think it would be.
Furthermore, when you make the transition to Objective-C garbage collection, you'll find that
```
-finalize
```
will run at very different times — and in very different contexts — than
```
-dealloc
```
did.  For one thing, finalization takes place on a different thread, so you really
can't
safely send
```
-removeObserver:forKeyPath:
```
to another object in a
```
-finalize
```
method.
Stick to memory (and other scarce resource) management in
```
-dealloc
```
and
```
-finalize
```
, and use a separate
```
-invalidate
```
method to have an owner tell an object you're done with it at a deterministic point; do things like removing KVO observations there.  The intent of your code will be clearer and you will have fewer subtle bugs to take care of.

s: huggingface

c: devops

d: intermediate


q:
I'd like to have a python program alert me when it has completed its task by making a beep noise.  Currently,  I use import os and then use a command line speech program to say "Process complete".  I much rather it be a simple "bell."

I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't think that has much anything to do with this.

I've also tried

print(\a)

but that didn't work.

I'm using a Mac, if you couldn't tell by my Cocoa comment, so that may help.

[A]
Have you tried :
```
```
import sys
sys.stdout.write('\a')
sys.stdout.flush()
```
```
That works for me here on Mac OS 10.5
Actually, I think your original attempt works also with a little modification:
```
```
print('\a')
```
```
(You just need the single quotes around the character sequence).


q: Other than Notepad++, what text editor do you use to program in Windows?

[A]
Textpad
is what I would use for random text editing (checking out HTML source, quick hackery, scripts and the like).
For actual Java development it's Eclipse all the way, although people tell me the IDEA is the cat's pyjamas.


q: I'm seeing strange errors when my C++ code has min() or max() calls. I'm using Visual C++ compilers.

[A]
Check if your code is including the
windows.h
header file and either your code or other third-party headers have their own
min()
/
max()
definitions. If yes, then prepend your
windows.h
inclusion with a definition of
NOMINMAX
like this:
```
```
#define NOMINMAX
#include <windows.h>
```
```


q:
I've only done a bit of Flex development thus far, but I've preferred the approach of creating controls programmatically over mxml files, because (and please, correct me if I'm wrong!) I've gathered that you can't have it both ways -- that is to say, have the class functionality in a separate ActionScript class file but have the contained elements declared in mxml.

There doesn't seem to be much of a difference productivity-wise, but doing data binding programmatically seems somewhat less than trivial. I took a look at how the mxml compiler transforms the data binding expressions. The result is a bunch of generated callbacks and a lot more lines than in the mxml representation. So here's the question: is there a way to do data binding programmatically that doesn't involve a world of hurt?

[A]
Don't be afraid of MXML. It's great for laying out views. If you write your own
reusable
components then writing them in ActionScript may sometimes give you a little more control, but for non-reusable views MXML is much better. It's more terse, bindings are extemely easy to set up, etc.
However, bindings in pure ActionScript need not be that much of a pain. It will never be as simple as in MXML where a lot of things are done for you, but it can be done with not too much effort.
What you have is
```
BindingUtils
```
and it's methods
```
bindSetter
```
and
```
bindProperty
```
. I almost always use the former, since I usually want to do some work, or call
```
invalidateProperties
```
when values change, I almost never just want to set a property.
What you need to know is that these two return an object of the type
```
ChangeWatcher
```
, if you want to remove the binding for some reason, you have to hold on to this object. This is what makes manual bindings in ActionScript a little less convenient than those in MXML.
Let's start with a simple example:
```
```
BindingUtils.bindSetter(nameChanged, selectedEmployee, "name");
```
```
This sets up a binding that will call the method
```
nameChanged
```
when the
```
name
```
property on the object in the variable
```
selectedEmployee
```
changes. The
```
nameChanged
```
method will recieve the new value of the
```
name
```
property as an argument, so it should look like this:
```
```
private function nameChanged( newName : String ) : void
```
```
The problem with this simple example is that once you have set up this binding it will fire each time the property of the specified object changes. The value of the variable
```
selectedEmployee
```
may change, but the binding is still set up for the object that the variable pointed to before.
There are two ways to solve this: either to keep the
```
ChangeWatcher
```
returned by
```
BindingUtils.bindSetter
```
around and call
```
unwatch
```
on it when you want to remove the binding (and then setting up a new binding instead), or bind to yourself. I'll show you the first option first, and then explain what I mean by binding to yourself.
The
```
currentEmployee
```
could be made into a getter/setter pair and implemented like this (only showing the setter):
```
```
public function set currentEmployee( employee : Employee ) : void {
    if ( _currentEmployee != employee ) {
        if ( _currentEmployee != null ) {
            currentEmployeeNameCW.unwatch();
        }

        _currentEmployee = employee;

        if ( _currentEmployee != null ) {
            currentEmployeeNameCW = BindingUtils.bindSetter(currentEmployeeNameChanged, _currentEmployee, "name");
        }
    }
}
```
```
What happens is that when the
```
currentEmployee
```
property is set it looks to see if there was a previous value, and if so removes the binding for that object (
```
currentEmployeeNameCW.unwatch()
```
), then it sets the private variable, and unless the new value was
```
null
```
sets up a new binding for the
```
name
```
property. Most importantly it saves the
```
ChangeWatcher
```
returned by the binding call.
This is a basic binding pattern and I think it works fine. There is, however, a trick that can be used to make it a bit simpler. You can bind to yourself instead. Instead of setting up and removing bindings each time the
```
currentEmployee
```
property changes you can have the binding system do it for you. In your
```
creationComplete
```
handler (or constructor or at least some time early) you can set up a binding like so:
```
```
BindingUtils.bindSetter(currentEmployeeNameChanged, this, ["currentEmployee", "name"]);
```
```
This sets up a binding not only to the
```
currentEmployee
```
property on
```
this
```
, but also to the
```
name
```
property on this object. So anytime either changes the method
```
currentEmployeeNameChanged
```
will be called. There's no need to save the
```
ChangeWatcher
```
because the binding will never have to be removed.
The second solution works in many cases, but I've found that the first one is sometimes necessary, especially when working with bindings in non-view classes (since
```
this
```
has to be an event dispatcher and the
```
currentEmployee
```
has to be bindable for it to work).


q: What are the basic steps to compile an OpenGL application using GLUT (OpenGL Utility Toolkit) under Visual C++ Express Edition?

[A]
If you don't have Visual C++ Express Edition (VCEE), download and install
VCEE
.
The default install of Visual C++ Express Edition builds for the .Net platform. We'll need to build for the Windows platform since OpenGL and GLUT are not yet fully supported under .Net. For this we need the Microsoft Platform SDK. (If you're using an older version of VCEE, download and install the
Microsoft Platform SDK
. Visual C++ Express Edition will need to be configured to build for Windows platform. All these instructions are available
here
.)
If you don't have GLUT, download and unzip Nate Robin's
Windows port of GLUT
.
Add
glut.h
to your
Platform SDK/include/GL/
directory
Link the project with
glut.lib
. (Go to VCEE
Project Properties -> Additional Linker Directories
and add the directory which has
glut.lib
.
Add
glut.dll
to the
Windows/System32
directory, so that all programs using GLUT
can find it at runtime.
Your program which uses GLUT or OpenGL should compile under Visual C++ Express Edition now.


q:
I'd like to provide some way of creating dynamically loadable plugins in my software.
Typical way to do this is using the LoadLibrary WinAPI function to load a dll and calling GetProcAddress to get an pointer to a function inside that dll.

My question is how do I dynamically load a plugin in C#/.Net application?

[A]
The following code snippet (C#) constructs an instance of any concrete classes derived from
```
Base
```
found in class libraries (*.dll) in the application path and stores them in a list.
```
```
using System.IO;
using System.Reflection;

List<Base> objects = new List<Base>();
DirectoryInfo dir = new DirectoryInfo(Application.StartupPath);

foreach (FileInfo file in dir.GetFiles("*.dll"))
{
    Assembly assembly = Assembly.LoadFrom(file.FullName);
    foreach (Type type in assembly.GetTypes())
    {
        if (type.IsSubclassOf(typeof(Base)) && type.IsAbstract == false)
        {
            Base b = type.InvokeMember(null,
                                       BindingFlags.CreateInstance,
                                       null, null, null) as Base;
            objects.Add(b);
        }
    }
}
```
```
Edit:
The classes referred to by
Matt
are probably a better option in .NET 3.5.


q: In my C/C++ program, I'm using OpenCV to capture images from my webcam. The camera (Logitech QuickCam IM) can capture at resolutions 320x240, 640x480 and 1280x960. But, for some strange reason, OpenCV gives me images of resolution 320x240 only. Calls to change the resolution using cvSetCaptureProperty() with other resolution values just don't work. How do I capture images with the other resolutions possible with my webcam?

[A]
There doesn't seem to be a solution. The resolution can be increased to
640x480
using
this hack
shared by
lifebelt77
. Here are the details reproduced:
Add to
highgui.h
:
```
```
#define CV_CAP_PROP_DIALOG_DISPLAY 8
#define CV_CAP_PROP_DIALOG_FORMAT 9
#define CV_CAP_PROP_DIALOG_SOURCE 10
#define CV_CAP_PROP_DIALOG_COMPRESSION 11
#define CV_CAP_PROP_FRAME_WIDTH_HEIGHT 12
```
```
Add the function
icvSetPropertyCAM_VFW
to
cvcap.cpp
:
```
```
static int icvSetPropertyCAM_VFW( CvCaptureCAM_VFW* capture, int property_id, double value )
{
    int result = -1;
    CAPSTATUS capstat;
    CAPTUREPARMS capparam;
    BITMAPINFO btmp;

    switch( property_id )
    {
        case CV_CAP_PROP_DIALOG_DISPLAY:
            result = capDlgVideoDisplay(capture->capWnd);
            //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEODISPLAY,0,0);
            break;

        case CV_CAP_PROP_DIALOG_FORMAT:
            result = capDlgVideoFormat(capture->capWnd);
            //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOFORMAT,0,0);
            break;

        case CV_CAP_PROP_DIALOG_SOURCE:
            result = capDlgVideoSource(capture->capWnd);
            //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOSOURCE,0,0);
            break;

        case CV_CAP_PROP_DIALOG_COMPRESSION:
            result = capDlgVideoCompression(capture->capWnd);
            break;

        case CV_CAP_PROP_FRAME_WIDTH_HEIGHT:
            capGetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));
            btmp.bmiHeader.biWidth = floor(value/1000);
            btmp.bmiHeader.biHeight = value-floor(value/1000)*1000;
            btmp.bmiHeader.biSizeImage = btmp.bmiHeader.biHeight *
            btmp.bmiHeader.biWidth * btmp.bmiHeader.biPlanes *
            btmp.bmiHeader.biBitCount / 8;
            capSetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));
            break;

        default:
            break;
    }

    return result;
}
```
```
and edit
captureCAM_VFW_vtable
as following:
```
```
static CvCaptureVTable captureCAM_VFW_vtable =
{
6,
(CvCaptureCloseFunc)icvCloseCAM_VFW,
(CvCaptureGrabFrameFunc)icvGrabFrameCAM_VFW,
(CvCaptureRetrieveFrameFunc)icvRetrieveFrameCAM_VFW,
(CvCaptureGetPropertyFunc)icvGetPropertyCAM_VFW,
(CvCaptureSetPropertyFunc)icvSetPropertyCAM_VFW, // was NULL
(CvCaptureGetDescriptionFunc)0
};
```
```
Now rebuilt
highgui.dll
.


q: How do I convert the RGB values of a pixel to a single monochrome value?

[A]
I found one possible solution in the
Color FAQ
. The
luminance component
Y (from the
CIE XYZ system
) captures what is most perceived by humans as color in one channel. So, use those coefficients:
```
```
mono = (0.2125 * color.r) + (0.7154 * color.g) + (0.0721 * color.b);
```
```


q: Is it possible to compile and run OpenGL programs from under Cygwin? If yes, how?

[A]
It is possible to compile and run OpenGL programs under Cygwin. I illustrate the basic steps here:
I assume you know OpenGL programming. If not, get the
Red Book
(
The OpenGL Programming Guide
). It is mandatory reading for OpenGL anyway.
I assume you have Cygwin installed. If not, visit
cygwin.com
and install it.
To compile and run OpenGL programs, you need the Cygwin package named
opengl
. In the Cygwin installer, it can be found under the
Graphics section
. Please install this package.
Write a simple OpenGL program, say
ogl.c
.
Compile the program using the flags
-lglut32 -lglu32 -lopengl32
. (This links your program with the GLUT, GLU and OpenGL libraries. An OpenGL program might typically use functions from all the 3 of them.) For example:
$ gcc ogl.c -lglut32 -lglu32 -lopengl32
Run the program. It's as simple as that!


q: I want to use the mouse scrollwheel in my OpenGL GLUT program to zoom in and out of a scene? How do I do that?

[A]
Note that venerable
Nate Robin's GLUT
library doesn't support the scrollwheel. But, later implementations of GLUT like
FreeGLUT
do.
Using the scroll wheel in FreeGLUT is dead simple. Here is how:
Declare a callback function that shall be called whenever the scroll wheel is scrolled. This is the prototype:
```
```
void mouseWheel(int, int, int, int);
```
```
Register the callback with the (Free)GLUT function
glutMouseWheelFunc()
.
```
```
glutMouseWheelFunc(mouseWheel);
```
```
Define the callback function. The second parameter gives the direction of the scroll. Values of +1 is forward, -1 is backward.
```
```
void mouseWheel(int button, int dir, int x, int y)
{
    if (dir > 0)
    {
        // Zoom in
    }
    else
    {
        // Zoom out
    }

    return;
}
```
```
That's it!


q:
With the Visual Studio 2005 C++ compiler, I get the following warning when my code uses the fopen() and such calls:

1>foo.cpp(5) : warning C4996: 'fopen' was declared deprecated
1>        c:\program files\microsoft visual studio 8\vc\include\stdio.h(234) : see declaration of 'fopen'
1>        Message: 'This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.'

How do I prevent this?

[A]
It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like
fopen_s
), you need to place a definition of
_CRT_SECURE_NO_DEPRECATE
before your included header files. For example:
```
```
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
```
```
The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add
_CRT_SECURE_NO_DEPRECATE
to
Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions
.


q:
In my simple OpenGL program I get the following error about exit redefinition:

1>c:\program files\microsoft visual studio 8\vc\include\stdlib.h(406) : error C2381: 'exit' : redefinition; __declspec(noreturn) differs
1>        c:\program files\microsoft visual studio 8\vc\platformsdk\include\gl\glut.h(146) : see declaration of 'exit'

I'm using Nate Robins' GLUT for Win32 and get this error with Visual Studio 2005 or Visual C++ 2005 (Express Edition). What is the cause of this error and how do I fix it?

[A]
Cause:
The
stdlib.h
which ships with the recent versions of Visual Studio has a different (and conflicting) definition of the
exit()
function. It clashes with the definition in
glut.h
.
Solution:
Override the definition in glut.h with that in stdlib.h. Place the stdlib.h line above the glut.h line in your code.
```
```
#include <stdlib.h>
#include <GL/glut.h>
```
```


q: I want to use the functions exposed under the OpenGL extensions. I'm on Windows, how do I do this?

[A]
Easy solution
: Use
GLEW
. See how
here
.
Hard solution
:
If you have a
really strong reason
not to use GLEW, here's how to achieve the same without it:
Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the
OpenGL Extension Registry
.
Example: I wish to use the capabilities of the
EXT_framebuffer_object
extension. The APIs I wish to use from this extension are:
```
```
glGenFramebuffersEXT()
glBindFramebufferEXT()
glFramebufferTexture2DEXT()
glCheckFramebufferStatusEXT()
glDeleteFramebuffersEXT()
```
```
Check if your graphic card supports the extension you wish to use. If it does, then your work is almost done! Download and install the latest drivers and SDKs for your graphics card.
Example: The graphics card in my PC is a
NVIDIA 6600 GT
. So, I visit the
NVIDIA OpenGL Extension Specifications
webpage and find that the
EXT_framebuffer_object
extension is supported. I then download the latest
NVIDIA OpenGL SDK
and install it.
Your graphic card manufacturer provides a
glext.h
header file (or a similarly named header file) with all the declarations needed to use the supported OpenGL extensions. (Note that not all extensions might be supported.) Either place this header file somewhere your compiler can pick it up or include its directory in your compiler's include directories list.
Add a
```
#include <glext.h>
```
line in your code to include the header file into your code.
Open
glext.h
, find the API you wish to use and grab its corresponding
ugly-looking
declaration.
Example: I search for the above framebuffer APIs and find their corresponding ugly-looking declarations:
```
```
typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); for GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);
```
```
All this means is that your header file has the API declaration in 2 forms. One is a wgl-like ugly function pointer declaration. The other is a sane looking function declaration.
For each extension API you wish to use, add in your code declarations of the function name as a type of the ugly-looking string.
Example:
```
```
PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT;
PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT;
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT;
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT;
PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT;
```
```
Though it looks ugly, all we're doing is to declare function pointers of the type corresponding to the extension API.
Initialize these function pointers with their rightful functions. These functions are exposed by the library or driver. We need to use
wglGetProcAddress()
function to do this.
Example:
```
```
glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress("glGenFramebuffersEXT");
glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress("glBindFramebufferEXT");
glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress("glFramebufferTexture2DEXT");
glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress("glCheckFramebufferStatusEXT");
glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress("glDeleteFramebuffersEXT");
```
```
Don't forget to check the function pointers for
NULL
. If by chance
wglGetProcAddress()
couldn't find the extension function, it would've initialized the pointer with NULL.
Example:
```
```
if (NULL == glGenFramebuffersEXT || NULL == glBindFramebufferEXT || NULL == glFramebufferTexture2DEXT
    || NULL == glCheckFramebufferStatusEXT || NULL == glDeleteFramebuffersEXT)
{
    // Extension functions not loaded!
    exit(1);
}
```
```
That's it, we're done! You can now use these function pointers just as if the function calls existed.
Example:
```
```
glGenFramebuffersEXT(1, &fbo);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorTex[0], 0);
```
```
Reference:
Moving Beyond OpenGL 1.1 for Windows
by Dave Astle — The article is a bit dated, but has all the information you need to understand why this pathetic situation exists on Windows and how to get around it.


q:
What is the best way to make a delphi application (delphi 2007 for win32 here) go completely full screen, removing the application border and covering windows task bar ?

I am looking for something similar to what IE does when you hit F11.

I wish this to be a run time option for the user not a design time decision by my good self.

As Mentioned in the accepted answer

BorderStyle := bsNone;

was part of the way to do it.  Strangely I kept getting a E2010 Incompatible types: 'TFormBorderStyle' and 'TBackGroundSymbol' error when using that line (another type had bsNone defined).

To overcome this I had to use :

BorderStyle := Forms.bsNone;

[A]
Maximize the form and
hide the title bar
.  The maximize line is done from memory, but I'm pretty sure WindowState is the property you want.
There's also
this
article, but that seems too complicated to me.
```
```
procedure TForm1.FormCreate(Sender: TObject) ;
begin
   //maximize the window
   WindowState := wsMaximized;
   //hide the title bar
   SetWindowLong(Handle,GWL_STYLE,GetWindowLong(Handle,GWL_STYLE) and not WS_CAPTION);
   ClientHeight := Height;
end;
```
```
Edit:  Here's a complete example, with "full screen" and "restore" options.  I've broken out the different parts into little procedures for maximum clarity, so this could be greatly compressed into just a few lines.
```
```
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    btnGoFullScreen: TButton;
    btnNotFullScreen: TButton;
    btnShowTitleBar: TButton;
    btnHideTitleBar: TButton;
    btnQuit: TButton;
    procedure btnGoFullScreenClick(Sender: TObject);
    procedure btnShowTitleBarClick(Sender: TObject);
    procedure btnHideTitleBarClick(Sender: TObject);
    procedure btnNotFullScreenClick(Sender: TObject);
    procedure btnQuitClick(Sender: TObject);
  private
    SavedLeft : integer;
    SavedTop : integer;
    SavedWidth : integer;
    SavedHeight : integer;
    SavedWindowState : TWindowState;
    procedure FullScreen;
    procedure NotFullScreen;
    procedure SavePosition;
    procedure HideTitleBar;
    procedure ShowTitleBar;
    procedure RestorePosition;
    procedure MaximizeWindow;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnQuitClick(Sender: TObject);
begin
  Application.Terminate;
end;

procedure TForm1.btnGoFullScreenClick(Sender: TObject);
begin
  FullScreen;
end;

procedure TForm1.btnNotFullScreenClick(Sender: TObject);
begin
  NotFullScreen;
end;

procedure TForm1.btnShowTitleBarClick(Sender: TObject);
begin
  ShowTitleBar;
end;

procedure TForm1.btnHideTitleBarClick(Sender: TObject);
begin
  HideTitleBar;
end;

procedure TForm1.FullScreen;
begin
  SavePosition;
  HideTitleBar;
  MaximizeWindow;
end;

procedure TForm1.HideTitleBar;
begin
  SetWindowLong(Handle,GWL_STYLE,GetWindowLong(Handle,GWL_STYLE) and not WS_CAPTION);
  ClientHeight := Height;
end;

procedure TForm1.MaximizeWindow;
begin
  WindowState := wsMaximized;
end;

procedure TForm1.NotFullScreen;
begin
  RestorePosition;
  ShowTitleBar;
end;

procedure TForm1.RestorePosition;
begin
  //this proc uses what we saved in "SavePosition"
  WindowState := SavedWindowState;
  Top := SavedTop;
  Left := SavedLeft;
  Width := SavedWidth;
  Height := SavedHeight;
end;

procedure TForm1.SavePosition;
begin
  SavedLeft := Left;
  SavedHeight := Height;
  SavedTop := Top;
  SavedWidth := Width;
  SavedWindowState := WindowState;
end;

procedure TForm1.ShowTitleBar;
begin
  SetWindowLong(Handle,gwl_Style,GetWindowLong(Handle,gwl_Style) or ws_Caption or ws_border);
  Height := Height + GetSystemMetrics(SM_CYCAPTION);
  Refresh;
end;

end.
```
```


q: What is the proper way for an MFC application to cleanly close itself?

[A]
```
```
AfxGetMainWnd()->PostMessage(WM_CLOSE);
```
```


q:
I've recently started work on the Compact Framework and I was wondering if anyone had some recommendations for unit testing beyond what's in VS 2008. MSTest is ok, but debugging the tests is a nightmare and the test runner is so slow.

I see that NUnitLite on codeplex is an option, but it doesn't look very active; it's also in the roadmap for NUnit 3.0, but who knows when that will come out. Has anyone had any success with it?

[A]
We use NUnitLite, although I think we did have had to add some code to it in order for it to work.
One of the problems we found is that if you are using parts of the platform that only exist in CF, then you can only run those tests in NUnitLite on an emulator or Windows Mobile device, which makes it hard to run the tests as part of an integrated build process. We got round this by added a new test attribute allowing you to disable the tests what would only run on the CF (typically these would be p/invoking out to some windows mobile only dll).


q:
I need to be able to find the last occurrence of a character within an element.

For example:

<mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl>

If I try to locate it through using substring-before(mediaurl, '.') and substring-after(mediaurl, '.') then it will, of course, match on the first dot.

How would I get the file extension?  Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT.

[A]
How about tokenize with "/" and take the last element from the array ?
```
```
Example: tokenize("XPath is fun", "\s+")
Result: ("XPath", "is", "fun")
```
```
Was an XSLT fiddler sometime back... lost touch now. But HTH


q:
My scheduled reports in SQL server won't run. I checked the logs and found the job that was failing. The error message in the log was:

'EXECUTE AS LOGIN' failed for the requested login 'NT AUTHORITY\NETWORK
  SERVICE'. The step failed.

I'm using SQL authentication for the report so it shouldn't be issues with the permissions to the data. No sheduled reports on the server will run.

[A]
Can you check the permissions for your Network Service account?  Specifically make sure they have the "Act as part of the OS" permission.  If I'm reading the error message correctly, it looks like the NT AUTHORITY\NETWORK SERVICE account failed to execute as a logged on user. It doesn't look like it ever got to the query, looks like it's failing in the Windows authentication portion, so never gets to the SQL authentication piece.
You might also check the Security Event Log in Windows.  If it is an authentication problem, there might be additional information logged by the OS.


q: I've been using Subversion for code control with TortoiseSVN to interface with the server for the past few months, and in general it's been going great!  However, occasionally my FoxPro IDE will change the case of a file extension without warning where "program.prg" becomes "program.PRG")  TortoiseSVN apparently takes this to mean the first file was removed, becoming flagged as "missing" and the second name comes up as "non-versioned", wreaking havoc on my ability to track changes to the file.   I understand that Subversion has it origins in the case-sensitive world of *nix but, is there any way to control this behavior in either Subversion or TortoiseSVN to be file name case-insensitive when used with Windows?

[A]
Unfortunately, Subversion is case-sensitive. This is due to the fact that files from Subversion can be checked out on both case-sensitive file systems (e.g., *nix) and case-insensitive file systems (e.g., Windows, Mac).
This pre-commit hook script
may help you avoid problems when you check in files. If it doesn't solve your problem, my best suggestion is to write a little script to make sure that all extensions are lowercase and run it every time before you check in/check out. It'll be a PITA, but maybe your best bet.


q: I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?

[A]
This was the solution I came up with
http://sourceforge.net/projects/sshtools/
(most error handling omitted for clarity). This is an excerpt from
my blog
```
```
SshClient ssh = new SshClient();
ssh.connect(host, port);
//Authenticate
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(userName);
passwordAuthenticationClient.setPassword(password);
int result = ssh.authenticate(passwordAuthenticationClient);
if(result != AuthenticationProtocolState.COMPLETE){
     throw new SFTPException("Login to " + host + ":" + port + " " + userName + "/" + password + " failed");
}
//Open the SFTP channel
SftpClient client = ssh.openSftpClient();
//Send the file
client.put(filePath);
//disconnect
client.quit();
ssh.disconnect();
```
```


q:
Can a (||any) proxy server cache content that is requested by a client over https? As the proxy server can't see the querystring, or the http headers, I reckon they can't.

I'm considering a desktop application, run by a number of people behind their companies proxy. This application may access services across the internet and I'd like to take advantage of the in-built internet caching infrastructure for 'reads'. If the caching proxy servers can't cache SSL delivered content, would simply encrypting the content of a response be a viable option?

I am considering all GET requests that we wish to be cachable be requested over http with the body encrypted using asymmetric encryption, where each client has the decryption key. Anytime we wish to perform a GET that is not cachable, or a POST operation, it will be performed over SSL.

[A]
No, it's not possible to cache https directly. The whole communication between the client and the server is encrypted. A proxy sits between the server and the client, in order to cache it, you need to be able to read it, ie decrypt the encryption.
You can do something to cache it. You basically do the SSL on your proxy, intercepting the SSL sent to the client. Basically the data is encrypted between the client and your proxy, it's decrypted, read and cached, and the data is encrypted and sent on the server. The reply from the server is likewise descrypted, read and encrypted. I'm not sure how you do this on major proxy software (like squid), but it is possible.
The only problem with this approach is that the proxy will have to use a self signed cert to encrypt it to the client. The client will be able to tell that a proxy in the middle has read the data, since the certificate will not be from the original site.


q:
When I try to precompile a *.pc file that contains a #warning directive I recieve the following error:

PCC-S-02014, Encountered the symbol "warning" when expecting one of the following: (bla bla bla).

Can I somehow convince Pro*C to ignore the thing if it doesn't know what to do with it? I can't remove the #warning directive as it's used in a header file that I can't change and must include.

[A]
You can't.  Pro*C only knows #if and #include.  My best advice would be to preprocess the file as part of your build process to remove stuff Pro*C won't like.  Something like
```
```
grep -v -E '^#(warning|pragma|define)' unchangeable.h >unchangeable.pc.h
```
```
My other advice would be to avoid the abomination which is Pro*C, but I'm guessing you're stuck with it...


q:
We're having sporadic, random query timeouts on our SQL Server 2005 cluster. I own a few apps that use it, so I'm helping out in the investigation. When watching the % CPU time in regular ol' Perfmon, you can certainly see it pegging out. However, SQL activity monitor only gives cumulative CPU and IO time used by a process, not what it's using right then, or over a specific timeframe. Perhaps I could use the profiler and run a trace, but this cluster is very heavily used and I'm afraid I'd be looking for a needle in a haystack. Am I barking up the wrong tree?

Does anyone have some good methods for tracking down expensive queries/processes in this environment?

[A] Profiler may seem like a "needle in a haystack" approach, but it may turn up something useful. Try running it for a couple of minutes while the databases are under typical load, and see if any queries stand out as taking way too much time or hogging resources in some way. While a situation like this could point to some general issue, it could also be related to some specific issue with one or two sites, which mess things up enough in certain circumstances to cause very poor performance across the board.


q:
I have been a VB.net developer for a few years now but I am currently applying to a few companies that use C#. I have even been told that at least one of the companies doesn't want VB.net developers.

I have been looking online trying to find real differences between the two and have asked on crackoverflow. The only major differences are a few syntax difference which are trivial to me because I am also a Java developer.

What would be a good response to an interviewer when they tell me they are looking for a C# developer - or similar questions?

[A]
I think the truth will-out on this:
I'm a software developer, the syntax of the language is the final part of the puzzle. By employing me, you're getting someone with demonstrable experience of problem solving and logic. I'm experienced with the .NET environment, the CLR and the associated Windows stack, including SQL and Windows server. I don't know the C# syntax, but, I am used to object-oriented approach, I will have no problem getting totally up to speed on the finer points of the syntax within a couple of weeks. You can see from these examples of my code that I'm an experienced developer, I assure you the transition will be seamless. I have already made a start learning the language, I haven't had any problems so far.


q:
We have a website that uses #include file command to roll info into some web pages.  The authors can access the text files to update things like the occasional class or contact information for the department.

My question is this, I don't see anyone using this method and wonder if it is a good idea to keep using it.  If not, what method should I transition to instead?


q:
I've noticed that a few Wordpress blogs have query statistics present in their footer that simply state the number of queries and the total time required to process them for the particular page, reading something like:

23 queries. 0.448 seconds

I was wondering how this is accomplished.  Is it through the use of a particular Wordpress plug-in or perhaps from using some particular php function in the page's code?

[A]
Try adding this to the bottom of the footer in your template:
```
```
<?php echo $wpdb->num_queries; ?> <?php _e('queries'); ?>. <?php timer_stop(1); ?> <?php _e('seconds'); ?>
```
```


q:
For part of my application I have a need to create an image of a certain view and all of its subviews.

To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.

I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level.

[A]
You can use
```
-[NSView dataWithPDFInsideRect:]
```
to render the entire hierarchy of the view you send it to into a PDF, returned as an
```
NSData
```
object.  You can then do whatever you wish with that, including render it into a bitmap.
Are you sure you want a bitmap representation though?  After all, that PDF could be (at least in theory) resolution-independent.


q:
I'm thinking of learning the ASP.NET MVC framework for an upcoming project.  Can I use the advanced routing to create long URLs based on the sitemap hierarchy?

Example navigation path:

Home > Shop > Products > Household > Kitchen > Cookware > Cooksets > Nonstick

Typical (I think) MVC URL:

http://example.com/products/category/NonstickCooksets

Desired URL:

http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick

Can I do this?

[A]
The MVC routing lets you define pretty much any structure you want, you just need to define what each of the pieces mean semantically. You can have bits that are "hard-coded", like "shop/products", and then define the rest as variable, "{category}/{subcategory}/{speciality}", etc.
You can also define several routes that all map to the same end point if you like. Basically, when a URL comes into your MVC app, it goes through the routing table until it finds a pattern that matches, fills in the variables and passes the request off to the appropriate controller for processing.
While the default route is a simple Controller, Action, Id kind of setup, that's certainly not the extent of what you can do.


q:
.NET, Java and other high level database API's in various language often provide techniques known as prepared statements and parameter binding as opposed to sending plain text commands to the Database server. What I would like to know is what happens when you execute a statement like this:

SqlCommand cmd = new SqlCommand("GetMemberByID");
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@ID", memberID);
para.DbType = DbType.Integer;
cmd.Parameters.Add(param);

I know this is a best practice. SQL injection attacks are minimized this way. But what exactly happens under the hood when you execute these statements? Is the end result still a SQL safe string?  If not, what is the end result? And is this enough to prevent SQL injection attacks?

[A]
The MySQL manual page
on prepared statements provides lots of information (which should apply to any other RDBMS).
Basically, your statement is parsed and processed ahead of time, and the parameters are sent separately instead of being handled along with the SQL code.  This eliminates SQL-injection attacks because the SQL is parsed before the parameters are even set.


q:
What is the best way to disable Alt + F4 in a c# win form to prevent the user from closing the form?

I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.

[A]
You could handle the
```
FormClosing
```
event and set
```
FormClosingEventArgs.Cancel
```
to
```
true
```
.


q:
I am using xampp on Windows, but I would like to use something closer to my server setup.

Federico Cargnelutti tutorial explains how to setup LAMP VMWARE appliance; it is a great introduction to VMware appliances, but one of the commands was not working and it doesn't describe how to change the keyboard layout and the timezone.

ps: the commands are easy to find but I don't want to look for them each time I reinstall the server. I am using this question as a reminder.

[A]
Assuming you have VMware workstation, VMware player or anything that can run vmware appliance, you just need to:
Download, unzip
Ubuntu 8.04 Server
and start the virtual machine.
Update ubuntu and set the layout and the timezone:
```
sudo apt-get update
sudo apt-get upgrade
sudo dpkg-reconfigure console-setup
sudo dpkg-reconfigure tzdata
sudo vim /etc/network/interfaces
```
set a fixed IP
(Optional).
install apache+mysql+php:
```
sudo tasksel install lamp-server
```


q: What are some macros that you have found useful in Visual Studio for code manipulation and automation?

[A]
You might want to add in code snippets as well, they help to speed up the development time and increase productivity.
The standard VB code snippets come with the default installation. The C# code snippets must be downloaded and added seperately. (Link below for those)
As far as macros go, I generally have not used any but the working with Visual studio 2005 book has some pretty good ones in there.
C# Code snippets Link:
http://www.codinghorror.com/blog/files/ms-csharp-snippets.7z.zip
(Jeff Atwood provided the link)
HIH


q:
How do I convert function input parameters to the right type?

I want to return a string that has part of the URL passed into it removed.

This works, but it uses a hard-coded string:

function CleanUrl($input)
{
    $x = "http://google.com".Replace("http://", "")
    return $x
}

$SiteName = CleanUrl($HostHeader)
echo $SiteName

This fails:

function CleanUrl($input)
{
    $x = $input.Replace("http://", "")
    return $x
}

Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'.
At M:\PowerShell\test.ps1:13 char:21
+     $x = $input.Replace( <<<< "http://", "")

[A]
```
```
function CleanUrl([string] $url)
{
    return $url.Replace("http://", "")
}
```
```


q:
I have a job interview tomorrow for a .NET shop.  For the past few years I have been developing in languages other than .NET and figure it is probably a good idea to brush up on what is cool and new in the world of .NET.  I've been reading about LINQ and WPF but these are more technologies than trends.  What else should I look at?

Been reading things like:

http://msdn.microsoft.com/en-us/library/bb332048.aspx

http://msdn.microsoft.com/en-us/library/ms754130.aspx

Edit

As it turns out this interview was high level and we didn't really get into much which was more .NET specific than generics.

[A]
This is completely language agnostic so you may want to skip over it, but I've based a lot of my practice and preparation for job interviews around
Steve Yegge's getting a job at google post
.
I use a lot of the topics there not only as an interview preparedness guide, but also as a list of things that I
SHOULD
know about. Admittedly I am still working my way through some of the books and exercises, but every little bit helps.
EDIT:
I'm not sure if it necessarily a good thing to focus specifically on the latest
trends
in web development for job interviews. When I am interviewing someone I am more impressed if they can write a recursive function to solve some problem or write a really cool algorithm, then if they know all the details about
some latest thing that is going to fix everything but it's really just a buzzword


q:
I'd like to take an existing application (written in OCaml) and create an Emacs "interface" for it (like, for example, the Emacs GDB mode). I would prefer to do this without writing a ton of Lisp code. In MVC terms, I'd like for the View to be Emacs, but for the Model and Controller to remain (primarily) OCaml.

Does anybody know of a way to write Emacs extensions in a language other than Lisp? This could either take the form of bindings to the Emacs extension API in some other language (e.g., making OCaml a first-class Emacs extension language) or an Emacs interaction mode where, for example, the extension has a pipe into which it can write Emacs Lisp expressions and read out result values.

[A]
I don't know if this will work for your particular problem, but I have been doing something similar using the shell-command-to-string function:
```
```
(shell-command-to-string
    "bash -c \"script-to-exec args\"")
```
```
So for example, we have existing scripts written in python which will mangle a file, so the above lets me invoke the script via emacs lisp.
A quick google search
found this page
describing a system to write extensions in Python, so it seems feasible to do what you want... you will just have to see if anyone has written a similar framework for OCaml.


q: What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET?

[A]
For C#:
```
```
foreach(ObjectType objectItem in objectTypeList)
{
    // ...do some stuff
}
```
```
Answer for VB.NET from
Purple Ant
:
```
```
For Each objectItem as ObjectType in objectTypeList
    'Do some stuff '
Next
```
```


q:
I'd like to make a debug logging function with the same parameters as printf.  But one that can be removed by the pre-processor during optimized builds.

For example:

Debug_Print("Warning: value %d > 3!\n", value);

I've looked at variadic macros but those aren't available on all platforms. gcc supports them, msvc does not.

[A]
What platforms are they not available on? stdarg is part of the standard library:
http://www.opengroup.org/onlinepubs/009695399/basedefs/stdarg.h.html
Any platform not providing it is not a standard C implementation (or very, very old). For those, you will have to use varargs:
http://opengroup.org/onlinepubs/007908775/xsh/varargs.h.html


q:
The main web application of my company is crying out for a nifty set of libraries to make it in some way maintainable and scalable, and one of my colleagues has suggested CSLA. So I've bought the book but as :

programmers don't read books anymore

I wanted to gauge the SOFlow community's opinion of it.

So here are my questions:

How may people are using CSLA?

What are the pros and cons?

Does CSLA really not fit in with TDD?

What are my alternatives?

If you have stopped using it or decided against why?

[A]
We started using CSLA because we thought it would help with our model layer.  Was sort of overkill and mostly all we use now is the SmartDate class, just because we're already linked to the library.
We thought the validation interface would really help us enforce business rules but it didn't work well with WCF and serialization (we're still stuck on version 2.0.3.0, so things might have changed).


q:
I want a data structure that will allow querying how many items in last X minutes. An item may just be a simple identifier or a more complex data structure, preferably the timestamp of the item will be in the item, rather than stored outside (as a hash or similar, wouldn't want to have problems with multiple items having same timestamp).

So far it seems that with LINQ I could easily filter items with timestamp greater than a given time and aggregate a count. Though I'm hesitant to try to work .NET 3.5 specific stuff into my production environment yet. Are there any other suggestions for a similar data structure?

The other part that I'm interested in is aging old data out, If I'm only going to be asking for counts of items less than 6 hours ago I would like anything older than that to be removed from my data structure because this may be a long-running program.

[A]
I think that an important consideration will be the frequency of querying vs. adding/removing.  If you will do frequent querying (especially if you'll have a large collection) a B-tree may be the way to go:
http://en.wikipedia.org/wiki/B-tree
You could have some thread go through and clean up this tree periodically or make it part of the search (again, depending on the usage).  Basically, you'll do a tree search to find the spot "x minutes ago", then count the number of children on the nodes with newer times.  If you keep the number of children under the nodes up to date, this sum can be done quickly.


q: What does it mean when you get or create a date in UTC format in JavaScript?

[A]
getUTC is for converting times to Coordinated Universal Time (UTC, the acronym is ordered differently than what it stands for) which is the standard time based on the time in Greenwich, London.
The universal time is calculated using a time offset (in minutes when in JavaScript.) This offset is based on the time zone configured on the client browser's operating system.
If you plan on storing dates for users in multiple time zones, this is what you should use.


q:
Is there a method for handling errors from COM objects in RDML? For instance, when calling Word VBA methods like PasteSpecial, an error is returned and the LANSA application crashes. I cannot find anything in the documentation to allow handling of these errors.

Actually, error handling in general is a weak-point for LANSA and RDML, but that's another topic.

[A]
Does anyone know of anyway to
  reduce/optimize the PDF export phase
  and or the size of the PDF without
  lowering the total page count?
I have a few ideas and questions:
1. Is this a graphics-heavy report?  If not, do you have tables that start out as text but are converted into a graphic by the SSRS PDF renderer (check if you can select the text in the PDF)?  41K per page might be more than it should be, or it might not, depending on how information-dense your report is.  But we've had cases where we had minor issues with a report's layout, like having a table bleed into the page's margins, that resulted in the SSRS PDF renderer "throwing up its hands" and rendering the table as an image instead of as text.  Obviously, the fewer graphics in your report, the smaller your file size will be.
2. Is there a way that you could easily break the report into pieces?  E.g., if it's a 10-location report, where Location 1 is followed by Location 2, etc., on your final report, could you run the Location 1 portion independent of the Location 2 portion, etc.?  If so, you could join the 10 sub-reports into one final PDF using
PDFSharp
after you've received them all.  This leads to some difficulties with page numbering, but nothing insurmountable.
3. Does anyone else have any other
  theories as to why this runs on the
  server but not through the API?
My guess would be the sheer size of the report.  I don't remember everything about what's an IIS setting and what's SSRS-specific, but there might be some overall IIS settings (maybe in Metabase.xml) that you would have to be updated to even allow that much data to pass through.
You could isolate the question of whether the time is the problem by taking one of your working reports and building in a long wait time in your stored procedures with WAITFOR (assuming SQL Server for your DBMS).
Not solutions, per se, but ideas.  Hope it helps.


q:
I'm looking at adding scripting functionality to an existing codebase and am weighing up the pros/cons of various packages. Lua is probably the most obvious choice, but I was wondering if people have any other suggestions based on their experience.

Scripts will be triggered upon certain events and may stay resident for a period of time. For example upon startup a script may define several options which the program presents to the user as a number of buttons. Upon selecting one of these buttons the program will notify the script where further events may occur.

These are the only real requirements;

Must be a cross-platform library that is compilable from source

Scripts must be able to call registered code-side functions

Code must be able to call script-side functions

Be used within a C/C++ codebase.

[A]
I have played around a little bit with
Spidermonkey
. It seems like it would at least be worth a look at in your situation. I have heard good things about Lua as well. The big argument for using a javascript scripting language is that a lot of developers know it already and would probably be more comfortable from the get go, whereas Lua most likely would have a bit of a learning curve.
I'm not completely positive but I think that spidermonkey your 4 requirements.


q:
My company has tried to adopt the scrum methodology with mixed success.  Theses are some areas where we've had issues.  How do you handle these?

Tracking requirements from
Product Marketing through to product.  We're trying out JIRA to track all requirements individually and assigning a release to each one as it is picked for implementation.

Who creates stories? Product
Management who doesn't know enough
to create effectively small stories,
developers who may not have domain
knowledge, an analyst in between?

Functional specs

do you write them or just try to get them into a story
definition?

Do you write functional
specs per story?  Per feature?

How do you see the relationship between functional specs and stories?

answering the question from people
with VP in their title "what are we
going to get by [8 months from
now]?"

[A]
You should translate your requirements into a Product Backlog. This backlog is what you use to decide what Sprint Backlog items are chosen for each Sprint iteration. Management decides what is on the Product Backlog, but the team needs to agree to what they can produce in the Sprint (this is a negotiation that occurs at every sprint).
Your Product Owner (usually a product manager) drives the creation of the stories. The Stories are simple (as a system admin, I need to be able to add a user). If your product management does not understand your product, you are in trouble.
Agile is about designing as required. The design is never in the story. The spec can be per story, or per feature. You could design all your CRUD inside of one spec, which covers multiple stories.
The Product Owner gets a product demo at the end of every Sprint. So value is demonstrated at every cycle. So your VP would get reports on a monthly basis (ususally 3 weeks of dev + 1 week to prepare for the Sprint demo).


q:
I'm creating a plugin framework, where my application loads a series of plugin DLL's, then creates a new window and pass this new window's handle to the plugin. The plugin can, then, use this handle to create their own GUI.

Everything seems to be working very well. The only problem is that when I press TAB on a plugin widget (An editbox, for example), it doen't jump to another widget. I figured out that some Windows messages are passed, and some others aren't. The WM_KEYDOWN is passed for other keys, because I can type on the editbox, but this message doesn't handle TAB key.

Hope somebody has a hint.

I'm using Borland VCL with CBuilder, but I think I could use any framework under WIN32 to create these plugins, since they never know how their parent windows were created.

[A]
I believe you'll have to take the following steps:
Subclass
your edit controls (and other controls as needed).
Capture the
WM_KEYDOWN
message in your edit control's WndProc.
Check to see if the shift key is currently held down (using
GetKeyState
or similar).
Call
GetWindow
, passing in a handle to your edit control and either GW_HWNDPREV or GW_HWNDNEXT depending on whether shift is held down. This will give you the handle to the window that should receive focus.
Call
SetFocus
and pass in the window handle you got in step 4.
Make sure you handle the case where your edit controls are multiline, as you might want to have a real tab character appear instead of moving to the next control.
Hope that helps!


q:
An answer to a Stack Overflow question stated that a particular framework violated a plain and simple OOP rule: Single Responsibility Principle (SRP).

Is the Single Responsibility Principle really a rule of OOP?

My understanding of the definition of Object Orientated Programming is "a paradigm where objects and their behaviour are used to create software". This includes the following techniques: Encapsulation, Polymorphism & Inheritance.

Now don't get me wrong - I believe SRP to be the key to most good OO designs, but I feel there are cases where this principle can and should be broken (just like database normalization rules). I aggressively push the benefits of SRP, and the great majority of my code follows this principle.

But, is it a rule, and thus implies that it shouldn't be broken?

[A]
Very few rules, if any, in software development are without exception. Some people think there are no place for
goto
but they're wrong.
As far as OOP goes, there isn't a single definition of object-orientedness so depending on who you ask you'll get a different set of hard and soft principles, patterns, and practices.
The classic idea of OOP is that messages are sent to otherwise opaque objects and the objects interpret the message with knowledge of their own innards and then perform a function of some sort.
SRP is a software engineering principle that can apply to the role of a class, or a function, or a module. It contributes to the cohesion of something so that it behaves well put together without unrelated bits hanging off of it or having multiple roles that intertwine and complicate things.
Even with just one responsibilty, that can still range from a single function to a group of loosely related functions that are part of a common theme. As long as you're avoiding jury-rigging an element to take the responsibilty of something it wasn't primarily designed for or doing some other ad-hoc thing that dilute the simplicity of an object, then violate whatever principle you want.
But I find that it's easier to get SRP correct then to do something more elaborate that is just as robust.


q: I know this site is written using ASP.Net MVC and I do not see "/Home" in the url.  This proves to me that it can be done.  What special route and do I need?

[A]
Just change "Home" to an empty string.
```
```
routes.MapRoute(
    "Home",
    "",
    new { action = Index, controller = Home }
);
```
```


q:
Sometimes a labeled break or continue can make code a lot more readable.

OUTERLOOP: for ( ;/*stuff*/; ) {
    //...lots of code

    if ( isEnough() ) break OUTERLOOP;
    //...more code
}

I was wondering what the common convention for the labels was. All caps? first cap?

[A]
The convention is to avoid labels altogether.
There are very, very few valid reasons to use a label for breaking out of a loop. Breaking out is ok, but you can remove the need to break at all by modifying your design a little. In the example you have given, you would extract the 'Lots of code' sections and put them in individual methods with meaningful names.
```
```
for ( ;/*stuff*/; )
{
    lotsOfCode();

    if ( !isEnough() )
    {
        moreCode();
    }
}
```
```
Edit:
having seen the actual code in question (
over here
), I think the use of labels is probably the best way to make the code readable. In most cases using labels is the wrong approach, in this instance, I think it is fine.


q:
I've been tasked with improving the performance of an ASP.NET 2.0 application.
  The page I'm currently focused on has many problems but one that I'm having trouble digging into is the render time of the page.  Using Trace.axd the duration between Begin Render and End Render is 1.4 seconds.  From MSDN I see that

All ASP.NET Web server controls have a
  Render method that writes out the
  control's markup that is sent to the
  browser.

If I had the source code for all the controls on the page, I would just instrument them to trace out their render time.  Unfortunately, this particular page has lots of controls, most of them third-party.  Is there tool or technique to get better visibility into what is going on during the render?  I would like to know if there is a particularly poorly performing control, or if there are simply too many controls on the page.

[A]
```
```
<%@Page Trace="true" %>
```
```
See
http://www.asp101.com/articles/robert/tracing/default.asp
.


q:
If I press Ctrl+B that ought to give me ASCII code 2, but Ctrl+C is going to be interpreted as a Break.

So I figure I've got to redirect a file in.  How do I get these characters into a file?

[A]
```
```
perl -e 'print "\xFF"'
```
```
where
```
FF
```
is the hex code of the ACSII code you want to print. So for ACSII code 2, it would be \x02.


q:
I'm not sure how this question will be recieved here but lets give it a shot...

It's time for me to get a new dev PC. What's the best choice these days?

I typically have 2-3 Visual Studios open along with mail and all that stuff. Ideally I would imagine 2+ GB of RAM would be nice as my current XP box is dying. =)

I hopped on the Dell site (my days of building PC's are behind me. I just need something that gets the job done.) and started browsing around only to be confused from all the processor choices. What does a typical dev box need these days? Duo? Quad?

Is it worth going to 64 bit Vista as well?

It's been a while since I got a new machine so I'm just looking for some guidance.

Thanks

[A]
People are probably going to yell at me...but I've found that Vista 64 is mostly worth it.  The main reason for me though is that I'm always maxing out my memory and having a 64bit OS allows me to go past the <4GB limit of 32bit.
But even if you don't get 64bit, just buy 2 2GB RAM cards anyways....you will be able to use most of it (my system shows 3.5GB on 32bit) and then you've got it for if you upgrade later and (if your system has 4 slots) you'll have room to expand to 8GB later on....


q: I understand what System.WeakReference does, but what I can't seem to grasp is a practical example of what it might be useful for. The class itself seems to me to be, well, a hack.  It seems to me that there are other, better means of solving a problem where a WeakReference is used in examples I've seen.  What's the canonical example of where you've really got to use a WeakReference?  Aren't we trying to get farther away from this type of behavior and use of this class?

[A]
I use it to implement a cache where unused entries are automatically garbage collected:
```
```
class Cache<TKey,TValue> : IEnumerable<KeyValuePair<TKey,TValue>>
{ Dictionary<TKey,WeakReference> dict = new Dictionary<TKey,WeakReference>();

   public TValue this[TKey key]
    { get {lock(dict){ return getInternal(key);}}
      set {lock(dict){ setInteral(key,value);}}
    }

   void setInteral(TKey key, TValue val)
    { if (dict.ContainsKey(key)) dict[key].Target = val;
      else dict.Add(key,new WeakReference(val));
    }

   public void Clear() { dict.Clear(); }

   /// <summary>Removes any dead weak references</summary>
   /// <returns>The number of cleaned-up weak references</returns>
   public int CleanUp()
    { List<TKey> toRemove = new List<TKey>(dict.Count);
      foreach(KeyValuePair<TKey,WeakReference> kv in dict)
       { if (!kv.Value.IsAlive) toRemove.Add(kv.Key);
       }

      foreach (TKey k in toRemove) dict.Remove(k);
      return toRemove.Count;
    }

    public bool Contains(string key)
     { lock (dict) { return containsInternal(key); }
     }

     bool containsInternal(TKey key)
      { return (dict.ContainsKey(key) && dict[key].IsAlive);
      }

     public bool Exists(Predicate<TValue> match)
      { if (match==null) throw new ArgumentNullException("match");

        lock (dict)
         { foreach (WeakReference weakref in dict.Values)
            { if (   weakref.IsAlive
                  && match((TValue) weakref.Target)) return true;
         }
      }

       return false;
     }

    /* ... */
   }
```
```


q:
I have a few C# .dll projects which are common to many applications.  Currently, I have one big repository. I have each DLL stored as a separate project within the repository and every application project stored as a project within the same repository.

I recently switched to Subversion for source control and I fear that I did not do a good job of structuring the repository. I would like to hear what others are doing.

[A]
Subversion repositories are typical sub-divided into:
```
```
branch/
tags/
trunk/
```
```
You would either place all of your DLL and application projects into the
trunk
and then use
branch
and
tags
for all of them as necessary too:
```
```
branch/
tags/
trunk/
    project1/
    project2/
```
```
Alternatively, you could create folders for each project in the root and then place the common branch, tags and trunk folders within them.
```
```
project1/
    branch/
    tags/
    trunk/

project2/
    branch/
    tags/
    trunk/
```
```
Note that this practice is simply convention and nothing in SVN requires (or really promotes) doing it exactly this way. However, everyone is used to it. So, you would be doing people a favor to go along.
To elaborate further, the
trunk
is where your main development will take place. When you want to mark a particular revision (e.g. a release version), then simply
svn
copy
the project into the tags directory. Also, just copy code into the
branch
directory when you want to do something dramatic or prolonged and don't want to hinder progress in the
trunk
. Later you can
svn
merge
your
branch
back into the
trunk
when it is ready for action!
If you want to correct mishaps in your current Subverion repository, then just use
svn
move
to relocate them. Unlike the delete and add process of
CVS
, move will retain version history for the new location.


q:
I have a solution with several projects, where the startup project has a post-build event that does all the copying of "plugin" projects and other organizing tasks. After upgrading the solution from VS 2005 to VS 2008, it appears as though the post-build event only fires if I modify the startup project, which means my updated plugins don't get plugged in to the current debugging session. This makes sense, but it seems like a change in behavior. Is anyone else noticing a change in behavior with regard to which projects get built?

Does anyone know of a workaround that I can use to force the startup project to rebuild whenever I hit F5? Perhaps I configured VS 2005 to work this way so long ago that I've forgotten all about it ...

[A]
I don't know if this is the right way to do it but you could add a prebuild event to your startup projcet (if it's static) to clean the project which will force a rebuild.
something like:
```
```
devenv project.csproj /clean
```
```


q:
I have created a UserControl that has a ListView in it. The ListView is publicly accessible though a property. When I put the UserControl in a form and try to design the ListView though the property, the ListView stays that way until I compile again and it reverts back to the default state.

How do I get my design changes to stick for the ListView?

[A]
Just so I'm clear, you've done something like this, right?
```
```
public ListView MyListView { get { return this.listView1; } }
```
```
So then you are accessing (at design time) the MyListView property on your UserControl?
I think if you want proper design-time support you're better off changing the "Modifier" property on the ListView itself (back on the original UserControl) to Public - that way you can modify the ListView directly on instances of the UserControl. I've had success doing that anyway.


q:
As I browse through the site, I find a lot of terms that many developers just starting out (and even some advanced developers) may be unfamiliar with.

It would be great if people could post here with a term and definition that might be unknown to beginners or those from different programming backgrounds.

Some not-so-common terms I've seen are 'auto boxing', 'tuples', 'orthogonal code', 'domain driven design', 'test driven development', etc.

Code snippets would also be helpful where applicable..


q: I'm generating some xml files that needs to conform to an xsd file that was given to me.  How should I verify they conform?

[A]
Here's how to do it using
Xerces2
. A tutorial for this,
here
(req. signup).
Original attribution: blatantly copied from
here
:
```
```
import org.apache.xerces.parsers.DOMParser;
import java.io.File;
import org.w3c.dom.Document;

public class SchemaTest {
  public static void main (String args[]) {
      File docFile = new File("memory.xml");
      try {
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/validation", true);
        parser.setProperty(
             "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
             "memory.xsd");
        ErrorChecker errors = new ErrorChecker();
        parser.setErrorHandler(errors);
        parser.parse("memory.xml");
     } catch (Exception e) {
        System.out.print("Problem parsing the file.");
     }
  }
}
```
```


q: I know that there is no official API for Google Analytics but is there a way to access Google Analytics Reports with C#?

[A]
This guy
has had some success with at least some light Analytics integration.  Now I realize this isn't exactly what you're looking for, but he does mention a book and perhaps you can get in touch with him.


q:
I'm wondering about instances when it makes sent to use #define and #if statements. I've known about it for a while, but never incorporated it into my way of coding. How exactly does this affect the compilation?

Is #define the only thing that determines if the code is included when compiled? If I have #define DEBUGme as a custom symbol, the only way to exclude it from compile is to remove this #define statement?

[A]
Well, defines are used often for compile time constants and macros.  This can make your code a bit faster as there are really no function calls, the output values of the macros are determined at compile time.  The #if's are very useful.  The most simple example that I can think of is checking for a debug build to add in some extra logging or messaging, maybe even some debugging functions.  You can also check different environment variables this way.
Others with more C/C++ experience can add more I am sure.


q:
I need to validate an XML string (and not a file)
against a DTD description file.

How can that be done in python?

[A]
Another good option is
lxml's validation
which I find quite pleasant to use.
A simple example taken from the lxml site:
```
```
from StringIO import StringIO

from lxml import etree

dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>"""))
root = etree.XML("<foo/>")
print(dtd.validate(root))
# True

root = etree.XML("<foo>bar</foo>")
print(dtd.validate(root))
# False
print(dtd.error_log.filter_from_errors())
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
```
```


q:
I use VNC to connect to a Linux workstation at work.  At work I have a 20" monitor that runs at 1600x1200, while at home I use my laptop with its resolution of 1440x900.
If I set the vncserver to run at 1440x900 I miss out on a lot of space on my monitor, whereas if I set it to run at 1600x1200 it doesn't fit on the laptop's screen, and I have to scroll it all the time.

Is there any good way to resize a VNC session on the fly?

My VNC server is RealVNC E4.x (I don't remember the exact version) running on SuSE64.

[A]
As far as I know there's no way to change the client's resolution just using VNC, as it is just a "monitor mirroring" application.
TightVNC
however (which is a VNC client and server application) can resize the screen on the client side, i.e. making everything a little smaller (similar to image resizing techniques in graphics programs). That should work if you don't use too small font sizes. VNC should theoretically be compatible between different VNC applications.


q:
I work on a complex application where different teams work on their own modules with a degree of overlap. A while back we got a Mediawiki instance set up, partly at my prompting. I have a hard job getting people to actually use it, let alone contribute.

I can see a lot of benefit in sharing information. It may at least reduce the times we reinvent the wheel.

The wiki is not very structured, but I'm not sure that is a problem as long as you can search for what you need.

Any hints?

[A]
Sell the idea of using the wiki to the developers. You've identified some benefits, share those with the developers. If they can see that they'll get something of value out of it they'll start using it.
Example advantages from
What Is a Wiki
Good for writing down quick ideas or longer ones, giving you more time for formal writing and editing.
Instantly collaborative without emailing documents, keeping the group in sync.
Accessible from anywhere with a web connection (if you don't mind writing in web-browser text forms).
Your archive, because every page revision is kept.
Exciting, immediate, and empowering--everyone has a say.


q:
I'm using NHibernate on a project and I need to do data auditing.  I found this article on codeproject which discusses the IInterceptor interface.

What is your preferred way of auditing data?  Do you use database triggers?  Do you use something similar to what's dicussed in the article?

[A]
I prefer the CodeProject approach you mentioned.
One problem with database triggers is that it leaves you no choice but to use Integrated Security coupled with ActiveDirectory as access to your SQL Server. The reason for that is that your connection should inherit the identity of the user who triggered the connection; if your application uses a named "sa" account or other user accounts, the "user" field will only reflect "sa".
This can be overriden by creating a named SQL Server account for each and every user of the application, but this will be impractical for non-intranet, public facing web applications, for example.


q: How can a sdbm hash function (such as this) be implemented in C# ?

[A]
You can take the C code almost without changes:
```
```
uint sdbm( string str )
{
    uint hash = 0;
    foreach( char ch in str )
    {
        hash = ch + (hash << 6) + (hash << 16) - hash;
    }
    return hash;
}
```
```
Or did you think of something more sophisticated?


q:
I use solr to search for documents and when trying to search for documents using this query "id:*", I get this query parser exception telling that it cannot parse the query with * or ? as the first character.

HTTP Status 400 - org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery

type Status report

message org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery

description The request sent by the client was syntactically incorrect (org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery).

Is there any patch for getting this to work with just * ? Or is it very costly to do such a query?

[A]
I'm assuming with id:* you're just trying to match all documents, right?
I've never used solr before, but in my Lucene experience, when ingesting data, we've added a hidden field to every document, then when we need to return every record we do a search for the string constant in that field that's the same for every record.
If you can't add a field like that in your situation, you could use a RegexQuery with a regex that would match anything that could be found in the id field.
Edit: actually answering the question.  I've never heard of a patch to get that to work, but I would be surprised if it could even be made to work reasonably well.  See
this question
for a reason why unconstrained PrefixQuery's can cause a problem.


q:
Does anyone here have any useful code which uses reduce() function in python? Is there any code other than the usual + and * that we see in the examples?

Refer Fate of reduce() in Python 3000 by GvR

[A]
Not sure if this is what you are after but you can
search source code on Google
.
Follow the link for a search on
'function:reduce() lang:python'
on Google Code search
At first glance the following projects use
```
reduce()
```
MoinMoin
Zope
Numeric
ScientificPython
etc. etc. but then these are hardly surprising since they are huge projects.
The functionality of reduce can be done using function recursion which I guess Guido thought was more explicit.
Update:
Since Google's Code Search was discontinued on 15-Jan-2012, besides reverting to regular Google searches, there's something called
Code Snippets Collection
that looks promising. A number of other resources are mentioned in answers this (closed) question
Replacement for Google Code Search?
.
Update 2 (29-May-2017):
A good source for Python examples (in open-source code) is the
Nullege search engine
.


q: In WPF, how would I apply multiple styles to a FrameworkElement?  For instance, I have a control which already has a style.  I also have a separate style which I would like to add to it without blowing away the first one.  The styles have different TargetTypes, so I can't just extend one with the other.

[A]
But you can extend from another.. take a look at the BasedOn property
```
```
<Style TargetType="TextBlock">
      <Setter Property="Margin" Value="3" />
</Style>

<Style x:Key="AlwaysVerticalStyle" TargetType="TextBlock"
       BasedOn="{StaticResource {x:Type TextBlock}}">
     <Setter Property="VerticalAlignment" Value="Top" />
</Style>
```
```


q: Here is the scenario that I have. I have a cvs repository in one location (A) and I want to replicate it and keep it in sync with a repository in another location(B). This would be a single directional sync from A to B. What is the best way to do this? If it is not really feasible in CVS then which source code control system would you recommend to accomplish this? Thanks

[A]
When using CVS, I don't know any tools to do that other than files syncing. You can achieve that using tools like
```
rsync
```
(Unix) or
```
xcopy
```
/
```
robocopy
```
(Windows).
If you plan on migrating to Subversion, it provides a tool called svnsync that allows to sync a repository from another one.


q:
What's the best way to convert a string to an enumeration value in C#?

I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value.

In an ideal world, I could do something like this:

StatusEnum MyStatus = StatusEnum.Parse("Active");

but that isn't a valid code.

[A]
You're looking for
Enum.Parse
.
```
```
SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");
```
```


q:
I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents.

The contents need to be handle when enter is pushed.  That part I think I have figured out but any suggestions would be welcome.

The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.

Edit: The textbox controls an piece of RF hardware.  What the user wants to be able to do is enter a setting and press enter.  The setting is sent to the hardware.  Without doing anything else the user wants to be able to type in a new setting and press enter again.

[A]
OK, are you sure that is wise? I am picturing two scenarios here:
There is a default button on the form, which is "clicked" when enter is pushed".
There is no default button, and you want the user to have to press enter, regardless.
Both of these raise the same questions:
Is there any validation that is taking place on the text?
Why not create a user control to encapsulate this logic?
If you know the enter button is being pushed and consumed fine, how are you having problems with
TextBoxName.Text = string.Empty
?
Also, as a polite note, can you please try and break up your question a bit? One big block is a bit of a pain to read..


q:
I've seen these words a lot around Subversion (and I guess general repository) discussions.

I have been using SVN for my projects for the last few years, but I've never grasped the complete concept of these directories.

What do they mean?

[A]
In SVN a tag and branch are really similar.
Tag
= a defined slice in time, usually used for releases
Branch
= also a defined slice in time that development can continue on, usually used for major version like 1.0, 1.5, 2.0, etc, then when you release you tag the branch.  This allows you to continue to support a production release while moving forward with breaking changes in the trunk
Trunk
= development work space, this is where all development should happen, and then changes merged back from branch releases.


q:
I have a custom action in a workflow and would like to report an error to the user when something goes wrong.  What's the best way of doing that?

UPD: Ideally I would like to put the workflow in the error state and log a message to the workflow log.  That doesn't seem possible.  What's the closest I can get to it? I want to a reusable solution,something that's easy for users to set up when using my custom action in SharePoint Designer.

Added more details to the question.

@mauro that takes care of storing the error, but how do I display the error to the user in a way which makes sense?

@AdamSane That's seems like a rather fragile solution.  It's not a matter of setting this up once on a single site.  I need something others can add using SPD.

[A]
Add the error to a hidden list with that users name. Set the visibility on the list (for users) to only read/write their own values. Then use a custom web part or FlexListViewer to view the contents of that list and display it to the user. Once they acknowledge that error, remove it from the list.
If necessary, you can add a different workflow action on that message list, that says pause for 2 days and then email. Whatever, depending on your requirements.
Otherwise you can have a custom db table that you use for pretty much the same thing, this way sharepoint does most of the work for you.
Update
This can be packaged up as a feature and deployed to each site as needed. The strengths of this approach (adding a list item to a list, querying, alerting a user, and emailing a user) are all built into the sharepoint itself. In this case you can focus on your custom logic only, while letting sharepoint focus on the implementation details.


q:
I need to programatically determine whether .NET 3.5 is installed. I thought it would be easy:

<% Response.Write(Environment.Version.ToString()); %>

Which returns "2.0.50727.1434" so no such luck...

In my research I have that there are some rather obscure registry keys I can look at but I'm not sure if that is the route to go. Does anyone have any suggestions?

[A]
That is because technically .NET 3.5 is an extension of the 2.0 framework.  The quickest way is to include an assembly from .NET 3.5 and see if it breaks.
```
```
System.Web.Extensions
```
```
Is a good assembly that is only included in version 3.5.  Also it seems that you are using ASP.NET to run this check, this really limits you because you will be unable to check the file system or the registry running in the protected mode of ASP.NET.  Or you can always problematically try loading an assembly from the GAC that should only be in .NET 3.5, however you may run in to problems with permissions again.
This may be one of those times where you ask your self "What am I trying to accomplish?" and see if there are alternative routes.


q:
I'd like to implement a way of recording the version of a project within code, so that it can be used when testing and to help track bugs.
It seems the best version number to use would just be the current revision number from Subversion. Is there an easy way to hook this number into a (C++ in my case) header file or something, which I can then get at in code? I guess this is a post commit hook or something?

Does anyone have any experience of implementing this (with code to share, please?), or can suggest a better alternative?
Thanks.

[A]
You can use the
```
svn:keywords
```
property to enable the
```
Rev
```
keyword.
You can then use
```
$Rev$
```
in your code and SVN will expand it automatically when updating to
```
$Rev: 256 $
```
which can then parse...
More info on the Subversion manual


q: What would be the easiest way to separate the directory name from the file name when dealing with SaveFileDialog.FileName in C#?

[A]
Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:
```
```
string filename = dialog.Filename;
string path = filename.Substring(0, filename.LastIndexOf("\"));
string file = filename.Substring(filename.LastIndexOf("\") + 1);
```
```


q:
I'm aware of some of the test data generators out there, but most seem to just fill name and address style databases [feel free to correct me].

We have a large integrated and normalised application - e.g. invoices have part numbers linked to stocking tables, customer numbers linked to customer tables, change logs linked to audit information, etc which are obviously difficult to fill randomly. Currently we obfuscate real life data to get test data (but not very well).

What tools\methods do you use to create large volumes of data to test with?

[A]
Where I work we use
RedGate Data Generator
to generate test data.
Since we work in the banking domain. When we have to work with nominative data (Credit card numbers, personnal ID, phone numbers) we developed an application that can
mask
these database fields so we can work with them as real data.
I can say with Redgate you can get close to what your real data can look like on a production server since you can customize every field of every table in your BD.


q:
I've seen projects where the classes in the DB layer have just static functions in them and other projects where those classes need to be instantiated to get access to the member functions.

Which is "better" and why?

[A]
It's all about the purpose of the DB Layer.
If you use an instance to access the DB layer, you are allowing multiple versions of that class to exist. This is desirable if you want to use the same DB layer to access multiple databases for example.
So you might have something like this:
```
```
DbController acrhive = new DbController("dev");
DbController prod = new DbController("prod");
```
```
Which allows you to use multiple instances of the same class to access different databases.
Conversely you might want to allow only one database to be used within your application at a time. If you want to do this then you could look at using a static class for this purpose.


q: If you had to provide a wizard like form entry experience in mvc how would you abstract the page flow?

[A]
There are a couple ways, create an action for each step of the wizard process, or create a parameter that is passed in to the action method.  Like
step
that will allow you to know what the state of the wizard is in.


q: Starting with 2005, VS started this behavior of when starting debugging session it spawns up a webserver for every project in a solution.  I have a solution with 15 projects so it takes a while and is a waste of resources.  Is there a way to configure it differently besides just using IIS?

[A]
Some details here on why it does it and how you can overcome it:
http://vishaljoshi.blogspot.com/2007/12/tips-tricks-start-up-options-and.html
There are instances when you might have many web applications or web sites in the same solution and you may be actually debugging only one of them...  In such scenario it might not be desirable to have multiple instances of ASP.NET Development Server running...  VS provides an explicit setting in the property grid of web application/site called Development Web Server - "Always Start When Debugging" which is set to True by default...  If you set this Property to be False only one web server instance will be created for the start up web project...


q:
I have a bunch of files that I need to be able to transport and install quickly. My current method for doing so is moving a flash drive with a readme file of where stuff goes whenever I need to move stuff, which is rather inelegant and cumbersome.

My idea for a solution would be to write up a quick script to move files around that I could just click on. I've done some bash scripting before but batch scripting is a little odd to me. Does anyone have a good online reference guide I could use?

An alternative soulution I could accept would be a program that makes an installer for you, though I'm a bit against that as I would lose a lot of control. However, I'd be alright with it if it was extremely simple,

[A]
Sounds like
```
robocopy
```
tool is exactly what you need.
Very
powerful
replication command-line tool.
MS TechNet reference
,
Wikipedia article
about
```
robocopy
```
,
Full command switch
guide
,
Batch scripting
guide
.


q:
Let's say that you want to output or concat strings. Which of the following styles do you prefer?

var p = new { FirstName = "Bill", LastName = "Gates" };

Console.WriteLine("{0} {1}", p.FirstName, p.LastName);

Console.WriteLine(p.FirstName + " " + p.LastName);

Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?

Do you have any rational arguments to use one and not the other?

I'd go for the second one.

[A]
Personally, the second one as everything you are using is in the direct order it will be output in.  Whereas with the first you have to match up the {0} and {1} with the proper var, which is easy to mess up.
At least it's not as bad as the C++ sprint where if you get the variable type wrong the whole thing will blow up.
Also, since the second is all inline and it doesn't have to do any searching and replacing for all the {0} things, the latter should be faster... though I don't know for sure.


q:
Are there any good online resources for how to create, maintain and think about writing test routines for numerical analysis code?

One of the limitations I can see for something like testing matrix multiplication is that the obvious tests (like having one matrix being the identity) may not fully test the functionality of the code.

Also, there is the fact that you are usually dealing with large data structures as well. Does anyone have some good ideas about ways to approach this, or have pointers to good places to look?

[A]
Check out a book by
David Gries
called
The Science of Programming
. It's about proving the correctness of programs. If you want to be sure that your programs are correct (to the point of proving their correctness), this book is a good place to start.
Probably not exactly what you're looking for, but it's the computer science answer to a software engineering question.


q:
Is it possible (in Vb.Net 2005), without manually parsing the dataset table properties, to create the table and add it to the database?

We have old versions of our program on some machines, which obviously has our old database, and we are looking for a way to detect if there is a missing table and then generate the table based on the current status of the table in the dataset.  We were re-scripting the table every time we released a new version (if new columns were added) but we would like to avoid this step if possible.

[A]
See this MSDN Forum Post:
Creating a new Table in SQL Server from ADO.net DataTable
.
Here the poster seems to be trying to do the same thing as you, and provides code that generates a Create Table statement using the schema contained in a DataTable.
Assuming this works as it should, you could then take that code, and submit it to the database through
```
SqlCommand.ExecuteNonQuery()
```
in order to create your table.


q:
I'm using ColdFusion to return a result set from a SQL database and turn it into a list.

I need some way to generate an alphabetical navigation bar for that list.  I have ColdFusion and the jQuery library available.

I'm looking to generate something like this:

A | B | C | ...
- A
- A
- B
- B
- B
- C
- D

Where clicking on one of the letters drops you down the page to the first item for that letter.  Not all 26 letters of the alphabet are necessarily in use.

[A]
I would get the SQL result set to return the list in the first place, you can easily just take the first letter of the required item, and a count.  The quickest way would be to do a join on a table of 26 characters (less string manipulation that way).
In CF use the count value to ensure that if there is no result you either only display the letter (as standard text) or dont display it at all.
How many rows are you going to be working on as there may be better ways of doing this.  For example, storing the first letter of your required link field in a separate column on insert would reduce the overhead when selecting.


q:
Say we have the following method:

private MyObject foo = new MyObject();

// and later in the class

public void PotentialMemoryLeaker(){
  int firedCount = 0;
  foo.AnEvent += (o,e) => { firedCount++;Console.Write(firedCount);};
  foo.MethodThatFiresAnEvent();
}

If the class with this method is instantiated and the PotentialMemoryLeaker method is called multiple times, do we leak memory?

Is there any way to unhook that lambda event handler after we're done calling MethodThatFiresAnEvent?

[A]
Yes, save it to a variable and unhook it.
```
```
DelegateType evt = (o, e) => { firedCount++; Console.Write(firedCount); };
foo.AnEvent += evt;
foo.MethodThatFiresAnEvent();
foo.AnEvent -= evt;
```
```
And yes, if you don't, you'll
leak
memory, as you'll hook up a new delegate object each time. You'll also notice this because each time you call this method, it'll dump to the console an increasing number of lines (not just an increasing number, but for one call to MethodThatFiresAnEvent it'll dump any number of items, once for each hooked up anonymous method).


q: For a person without a comp-sci background, what is a lambda in the world of Computer Science?

[A]
It refers to
lambda calculus
, which is a formal system that just has lambda expressions, which represent a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type, i.e.,
```
λ : λ → λ
```
.
Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product:
```
```
(lambda (x y) (* x y))
```
```
It can be applied in-line like this (evaluates to
50
):
```
```
((lambda (x y) (* x y)) 5 10)
```
```


q:
I've been developing a "Form Builder" in Javascript, and coming up to the part where I'll be sending the spec for the form back to the server to be stored. The builder maintains an internal data structure that represents the fields, label, options (for select/checkbox/radio), mandatory status, and the general sorting order of the fields.

When I want to send this structure back to the server, which format should I communicate it with?

Also, when restoring a server-saved form back into my Javascript builder, should I load in the data in the same format it sent it with, or should I rebuild the fields using the builder's createField() functions?

[A]
I'd implement some sort of custom
```
text serialization
```
and transmit plain text. As you say, you can rebuild the information doing the reversed process.


q:
I am a broke college student. I have built a small web app in PHP5 and MySQL, and I already have a domain. What is an affordable way to get it online? A few people have suggested amazon's cloud services, but that seems equivalent to slitting my wrists and watching money slowly trickle out. So suggestions? Hosting companies, CIA drop sites, anything?

Update: A lot of suggestions have been for Dreamhost. Their plan allows for 5TB of bandwidth. Could anyone put this in perspective? For instance, how much bandwidth does a site with the kind of traffic StackOverflow get?

[A]
I use and recommend
DreamHost
for both their prices and customer service.  I've hosted several sites here and performance has always been good.  $5.95 a month for their basic package.


q:
In GWT I have to specify what locales are supported in my application. The code get compiled in various files, one for each locale (beside other versions), but I have to give my clients one only URL. This URL is supposed to be a page that should be displayed according to the locale preferred by the browser.
I dont't want to have an HTTP parameter for the locale since I want to forse the locale preferred by the browser.
How can this be coded in GWT?

Should I try to to this using apache rewrite rules? I thied it, but I think I cannot access such parameter easely in a rewrite rule.

Thanks a lot,
Giuseppe

[A]
Unless I am reading the documentation incorrectly I don't think you have to do anything.
GWT and Locale
By making locale a client property, the standard startup process in gwt.js  chooses the appropriate localized version of an application, providing ease of use (it's easier than it might sound!), optimized performance, and minimum script size.
The way I read it, as long as your module has added all the locale choices to it, it should be automatic?