q:
Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no  longer supported.

The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases.

[A]
Just write
```
<input type="button" ... />
```
into your html.  There's nothing special at all with the html controls.


q:
I'm trying to create a standard way of rolling out web applications for our company.  Currently we do it with zip files, vbscript/javascript, and manual some steps.

For thick client installs we generate MSI installers using Wise/Wix.  We don't create installers currently for websites as in general they are just xcopy deploy.  However we have some config files that need to be changed, verify that certain handlers are registered in IIS...  The list goes on.

Do most people use MSI installers for web applications as well, or some other tool/scripting language?

[A]
You may want to look at:
How do I get a deployable output from a build script with ASP.NET
Step by Step ASP.NET Automated Build/Deploy
We use MSI to create basic installers for our web projects too, often using the Web Setup Projects in VS and sometimes completely custom installers. You may also want to look at
MSDeploy
.

s: huggingface

c: devops

d: intermediate


q:
I need to update a combobox with a new value so it changes the reflected text in it. The cleanest way to do this is after the comboboxhas been initialised and with a message.

So I am trying to craft a postmessage to the hwnd that contains the combobox.

So if I want to send a message to it, changing the currently selected item to the nth item, what would the postmessage look like?

I am guessing that it would involve ON_CBN_SELCHANGE, but I can't get it to work right.

[A]
You want
ComboBox_SetCurSel
:
```
```
ComboBox_SetCurSel(hWndCombo, n);
```
```
or if it's an MFC CComboBox control you can probably do:
```
```
m_combo.SetCurSel(2);
```
```
I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN_SELCHANGE is the notification that the control sends
back to you
when the selection is changed.
Finally, you might want to add the c++ tag to this question.


q:
I have the following query:

select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;

What would be the difference if I replaced all calls to count(column_name) to count(*)?

This question was inspired by How do I find duplicate values in a table in Oracle?.

To clarify the accepted answer (and maybe my question), replacing count(column_name) with count(*) would return an extra row in the result that contains a null and the count of null values in the column.

[A]
```
count(*)
```
counts NULLs and
```
count(column)
```
does not
[edit] added this code so that people can run it
```
```
create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,null)

select count(*),count(id),count(id2)
from #bla
```
```
results
7   3   2


q:
I'm migrating a Hibernate application's cache from EHCache to JBoss TreeCache.
I'm trying to find how to configure the equivalent to maxElementsOnDisk to limit the cache size on disk, but I couldn't find anything similar to configure in a FileCacheLoader with passivation activated.

Thanks

[A]
This page
seems to imply that the correct configuration element is:
```
```
<attribute name="MaxCapacity">20000</attribute>
```
```
However, I've only ever used EHCache myself.


q: What is the best way to vertically center the content of a div when the height of the content is variable.  In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.

[A]
This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks.  When we get browser support for css 3 you'll get your vertical centering without sinning.
For a better explanation of the technique you can look
the article I adapted it from
, but basically it involves adding an extra element and applying different styles in IE and browsers that support
```
position:table\table-cell
```
on non-table elements.
```
```

            Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.

```
```
There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.
Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases.  If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.
Update:
We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See
this other question
for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.


q:
I have the following code:

SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;

Is there any difference to the results or performance if I replace the COUNT(*) with COUNT('x')?

(This question is related to a previous one)

[A]
The major performance difference is that COUNT(*) can be satisfied by examining the primary key on the table.
i.e. in the simple case below, the query will return immediately, without needing to examine any rows.
```
```
select count(*) from table
```
```
I'm not sure if the query optimizer in SQL Server will do so, but in the example above, if the column you are grouping on has an index the server should be able to satisfy the query without hitting the actual table at all.
To clarify: this answer refers specifically to SQL Server.  I don't know how other DBMS products handle this.


q:
Suppose I have fileA.h which declares a class classA with template function SomeFunc<T>(). This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of SomeFunc() (like for SomeFunc<int>()) in fileA.C (ie. not in the header file).

If I now call SomeFunc<int>() from some other code (maybe also from another library), would it call the generic version, or the specialization?

I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.

[A]
Unless the specialized template function is also listed in the header file, the other application will have no knowledge of the specialized version.  The solution is the add
```
SomeFunc<int>()
```
to the header as well.


q:
In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?

Am I going to get myself into trouble if I change this:

<cfcomponent>
    <cfset variables.foo = "a private instance variable">

    <cffunction name = "doSomething">
        <cfset var bar = "a function local variable">
        <cfreturn "I have #variables.foo# and #bar#.">
    </cffunction>
</cfcomponent>

to this?

<cfcomponent>
    <cfset foo = "a private instance variable">

    <cffunction name = "doSomething">
        <cfset var bar = "a function local variable">
        <cfreturn "I have #foo# and #bar#.">
    </cffunction>
</cfcomponent>

[A]
It won't matter to specify "variables" when you create the variable, because foo will be placed in the variables scope by default; but it will matter when you access the variable.
```
```
<cfcomponent>
    <cfset foo = "a private instance variable">

    <cffunction name="doSomething">
        <cfargument name="foo" required="yes"/>
        <cfset var bar = "a function local variable">
        <cfreturn "I have #foo# and #bar#.">
    </cffunction>

    <cffunction name="doAnotherThing">
        <cfargument name="foo" required="yes"/>
        <cfset var bar = "a function local variable">
        <cfreturn "I have #variables.foo# and #bar#.">
    </cffunction>

</cfcomponent>
```
```
doSomething("args") returns "I have
args
and a
function local variable
"
doAnotherThing("args") returns "I have
a private instance of a variable
and a
function local variable
."


q:
Those of you who have used Pex, what do you think its advantages and disadvantages are of Pex as a tool?

Also, what do you think are the advantages and disadvantages of "Automated Exploratory Testing" in general, as a supplement to TDD/Unit Testing?

[A]
I think Pex as an exploratory testing tool is really intriguing. In that regard, I see it as something I'd want to hand off to QA to use.
As a TDD tool, it needs some work, as TDD is a design activity. However, I do like the direction that Peli is heading. There's something to be said for automated assisted design. For example, just because TDD is a design tool, there's no reason I can't have an automated tool point out potential edge cases while I'm designing, right? Build quality in from the start.
Check out this post in which Peli uses Pex in a TDD style workflow.
http://blog.dotnetwiki.org/TDDingABinaryHeapWithPexPart1.aspx


q:
Is accessing a bool field atomic in C#? In particular, do I need to put a lock around:

class Foo
{
   private bool _bar;

   //... in some function on any thread (or many threads)
   _bar = true;

   //... same for a read
   if (_bar) { ... }
}

[A]
Yes.
Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.
as found in
C# Language Spec
.
Edit: It's probably also worthwhile understanding the
volatile
keyword.


q:
I've got the following in my .css file creating a little image next to each link on my site:

div.post .text a[href^="http:"]
{
    background: url(../../pics/remote.gif) right top no-repeat;
    padding-right: 10px;
    white-space: nowrap;
}

How do I modify this snippet (or add something new) to exclude the link icon next to images that are links themselves?

[A]
It might be worth it to add a class to those
```
<a>
```
tags and then add another declaration to remove the background:
```
```
div.post .text a.noimage{
   background:none;
}
```
```


q:
I'm using MySQL in particular, but I'm hoping for a cross-vendor solution.  I'm using the NOW() function to add a timestamp as a column for each record.

INSERT INTO messages
(typeId, messageTime, stationId, message)
VALUES
(?, NOW(), ?, ?)

[A]
```
```
SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= messageTime
```
```


q:
How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.

Edit: Here's the code I'm now using this for, based on the answer from Santiago below.

public DataTemplate Create(Type type)
{
  return (DataTemplate)XamlReader.Load(
          @"<DataTemplate
            xmlns=""http://schemas.microsoft.com/client/2007"">
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
            </DataTemplate>"
   );
}

This works really nicely and allows me to change the binding on the fly.

[A]
citation from MSDN
:
The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element.


q:
I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item.

Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, _File

However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following?

<Menu>
<MenuItem>
    <MenuItem.Header>
    <UserControl>
        <Image Source="..." />
        <Label Text="_Open" />
    </UserControl>
    </MenuItem.Header>
</MenuItem>
...

[A]
The problem is you placed the image inside of the content of the MenuHeader which means that you'll lose the accelerator key. If you're just trying to have an image in the menu header, do the following.
```
```
<MenuItem Header="_Open">
  <MenuItem.Icon>
    <Image Source="images/Open.png"/>
  </MenuItem.Icon>
</MenuItem>
```
```
If you want to customize the look and feel even further, modify the
controltemplate
and style for the menu. From experience, styling the menus and menuitems are much more difficult then styling the other WPF controls.


q:
By default the webjump hotlist has the following which I use quite often:

M-x webjump RET Google
M-x webjump RET Wikipedia

How can I add 'Stackoverflow' to my list?

[A]
Here's some example code in
a webjump.el file on a site run by Apple:
```
```
;;   (require 'webjump)
;;   (global-set-key "\C-cj" 'webjump)
;;   (setq webjump-sites
;;         (append '(
;;                   ("My Home Page" . "www.someisp.net/users/joebobjr/")
;;                   ("Pop's Site"   . "www.joebob-and-son.com/")
;;                   )
;;                 webjump-sample-sites))
```
```


q: I have a Windows Form that takes quite a bit of time to load initially.  However, each subsequent request to load the Form doesn't take as long.  Is there a way to optimize a Form's load time?

[A]
You can use
ngen
.
I also use this tip to reduce the
Memory footprint on startup
.
The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. The runtime can use native images from the cache instead using the just-in-time (JIT) compiler to compile the original assembly.


q: What's a good program to record videos or screencasts being played on screen?

[A]
I've had success with Camtasia / CamStudio.  Check out
http://showmedo.com
for tutorials.  It's a little recursive though - it would be better to capture it from source.


q:
is there an easy way to transform HTML into markdown with JAVA?

I am currently using the Java MarkdownJ library to transform markdown to html.

import com.petebevin.markdown.MarkdownProcessor;
...
public static String getHTML(String markdown) {
    MarkdownProcessor markdown_processor = new MarkdownProcessor();
    return markdown_processor.markdown(markdown);
}

public static String getMarkdown(String html) {
/* TODO Ask stackoverflow */
}

[A]
I am working on the same issue, and experimenting with a couple different techniques.
The answer above could work. You could use the
jTidy library
to do the initial cleanup work and convert from HTML to XHTML. You use the
XSLT stylesheet
linked above.
Unfortunately there is no library that has a one-stop function to do this in Java. You could try using the Python script
html2text
with Jython, but I haven't yet tried this!


q:
I understand the main function of the lock key word from MSDN

lock Statement (C# Reference)

The lock keyword marks a statement
  block as a critical section by
  obtaining the mutual-exclusion lock
  for a given object, executing a
  statement, and then releasing the
  lock.

When should the lock be used?

For instance it makes sense with multi-threaded applications because it protects the data.  But is it necessary when the application does not spin off any other threads?

Is there performance issues with using lock?

I have just inherited an application that is using lock everywhere, and it is single threaded and I want to know should I leave them in, are they even necessary?

Please note this is more of a general knowledge question, the application speed is fine, I want to know if that is a good design pattern to follow in the future or should this be avoided unless absolutely needed.

[A]
Generally speaking if your application is single threaded, you're not going to get much use out of the lock statement. Not knowing your application exactly, I don't know if they're useful or not - but I suspect not. Further, if you're application is using lock everywhere I don't know that I would feel all that confident about it working in a multi-threaded  environment anyways - did the original developer
actually
know how to develop multi-threaded code, or did they just add lock statements everywhere in the vague hope that that would do the trick?


q:
I have a page results page (you get there after submitting your search query elsewhere) whit a whole bunch of gridviews for different type of data objects.

Obviously, some of the queries take longer than the others. How can I make each gridview render as soon as it has the data it needs?

This has been tricky for me because it must work on a postback as well as a pageload. Also, the object data sources just fire automatically on page load/postback; I'm not calling any methods programatically to get the data. Will I have to change this?

[A]
Could you put the DataGrids inside panels that have their visibility set to false, then call a client-side javascript function from the body's onload event that calls a server side function that sets the visibility of the panels to true?
If you combined this with an asp:updateProgress control and wrapped the whole thing in an UpdatePanel, you should get something close to what you're looking for - especially if you rigged the js function called in onload to only show one panel and call a return function that showed the next etc.


q: What's the best way to determine which version of the .NET Compact Frameworks (including Service Packs) is installed on a device through a .NET application.

[A]
I have battled this problem myself last week and consider myself somewhat of an expert now ;)
I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put
```
```
#define _BIND_TO_CURRENT_MFC_VERSION 1
#define _BIND_TO_CURRENT_CRT_VERSION 1
```
```
into
every
project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled.
There are more flags that define what versions to bind to; it's documented on
http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx
. As an alternative to the lines above, you can also put
```
```
#define _BIND_TO_CURRENT_VCLIBS_VERSION 1
```
```
which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP).
Then, check what the embedded manifest says. Download XM Resource Editor:
http://www.wilsonc.demon.co.uk/d10resourceeditor.htm
. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version.
What I found is that in many cases,
both
versions were included in the manifest. This means that some libraries use the sp1 version and others don't.
A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the
```
_BIND_TO_CURRENT_CRT_VERSION
```
preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere.
Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.


q:
I have a web page that I have hooked up to a stored procedure. In this SQL data source, I have a parameter that I'm passing back to the stored procedure of type int.

ASP.NET seems to want to default to int32, but the number won't get higher than 6.  Is it ok to override the ASP.NET default and put in 16 or will there be a conflict somewhere down the road?

specification: the database field has a length of 4 and precision of 10, if that makes a difference in the answer.


q:
Is there a way to get at the ItemContaner of a selected item in a listbox?  In Silverlight 2.0 Beta 1 I could, but the container is hidden in Beta 2 of Silverlight 2.0.

I'm trying to resize the listbox item when it is unselected to a specific size and when selected to a variable size.  I also want to get the relative position of the selected item for animations.   Growing to a variable size and getting the relative pasition is why i need to get to the listbox item.

I should clarify i'm not adding items to the listbox explicitly.  I am using data binding in xaml and DataTemplates.  What I have trouble accessing is the ItemContainer of the selected item's DataTemplate.

[A]
If you are adding non-UI elements to the listbox (such as strings or non-UI data objects), then this is probably pretty difficult.  However if you wrap your items in some sort of FrameworkElement-derived object before adding them to the listbox, you can use TransformToVisual to get the relative size and use Height and Width to set the size of the item.
In general you can wrap your objects in a ContentControl like the following.  Instead of:
```
```
_ListBox.Items.Add(obj0);
_ListBox.Items.Add(obj1);
```
```
Do this:
```
```
_ListBox.Items.Add(new ContentControl { Content = obj0 });
_ListBox.Items.Add(new ContentControl { Content = obj1 });
```
```
Now when you get _ListBox.SelectedItem you can cast it to ContentControl and set the size and get the relative position.  If you need the original object, simply get the value of the item's Content property.


q:
Given a controller method like:

def show
  @model = Model.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml => model }
  end
end

What's the best way to write an integration test that asserts that the return has the expected XML?

[A]
Set the request objects accept header:
```
```
@request.accept = 'text/xml' # or 'application/xml' I forget which
```
```
Then you can assert the response body is equal to what you were expecting
```
```
assert_equal '<some>xml</some>', @response.body
```
```


q:
Erasing programs such as Eraser recommend overwriting data maybe 36 times.

As I understand it all data is stored on a hard drive as 1s or 0s.

If an overwrite of random 1s and 0s is carried out once over the whole file then why isn't that enough to remove all traces of the original file?

[A]
There are "disk repair" type applications and services that can still read data off a hard drive even after it's been formatted, so simply overwriting with random 1s and 0s one time isn't sufficient if you really need to securely erase something.
I would say that for the average user, this is more than sufficient, but if you are in a high-security environment (government, military, etc.) then you need a much higher level of "delete" that can pretty effectively guarantee that no data will be recoverable from the drive.


q: In a LotusScript Agent that is being run via WebQueryOpen, how do you get the name of the current server?

[A]
```
```
Set s = New NotesSession
Set db = s.CurrentDatabase

If db.Server <> "" Then
  Set sName = New NotesName(db.Server)
Else
  Set sName = New NotesName(s.Username)
End If
```
```


q: Is there an equivalent operator to Haskell's list difference operator \\ in F#?

[A]
Nope... Just write it and make it an infix operator --using the set of special characters. Backslash (
```
\
```
) is not in the list below, so it will not work as an infix operator. See the
manual
:
infix-op :=
```
```
or || & && <OP >OP $OP = |OP &OP ^OP :: -OP +OP *OP /OP %OP

**OP
```
```
prefix-op :=
```
```
!OP ?OP ~OP -OP +OP % %% & &&
```
```


q:
The most common method for corrupting compressed files is to inadvertently do an ASCII-mode FTP transfer, which causes a many-to-one trashing of CR and/or LF characters.

Obviously, there is information loss, and the best way to fix this problem is to transfer again, in FTP binary mode.

However, if the original is lost, and it's important, how recoverable is the data?

[Actually, I already know what I think is the best answer (it's very difficult but sometimes possible - I'll post more later), and the common non-answers (lots of off-the-shelf programs for repairing CRCs without repairing data), but I thought it would be interesting to try out this question during the stackoverflow beta period, and see if anyone else has gone down the successful-recovery path or discovered tools I don't know about.]

[A]
You could try writing a little script to replace all of the CRs with CRLFs (assuming the direction of trashing was CRLF to CR), swapping them randomly per block until you had the correct crc.  Assuming that the data wasn't particularly large, I guess that might not use all of your CPU until the heat death of the universe to complete.
As there is definite information loss, I don't know that there is a better way.  Loss in the CR to CRLF direction might be slightly easier to roll back.


q: With text-recognition improving and CAPTCHA-breakers using Mechanical Turks to break otherwise unbreakable keys, what's the next technology to keep scripts from spam-botting a site that relies on user input?

[A]
I am a fan of limiting logins by using a credit card or cell phone SMS (like Craigslist and Gmail). These methods don't cost much (<$1), but can be highly effective in keeping spam accounts under control.
However, this is tricky on a site like SO because one of the founding goals is to have minimum friction and allow anonymous users to contribute. I guess that's where the throttling and voting comes into play.


q: I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong?

[A]
At the top of your external JavaScript file, add the following:
```
```
/// <reference path="jQuery.js"/>
```
```
Make sure the path is correct, relative to the file's position in the folder structure, etc.
Also, any references need to be at the top of the file, before
any
other text, including comments - literally, the very first thing in the file. Hopefully future version of Visual Studio will work regardless of where it is in the file, or maybe they will do something altogether different...
Once you have done that and
saved the file
, hit
Ctrl
+
Shift
+
J
to force Visual Studio to update Intellisense.


q:
I have been hearing the podcast blog for a while, I hope I dont break this.
The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp_xml_preparedocument that is used to get transfer XMLs to an object and throught code.

I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes.

[A]
If your XML conforms to a particular XSD schema, you can look into using the "xsd.exe" command line tool to generate C# object classes that you can bind the XML to, and then form your insert statements using the properties of those objects:
MSDN XSD Doc


q:
I'm trying to get the GWTShell mode to load my context.xml file in which my database is described.

The only usable info can be found here, but this doesn't seem to work for the context.xml part.

[A]
As of version 1.4, I have been running all my server side code, in my container of choice (Glassfish) and hooking up the GWTShell to that. Are you using Netbeans, Eclipse or something else? The Netbeans plugin gwt4nb does this for you out of the box, you just have to start your web project in debug mode. I'm sure the GWT plugin for Eclipse does the same thing.
I realise this doesn't directly answer your question -> but my question is, is there a reason you're trying to get GWT to pick up your database settings and not just running your project as normal instead. I find this much better and robust way of running the GWTShell.
Edit: Sorry I don't really use Eclipse, so I can't help you with plugins for it. I find Netbeans far superior for J2EE/web type projects. It's a bit slower, but far more functional. The plugin for that is called 'GWT4NB', it's free and it will set up your ant script in such a way that you just have to right-click on your web project and choose debug. I can understand if you don't want to switch IDEs though.


q:
I am getting the following error in an MS Access ADP when trying to add a record on a form linked to a MS SQL Server 2000 table:

Run-time error '31004':

The value of an (AutoNumber) field
  cannot be retrived prior to being
  saved.

Please save the record that contains
  the (AutoNumber) field prior to
  performing this action.
  note: retrieved is actually spelled wrong in the error.

Does anyone know what this means?

I've done a web search and was only able to find the answer at a certain site that only experts have access to.

[A]
Are you trying to assign the value of an Identity field to a variable or something else before you have saved the record?
For whatever reason, your app is trying to read the value of the identity field before the record has been saved, which is what generates that identity field.  In other words, no value exists for the Autonumber field until the row is saved.
I think we'd need to see more code or know more about the steps that lead up to this error to resolve it in more detail.


q:
I would like to be able to define and use a custom type in some of my PowerShell scripts. For example, let's pretend I had a need for an object that had the following structure:

Contact
{
    string First
    string Last
    string Phone
}

How would I go about creating this so that I could use it in function like the following:

function PrintContact
{
    param( [Contact]$contact )
    "Customer Name is " + $contact.First + " " + $contact.Last
    "Customer Phone is " + $contact.Phone
}

Is something like this possible, or even recommended in PowerShell?

[A]
There is the concept of PSObject and Add-Member that you could use.
```
```
$contact = New-Object PSObject

$contact | Add-Member -memberType NoteProperty -name "First" -value "John"
$contact | Add-Member -memberType NoteProperty -name "Last" -value "Doe"
$contact | Add-Member -memberType NoteProperty -name "Phone" -value "123-4567"
```
```
This outputs like:
```
```
[8] » $contact

First                                       Last                                       Phone
-----                                       ----                                       -----
John                                        Doe                                        123-4567
```
```
The other alternative (that I'm aware of) is to define a type in C#/VB.NET and load that assembly into PowerShell for use directly.
This behavior is definitely encouraged because it allows other scripts or sections of your script work with an actual object.


q:
Suppose the following:

>>> s = set([1, 2, 3])

How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.

Quick and dirty:

>>> elem = s.pop()
>>> s.add(elem)

But do you know of a better way? Ideally in constant time.

[A]
Two options that don't require copying the whole set:
```
```
for e in s:
    break
# e is now an element from s
```
```
Or...
```
```
e = next(iter(s))
```
```
But in general, sets don't support indexing or slicing.


q:
I have a page that uses

$(id).show("highlight", {}, 2000);

to highlight an element when I start a ajax request, that might fail so that I want to use something like

$(id).show("highlight", {color: "#FF0000"}, 2000);

in the error handler. The problem is that if the first highlight haven't finished, the second is placed in a queue and wont run until the first is ready. Hence the question: Can I somehow stop the first effect?

[A]
From the jQuery docs:
http://docs.jquery.com/Effects/stop
Stop the currently-running animation on the matched elements.
...
When
```
.stop()
```
is called on an element, the currently-running animation (if any) is immediately stopped. If, for instance, an element is being hidden with
```
.slideUp()
```
when
```
.stop()
```
is called, the element will now still be displayed, but will be a fraction of its previous height. Callback functions are not called.
If more than one animation method is called on the same element, the later animations are placed in the effects queue for the element. These animations will not begin until the first one completes. When
```
.stop()
```
is called, the next animation in the queue begins immediately. If the
```
clearQueue
```
parameter is provided with a value of
```
true
```
, then the rest of the animations in the queue are removed and never run.
If the
```
jumpToEnd
```
argument is provided with a value of true, the current animation stops, but the element is immediately given its target values for each CSS property. In our above
```
.slideUp()
```
example, the element would be immediately hidden. The callback function is then immediately called, if provided...


q:
I am working on an application for college music majors. A feature i am considering is slowing down music playback without changing its pitch. I have seen this done in commercial software, but cannot find any libraries or open source apps that do anything like this.

Are there libraries out there?

How could this be done from scratch from various file formats?

Note: I am working in java but am not oppossed to changing languages.

[A]
Timestretching is quite hard. The more you slow down or speed up the sound the more artifacts you get. If you want to know what they sound like listen to "The Rockafeller Skank" by Fat Boy Slim. There are a lot of ways to do it that all have their own strengths and weaknesses. The math can get really complex. That's why there are so many proprietary algorithms.
This page explains things a bit clearer than I can and links to the Dirac library.
http://www.dspdimension.com/admin/time-pitch-overview/
I found this link for java code to do pitch shifting/timestretching
http://www.adetorres.com/keychanger/KeyChangerReadme.html


q: I started a project a long time ago and created a Data Access Layer project in my solution but have never developed anything in it.  What is the purpose of a data access layer?  Are there any good sources that I could learn more about the Data Access Layer?

[A]
I recommend you read up here:
http://msdn.microsoft.com/en-us/practices/default.aspx
Using a DAL will help you isolate your data access from your presentation and business logic. I use it a lot so that I can easily swap out (through reflection and dynamically loading assemblies) data providers.
Read up, lots of good info there.
Also, look into the
Data Access Block
if you are planning on using .NET. It can be a big help.


q: We can successfully consume a .NET 2.0 web service from a Flex/AS3 application. Aside from SSL, how else can we make the security more robust (i.e., authentication)?

[A]
If you're talking about
securing the information
going over the wire, you can use Web Service Extensions (WSE) to encrypt the body of the soap message so that you don't have to secure the channel. This way the message can get passed around from more than one endpoint (ie. it can get forwarded) and you don't need multiple https certs.
If you're talking abut
autentication
then you could do forms auth with either a password in the body or in the soap headers (once again either encrypt the body or the channel). Or one of the easiest ways to secure a webservice (if it's an internal set of services) is have IIS do it, turn on NTLM and do authentication there. You can do authorization later on in the pipeline with an HTTPModule that checks peoples credential against the code they're trying to call.


q: I'm working on a simple ASP.Net page (handler, actually) where I check the value of the LOGON_USER server variable.  This works using Visual Studio's built-in web server and it works in other sites deployed to the live intranet site.  But it doesn't work on the IIS instance on my local XP machine.  How can I fix it, or what's going on if I can't?

[A]
What authentication do you have enabled in IIS?  Anonmyous, Basic, Digest, Integrated Windows?  Sounds to me like anonymous access is enabled/allowed, and nothing else.  This would means that LOGON_USER is not populated.
When you access your local IIS, trying using
http://127.0.0.1
in particular if you use IE.  IE will recognize "localhost" as being in your local trusted zone and will automatically pass your XP login credentials through when Integrated Windows auth is enabled.


q: I've been playing with RSS feeds this week, and for my next trick I want to build one for our internal application log.  We have a centralized database table that our myriad batch and intranet apps use for posting log messages.  I want to create an RSS feed off of this table, but I'm not sure how to handle the volume- there could be hundreds of entries per day even on a normal day.  An exceptional make-you-want-to-quit kind of day might see a few thousand.  Any thoughts?

[A]
Without knowing your application, I can't offer specific advice.
That said, it's common in these sorts of systems to have a level of severity. You could have a query string parameter that you tack on to the end of the URL that specifies the severity. If set to "DEBUG" you would see every event, no matter how trivial. If you set it to "FATAL" you'd only see the events that that were "System Failure" in magnitude.
If there are still too many events, you may want to sub-divide your events in to some sort of category system. Again, I would have this as a query string parameter.
You can then have multiple RSS feeds for the various categories and severities. This should allow you to tune the level of alerts you get an acceptable level.


q:
I am wanting to use ActiveScaffold to create assignment records for several students in a single step.  The records will all contain identical data, with the exception of the student_id.

I was able to override the default form and replace the dropdown box for selecting the student name with a multi-select box - which is what I want.  That change however, was only cosmetic, as the underlying code only grabs the first selected name from that box, and creates a single record.

Can somebody suggest a good way to accomplish this in a way that doesn't require my deciphering and rewriting too much of the underlying ActiveScaffold code?

Update: I still haven't found a good answer to this problem.

[A]
if your assingnments have
```
has_many :students
```
or
```
has_and_belongs_to_many :students
```
, then you can change the id of the multi-select box to assignment_student_ids[], and it should work.


q:
In Firefox you can enter the following into the awesome bar and hit enter:

javascript:self.resizeTo(1024,768);

How do you do the same thing in IE?

[A]
Try:
```
```
javascript:resizeTo(1024,768);
```
```
This works in IE7 at least.


q: I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?

[A]
I don't think there's a way to do it with any built-in commands. I would suggest you download something like
Gnuwin32
or
UnxUtils
and use the
```
sed
```
command (or download only
```
sed
```
):
```
```
sed -c s/FOO/BAR/g filename
```
```


q:
I am currently working on (or at least planning) a couple of projects that work with large amounts of repetitive data. The kind of data that works well in a spreadsheet or database, but is nasty in XML. :)

NetCDF seems like a great option for a file format. However, my work is in C# and there is no "official" NetCDF implementation available. There is an "official" Python version that I could potentially use with IronPython. Another option is the "NetCDF Library for .Net" on CodePlex but it seems pretty quiet (http://www.codeplex.com/netcdf).

Has anyone worked with either of these libraries? Can you provide any recommendations?

[A]
First, are you sure that NetCDF is the right choice?  If you want to interact with other programs that need to read in large amounts of data and they already support NetCDF, then it's probably a great choice.  There aren't that many standard and well-supported file formats that support large multidimensional arrays.  But if you're only going to be reading and writing files from C#, it may not be such a good choice.
I'm a big fan of the "classic" NetCDF file format.  It's compact and extremely simple, but flexible enough to support lots of common kinds of multidimensional well-structured data.  It only took me one day to write a complete parser for classic NetCDF, and it only took an hour to write a program to output a well-formed special case of a classic NetCDF file.  You could implement a pure C# NetCDF library yourself and it wouldn't be much trouble.  You could easily start by implementing only the features you need.
Here's the specification.
Unfortunately, NetCDF-4 chose to use HDF-5 as its data format.  It adds a lot of complexity and makes it much more difficult to write a complete NetCDF parser in another language.  HDF-5 is very general-purpose and in my opinion, it was overengineered - it tries to be too many things to too many people.  I would not recommend trying to work with it directly unless you plan to spend a month writing unit tests.  If you must use netCDF-4 / HDF-5 from C#, your only realistic option would be to wrap the C library using SWIG or something like that.
Note that NetCDF for Python is just a wrapper around the C code, so it's not really all that helpful; if you're going to use a wrapped C library you may as well just write a C# wrapper rather than use Python as a middle layer.


q:
I wrote a simple web service in C# using SharpDevelop (which I just got and I love).

The client wanted it in VB, and fortunately there's a Convert To VB.NET feature.  It's great.  Translated all the code, and it builds.  (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.)

But I get this error when I try to load the service now.

Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'.

Source Error:

Line 1:  <%@ WebService Class="flightinfo.Soap,flightinfo" %>

I have deleted the bins and rebuilt, and I have searched google (and stackoverflow).  I have scoured the project files for any remnants of C#.

Any ideas?

[A]
```
```
<%@ WebService Class="flightinfo.Soap,flightinfo" %>
```
```
What is the name of your class?


q:
What is a good challenge to improve your skills in object oriented programming?

The idea behind this poll is to provide an idea of which exercises are useful for learning OOP.

The challenge should be as language agnostic as possible, requiring either little or no use of specific libraries, or only the most common of libraries. Try to include only one challenge per answer, so that a vote will correspond to the merits of that challenge alone. Would also be nice if a level of skill required was indicated, and also the rationale behind why it is a useful exercise.

Solutions to the challenges could then be posted as answers to a "How to..." question and linked to from here.

For example:

Challenge - implement a last-in-first-out stack

Skill level - beginner

Rationale - gives experience of how to reference objects

[A] Certainly a good challenge, although less accessible than a "start from scratch" assignment, is to refactor some existing code that either doesn't use inheritance or doesn't use very much of it to make greater use of inheritance.  The process of refactoring will expose a lot of the benefits and gotchas of oop, as it certainly has for me on my most recent project.  It also pushed me to understand the concepts better than past projects have where I've created my own object oriented designs.


q: Is there a way to access Visual Studio's built-in ASP.NET Development Server over HTTPS?

[A]
Cassini does not support HTTPS.
However, you can use IIS to do this, if your using IIS 5.1, download the MS IIS toolpack for IIS 6.0, it comes with a tool to create self signed SSL certificates. This works on IIS 5.1
http://www.microsoft.com/downloads/details.aspx?FamilyID=56fc92ee-a71a-4c73-b628-ade629c89499&DisplayLang=en
The one tool you need (SelfSSL.exe) works just fine with IIS 5.1. Unfortunately, it comes bundled with a bunch of other stuff.
Steps:
Install the IIS Tools File. If you want, you can click Custom and tell it to only install SelfSSL.
Activate the site in IIS that you want to install a SSL certificate too.
Go to Start / Programs / IIS Resources / SelfSSL
This will launch a command prompt in the SelfSSL directory.
Using the provided help, run SelfSSL. The command I used was: selfssl.exe /N:cn=[MACHINENAME] /K:1024 /V:90
/S:5 /P:443
The /S switch indicates which site to install the certificate. You can figure out the number by looking at your sites in IIS and counting (Starting at 1 for the first site, not 0), to the site you want.
Once this has ran, browse to your localhost over HTTPS
You should receive an error message stating that this certificate is from a untrusted source. You can either add your machinename to the browsers “Trusted Authorities” list, or you can tell the browser to ignore this.
At this point, you will be able to run your localhost over HTTPS.


q:
Silverlight v2.0 is getting closer and closer to RTM but I have yet to hear any stats as to how many browsers are running Silverlight. If I ask Adobe (by googling "Flash install base") they're only too happy to tell me that 97.7% of browsers are running Flash player 9 or better.

Not that I believe everything I read, but where are these statistics from Microsoft or some other vendor about Silverlight? I'm going to be making a technology choice soon and a little bit of empirical evidence would be an asset at this point...

All you Silverlight developers out there, show me your stats!

[A]
If you are developing something for a general audience, I would highly recommend against Silverlight as you immediately cut out Linux users.
I went to watch videos for the Olympics (and I run exclusively Linux), and I couldn't watch the video on their site because they were in Silverlight.  On top of that, they actively removed all videos from YouTube, so I had no alternative but to try and scrounge up a Windows boot.  This only served to give me a very negative opinion of NBC, and consider them quite amateurish to pick such a restricting technology for something that should be available for everyone.
While Flash has it's problems, it works fine in Linux, so I would say (at this point), it is a much superior technology choice.
If you KNOW your audience is entirely on Windows (maybe Mac).... then you can consider Silverlight with knowing you won't be cutting out part of your audience.


q:
How much traffic can one web server handle? What's the best way to see if we're beyond that?

I have an ASP.Net application that has a couple hundred users. Aspects of it are fairly processor intensive, but thus far we have done fine with only one server to run both SqlServer and the site. It's running Windows Server 2003, 3.4 GHz with 3.5 GB of RAM.

But lately I've started to notice slows at various times, and I was wondering what's the best way to determine if the server is overloaded by the usage of the application or if I need to do something to fix the application (I don't really want to spend a lot of time hunting down little optimizations if I'm just expecting too much from the box).

[A]
What you need is some info on
Capacity Planning
..
Capacity planning is the process of planning for growth and forecasting peak usage periods in order to meet system and application capacity requirements. It involves extensive performance testing to establish the application's resource utilization and transaction throughput under load. First, you measure the number of visitors the site currently receives and how much demand each user places on the server, and then you calculate the computing resources (CPU, RAM, disk space, and network bandwidth) that are necessary to support current and future usage levels.


q: Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.


q:
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example:

$unsafe_variable = $_POST['user_input'];

mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");

That's because the user can input something like value'); DROP TABLE table;--, and the query becomes:

INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')

What can be done to prevent this from happening?

[A]
I'd recommend using
PDO
(PHP Data Objects) to run parameterized SQL queries.
Not only does this protect against SQL injection, but it also speeds up queries.
And by using PDO rather than
```
mysql_
```
,
```
mysqli_
```
, and
```
pgsql_
```
functions, you make your application a little more abstracted from the database, in the rare occurrence that you have to switch database providers.


q:
I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement.  What are the recommended Python solutions in this scenario?

[A]
The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the
```
match
```
-
```
case
```
statement which provides a first-class implementation of a "switch" for Python. For example:
```
```
def f(x):
    match x:
        case 'a':
            return 1
        case 'b':
            return 2
        case _:
            return 0   # 0 is the default case if x is not found
```
```
The
```
match
```
-
```
case
```
statement is considerably more powerful than this simple example.
You could use a dictionary:
```
```
def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]
```
```


q:
I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:

[======>                    ] 37%

and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?

[A]
There are two ways I know of to do this:
Use the backspace escape character ('\b') to erase your line
Use the
```
curses
```
package, if your programming language of choice has bindings for it.
And a Google revealed
ANSI Escape Codes
, which appear to be a good way. For reference, here is a function in C++ to do this:
```
```
void DrawProgressBar(int len, double percent) {
  cout << "\x1B[2K"; // Erase the entire current line.
  cout << "\x1B[0E"; // Move to the beginning of the current line.
  string progress;
  for (int i = 0; i < len; ++i) {
    if (i < static_cast<int>(len * percent)) {
      progress += "=";
    } else {
      progress += " ";
    }
  }
  cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
  flush(cout); // Required.
}
```
```


q:
I need to join two binary files with a *.bat script on Windows.

How can I achieve that?

[A]
You can use
```
copy /b
```
like this:
```
```
copy /b file1+file2 destfile
```
```


q:
Every sample that I have seen uses static XML in the xmldataprovider source, which is then used to databind UI controls using XPath binding.
Idea is to edit a dynamic XML (structure known to the developer during coding), using the WPF UI.

Has anyone found a way to load a dynamic xml string (for example load it from a file during runtime), then use that xml string as the XmlDataprovider source?

Code snippets would be great.

Update: To make it more clear,
Let's say I want to load an xml string I received from a web service call. I know the structure of the xml. So I databind it to WPF UI controls on the WPF Window. How to make this work? All the samples over the web, define the whole XML inside the XAML code in the XmlDataProvider node. This is not what I am looking for. I want to use a xml string in the codebehind to be databound to the UI controls.

[A]
using your webservice get your XML and create an XML Document from it, You can then set the Source of your xmlDataProvider to the XMLDocument you got from the service.
I'm not at a pc with visual studio to test it but it should be possible for you to do this.
The steps are as you mentioned in your question:
```
1. Get XML from webservice
2. Convert XML String to XML Document
3. Set the XMLDataProvider.Document value to your XML Document
4. Bind that to your controls
```


q:
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?

[A]
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)


q:
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.

[A]
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);
  }
}
```
```


q: 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?

[A]
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.


q:
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?

[A]
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.


q: 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?

[A]
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.


q: 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?

[A]
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 ?


q:
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?

[A]
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.


q:
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

[A]
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/


q:
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?

[A]
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>
```
.


q: 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?

[A]
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
)


q:
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?

[A]
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.


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

[A]
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!


q:
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.

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


q:
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.

[A]
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


q:
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.

[A]
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);
  ...
}
```
```


q: 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?

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
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).


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

[A]
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.


q:
How does one start development in Silverlight?

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

[A]
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
.


q:
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?

[A]
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.


q: 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.

[A]
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
.


q: 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)?

[A]
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.


q: 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

[A]
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


q:
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...

[A]
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.


q:
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.

[A]
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.


q:
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>

[A]
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.


q:
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()

[A]
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"))
```
```


q:
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

[A]
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
```
```


q:
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?

[A]
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 \


q:
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?

[A]
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);
```
```


q:
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?

[A]
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);
```
```


q:
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?

[A]
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();
```
```


q:
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.


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

[A]
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.


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

[A]
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


q: 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?

[A]
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


q:
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]

[A]
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.


q:
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?

[A]
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.