Question:
I've been working through Practical Common Lisp and as an exercise decided to write a macro to determine if a number is a multiple of another number:

(defmacro multp (value factor)

   `(= (rem ,value ,factor)  0))

so that :
(multp 40 10)
evaluates to true whilst
(multp 40 13)
does not

The question is does this macro leak in some way?  Also is this "good" Lisp?  Is there already an existing function/macro that I could have used?

Answer:
Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both
```
value
```
and
```
factor
```
are evaluated only once and in order, and
```
rem
```
doesn't have any side effects.
This is not good Lisp though, because there's no reason to use a macro in this case. A function
```
```
(defun multp (value factor)
  (zerop (rem value factor)))
```
```
is identical for all practical purposes. (Note the use of
```
zerop
```
. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero,
```
(= ... 0)
```
might be better)


Question:
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.

EDIT: The Java Tutorials - Drag and Drop and Data Transfer.

Answer:
Found this code out there on the
tubes
:
```
```
class DnDTabbedPane extends JTabbedPane {
  private static final int LINEWIDTH = 3;
  private static final String NAME = "test";
  private final GhostGlassPane glassPane = new GhostGlassPane();
  private final Rectangle2D lineRect   = new Rectangle2D.Double();
  private final Color     lineColor  = new Color(0, 100, 255);
  //private final DragSource dragSource  = new DragSource();
  //private final DropTarget dropTarget;
  private int dragTabIndex = -1;

  public DnDTabbedPane() {
    super();
    final DragSourceListener dsl = new DragSourceListener() {
      public void dragEnter(DragSourceDragEvent e) {
        e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
      }
      public void dragExit(DragSourceEvent e) {
        e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
        lineRect.setRect(0,0,0,0);
        glassPane.setPoint(new Point(-1000,-1000));
        glassPane.repaint();
      }
      public void dragOver(DragSourceDragEvent e) {
        //e.getLocation()
        //This method returns a Point indicating the cursor location in screen coordinates at the moment
        Point tabPt = e.getLocation();
        SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
        Point glassPt = e.getLocation();
        SwingUtilities.convertPointFromScreen(glassPt, glassPane);
        int targetIdx = getTargetTabIndex(glassPt);
        if(getTabAreaBound().contains(tabPt) && targetIdx>=0 &&
           targetIdx!=dragTabIndex && targetIdx!=dragTabIndex+1) {
          e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
        }else{
          e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
        }
      }
      public void dragDropEnd(DragSourceDropEvent e) {
        lineRect.setRect(0,0,0,0);
        dragTabIndex = -1;
        if(hasGhost()) {
          glassPane.setVisible(false);
          glassPane.setImage(null);
        }
      }
      public void dropActionChanged(DragSourceDragEvent e) {}
    };
    final Transferable t = new Transferable() {
      private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);
      public Object getTransferData(DataFlavor flavor) {
        return DnDTabbedPane.this;
      }
      public DataFlavor[] getTransferDataFlavors() {
        DataFlavor[] f = new DataFlavor[1];
        f[0] = this.FLAVOR;
        return f;
      }
      public boolean isDataFlavorSupported(DataFlavor flavor) {
        return flavor.getHumanPresentableName().equals(NAME);
      }
    };
    final DragGestureListener dgl = new DragGestureListener() {
      public void dragGestureRecognized(DragGestureEvent e) {
        Point tabPt = e.getDragOrigin();
        dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
        if(dragTabIndex<0) return;
        initGlassPane(e.getComponent(), e.getDragOrigin());
        try{
          e.startDrag(DragSource.DefaultMoveDrop, t, dsl);
        }catch(InvalidDnDOperationException idoe) {
          idoe.printStackTrace();
        }
      }
    };
    //dropTarget =
    new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true);
    new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);
  }

  class CDropTargetListener implements DropTargetListener{
    public void dragEnter(DropTargetDragEvent e) {
      if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction());
      else e.rejectDrag();
    }
    public void dragExit(DropTargetEvent e) {}
    public void dropActionChanged(DropTargetDragEvent e) {}
    public void dragOver(final DropTargetDragEvent e) {
      if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) {
        initTargetLeftRightLine(getTargetTabIndex(e.getLocation()));
      }else{
        initTargetTopBottomLine(getTargetTabIndex(e.getLocation()));
      }
      repaint();
      if(hasGhost()) {
        glassPane.setPoint(e.getLocation());
        glassPane.repaint();
      }
    }

    public void drop(DropTargetDropEvent e) {
      if(isDropAcceptable(e)) {
        convertTab(dragTabIndex, getTargetTabIndex(e.getLocation()));
        e.dropComplete(true);
      }else{
        e.dropComplete(false);
      }
      repaint();
    }
    public boolean isDragAcceptable(DropTargetDragEvent e) {
      Transferable t = e.getTransferable();
      if(t==null) return false;
      DataFlavor[] f = e.getCurrentDataFlavors();
      if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
        return true;
      }
      return false;
    }
    public boolean isDropAcceptable(DropTargetDropEvent e) {
      Transferable t = e.getTransferable();
      if(t==null) return false;
      DataFlavor[] f = t.getTransferDataFlavors();
      if(t.isDataFlavorSupported(f[0]) && dragTabIndex>=0) {
        return true;
      }
      return false;
    }
  }

  private boolean hasGhost = true;
  public void setPaintGhost(boolean flag) {
    hasGhost = flag;
  }
  public boolean hasGhost() {
    return hasGhost;
  }
  private int getTargetTabIndex(Point glassPt) {
    Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);
    boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM;
    for(int i=0;i<getTabCount();i++) {
      Rectangle r = getBoundsAt(i);
      if(isTB) r.setRect(r.x-r.width/2, r.y,  r.width, r.height);
      else   r.setRect(r.x, r.y-r.height/2, r.width, r.height);
      if(r.contains(tabPt)) return i;
    }
    Rectangle r = getBoundsAt(getTabCount()-1);
    if(isTB) r.setRect(r.x+r.width/2, r.y,  r.width, r.height);
    else   r.setRect(r.x, r.y+r.height/2, r.width, r.height);
    return   r.contains(tabPt)?getTabCount():-1;
  }
  private void convertTab(int prev, int next) {
    if(next<0 || prev==next) {
      //System.out.println("press="+prev+" next="+next);
      return;
    }
    Component cmp = getComponentAt(prev);
    String str = getTitleAt(prev);
    if(next==getTabCount()) {
      //System.out.println("last: press="+prev+" next="+next);
      remove(prev);
      addTab(str, cmp);
      setSelectedIndex(getTabCount()-1);
    }else if(prev>next) {
      //System.out.println("   >: press="+prev+" next="+next);
      remove(prev);
      insertTab(str, null, cmp, null, next);
      setSelectedIndex(next);
    }else{
      //System.out.println("   <: press="+prev+" next="+next);
      remove(prev);
      insertTab(str, null, cmp, null, next-1);
      setSelectedIndex(next-1);
    }
  }

  private void initTargetLeftRightLine(int next) {
    if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
      lineRect.setRect(0,0,0,0);
    }else if(next==getTabCount()) {
      Rectangle rect = getBoundsAt(getTabCount()-1);
      lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }else if(next==0) {
      Rectangle rect = getBoundsAt(0);
      lineRect.setRect(-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }else{
      Rectangle rect = getBoundsAt(next-1);
      lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);
    }
  }
  private void initTargetTopBottomLine(int next) {
    if(next<0 || dragTabIndex==next || next-dragTabIndex==1) {
      lineRect.setRect(0,0,0,0);
    }else if(next==getTabCount()) {
      Rectangle rect = getBoundsAt(getTabCount()-1);
      lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
    }else if(next==0) {
      Rectangle rect = getBoundsAt(0);
      lineRect.setRect(rect.x,-LINEWIDTH/2,rect.width,LINEWIDTH);
    }else{
      Rectangle rect = getBoundsAt(next-1);
      lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);
    }
  }

  private void initGlassPane(Component c, Point tabPt) {
    //Point p = (Point) pt.clone();
    getRootPane().setGlassPane(glassPane);
    if(hasGhost()) {
      Rectangle rect = getBoundsAt(dragTabIndex);
      BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
      Graphics g = image.getGraphics();
      c.paint(g);
      image = image.getSubimage(rect.x,rect.y,rect.width,rect.height);
      glassPane.setImage(image);
    }
    Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane);
    glassPane.setPoint(glassPt);
    glassPane.setVisible(true);
  }

  private Rectangle getTabAreaBound() {
    Rectangle lastTab  = getUI().getTabBounds(this, getTabCount()-1);
    return new Rectangle(0,0,getWidth(),lastTab.y+lastTab.height);
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if(dragTabIndex>=0) {
      Graphics2D g2 = (Graphics2D)g;
      g2.setPaint(lineColor);
      g2.fill(lineRect);
    }
  }
}

class GhostGlassPane extends JPanel {
  private final AlphaComposite composite;
  private Point location = new Point(0, 0);
  private BufferedImage draggingGhost = null;
  public GhostGlassPane() {
    setOpaque(false);
    composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
  }
  public void setImage(BufferedImage draggingGhost) {
    this.draggingGhost = draggingGhost;
  }
  public void setPoint(Point location) {
    this.location = location;
  }
  public void paintComponent(Graphics g) {
    if(draggingGhost == null) return;
    Graphics2D g2 = (Graphics2D) g;
    g2.setComposite(composite);
    double xx = location.getX() - (draggingGhost.getWidth(this) /2d);
    double yy = location.getY() - (draggingGhost.getHeight(this)/2d);
    g2.drawImage(draggingGhost, (int)xx, (int)yy , null);
  }
}
```
```


Question: What is the best way to write a Safari extension? I've written a couple XUL extensions for Firefox, and now I'd like to write versions of them for Safari. Is there a way that would allow you to add buttons or forms to the browser UI, since this is not possible with an Input manager or Service menu?

Answer:
Safari plugin development is non-trivial. The interface is written in Objective-C, and most of it is not even part of WebKit (so you can't see the source), but there's machinery to inspect and patch the object hierarchy of a running application. It requires understanding of Cocoa and Objective-C, but no lower.
Here's a high level overview I had in my bookmarks of the process
http://livingcode.org/2006/tab-dumping-in-safari
. It goes over creating Safari plugins using Python with working (probably outdated) code. Instead of Python you can use anything that has Objective-C bindings.
There are two major parts to it:
You need to attach your code to a running Safari. This is typically done with SIMBL
http://www.culater.net/software/SIMBL/SIMBL.php
.
Once you're inside, you need to figure what to patch. There's a tutorial on reversing Cocoa applications
http://www.culater.net/wiki/moin.cgi/CocoaReverseEngineering
, which links to the most important tool, class-dump
http://www.codethecode.com/projects/class-dump/
(the link on wiki is broken). Class-dump gives you a complete hierarchy of Safari's classes, where you can guess by names what, specifically, you need to patch. This is a very trial and error mode.
Reading the links above will give you the scope of the project.


Question:
I'm not a math guy in the least but I'm interested in learning about rigid body physics (for the purpose of implementing a basic 3d physics engine).  In school I only took Maths through Algebra II, but I've done 3d dev for years so I have a fairly decent understanding of vectors, quaternions, matrices, etc.  My real problem is reading complex formulas and such, so I'm looking for some decent rigid body dynamics references that will make some sense.

Anyone have any good references?

Answer:
Physics for Game Programmers
I think is better than
Physics for Game Developers
.
If you want something thick in your bookshelf (like I do), Eberly's
3D Game Engine Design
and Erleben's
Physics-Based Animation
can accompany the above.


Question: I see them all the time and always ignore them. Can someone explain to me why they have become so prevalent?  If I'm using a site that allows me to explore it via tags (e.g., this one, del.icio.us, etc.) that's what I will do.  Why would I need a "cloud" of tags upon which to click?  I can just type that tag(s) into a search box.  What am I missing?

Answer:
It's a easy mechanism to determine which tags are most popular or how dense that tag is populated ( amount of tags).
It's just a intuative interface, I'm fairly certain that's one of the bigger reason's why they are so popular, that and they are very Web 2.0 also.


Question: If all of my __init__.py files are empty, do I have to store them into version control, or is there a way to make distutils create empty __init__.py files during installation?

Answer:
In Python,
```
__init__.py
```
files actually have a meaning! They mean that the folder they are in is a Python module. As such, they have a real role in your code and should most probably be stored in Version Control.
You could well imagine a folder in your source tree that is NOT a Python module, for example a folder containing only resources (e.g. images) and no code. That folder would not need to have a
```
__init__.py
```
file in it. Now how do you make the difference between folders where distutils should create those files and folders where it should not ?


Question:
I'm currently playing around with HTML_QuickForm for generating forms in PHP.  It seems kind of limited in that it's hard to insert my own javascript or customizing the display and grouping of certain elements.

Are there any alternatives to QuickForm that might provide more flexibility?

Answer:
If you find it hard to insert Javascript into the form elements, consider using a JavaScript framework such as
Prototype
or
jQuery
. There, you can centralize the task of injecting event handling into form controls.
By that, I mean that you won't need to insert event handlers into the HTML form code. Instead, you register those events from somewhere else. For example, in Prototype you would be able to write something like this:
```
```
$('myFormControl').observe('click', myClickFunction)
```
```
Also have a look at the answers to
another question
.
/EDIT: of course, you can also insert custom attributes and thus event handlers into the form elements using HTML_QuickForm. However, the above way is superior.


Question:
I'm writing a pretty straightforward e-commerce app in asp.net, do I need to use transactions in my stored procedures?

Read/Write ratio is about 9:1

Answer:
Many people ask - do I need transactions? Why do I need them? When to use them?
The answer is simple: use them all the time, unless you have a very good reason not to (for instance, don't use atomic transactions for "long running activities" between businesses). The default should always be yes. You are in doubt? - use transactions.
Why are transactions beneficial? They help you deal with crashes, failures, data consistency, error handling, they help you write simpler code etc. And the list of benefits will continue to grow with time.
Here is some more info from
http://blogs.msdn.com/florinlazar/


Question:
I am using jQuery. I call a JavaScript function with next html:

<li><span><a href="javascript:uncheckEl('tagVO-$id')">$tagname</a></span></li>

I would like to remove the li element and I thought this would be easy with the $(this) object. This is my JavaScript function:

function uncheckEl(id) {
    $("#"+id+"").attr("checked","");
    $("#"+id+"").parent("li").css("color","black");
    $(this).parent("li").remove();  // This is not working
    retrieveItems();
}

But $(this) is undefined. Any ideas?

Answer:
Try something like this (e.g. to hide the
```
<li>
```
):
```
```
function unCheckEl(id, ref) {
  (...)
  $(ref).parent().parent().hide(); // this should be your

}
```
```
And your link:
```
```

```
```
```
$(this)
```
is not present inside your function, because how is it supposed to know where the action is called from? You pass no reference in it, so
```
$(this)
```
could refer to everything but the
```
<a>
```
.


Question: What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?

Answer:
Python CE
Python port for Windows CE (Pocket PC) devices. Intended to be as close to desktop version as possible (console, current directory support, testsuite passed).
(source:
sourceforge.net
)


Question:
Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server?

I'm not so concerned with browser security issues. etc. as the implementation would be for HTA. But is it possible?

Answer:
You can achieve that using HTA and
VBScript
. Just call an external tool to do the screenshotting. I forgot what the name is, but on Windows Vista there is a tool to do screenshots. You don't even need an extra install for it.
As for as automatic - it totally depends on the tool you use. If it has an API, I am sure you can trigger the screenshot and saving process through a couple of Visual Basic calls without the user knowing that you did what you did.
Since you mentioned HTA, I am assuming you are on Windows and (probably) know your environment (e.g. OS and version) very well.


Question: How to get the phone number of the device in Symbian?

Answer:
FYI: Actually i have found this.
http://www3.symbian.com/faq.nsf/AllByDate/100335073FFD8FEF80256E3200571A49?OpenDocument
But the fact is, the phone number is not always stored in SIM. The operator chooses to do it or not!


Question:
I am fairly new to Emacs and I have been trying to figure out how to change the default folder for C-x C-f on start-up. For instance when I first load Emacs and hit C-x C-f its default folder is C:\emacs\emacs-21.3\bin, but I would rather it be the desktop. I believe there is some way to customize the .emacs file to do this, but I am still unsure what that is.

Update: There are three solutions to the problem that I found to work, however I believe solution 3 is Windows only.

Solution 1: Add (cd "C:/Users/Name/Desktop") to the .emacs file

Solution 2: Add (setq default-directory "C:/Documents and Settings/USER_NAME/Desktop/") to the .emacs file

Solution 3: Right click the Emacs short cut, hit properties and change the start in field to the desired directory.

Answer:
I've put
```
```
(cd "c:/cvsroot/")
```
```
in my .emacs and it did the job


Question:
I am looking for some good links with best practices and sample code on creating RESTful web services using .NET.

Also, any other input you might have regarding REST would be greatly appreciated.

Answer:
Windows Communication Foundation
supports REST model since .NET 3.5
.
You can find documentation and code samples on MSDN:
REST and POX
Some resources to learn REST:
REST documentation on xFront.com
Architectural Styles and the Design
of Network-based Software
Architectures. Chapter 5:
Representational State Transfer
(REST)
(Ph.D dissertation of Roy Fielding - author of REST)
Wikipedia entry


Question:
Say I have:

void Render(void(*Call)())
{
    D3dDevice->BeginScene();
    Call();
    D3dDevice->EndScene();
    D3dDevice->Present(0,0,0,0);
}

This is fine as long as the function I want to use to render is a function or a static member function:

Render(MainMenuRender);
Render(MainMenu::Render);

However, I really want to be able to use a class method as well since in most cases the rendering function will want to access member variables, and Id rather not make the class instance global, e.g.

Render(MainMenu->Render);

However I really have no idea how to do this, and still allow functions and static member functions to be used.

Answer:
You can make a wrapper function
```
void Wrap(T *t)
```
that just calls
```
t->Call()
```
and have
```
Render
```
take such a function together with an object. That is:
```
```
void Wrap(T *t)
{
  t->Call();
}

void Render(void (*f)(T *), T *t)
{
  ...
  f(t);
  ...
}
```
```


Question: I want something that looks like a file handle but is really backed by an in-memory buffer to use for I/O redirects. How can I do this?

Answer:
This may not be possible.
GHC
, at least, seems to require a handle to have an OS file descriptor that is used for all read/write/seek operations.
See
```
/libraries/base/IOBase.lhs
```
from the GHC sources.
You may be able to get the same effect by enlisting the OS's help: create a temporary file, connect the handle to it and then memory map the file for the I/O redirects. This way, all the handle I/O would become visible in the memory mapped section.


Question:
Using C# .NET 2.0, I have a composite data class that does have the [Serializable] attribute on it.  I am creating an XMLSerializer class and passing that into the constructor:

XmlSerializer serializer = new XmlSerializer(typeof(DataClass));

I am getting an exception saying:

There was an error reflecting type.

Inside the data class there is another composite object.  Does this also need to have the [Serializable] attribute, or by having it on the top object, does it recursively apply it to all objects inside?

Answer:
Look at the inner exception that you are getting.  It will tell you which field/property it is having trouble serializing.
You can exclude fields/properties from xml serialization by decorating them with the
```
[XmlIgnore]
```
attribute.
```
XmlSerializer
```
does not use the
```
[Serializable]
```
attribute, so I doubt that is the problem.


Question:
I'm running PHP, Apache, and Windows.  I do not have a domain setup, so I would like my website's forms-based authentication to use the local user accounts database built in to Windows (I think it's called SAM).

I know that if Active Directory is setup, you can use the PHP LDAP module to connect and authenticate in your script, but without AD there is no LDAP.  What is the equivalent for standalone machines?

Answer:
Good Question!
I've given this some thought... and I can't think of a good solution.  What I can think of is a horrible horrible hack that just might work.  After seeing that no one has posted an answer to this question for nearly a day, I figured a bad, but working answer would be ok.
The SAM file is off limits while the system is running.  There are some DLL Injection tricks which you may be able to get working but in the end you'll just end up with password hashes and you'd have to hash the user provided passwords to match against them anyway.
What you really want is something that tries to authenticate the user against the SAM file. I think you can do this by doing something like the following.
Create a File Share on the server and make it so that only accounts that you want to be able to log in as are granted access to it.
In PHP use the system command to invoke a wsh script that: mounts the share using the username and password that the website user provides. records if it works, and then unmounts the drive if it does.
Collect the result somehow.  The result can be returned to php either on the stdout of the script, or hopefully using the return code for the script.
I know it's not pretty, but it should work.
I feel dirty :|
Edit: reason for invoking the external wsh script is that PHP doesn't allow you to use UNC  paths (as far as I can remember).


Question: What are the pros/cons of doing either way.  Is there One Right Way(tm) ?

Answer:
It depends on the situation. I tend to use Exceptions when I am writing business logic/application internals, and trigger_error for Validator's and things of that sort.
The pro's of using Exceptions at the logic level is to allow your application to do in case of such an error. You allow the application to chose instead of having the business logic know how to present the error.
The pro's of using trigger_error for Validator's and things of that nature are, say,
```
```
try {
    $user->login();
}  catch (AuthenticationFailureException $e) {
    set_error_handler("my_login_form_handler");
    trigger_error("User could not be logged in. Please check username and password and try again!");
} catch (PersistenceException $pe) { // database unavailable
    set_error_handler("my_login_form_handler");
    trigger_error("Internal system error. Please contact the administrator.");
}
```
```
where my_login_form_handler pretties up the string and places the element in a visible area above the login form.


Question:
How does one start development in Silverlight?

Does one need a new IDE? or Visual studio will support?

Answer:
Yes there is tooling support for Visual Studio. It is still in Beta though.
Get Started Building Silverlight 2 Applications
1) Install Visual Studio 2008 then Install Silverlight Tools Beta 2 for Visual Studio 2008
This add-on to Visual Studio 2008 allows you to use .NET to create Silverlight 2 Beta 2 Web sites. The Silverlight 2 Beta 2 Runtime and the Silverlight 2 Beta 2 SDK are installed as part of this install. For additional information read the overview and the Silverlight 2 Beta 2 Readme Notes. Note if you have Visual Studio 2008 Service Pack 1 Beta installed, please see this information for details on installing correctly.
2) Install Expression Blend 2.5 June 2008 Preview
This is a preview version of Expression Blend for designing Silverlight 2 experiences.
3) Install Deep Zoom Composer
This tool allows you to prepare your images for use with the Deep Zoom feature in Silverlight 2.
One thing to watch out for is that Silverlight does not support Synchronous calls to the server. All calls are
Asynchronous
as of
this Beta
.


Question:
I need to replace all WinAPI calls of the

CreateFile,

ReadFile,

SetFilePointer,

CloseHandle

with my own implementation (which use low-level file reading via Bluetooth).
The code, where functions will be replaced, is Video File Player and it already works with  the regular hdd files.
It is also needed, that Video Player still can play files from HDD, if the file in the VideoPlayer input is a regular hdd file.

What is the best practice for such task?

Answer:
I don't think this is best practice but it should work if you put it in an include file that's included everywhere the function you want to change is called:
```
```
#define CreateFile MyCreateFile

HRESULT MyCreateFile(whatever the params are);
```
```
Implementation of MyCreateFile looks something like this:
```
```
#undef CreateFile
HRESULT MyCreateFile(NobodyCanRememberParamListsLikeThat params)
{
    if (InputIsNormalFile())
        CreateFile(params);
    else
        // do your thing
}
```
```
You basically make every CreateFile call a MyCreateFile call where you can decide if you want need to use your own implementation or the orginal one.
Disclaimer: I think doing this is ugly and I wouldn't do it. I'd rather search and replace all occurences or something.


Question: Is it possible to use overlapped I/O with an anonymous pipe? CreatePipe() does not have any way of specifying FILE_FLAG_OVERLAPPED, so I assume ReadFile() will block, even if I supply an OVERLAPPED-structure.

Answer:
No. As explained
here
, anonymous pipes do not support asynchronous I/O. You need to use a named pipe. There's example code to do this on MSDN
here
and
here
.


Question: Is it possible to to programmatically trigger a postback from server code in ASP.NET?  I know that it is possible to do a Response.Redirect or Server.Transfer to redirect to a page, but is there a way to trigger a postback to the same page in server code (i.e. without using javascript trickery to submit a form)?

Answer:
You could do it with an Ajax request.  You'd have to have the page polling the server.  There isn't any way for the server to push information out to the browser without requesting it.  But having some Javascript that runs in the background and polls the server every 5 seconds (or more, depending on your needs) would probably be the best solution.
APPEND
If you go this route, you can have the server send back just a yes or no, or even just 0 or 1 depending on whether or not the postback should be performed.  Depending on your needs, there many be no reason to actually use the XML part of AJAX.  Just run a simple Asynchronous request, possibly with a few querystring variables, and get back a simple one word, or even a number as a response. That way you can keep the javascript for creating and parsing the XML out if it isn't needed.


Question: What are the most common memory optimizations in csharp, dotnet 2.0.  Wanted to see if there common things that people may not be doing by default in winform app

Answer:
use structs for small wrapper objects to avoid heap fragmentation
think carefully about object lifetimes, especially for large objects so they do not end up on the LOH unless you intend them to
think about allocations inside of a loop
make sure dynamically sized array will be of reasonable size, otherwise partition the problem


Question:
Is global memory initialized in C++? And if so, how?

(Second) clarification:

When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example.

The situation is: can a singleton reference be set - via an instance() call, prior to its initialization:

MySingleton* MySingleton::_instance = NULL;

and get two singleton instances as a result?

See my C++ quiz on on multiple instances of a singleton...

Answer:
Yes global primitives are initialized to NULL.
Example:
```
```
int x;

int main(int argc, char**argv)
{
  assert(x == 0);
  int y;
  //assert(y == 0); <-- wrong can't assume this.
}
```
```
You cannot make any assumptions about classes, structs, arrays, blocks of memory on the heap...
It's safest just to always initialize everything.


Question:
In Ruby on Rails Development (or MVC in general), what quick rule should I follow as to where to put logic.

Please answer in the affirmative - With Do put this here, rather than Don't put that there.

Answer:
Well, it sort of depends upon what the logic has to deal with...
Often, it makes sense to push more things into your models, leaving controllers small. This ensures that this logic can easily be used from anywhere you need to access the data that your model represents. Views should contain almost no logic. So really, in general, you should strive to make it so that you Don't Repeat Yourself.
Also, a quick bit of google reveals a few more concrete examples of what goes where.
Model: validation requirements, data relationships, create methods, update methods, destroy methods, find methods (note that you should have not only the generic versions of these methods, but if there is something you are doing a lot, like finding people with red hair by last name, then you should extract that logic so that all you have to do is call the find_redH_by_name("smith") or something like that)
View: This should be all about formatting of data, not the processing of data.
Controller: This is where data processing goes. From the internet: "The controller’s purpose is to respond to the action requested by the user, take any parameters the user has set, process the data, interact with the model, and then pass the requested data, in final form, off to the view."
Hope that helps.


Question:
is it possible to display ⇓ entity in ie6? It is being display in every browser but not IE 6.I am writing markup such as:

<span>&#8659;</span>

Answer:
According to
this page
, that symbol doesn't show in IE6 at all.
```
```
Symbol  Character  Numeric  Description
⇓       ⇓     ⇓  Down double arrow - -  * Doesn't show with MS IE6
```
```
If you really need that particular symbol, you may just have to go for a small graphic of the arrow - not an ideal solution, but if you need it to display in IE6 then that may be your only option.


Question:
I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?

What I'm doing now:

class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  def doGET
  [...]

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    pass

server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)
server.serve_forever()

Answer:
Sure; just start two different servers on two different ports in two different threads that each use the same handler.  Here's a complete, working example that I just wrote and tested.  If you run this code then you'll be able to get a Hello World webpage at both
http://localhost:1111/
and
http://localhost:2222/
```
```
from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write("Hello World!")

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    daemon_threads = True

def serve_on_port(port):
    server = ThreadingHTTPServer(("localhost",port), Handler)
    server.serve_forever()

Thread(target=serve_on_port, args=[1111]).start()
serve_on_port(2222)
```
```
update:
This also works with Python 3 but three lines need to be slightly changed:
```
```
from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
```
```
and
```
```
self.wfile.write(bytes("Hello World!", "utf-8"))
```
```


Question:
Can you have a multicolumn listview control where one of the columns is a checkbox?  Example code or links would be greatly appreciated.

I am using visual studio 2005

Answer:
Allan Anderson created a custom control to let you do this.
You can find it here:
http://www.codeproject.com/KB/list/aa_listview.aspx
Here's some example code for that control:
```
```
GlacialList mylist = new GlacialList();

mylist.Columns.Add( "Column1", 100 ); // this can also be added

         // through the design time support

mylist.Columns.Add( "Column2", 100 );
mylist.Columns.Add( "Column3", 100 );
mylist.Columns.Add( "Column4", 100 );

GLItem item;

item = this.glacialList1.Items.Add( "Atlanta Braves" );
item.SubItems[1].Text = "8v";
item.SubItems[2].Text = "Live";
item.SubItems[2].BackColor = Color.Bisque;
item.SubItems[3].Text = "MLB.TV";

item = this.glacialList1.Items.Add( "Florida Marlins" );
item.SubItems[1].Text = "";
item.SubItems[2].Text = "Delayed";
item.SubItems[2].BackColor = Color.LightCoral;
item.SubItems[3].Text = "Audio";

item.SubItems[1].BackColor = Color.Aqua; // set the background

      // of this particular subitem ONLY

item.UserObject = myownuserobjecttype; // set a private user object

item.Selected = true; // set this item to selected state

item.SubItems[1].Span = 2; // set this sub item to span 2 spaces

ArrayList selectedItems = mylist.SelectedItems;
           // get list of selected items
```
```


Question:
What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.

Here's the regex:

\s*#define(.*\\\n)+[\S]+(?!\\)

It should match all of this:

#define foo(x) if(x) \
doSomething(x)

But only some of this (shouldn't match the next line of code:

#define foo(x) if(x) \
doSomething(x)
normalCode();

And also shouldn't match single-line preprocessor macros.

I'm pretty sure that the regex above works - but as I said, there probably a better way of doing it, and I imagine that there are ways of breaking it. Can anyone suggest any?

Answer:
This is a simple test program I knocked up:
```
```
#!/usr/bin/env python

TEST1="""
#include "Foo.h"
#define bar foo\\
    x
#include "Bar.h"
"""

TEST2="""
#define bar foo
#define x 1 \\
    12 \\
    2 \\\\ 3
Foobar
"""

TEST3="""
#define foo(x) if(x) \\
doSomething(x)
"""

TEST4="""
#define foo(x) if(x) \\
doSomething(x)
normalCode();
"""

import re
matcher = re.compile(r"^[ \t]*#define(.*\\\n)+.*$",re.MULTILINE)

def extractDefines(s):
    mo = matcher.search(s)
    if not mo:
        print mo
        return
    print mo.group(0)

extractDefines(TEST1)
extractDefines(TEST2)
extractDefines(TEST3)
extractDefines(TEST4)
```
```
The re I used:
```
```
r"^[ \t]*#define(.*\\\n)+.*$"
```
```
Is very similar to the one use used, the changes:
[ \t] To avoid newlines at the start
of the define.
I rely on + being
greedy, so I can use a simple .*$ at
the end to get the first line of the
define that doesn't end with \


Question:
Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load JAR files dynamically. I'm told there's a way of doing it by writing your own ClassLoader, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a JAR file as its argument.

Any suggestions for simple code that does this?

Answer:
The following solution is hackish, as it uses reflection to bypass encapsulation, but it works flawlessly:
```
```
File file = ...
URL url = file.toURI().toURL();

URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, url);
```
```


Question:
I am trying to dynamicaly compile code using CodeDom. I can load other assemblies, but I cannot load System.Data.Linq.dll.  I get an error:

Metadata file 'System.Data.Linq.dll' could not be found

My code looks like:

CompilerParameters compilerParams = new CompilerParameters();
compilerParams.CompilerOptions = "/target:library /optimize";
compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = true;
compilerParams.IncludeDebugInformation = false;
compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("System.Data.Linq.dll");

Any ideas?

Answer:
That may be because this assembly is stored in a different location than mscorlib is.  It should work if you provide a full path to the assembly.  The most convenient way to get the full path is to let the .NET loader do the work for you.  I would try something like this:
```
```
compilerParams.ReferencedAssemblies.Add(typeof(DataContext).Assembly.Location);
```
```


Question:
Trying to do this sort of thing...

WHERE username LIKE '%$str%'

...but using bound parameters to prepared statements in PDO. e.g.:

$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();

I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.

I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?

Answer:
Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:
```
```
$str = "%$str%";
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
```
```


Question:
How can I show a grey transparent overlay in C#?

It should overlay other process which are not owned by the application doing the overlay.

Answer:
Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:
```
```
$str = "%$str%";
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
```
```


Question: An example of an app that does this is Enso, it pops up when you press the caps lock.

Answer:
You need to install a hook in user32.dll. Lookup the Win32-API call SetWindowsHookEx. You can call it from C# via the stuff in System.Runtime.InteropServices.
This article
discusses the topic nicely.
Edit
: Lars Truijens answer looks like a nicer approach actually.


Question: How do I select one or more random rows from a table using SQLAlchemy?

Answer:
Theres a couple of ways through SQL, depending on which data base is being used.
(I think SQLAlchemy can use all these anyways)
mysql:
```
```
SELECT colum FROM table
ORDER BY RAND()
LIMIT 1
```
```
PostgreSQL:
```
```
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
```
```
MSSQL:
```
```
SELECT TOP 1 column FROM table
ORDER BY NEWID()
```
```
IBM DB2:
```
```
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
```
```
Oracle:
```
```
SELECT column FROM
(SELECT column FROM table
ORDER BY dbms_random.value)
WHERE rownum = 1
```
```
However I don't know of any standard way


Question: Even though Silverlight2 is still in it's infancy, can anyone recommend a book to get started with? One that has more of a developer focus than a designer one?

Answer:
I'm currently working my way through
Introducing Microsoft Silverlight 2
, so far so good.
It's a typical Microsoft book serving up the
koolaid
, but gives a good introduction.  I saw the guy speak at one of the local .NET User Groups in the Metro Detroit area and was impressed.
alt text http://ecx.images-amazon.com/images/I/51YD6H7PQyL._SL500_BO2,204,203,200_PIsitb-dp-500-arrow,TopRight,45,-64_OU01_AA240_SH20_.jpg


Question:
HyperTerminal is a program that you can use to connect to other
  computers, Telnet sites, bulletin
  board systems (BBSs), online services,
  and host computers, using either your
  modem, a null modem cable or Ethernet
  connection.

But My main usage of Hyperterminal is to communicate with hardware through local (virtual )COM ports. I suppose it is removed in Vista for some reason.

Are there any other tools that functions similar to Hyperterminal?

[I am curious to know even if it is not for vista]

Answer:
Here are two:
Tera Term
Tera Term (Pro) is a free software terminal emulator (communication program) for MS-Windows. It supports VT100 emulation, telnet connection, serial port connection, and so on.
Kermit 95
Kermit 95: Internet and serial communications for Microsoft Windows® 95, Windows 98, Windows ME, Windows NT (4.0 and later), Windows 2000, Windows XP, and IBM OS/2 from the Kermit Project at Columbia University, offers you text-based terminal connections to Unix, VMS, and many other kinds of hosts, allowing you to interact directly with their shells and applications, to transfer files, and, if desired, to automate interactions and file transfers with its built-in platform- and transport-independent scripting language.


Question:
Is there a mod_rewrite equivalent for IIS 7.0 that's

a) more or less complete

b) suitable for a production environment, i.e. battle-tested/dependable/secure

Do you have an experience-based recommendation?

Answer:
Have a look at URLRewriter. Used it in production once without problems. But don't rely on that as the only quality check:
http://www.codeplex.com/urlrewriter
(It's free and has a Microsoft Public License)
Managed Fusion URL Rewriter is a powerful URL manipulation engine based on the Apache mod_rewrite extension. It is designed, from the ground up to bring all the features of Apache mod_rewrite to IIS 6.0 and IIS 7.0. Managed Fusion Url Rewriter works with ASP.NET on Microsoft's Internet Information Server (IIS) 6.0 and Mono XPS Server and is fully supported, for all languages, in IIS 7.0, including ASP.NET and PHP. Managed Fusion Url Rewriter gives you the freedom to go beyond the standard URL schemes and develop your own scheme.


Question:
I know a few advanced ways, to change directories. pushd and popd (directory stack) or cd - (change to last directory).

But I am looking for quick way to achieve the following:

Say, I am in a rather deep dir:

/this/is/a/very/deep/directory/structure/with\ lot\ of\ nasty/names

and I want to switch to

/this/is/another/very/deep/directory/structure/with\ lot\ of\ nasty/names

Is there a cool/quick/geeky way to do it (without the mouse)?

Answer:
Do you mean that the path names are the same, and only one directory name changes ("a" becomes "another")? In that case:
```
```
cd ${PWD/a/another}
```
```
will switch to the other directory.
```
$PWD
```
holds your current directory, and
```
${var/foo/bar}
```
gives you
```
$var
```
with the string 'foo' replaced by 'bar'.


Question:
I have a query where I wish to retrieve the oldest X records.  At present my query is something like the following:

SELECT Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate DESC

I know that normally I would remove the 'DESC' keyword to switch the order of the records, however in this instance I still want to get records ordered with the newest item first.

So I want to know if there is any means of performing this query such that I get the oldest X items sorted such that the newest item is first.  I should also add that my database exists on SQL Server 2005.

Answer:
Why not just use a subquery?
```
```
SELECT T1.*
FROM
(SELECT TOP X Id, Title, Comments, CreatedDate
FROM MyTable
WHERE CreatedDate > @OlderThanDate
ORDER BY CreatedDate) T1
ORDER BY CreatedDate DESC
```
```


Question:
Technical Debt via Martin Fowler, via Steve McConnell

YAGNI (You Ain't Gonna Need It) via Wikipedia

BDUF (Big Design Up Front) via Wikipedia

UPDATE: To clarify the question, I think I can also state it this way and keep my meaning:

"In what ways do you, as an Agile practioner, find the right balance between "quick and dirty" (unintentionally risking Technical Debt while attempting to adhere to YAGNI) and over-engineering (BDUF) within each iteration?"

Answer:
I find Robert Martin's
Test Driven Development
(TDD) approach helps with these concerns.
Why?
You only have to write enough code to pass the next test.
I think testable code is cleaner.
The design has to feed into tests which can help keep the design focused.
When you do have to change (refactor) you have tests to fall back on
Regardless of when the test are written (before or after) I find writing
the test helps you make practical decisions. E.g., we picked design A or B because
A is more testable.


Question: How can I open a cmd window in a specific location without having to navigate all the way to the directory I want?

Answer:
Try out
this "PowerToy" from Microsoft
:
Open Command Window Here
This PowerToy adds an "Open Command
  Window Here" context menu option on
  file system folders, giving you a
  quick way to open a command window
  (cmd.exe) pointing at the selected
  folder.
EDIT :
This software will not work on any version of Windows apart from Windows XP.


Question: I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change.

Answer:
From the
EmacsWiki Aquamacs FAQ
:
To change the font used to display the
current frame, go to the font panel.
You can do this with the keystroke
Apple-t, or via the menu: Options →
Show/Hide → Font Panel. Once there,
select the font you want.
To make the current frame’s font the
default, go to Options → Frame
Appearance Styles. Select “use current
style for foo mode”, where foo is the
mode of the current frame (e.g.,
foo=text for text mode), to use the
current style (including the font, but
also any other changes you’ve made to
the frame’s style) for all files of
this type. Select “use current style
as default” to use the current style
for all files for whose major mode no
special style has been defined.
There are also recommendations for monospaced fonts - Monaco or "Vera Sans Mono".


Question:
Can I use this approach efficiently?

using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString))
{
    cmd.Connection.Open();
    // set up parameters and CommandType to StoredProcedure etc. etc.
    cmd.ExecuteNonQuery();
}

My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?

Answer:
No, Disposing of the
```
SqlCommand
```
will not effect the Connection. A better approach would be to also wrap the
```
SqlConnection
```
in a using block as well:
```
```
using (SqlConnection conn = new SqlConnection(connstring))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand(cmdstring, conn))
    {
        cmd.ExecuteNonQuery();
    }
}
```
```
Otherwise, the Connection is unchanged by the fact that a Command that was using it was disposed (maybe that is what you want?). But keep in mind, that a Connection should
be disposed of as well, and likely more important to dispose of than a command.
EDIT:
I just tested this:
```
```
SqlConnection conn = new SqlConnection(connstring);
conn.Open();

using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 1", conn))
{
    Console.WriteLine(cmd.ExecuteScalar().ToString());
}

using (SqlCommand cmd = new SqlCommand("select field from table where fieldid = 2", conn))
{
    Console.WriteLine(cmd.ExecuteScalar().ToString());
}

conn.Dispose();
```
```
The first command was disposed when the using block was exited. The connection was still open and good for the second command.
So, disposing of the command definitely does not dispose of the connection it was using.


Question:
How do you create a database from an Entity Data Model.

So I created a database using the EDM Designer in VisualStudio 2008, and now I want to generate the SQL Server Schema to create storage in SQL Server.

Answer:
From what I understand you are not just supposed to use EDM as a "pretty" database designer, in fact EDM does not depend on a specific storage layer. It tries to abstract that part for the developer. There are design schemas (CSDL) and storage schemas (SSDL). Anyway, don't mean to lecture you. ;)
There is
EDM Generator
, which you use to create models and class, etc.. For a DDL kind of export, I've never done that but what I did was map my EDM to an existing database, which was easier for me to get started.
There is a great tutorial on MSDN, which details step by step instructions on how to go about using an existing database, but also touches the how to start from scratch approach.
http://msdn.microsoft.com/en-us/magazine/cc163286.aspx


Question: I've got a table of URLs and I don't want any duplicate URLs. How do I check to see if a given URL is already in the table using PHP/MySQL?

Answer:
You could do this query:
```
```
SELECT url FROM urls WHERE url = 'http://asdf.com' LIMIT 1
```
```
Then check if
mysql_num_rows()
== 1 to see if it exists.


Question: I believe the application has some parts that target .NET, and some that don't. I'm particularly interested in looking at the resource files, if there are any.

Answer:
If you want to disassemble native x86/64 app use
IDA
, .NET exe/dll can be disassembled using Reflector. There are
tons
of utilities to extract resources. Can you elaborate your question a bit?


Question: Having read the threads Is SqlCommand.Dispose enough? and Closing and Disposing a WCF Service I am wondering for classes such as SqlConnection or one of the several classes inheriting from the Stream class does it matter if I close Dispose rather than Close?

Answer:
For
```
SqlConnection
```
, from the perspective of the connection itself, they are equivalent.  According to Reflector,
```
Dispose()
```
calls
```
Close()
```
as well as doing a few additional memory-freeing operations -- mostly by setting members equal to null.
For Stream, they actually are equivalent.
```
Stream.Dispose()
```
simply calls Close().


Question: Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.

Answer:
Assuming a mythical object TreeItem, that conatins a Children collection to represent your hierarchy.
```
```
public void HandleTreeItems(Action<TreeItem> item, TreeItem parent)
    {
        if (parent.Children.Count > 0)
        {
            foreach (TreeItem ti in parent.Children)
            {
                HandleTreeItems(item, ti);
            }
        }

        item(parent);
    }
```
```
Now to call it, passing in the lambda that handles one item, by printing its name to the console.
```
```
HandleTreeItems(item => { Console.WriteLine(item.Name); }, TreeItemRoot);
```
```


Question: How do I set up a network between the Host and the guest OS in Windows vista?

Answer:
I don't run vista, but virtualbox should do most of the setup for you - all you need to do is assign an IP address, subnet mask, and (optionally) a default gateway to your guest OS, and it should just work.
Don't bother with any of the advanced network settings in the options for the VM - they're useful in some situations, but I've never had to use them, and I've been using virtualbox for some years now.
If you post the specific problem you're having perhaps I can help more. But your question is rather vague...


Question:
If you were to self-fund a software project which tools, frameworks, components would you employ to ensure maximum productivity for the dev team and that the "real" problem is being worked on.

What I'm looking for are low friction tools which get the job done with a minimum of fuss. Tools I'd characterize as such are SVN/TortioseSVN, ReSharper, VS itself. I'm looking for frameworks which solve the problems inherient in all software projects like ORM, logging, UI frameworks/components. An example on the UI side would be ASP.NET MVC vs WebForms vs MonoRail.

Answer:
Versioning.
Subversion
is the popular choice. If you can afford it,
Team Foundation Server
offers some benefits. If you want to be super-modern, consider a distributed versioning system, such as
git
,
bazaar
or
Mercurial
. Whatever you do, don't use SourceSafe or other lock-based tools, but rather merge-baseed ones. Consider installing both a Windows Explorer client (such as
TortoiseSVN
) as well as a Visual Studio add-in (such as
AnkhSVN
or
VisualSVN
).
Issue tracking.
Given that Joel Spolsky is on this site's staff,
FogBugz
deserves a mention.
Trac
,
Mantis
and
BugZilla
are widespread open-source choices.
Continuous integration.
CruiseControl.NET
is a popular and open-source choice. There's also
Draco.NET
.
Unit testing.
NUnit
is the popular open-source choice. Does the job. Consider installing the
TestDriven.NET
Visual Studio add-in.
That said, you want to look at the answers to
Essential Programming Tools
and
What is your best list of ‘must have’ development tools?
; while not .NET-specific, they should apply anyway.


Question:
If I have:

signed char * p;

and I do a comparison:

if ( *p == 0xFF )
   break;

it will never catch 0XFF, but if I replace it with -1 it will:

if ( *p == (signed char)0xFF )
   break;

How can this happen? Is it something with the sign flag? I though that 0xFF == -1 == 255.

Answer:
The value
```
0xFF
```
is a signed int value. C will promote the
```
*p
```
to an
```
int
```
when doing the comparison, so the first if statement is equivalent to:
```
```
if( -1 == 255 ) break;
```
```
which is of course false. By using
```
(signed char)0xFF
```
the statement is equivalent to:
```
```
if( -1 == -1 ) break;
```
```
which works as you expect. The key point here is that the comparison is done with
```
int
```
types instead of
```
signed char
```
types.


Question:
What is the best way to shred XML data into various database columns? So far I have mainly been using the nodes and value functions like so:

INSERT INTO some_table (column1, column2, column3)
SELECT
Rows.n.value('(@column1)[1]', 'varchar(20)'),
Rows.n.value('(@column2)[1]', 'nvarchar(100)'),
Rows.n.value('(@column3)[1]', 'int'),
FROM @xml.nodes('//Rows') Rows(n)

However I find that this is getting very slow for even moderate size xml data.

Answer:
I'm not sure what is the best method. I used OPENXML construction:
```
```
INSERT INTO Test
SELECT Id, Data
FROM OPENXML (@XmlDocument, '/Root/blah',2)
WITH (Id   int         '@ID',
      Data varchar(10) '@DATA')
```
```
To speed it up, you can create XML indices. You can set index specifically for
value
function performance optimization. Also you can use typed xml columns, which performs better.


Question:
I know that tables are for tabular data, but it's so tempting to use them for layout. I can handle DIV's to get a three column layout, but when you got 4 nested DIV's, it get tricky.

Is there a tutorial/reference out there to persuade me to use DIV's for layout?

I want to use DIV's, but I refuse to spend an hour to position my DIV/SPAN where I want it.

@GaryF: Blueprint CSS has to be the CSS's best kept secret.

Great tool - Blueprint Grid CSS Generator.

Answer:
This may be unhelpful but I somehow don't understand all these problems related to CSS. If a newspaper designer would try to embed a movie in the ad page, everybody would agree that he's a bit crazy. But still those same people pine after three-column layouts in HTML. HTML is just not apt to handle this kind of layout well at the moment. Furthermore, multi-column layouts are generally not really well-suited for reading on computer monitors. Aren't there enough viable alternatives?
And by the way, even tables don't offer a good way of implementing a fluent column layout so this is no reason at all to resort to such hacks. Assuming a halfway modern browser (i.e. > MSIE 6), tables don't offer any advantages over clean HTML + CSS that I know of.


Question:
Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top of your code file.

Now you want to create a class or use a symbol which is defined in multiple namespaces,
e.g. System.Windows.Controls.Image & System.Drawing.Image

Now unless you use the fully qualified name, there will be a crib/build error due to ambiguity inspite of the right 'using' declarations at the top. What is the way out here?

(Another knowledge base post.. I found the answer after about 10 minutes of searching because I didn't know the right keyword to search for)

Answer:
Use alias
```
```
using System.Windows.Controls;
using Drawing = System.Drawing;

...

Image img = ... //System.Windows.Controls.Image
Drawing.Image img2 = ... //System.Drawing.Image
```
```
C# using directive


Question: What method do you use when you want to get performance data about specific code paths?

Answer:
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.
Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.
I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with
DbgView
), including how many times the code was executed (and the average time spent of course)).
```
```
#pragma once
#include <tchar.h>
#include <windows.h>
#include <sstream>
#include <boost/noncopyable.hpp>

namespace scope_timer {
    class time_collector : boost::noncopyable {
        __int64 total;
        LARGE_INTEGER start;
        size_t times;
        const TCHAR* name;

        double cpu_frequency()
        { // cache the CPU frequency, which doesn't change.
            static double ret = 0; // store as double so devision later on is floating point and not truncating
            if (ret == 0) {
                LARGE_INTEGER freq;
                QueryPerformanceFrequency(&freq);
                ret = static_cast<double>(freq.QuadPart);
            }
            return ret;
        }
        bool in_use;

    public:
        time_collector(const TCHAR* n)
            : times(0)
            , name(n)
            , total(0)
            , start(LARGE_INTEGER())
            , in_use(false)
        {
        }

        ~time_collector()
        {
            std::basic_ostringstream<TCHAR> msg;
            msg << _T("scope_timer> ") <<  name << _T(" called: ");

            double seconds = total / cpu_frequency();
            double average = seconds / times;

            msg << times << _T(" times total time: ") << seconds << _T(" seconds  ")
                << _T(" (avg ") << average <<_T(")\n");
            OutputDebugString(msg.str().c_str());
        }

        void add_time(__int64 ticks)
        {
            total += ticks;
            ++times;
            in_use = false;
        }

        bool aquire()
        {
            if (in_use)
                return false;
            in_use = true;
            return true;
        }
    };

    class one_time : boost::noncopyable {
        LARGE_INTEGER start;
        time_collector* collector;
    public:
        one_time(time_collector& tc)
        {
            if (tc.aquire()) {
                collector = &tc;
                QueryPerformanceCounter(&start);
            }
            else
                collector = 0;
        }

        ~one_time()
        {
            if (collector) {
                LARGE_INTEGER end;
                QueryPerformanceCounter(&end);
                collector->add_time(end.QuadPart - start.QuadPart);
            }
        }
    };
}

// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)
#define TIME_THIS_SCOPE(name) \
    static scope_timer::time_collector st_time_collector_##name(_T(#name)); \
    scope_timer::one_time st_one_time_##name(st_time_collector_##name)
```
```


Question: I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?

Answer:
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.
The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).
It's not thread safe, it wasn't thread safe before I added the code to ignore recursion and it's even less thread safe now.
Although it's very efficient if it's called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don't.
I use this class when the problem at hand doesn't justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with
DbgView
), including how many times the code was executed (and the average time spent of course)).
```
```
#pragma once
#include <tchar.h>
#include <windows.h>
#include <sstream>
#include <boost/noncopyable.hpp>

namespace scope_timer {
    class time_collector : boost::noncopyable {
        __int64 total;
        LARGE_INTEGER start;
        size_t times;
        const TCHAR* name;

        double cpu_frequency()
        { // cache the CPU frequency, which doesn't change.
            static double ret = 0; // store as double so devision later on is floating point and not truncating
            if (ret == 0) {
                LARGE_INTEGER freq;
                QueryPerformanceFrequency(&freq);
                ret = static_cast<double>(freq.QuadPart);
            }
            return ret;
        }
        bool in_use;

    public:
        time_collector(const TCHAR* n)
            : times(0)
            , name(n)
            , total(0)
            , start(LARGE_INTEGER())
            , in_use(false)
        {
        }

        ~time_collector()
        {
            std::basic_ostringstream<TCHAR> msg;
            msg << _T("scope_timer> ") <<  name << _T(" called: ");

            double seconds = total / cpu_frequency();
            double average = seconds / times;

            msg << times << _T(" times total time: ") << seconds << _T(" seconds  ")
                << _T(" (avg ") << average <<_T(")\n");
            OutputDebugString(msg.str().c_str());
        }

        void add_time(__int64 ticks)
        {
            total += ticks;
            ++times;
            in_use = false;
        }

        bool aquire()
        {
            if (in_use)
                return false;
            in_use = true;
            return true;
        }
    };

    class one_time : boost::noncopyable {
        LARGE_INTEGER start;
        time_collector* collector;
    public:
        one_time(time_collector& tc)
        {
            if (tc.aquire()) {
                collector = &tc;
                QueryPerformanceCounter(&start);
            }
            else
                collector = 0;
        }

        ~one_time()
        {
            if (collector) {
                LARGE_INTEGER end;
                QueryPerformanceCounter(&end);
                collector->add_time(end.QuadPart - start.QuadPart);
            }
        }
    };
}

// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)
#define TIME_THIS_SCOPE(name) \
    static scope_timer::time_collector st_time_collector_##name(_T(#name)); \
    scope_timer::one_time st_one_time_##name(st_time_collector_##name)
```
```


Question:
It seems that Silverlight/WPF are the long term future for user interface development with .NET. This is great because as I can see the advantage of reusing XAML skills on both the client and web development sides. But looking at WPF/XAML/Silverlight they seem very large technologies and so where is the best place to get start?

I would like to hear from anyone who has good knowledge of both and can recommend which is a better starting point and why.

Answer:
Silverlight is a stripped down version of WPF so it should have fewer things to learn inside. On the other hand, the two platforms have different targets (web & rich client) so I guess it depends on what app you're going to build.
If you just want to learn for yourself (no app in the close future) I'd pick Silverlight because it would be less to assimilate. Still, Silverlight is pretty much a moving target, much more than WPF, so you'll have to keep up with some changes from time to time (the joys of being an early adopter :)).
WPF has lots more stuff that you will probably want to use at some point but I would wait for the needs to arise first.


Question: I am trying to retrieve a user on Sharepoint's user photo through the WSS 3.0 object model. I have been browsing the web for solutions, but so far I've been unable to find a way to do it. Is it possible, and if so how?

Answer:
Ah, You have to use the UserProfileManager class.
More information here:
http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofilemanager.aspx
Example use:
```
```
public override void ItemAdded(SPItemEventProperties properties)
{
    // Get list item on which the event occurred.
    SPListItem item = properties.ListItem;

    // Set the Author Image field to the user's PictureURL if it exists.
    using (SPWeb web = properties.OpenWeb())
    {
        // Author: {C32DB804-FF2D-4656-A38A-B0394BA5C931}
        SPFieldUserValue authorValue = new SPFieldUserValue(properties.OpenWeb(), item[new Guid("{C32DB804-FF2D-4656-A38A-B0394BA5C931}")].ToString());

        UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(web.Site));
        UserProfile profile = profileManager.GetUserProfile(authorValue.LookupId);
        UserProfileValueCollection values = profile[PropertyConstants.PictureUrl];

        if (values.Count > 0)
        {
            // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}
            SPFieldUrlValue urlValue = new SPFieldUrlValue(values.Value.ToString());
            item[new Guid("{37A5CA4C-7621-44d7-BF3B-583F742CE52F}")] = urlValue.Url;
        }
    }

    item.Update();

    // News Text: {7F55A8F0-4555-46BC-B24C-222240B862AF}
    //

    // Author Image: {37A5CA4C-7621-44d7-BF3B-583F742CE52F}
    //

    // Publish Date: {45E84B8B-E161-46C6-AD51-27A42E4992B5}
    //
}
```
```


Question:
I remember back in the day with the old borland DOS compiler you could do something like this:

asm {
 mov ax,ex
 etc etc...
}

Is there a semi-platform independent way to do this now? I have a need to make a BIOS call, so if there was a way to do this without asm code, that would be equally useful to me.

Answer:
A good start would be reading this article which talk about inline assembly in C/C++:
http://www.codeproject.com/KB/cpp/edujini_inline_asm.aspx
Example from the article:
```
```
#include <stdio.h>

int main() {
    /* Add 10 and 20 and store result into register %eax */
    __asm__ ( "movl $10, %eax;"
                "movl $20, %ebx;"
                "addl %ebx, %eax;"
    );

    /* Subtract 20 from 10 and store result into register %eax */
    __asm__ ( "movl $10, %eax;"
                    "movl $20, %ebx;"
                    "subl %ebx, %eax;"
    );

    /* Multiply 10 and 20 and store result into register %eax */
    __asm__ ( "movl $10, %eax;"
                    "movl $20, %ebx;"
                    "imull %ebx, %eax;"
    );

    return 0 ;
}
```
```


Question:
How do you make your application multithreaded ?
Do you use asynch functions ?
or do you spawn a new thread ?
I think that asynch functions are already spawning a thread so if your job is doing just some file reading, being lazy and just spawning your job on a thread would just "waste" ressources...
So is there some kind of design when using thread or asynch functions ?

Answer:
If you are talking about .Net, then don't forget the
ThreadPool
. The thread pool is also what asynch functions often use. Spawning to much threads can actually hurt your performance. A thread pool is designed to spawn just enough threads to do the work the fastest. So do use a thread pool instead of spwaning your own threads, unless the thread pool doesn't meet your needs.
PS: And keep an eye out on the
Parallel Extensions
from Microsoft


Question:
I am thinking about the design of an iPhone app I'd like to create.  One possible problem is that this application will have to run as root (to access certain network ports).  In a typical UNIX app, I'd just get the app to run with setuid, but I'm wondering if that is possible with an iPhone app.

I've read this question in Apple's forum, which is discouraging:

http://discussions.apple.com/thread.jspa?threadID=1664575

I understand that Apple wants to limit what a program can do, but there are plenty of good, legitimate reasons for a user to run a program with elevated privileges.  I'm not trying to create a hacker tool here.

I'm sure I could get around this on a jail-broken iPhone, but that's not what I'm after.  Is there any way to run an app with elevated privileges on an unbroken iPhone?

(BTW, there is no need to warn me about the NDA.)

Answer:
Section 3.3.4 of the iPhone SDK Agreement suggests that you mustn't work outside your sandbox.
Given that
Apple has been somewhat arbitrary on which applications they permit
, you should definitely double-check with them
before
you start developing.
Compared to 2.0.x,
the sandbox restrictions have actually increased in 2.1
; you can no longer even read from another application's sandbox. So, even if it currently
is
possible to elevate your app's privileges, it very likely won't be in a future release.


Question:
Should I still be using tables anyway?

The table code I'd be replacing is:

<table>
    <tr>
        <td>Name</td><td>Value</td>
    </tr>
    ...
</table>

From what I've been reading I should have something like

<label class="name">Name</label><label class="value">Value</value><br />
...

Ideas and links to online samples greatly appreciated.  I'm a developer way out of my design depth.

EDIT: My need is to be able to both to display the data to a user and edit the values in a separate (but near identical) form.

Answer:
I think tables are best used for tabular data, which it seems you have there.
If you do not want to use tables, the best thing would be to use definition lists(
```
<dl> and <dt>
```
). Here is how to style them to look like your old
```
<td>
```
layout.
http://maxdesign.com.au/articles/definition/


Question:
I want to write an onClick event which submits a form several times, iterating through selected items in a multi-select field, submitting once for each.

How do I code the loop?

I'm working in Ruby on Rails and using remote_function() to generate the JavaScript for the ajax call.

Answer:
My quick answer (as I've not coded it yet) would be to create another function that creates a POST using XMLHTTPRequest and the specific parameters for a single call. Then inside your onClick() handler call that function as you loop through your selected items.
I would suggest that you do a Proof of Concept just using a dummy HTML page and javascript and then try to figure out how to get it to work in RoR.
Also, why are you attempting to make the multiple calls from the browser as opposed to handling the looping conditions in the RoR controller?


Question:
I'm sure most of you are writing lots of automated tests and that you also have run into some common pitfalls when unit testing.

My question is do you follow any rules of conduct for writing tests in order to avoid problems in the future? To be more specific: What are the properties of good unit tests or how do you write your tests?

Language agnostic suggestions are encouraged.

Answer:
Keep these goals in mind (adapted from the book xUnit Test Patterns by Meszaros)
Tests should reduce risk, not
introduce it.
Tests should be easy to run.
Tests should be easy to maintain as
the system evolves around them
Some things to make this easier:
Tests should only fail because of
one reason.
Tests should only test one thing
Minimize test dependencies (no
dependencies on databases, files, ui
etc.)
Don't forget that you can do intergration testing with your xUnit framework too
but keep intergration tests and unit tests separate


Question:
In evaluating different systems integration strategies, I've come across some words of encouragement, but also some words of frustration over BizTalk Server.

What are some pros and cons to using BizTalk Server (both from a developer standpoint and a business user), and should companies also consider open source alternatives? What viable alternatives are out there?

EDIT: Jitterbit seems like an interesting choice. Open Source and seems to be nicely engineered. Anyone on here have any experience working with it?

Answer:
My experience with BizTalk was basically a frustrating waste of time.
There are so many edge cases and weird little business logic tweaks you have to make when you are doing B2B data integration (which is probably the hardest part of any enterprise application) that you just need to roll your own solution.
How hard is it to parse data files and convert them to a different format?  Not that hard.  Unless you're trying to inject a bloated middleware system like Biztalk into the middle of it.


Question:
I've just created a new Windows XP VM on my Mac using VMware Fusion. The VM is using NAT to share the host's internet connection.

How do I access a Rails application, which is accessible on the Mac itself using http://localhost:3000?

Answer:
On the XP machine, find your IP address by going to the command prompt and typing
```
ipconfig
```
. Try replacing the last number with 1 or 2. For example, if your IP address is 192.168.78.128, use
http://192.168.78.1:3000
.


Question:
I need to figure out what div is visible out of four possible divs using jQuery.  Only one of those div's will be visible at any given time.

This is what I have that works so far:

$("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id");

Is there a way to refactor this?  Is there an easier way to figure this out?

Answer:
Assign the same class to each div then:
```
```
$("div.myClass:visible").attr("id");
```
```


Question:
With all the fuss about opensource projects, how come there is still not a strong standard that enables you to make portable code (I mean in C/C++ not Java or C#)
Everyone is kind of making it's own soup.

There are even some third party libs like Apache Portable Runtime.

Answer:
I think the main reason there isn't any single library anyone agrees on is that everyone's requirements are different. When you want to wrap system libraries you'll often need to make some assumptions about what the use cases will be, unless you want to make the wrapper huge and impossible to work with. I think that might be the main reason there's no single, common cross platform runtime.
For GUI, the reason would be that each platform has its own UI conventions, you can't code one GUI that fits all, you'll simply get one that fits just one or even none at all.


Question:
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:

>>> class Foo:
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }

NOTE: It should not include methods. Only fields.

Answer:
The
```
dir
```
builtin will give you all the object's attributes, including special methods like
```
__str__
```
,
```
__dict__
```
and a whole bunch of others which you probably don't want. But you can do something like:
```
```
>>> class Foo(object):
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))
{ 'bar': 'hello', 'baz': 'world' }
```
```
So can extend this to only return data attributes and not methods, by defining your
```
props
```
function like this:
```
```
import inspect

def props(obj):
    pr = {}
    for name in dir(obj):
        value = getattr(obj, name)
        if not name.startswith('__') and not inspect.ismethod(value):
            pr[name] = value
    return pr
```
```


Question: There is a lot of information out there on object-relational mappers and how to best avoid impedance mismatch, all of which seem to be moot points if one were to use an object database.  My question is why isn't this used more frequently?  Is it because of performance reasons or because object databases cause your data to become proprietary to your application or is it due to something else?

Answer:
Familiarity.
The administrators of databases know relational concepts; object ones, not so much.
Performance.
Relational databases have been proven to scale far better.
Maturity.
SQL is a powerful, long-developed language.
Vendor support.
You can pick between many more first-party (SQL servers) and third-party (administrative interfaces, mappings and other kinds of integration) tools than is the case with OODBMSs.
Naturally, the object-oriented model is more familiar to the
developer
, and, as you point out, would spare one of ORM. But thus far, the relational model has proven to be the more workable option.
See also the recent question,
Object Orientated vs Relational Databases
.


Question:
I have a network C++ program in Windows that I'd like to test for network disconnects at various times.  What are my options?

Currently I am:

Actually disconnecting the network wire from the back of my computer

using ipconfig /release

Using the cports program to close out the socket completely

None of these methods though are ideal for me, and I'd like to emulate network problems more easily.

I would like for sometimes connects to fail, sometimes socket reads to fail, and sometimes socket writes to fail.  It would be great if there was some utility I could use to emulate these types of problems.

It would also be nice to be able to build some automated unit tests while this emulated bad network is up.

Answer:
The closest I can think of is doing something similar with
VEDekstop
from Shunra..
Simulating High Latency and Low Bandwidth in Testing of Database Applications
Shunra VE Desktop Standard is a Windows-based client software solution that simulates a wide area network link so that you can test applications under a variety of current and potential network conditions – directly from your desktop.


Question:
I get a URL from a user. I need to know:

a) is the URL a valid RSS feed?

b) if not is there a valid feed associated with that URL

using PHP/Javascript or something similar

(Ex. http://techcrunch.com fails a), but b) would return their RSS feed)

Answer:
a) Retrieve it and try to parse it. If you can parse it, it's valid.
b) Test if it's an HTML document (server sent
```
text/html
```
) MIME-type. If so, run it through an HTML parser and look for
```
<link>
```
elements with RSS feed relations.


Question:
Alan Storm's comments in response to my answer regarding the with statement got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of with, while avoiding its pitfalls.

Where have you found the with statement useful?

Answer:
Visual Basic.NET has a similar
```
With
```
statement. One of the more common ways I use it is to quickly set a number of properties. Instead of:
```
```
someObject.Foo = ''
someObject.Bar = ''
someObject.Baz = ''
```
```
, I can write:
```
```
With someObject
    .Foo = ''
    .Bar = ''
    .Baz = ''
End With
```
```
This isn't just a matter of laziness. It also makes for much more readable code. And unlike JavaScript, it does not suffer from ambiguity, as you have to prefix everything affected by the statement with a
```
.
```
(dot). So, the following two are clearly distinct:
```
```
With someObject
    .Foo = ''
End With
```
```
vs.
```
```
With someObject
    Foo = ''
End With
```
```
The former is
```
someObject.Foo
```
; the latter is
```
Foo
```
in the scope
outside
```
someObject
```
.
I find that JavaScript's lack of distinction makes it far less useful than Visual Basic's variant, as the risk of ambiguity is too high. Other than that,
```
with
```
is still a powerful idea that can make for better readability.


Question:
In python, you can have a function return multiple values.  Here's a contrived example:

def divide(x, y):
    quotient = x/y
    remainder = x % y
    return quotient, remainder

(q, r) = divide(22, 7)

This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value.  Let's have X return that value also").

When should you draw the line and define a different method?

Answer:
Firstly, note that Python allows for the following (no need for the parenthesis):
```
```
q, r = divide(22, 7)
```
```
Regarding your question, there's no hard and fast rule either way. For simple (and usually contrived) examples, it may seem that it's always possible for a given function to have a single purpose, resulting in a single value. However, when using Python for real-world applications, you quickly run into many cases where returning multiple values is necessary, and results in cleaner code.
So, I'd say do whatever makes sense, and don't try to conform to an artificial convention. Python supports multiple return values, so use it when appropriate.


Question:
When I downloaded Skype, I noticed that, in place of a normal "disk image" icon, there was a custom icon, and when I double clicked on the icon, the window used a colorful image as the background, prompting me to drag the skype icon into the applications folder.

How can I do that with my applications?

Thanks,
Jason

Answer:
Let me add to the other answers
jwz's howto
on setting view options on .dmg files. This is the simplest one that I got to work with no problems.
Also, to change the icon from the default .dmg icon:
In the Finder, open an inspector window (^I) for the file whose icon you want to use, click on the icon at the top (it will get a blue border) and copy it to the clipboard (^C).
Then open another inspector for your .dmg, click on the icon and press ^V to paste
(you can change the icon for any file like this).
For this kind of thing, you can always look at open-source programs and see what they do to get a similar result. For example here are the relevant source files for building pretty dmg files in:
Adium
Miro


Question:
How do I use the profiler in Visual Studio 2008?

I know theres a build option in Config Properties -> Linker -> Advanced -> Profile (/PROFILE), however I can't find anything about actauly using it, only articles I was able to find appear to only apply to older versions of Visual Studio (eg most say to goto Build->Profile to bring up the profile dialog box, yet in 2008 there is no such menu item).

Is this because Visual Studio 2008 does not include a profiler, and if it does where is it and where is the documentation for it?

Answer:
The profiler is only available in the Team System editions of Visual Studio 2008. The last version that I used that included a profiler was Visual C++ 6.0.
For Visual Studio 2005, you could try
Compuware DevPartner Performance Analysis Community Edition
.


Question:
I'm reading lines of input on a TCP socket, similar to this:

class Bla
  def getcmd
    @sock.gets unless @sock.closed?
  end

  def start
    srv = TCPServer.new(5000)
    @sock = srv.accept
    while ! @sock.closed?
      ans = getcmd
    end
  end
end

If the endpoint terminates the connection while getline() is running then gets() hangs.

How can I work around this? Is it necessary to do non-blocking or timed I/O?

Answer:
If you believe the
rdoc
for ruby sockets, they don't implement
```
gets
```
. This leads me to believe gets is being provided by a higher level of abstraction (maybe the IO libraries?) and probably isn't aware of socket-specific things like 'connection closed.'
Try using
```
recvfrom
```
instead of
```
gets
```


Question:
Suppose I have a COM object which users can access via a call such as:

Set s = CreateObject("Server")

What I'd like to be able to do is allow the user to specify an event handler for the object, like so:

Function ServerEvent

   MsgBox "Event handled"

End Function

s.OnDoSomething = ServerEvent

Is this possible and, if so, how do I expose this in my type library in C++ (specifically BCB 2007)?

Answer:
I'm a little hazy on the details, but maybe the link below might help:
http://msdn.microsoft.com/en-us/library/ms974564.aspx
It looks like your server object needs to implement
```
IProvideClassInfo
```
and then you call
```
ConnectObject
```
in your VBScript code. See also:
http://blogs.msdn.com/ericlippert/archive/2005/02/15/373330.aspx


Question:
I need to create a 2D int array of size 800x800.  But doing so creates a stack overflow (ha ha).

I'm new to C++, so should I do something like a vector of vectors?  And just encapsulate the 2d array into a class?

Specifically, this array is my zbuffer in a graphics program.  I need to store a z value for every pixel on the screen (hence the large size of 800x800).

Thanks!

Answer:
You need about 2.5 megs, so just using the heap should be fine.  You don't need a vector unless you need to resize it.  See
C++ FAQ Lite
for an example of using a "2D" heap array.
```
```
int *array = new int[800*800];
```
```
(Don't forget to
```
delete[]
```
it when you're done.)


Question:
The .NET Setup project seems to have a lot of options, but I don't see an "Uninstall" option.

I'd prefer if people could "uninstall" from the standard "start menu" folder rather than send them to the control panel to uninstall my app, so can someone please tell me how to do this?

Also, I am aware of non Microsoft installers that have this feature, but if possible I'd like to stay with the Microsoft toolkit.

Answer:
You can make shortcut to:
```
```
msiexec /uninstall [path to msi or product code]
```
```


Question:
I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.

I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?

Answer:
You can make shortcut to:
```
```
msiexec /uninstall [path to msi or product code]
```
```


Question:
Until recently we were using Inno Setup for our installations, something I would like to continue doing, unless we can get an uninstall option in the start menu (thanks Giovanni Galbo), however we now need to GAC some external libraries, something I suspect is only doable (or at least only supported) though the .NET Setup Project.

Is it possible to call a GAC'ing library from another setup application?

Answer:
Not sure about library, but you can call
gacutil.exe
to install/uninstall assemblies.


Question:
I'm drawing old school (unthemed - themed radios are a whole other problem) radio buttons myself using DrawFrameControl:

DrawFrameControl(dc, &rectRadio, DFC_BUTTON, isChecked() ? DFCS_BUTTONRADIO | DFCS_CHECKED : DFCS_BUTTONRADIO);

I've never been able to figure out a sure fire way to figure out what to pass for the RECT. I've been using a 12x12 rectangle but I'de like Windows to tell me the size of a radio button.

DrawFrameControl seems to scale the radio button to fit the rect I pass so I have to be close to the "right" size of the radio looks off from other (non-owner drawn) radios on the screen.

Anyone know how to do this?

Answer:
It has been a while since I worked on this, so what I am describing is what I did, and not necessarily a direct answer to the question.
I happen to use bit maps 13 x 13 rather than 12 x 12.   The bitmap part of the check box seems to be passed in the WM_DRAWITEM.  However, I had also set up WM_MEASUREITEM and fed it the same values, so my answer may well be "Begging the question" in the correct philosophical sense.
```
case WM_MEASUREITEM:
            lpmis = (LPMEASUREITEMSTRUCT) lParam;

            lpmis->itemHeight = 13;
            lpmis->itemWidth = 13;

            break;

        case WM_DRAWITEM:
            lpdis = (LPDRAWITEMSTRUCT) lParam;
            hdcMem = CreateCompatibleDC(lpdis->hDC);

            if (lpdis->itemState & ODS_CHECKED)  // if selected
                {
                SelectObject(hdcMem, hbmChecked);
                }
            else
                {
                if (lpdis->itemState & ODS_GRAYED)
                    {
                    SelectObject(hdcMem, hbmDefault);
                    }
                else
                    {
                    SelectObject(hdcMem, hbmUnChecked);
                    }
                }
            StretchBlt(
                lpdis->hDC,         // destination DC
                lpdis->rcItem.left, // x upper left
                lpdis->rcItem.top,  // y upper left

                // The next two lines specify the width and
                // height.
                lpdis->rcItem.right - lpdis->rcItem.left,
                lpdis->rcItem.bottom - lpdis->rcItem.top,
                hdcMem,    // source device context
                0, 0,      // x and y upper left
                13,        // source bitmap width
                13,        // source bitmap height
                SRCCOPY);  // raster operation

            DeleteDC(hdcMem);
            return TRUE;
```
This seems to work well for both Win2000 and XP, though I have nbo idea what Vista might do.
It might be worth an experiment to see what leaving out WM_MEASUREITEM does, though I usually discover with old code that I usually had perfectly good reason for doing something that looks redundant.


Question: How can I get PDO to work on my mac (os x 10.5)? I'm using the built in php and php in Zend/Eclipse. Can't seem to find useful drivers for it at all.

Answer:
I'm not sure this will help with the PDO drivers specifically, but you might look into
BitNami's MAPPStack
.
I had a ton of trouble with Postgres, PHP, and Apache on my Mac, some of it having to do with 64- vs 32-bit versions of some or all of them.  So far, the BitNami MAPPStack install is working nicely in general.  Maybe it will help with your PDO issues as well.


Question:
I am using a rich text editor on a web page.  .NET has feature that prevent one from posting HTML tags, so I added a JavaScript snippet to change the angle brackets to and alias pair of characters before the post. The alias is replaced on the server with the necessary angle bracket and then stored in the database.  With XSS aside, what are common ways of fixing this problem. (i.e. Is there a better way?)

If you have comments on XSS(cross-site scripting), I'm sure that will help someone.

Answer: My first comment would be to avoid using JavaScript to change the angle brackets. Bypassing this is as simple as disabling JavaScript in the browser. Almost all server-side languages have some utility method that converts some HTML characters into their entity counterparts. For instance, PHP uses htmlentities(), and I am sure .NET has an equivalent utility method. In the least, you can do a regex replace for angle brackets, parenthesis and double quotes, and that will get you a long way toward a secure solution.


Question: Navision is also known as Microsoft Dynamics NAV.

Answer:
Navision's application logic is written using a proprietary language called C/AL, which is loosely based on Pascal.  It currently offers both a native database option as well as MS SQL Server.
The next version (NAV 2009) will use .NET assemblies served via IIS.  C/AL logic will be translated to C# code and deployed to the server.


Question:
I'm just curious if any project exists that attempts to group all (or most) of PHP's built-in functions into a more object-oriented class hierarchy. For example, grouping all the string functions into a single String class, etc.

I realize this won't actually solve any problems (unless the modifications took place at the PHP source code level), since all the built-in functions would still be accessible in the global namespace, but it would certainly make usability much easier.

Answer: I think something like this is intergral for PHP to move forward.  Being mainly a .Net programmer, I find PHP painful to work in with it's 1 million and 1 global functions.  It's nice that PHP 5.3 has namespaces, but it doesn't help things much when their own libraries aren't even object oriented, let alone employ namespaces.  I don't mind PHP as a language so much, but their API is terribly disorganized, and it probably needs a complete overhaul.  Kind of like what VB went through when it became VB.Net.


Question:
I'm looking for a Java profiler that works well with the JVM coming with WebSphere 6.0.2 (IBM JVM 1.4.2). I use yourkit for my usual profiling needs, but it specifically refuses to work with this old jvm (I'm sure the authors had their reasons...).

Can anybody point to a decent profiler that can do the job? Not interested in a generic list of profilers, BTW, I've seen the other stackoverflow theread, but I'd rather not try them one by one.

I would prefer a free version, if possible, since this is a one-off need (I hope!) and I would rather not pay for another profiler just for this.

Answer:
What are you looking to profile?  Is it stuff in the JVM or the App Server? If it's the latter, there's loads of stuff in WAS 6 GUI to help with this.  Assuming you really want to see stuff like the heap etc, then the IBM
HeapAnalyzer
might help.  There are other tools listed off the bottom of this page.
Something else I've learned, ideally, youll be able to connect your IDE's profiler to the running JVM.  Some let you do this to a remote one as well as the local one you are developing on.  Is the JVM you wish to profile in live or remote?  If so, you might have to force dumps and take them out of the live environment to look at at your leisure.  Otherwise, set up something local and get the info from it that way.


Question:
I am wondering what the best way to obtain the current domain is in ASP.NET?

For instance:

http://www.domainname.com/subdir/ should yield http://www.domainname.com
http://www.sub.domainname.com/subdir/ should yield http://sub.domainname.com

As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.

Answer:
As per
this link
a good starting point is:
```
```
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
```
```
However, if the domain is
http://www.domainname.com:500
this will fail.
Something like the following is tempting to resolve this:
```
```
int defaultPort = Request.IsSecureConnection ? 443 : 80;
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
  + (Request.Url.Port != defaultPort ? ":" + Request.Url.Port : "");
```
```
However, port 80 and 443 will depend on configuration.
As such, you should use
```
IsDefaultPort
```
as in the
Accepted Answer
above from Carlos Muñoz.