Question:
I have the problem that an specific step in Ant can only be executed when we have Java 1.5 installed in the build computer.  The task definition uses  uses a jar file that was compiled using 1.5, so running with a 1.4 virtual machine will throw an IncompatibleClassVersion exception.

I have to find a solution meanwhile to have this task working for this specific project that requires 1.4, but a question came to me.  How can I avoid defining this task and executing this optional step if I don't have a specific java version?

I could use the "if" or "unless" tags on the target tag, but those only check if a property is set or not.  I also would like to have a solution that doesn't require extra libraries, but I don't know if the build-in functionality in standard is enough to perform such a task.

Answer:
The Java version is exposed via the
ant.java.version
property. Use a
condition
to set a property and execute the task only if it is true.
```
```
<?xml version="1.0" encoding="UTF-8"?>

<project name="project" default="default">

    <target name="default" depends="javaCheck" if="isJava6">
        <echo message="Hello, World!" />
    </target>

    <target name="javaCheck">
        <echo message="ant.java.version=${ant.java.version}" />
        <condition property="isJava6">
            <equals arg1="${ant.java.version}" arg2="1.6" />
        </condition>
    </target>

</project>
```
```


Question:
I want to generate some XML in a stored procedure based on data in a table.

The following insert allows me to add many nodes but they have to be hard-coded or use variables (sql:variable):

SET @MyXml.modify('
      insert
         <myNode>
            {sql:variable("@MyVariable")}
         </myNode>
      into (/root[1]) ')

So I could loop through each record in my table, put the values I need into variables and execute the above statement.

But is there a way I can do this by just combining with a select statement and avoiding the loop?

Edit I have used SELECT FOR XML  to do similar stuff before but I always find it hard to read when working with a hierarchy of data from multiple tables. I was hoping  there would be something using the modify where the XML generated is more explicit and more controllable.

Answer:
Can you tell a bit more about what exactly you are planning to do.
Is it simply generating XML data based on a content of the table
or adding some data from the table to an existing xml structure?
There are
great series of articles
on the subject on XML in SQLServer written by Jacob Sebastian, it starts with the
basics of generating XML from the data in the table


Question:
Under the View-Model-ViewModel pattern for WPF, I am trying to databind the Heights and Widths of various definitions for grid controls, so I can store the values the user sets them to after using a GridSplitter. However, the normal pattern doesn't seem to work for these particular properties.

Note: I'm posting this as a reference question that I'm posting as Google failed me and I had to work this out myself. My own answer to follow.

Answer:
There were a number of gotchas I discovered:
Although it may appear like a double in XAML, the actual value for a *Definition's Height or Width is a 'GridLength' struct.
All the properties of GridLength are readonly, you have to create a new one each time you change it.
Unlike every other property in WPF, Width and Height don't default their databinding mode to 'TwoWay', you have to manually set this.
Thusly, I used the following code:
```
```
private GridLength myHorizontalInputRegionSize = new GridLength(0, GridUnitType.Auto)
public GridLength HorizontalInputRegionSize
{
    get
    {
        // If not yet set, get the starting value from the DataModel
        if (myHorizontalInputRegionSize.IsAuto)
            myHorizontalInputRegionSize = new GridLength(ConnectionTabDefaultUIOptions.HorizontalInputRegionSize, GridUnitType.Pixel);
        return myHorizontalInputRegionSize;
    }
    set
    {
        myHorizontalInputRegionSize = value;
        if (ConnectionTabDefaultUIOptions.HorizontalInputRegionSize != myHorizontalInputRegionSize.Value)
        {
            // Set the value in the DataModel
            ConnectionTabDefaultUIOptions.HorizontalInputRegionSize = value.Value;
        }
        OnPropertyChanged("HorizontalInputRegionSize");
    }
}
```
```
And the XAML:
```
```
<Grid.RowDefinitions>
    <RowDefinition Height="*" MinHeight="100" />
    <RowDefinition Height="Auto" />
    <RowDefinition Height="{Binding Path=HorizontalInputRegionSize,Mode=TwoWay}" MinHeight="50" />
</Grid.RowDefinitions>
```
```


Question: I miss it so much (used it a lot in C#). can you do it in C++?

Answer:
Yes, you can. See
here
.
```
```
#pragma region Region_Name
//Your content.
#pragma endregion Region_Name
```
```


Question: Can share with me any of this script?

Answer:
The default one is called commit-email.pl and is included when you install Subversion. But
here
is one in ruby:
```
```
#!/usr/bin/ruby -w

# A Subversion post-commit hook. Edit the configurable stuff below, and
# copy into your repository's hooks/ directory as "post-commit". Don't
# forget to "chmod a+x post-commit".

# ------------------------------------------------------------------------

# You *will* need to change these.

address="FOO@SOME_DOMAIN.com"
sendmail="/usr/sbin/sendmail"
svnlook="/usr/bin/svnlook"

# ------------------------------------------------------------------------

require 'cgi'

# Subversion's commit-email.pl suggests that svnlook might create files.
Dir.chdir("/tmp")

# What revision in what repository?
repo = ARGV.shift()
rev = ARGV.shift()

# Get the overview information.
info=`#{svnlook} info #{repo} -r #{rev}`
info_lines=info.split("\n")
author=info_lines.shift
date=info_lines.shift
info_lines.shift
comment=info_lines

# Output the overview.
body = "
#{author} #{date}
"
body << "
"
comment.each { |line|  body << "#{CGI.escapeHTML(line)}
\n" }
body << "
"
body << "
"

# Get and output the patch.
changes=`#{svnlook} diff #{repo} -r #{rev}`
body << "
"
changes.each do |top_line|
  top_line.split("\n").each do |line|
    color = case
      when line =~ /^Modified: / || line =~ /^=+$/ || line =~ /^@@ /: "gray"
      when line =~ /^-/: "red"
      when line =~ /^\+/: "blue"
      else "black"
    end
    body << %Q{#{CGI.escapeHTML(line)}
\n}
 end
end
body << "
"

# Write the header.
header = ""
header << "To: #{address}\n"
header << "From: #{address}\n"
header << "Subject: [SVN] #{repo} revision #{rev}\n"
header << "Reply-to: #{address}\n"
header << "MIME-Version: 1.0\n"
header << "Content-Type: text/html; charset=UTF-8\n"
header << "Content-Transfer-Encoding: 8bit\n"
header << "\n"

# Send the mail.
begin
    fd = open("|#{sendmail} #{address}", "w")
    fd.print(header)
    fd.print(body)
rescue
    exit(1)
end
fd.close

# We're done.
exit(0)
```
```


Question:
In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company, Region, Area, Site, Room, Till. For a particular company I need to write some MDX that lists all regions, areas and sites (but not any levels below Site). Currently I am achieving this with the following MDX

HIERARCHIZE({
[Location].[Test Company],
Descendants([Location].[Test Company], [Location].[Region]),
Descendants([Location].[Test Company], [Location].[Area]),
Descendants([Location].[Test Company], [Location].[Site])
})

Because my knowledge of MDX is limited, I was wondering if there was a simpler way to do this, with a single command rather that four? Is there a less verbose way of achieveing this, or is my example the only real way of achieving this?

Answer:
The command you want is DESCENDANTS. Keep the 'family tree' analogy in mind, and you can see that this will list the descendants of a member, down as far as you want.
You can specify the 'distance' (in levels) from the chosen member, 3 in your case.
There are a few weird options you can specify with the third argument, you want SELF_AND_AFTER, see
http://msdn.microsoft.com/en-us/library/ms146075.aspx
EDIT - oops, as santiiiii noticed, it should be SELF_AND_BEFORE


Question:
I'm expanding my Ruby understanding by coding an equivalent of Kent Beck's xUnit in Ruby.  Python (which Kent writes in) has an assert() method in the language which is used extensively.  Ruby does not.  I think it should be easy to add this but is Kernel the right place to put it?

BTW, I know of the existence of the various Unit frameworks in Ruby - this is an exercise to learn the Ruby idioms, rather than to "get something done".

Answer:
What's your reason for adding the assert method to the Kernel module? Why not just use another module called
```
Assertions
```
or something?
Like this:
```
```
module Assertions
  def assert(param)
    # do something with param
  end

  # define more assertions here
end
```
```
If you really need your assertions to be available
everywhere
do something like this:
```
```
class Object
  include Assertions
end
```
```
Disclaimer: I didn't test the code but in principle I would do it like this.


Question:
I'm making a simple jquery command:

element.html("&nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;");

using the attributes/html method:  http://docs.jquery.com/Attributes/html

It works on my local app engine server, but it doesn't work once I push to the Google server. The element empties but doesn't fill with spaces.

So instead of "      " (6 spaces) it's just "".

Once again, this is running on App Engine, but I don't think that should matter...

Answer:
Have you tried using
```

```
instead of spaces? The
```
html()
```
method just pumps the string into the innerHTML of the element(s).


Question:
In SQL, how do update a table, setting a column to a different value for each row?

I want to update some rows in a PostgreSQL database, setting one column to a number from a sequence, where that column has a unique constraint. I hoped that I could just use:

update person set unique_number = (select nextval('number_sequence') );

but it seems that nextval is only called once, so the update uses the same number for every row, and I get a 'duplicate key violates unique constraint' error. What should I do instead?

Answer:
Don't use a subselect, rather use the nextval function directly, like this:
```
```
update person set unique_number = nextval('number_sequence');
```
```


Question:
When using IF statements in Python, you have to do the following to make the "cascade" work correctly.

if job == "mechanic" or job == "tech":
        print "awesome"
elif job == "tool" or job == "rock":
        print "dolt"

Is there a way to make Python accept multiple values when checking for "equals to"? For example,

if job == "mechanic" or "tech":
    print "awesome"
elif job == "tool" or "rock":
    print "dolt"

Answer:
```
```
if job in ("mechanic", "tech"):
    print "awesome"
elif job in ("tool", "rock"):
    print "dolt"
```
```
The values in parentheses are a tuple. The
```
in
```
operator checks to see whether the left hand side item occurs somewhere inside the right handle tuple.
Note that when Python searches a tuple or list using the
```
in
```
operator, it does a linear search. If you have a large number of items on the right hand side, this could be a performance bottleneck. A larger-scale way of doing this would be to use a
```
frozenset
```
:
```
```
AwesomeJobs = frozenset(["mechanic", "tech", ... lots of others ])
def func():
    if job in AwesomeJobs:
        print "awesome"
```
```
The use of
```
frozenset
```
over
```
set
```
is preferred if the list of awesome jobs does not need to be changed during the operation of your program.


Question:
I'm experimenting with OpenSSL on my network application and I want to test if the data sent is encrypted and can't be seen by eavesdropper.

What tools can you use to check? Could this be done programmatically so it could be placed in a unit test?

Answer:
check out wire shark
http://www.wireshark.org/
and tcp dump
http://en.wikipedia.org/wiki/Tcpdump
Not sure about integrating these into unit tests. They will let you look at a very low level whats going on at the network level.
Perhaps for the unit test determine what the stream looks like unencrypted and make sure the encrypted stream is not similar


Question: Is the sorting algorithm used by .NET's Array.Sort() method a stable algorithm?

Answer:
From
MSDN
:
This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
The sort uses introspective sort. (Quicksort in version 4.0 and earlier of the .NET framework).
If you need a stable sort, you can use
Enumerable.OrderBy
.


Question:
Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?

Answer - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.

Answer:
For a general InputStream, I would wrap it in a BufferedInputStream and do something like this:
```
```
BufferedInputStream bis = new BufferedInputStream(inputStream);
bis.mark(2);
int byte1 = bis.read();
int byte2 = bis.read();
bis.reset();
// note: you must continue using the BufferedInputStream instead of the inputStream
```
```


Question: I've been searching and can't find the download files on opengl.org. can someone please point me to the right direction?

Answer:
OpenGL is just a standard. The implementations come with your graphics card drivers and are exposed using WGL extensions in Windows. There is a 'standard' implementation in the platform SDK that is accessed by including the OpenGL headers and the windows header, but this is a basic version (1.1 in XP. I think it's 1.4 in Vista).
If you want an easier method to gain access to all the features from your card's supported features and the basic set of features in the Windows standard OpenGL implementation then I'd suggest looking at GLEW (The openGL Extension Wrangler) which handles all the WGL calls to set up extensions for you.


Question:
C++ preprocessor #define is totally different.

Is the PHP define() any different than just creating a var?

define("SETTING", 0);
$something = SETTING;

vs

$setting = 0;
$something = $setting;

Answer:
Here are the differences, from the
manual
Constants do not have a dollar sign    ($) before them;
Constants may only be defined using the define() function, not by simple assignment;
Constants may be defined and accessed anywhere without regard to variable scoping rules;
Constants may not be redefined or undefined once they have been set; and
Constants may only evaluate to scalar values.
For me, the main benefit is the global scope. I certainly don't worry about their efficiency - use them whenever you need a global scalar value which should not be alterable.


Question:
Microsoft recently announced that the Javascript/HTML DOM library jQuery will be integrated into the ASP.NET MVC framework and into ASP.NET / Visual Studio.

What is the best practice or strategy adopting jQuery using ASP.NET 2.0? I'd like to prepare a large, existing ASP.NET Web Application (not MVC) for jQuery. How would I deal with versioning and related issues?

Are the any caveats integrating jQuery and ASP.NET Ajax? Or 3rd party components like Telerik or Intersoft controls?

Answer:
There's a small issue which is mentioned by David Ward here:
http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/
But there should not be any major concerns about integrating jQuery into an existing application, you wouldn't notice major advantages unless you're planning a lot of updating/ reworking of existing code to take advantages of jQuerys power.


Question:
last time I asked how to populate a data structure here. Now I would like to know if there's something in Java, like the print_r I use in PHP, to represent what I have populated in the Maps and lists without having to do my own algorithm.

Any ideas?

Answer:
Calling
```
toString
```
on the collection should return a string containing all the elements string representations.
This won't work with built-in arrays though, as they don't have a
```
toString
```
override and will just give you a memory address.


Question:
Background:
I am developing a site in Asp.net 2.0 . Up until now i was handling both the design and development of the site. I used css for the design part.
Now the company wants to outsource the design work to a web designer.

Question:
How exactly are a designer and developer supposed to coordinate
What specifications should i give to the web designer, Do i need to provide him with the aspx pages i have developed, does he also need to look at the code behind.

And how do i incorporate the designed pages in the existing aspx pages.

I would appreciate if someone who is experienced in this provides some insight

thanks.

Answer:
How will the designer deliver their designs? Will they just provide the necessary graphic elements or will they deliver a valid HTML page? I would suggest you both agree on the DOM for the page and work from there.If they just provide graphics you have full control of the DOM.
The code behind model for .Net was supposed to help separate design and development but IMHO nothing has yet managed a perfect separation because you can't always make a 100% distinction.


Question:
Suppose I have one long long int and want to take its bits and construct four unsigned short ints out of it.

Particular order doesn't matter much here.

I generally know that I need to shift bits and truncate to the size of unsigned short int.  But I think I may make some weird mistake somewhere, so I ask.

Answer:
```
```
#include <stdint.h>
#include <stdio.h>

union ui64 {
    uint64_t one;
    uint16_t four[4];
};

int
main()
{
    union ui64 number = {0x123456789abcdef0};
    printf("%x %x %x %x\n", number.four[0], number.four[1],
                            number.four[2], number.four[3]);
    return 0;
}
```
```


Question: I am am trying to load a SQL table from a flat file. The flat i am talking about is a comma separated file. This has all the data required to populate a table will each column separated by a comma ",". I need some way by which i can load this content into the table faster.

Answer:
If you are using SQL Server, use
```
BULK INSERT
```
If you are using Oracle, see my answer
here


Question:
My favorite equation for centering an xhtml element using only CSS is as follows:

display: block;
position: absolute;
width: _insert width here_;
left: 50%;
margin-left: _insert width divided by two & multiplied by negative one here_

There's also the simpler margin:auto method in browsers that support it. Does anyone else have tricky ways to force content to display centered in its container? (bonus points for vertical centering)

edit - oops, forgot the 'negative' part of one in the margin-left. fixed.

Answer:
Well that seems like massive overkill, I've got to say. I tend to set the container to
```
text-align:center;
```
for old browsers,
```
margin:auto;
```
for modern browsers, and leave it like that. Then reset text-align in the element (if it contains text).
Of course, some things need setting as block, and widths need setting... But what on earth are you trying to style that needs
that
much hacking around?
```
```

```
```


Question:
In Oracle, I have set the log_archive_dest1='D:\app\administrator\orcl\archive' parameter and shutdown the database. When I tried to start up the db, I got the following error:

SQL> startup mount;

ORA-16032: parameter LOG_ARCHIVE_DEST_1 destination string cannot be translated

ORA-09291: sksachk: invalid device specified for archive destination

OSD-04018: Unable to access the specified directory or device.

O/S-Error: (OS 3) The system cannot find the path specified.

Does anyone have any ideas of how I might fix this?

Answer:
I've never used Oracle but some things you might try are
Make sure the permissions on the file path you're using allow the database to read / write to it?
Make sure all the folders in the path already exist
On Windows you might find the '\' characters confuse the database. Do you specify other paths in the same way for Oracle? An alternative may be to use '/' instead of '\'. Different programs that originated in the Unix world handle Windows paths in different ways


Question:
I have integrated SRM 5.0 into Portal. Most of the iviews are IAC i.e., all are ITS based services.

The issue is that the Portal Theme does not get reflected on these services after integration.

When a BSP or Webdynpro is integrated then the application reflects the Portal Theme when executed from Portal but the ITS services are not getting this.

I tried using SE80 and editing EBPApplication.css. In BBPGLOBAL i changed all color attributes to custom colour but no effect.

Whch property should i change to remove the blue colour.

Answer:
The key value pair table, but with everything is stored as a string and with another column (if necessary) saying which type should the value be casted to.
```
```
CREATE TABLE configKVP(clientId int, key varchar, value varchar, type varchar)
```
```
If the value cannot be casted to the type, then you know it's a misconfiguration and there's no ambiguity.


Question:
I want to be able to access custom URLs with apache httpclient. Something like this:

HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("media:///squishy.jpg");
int statusCode = client.executeMethod(method);

Can I somehow register a custom URL handler? Or should I just register one with Java, using

URL.setURLStreamHandlerFactory(...)

Regards.

Answer:
I don't think there's a way to do this in commons httpclient. It doesn't make a whole lot of sense either, after all it is a HTTP client and "media:///squishy.jpg" is not HTTP, so all the code to implement the HTTP protocol probably couldn't be used anyways.
```
```
URL.setURLStreamHandlerFactory(...)
```
```
could be the way to go, but you'll probably have to do a lot of protocol coding by hand, depending on your "media"-protocol.


Question: I have a interest in a reported bug which Microsoft have made available a hotfix for. When looking on the site, I'm not able to figure out if this fix is included in a service pack or not. Do anyone know where I can find this out?

Answer:
You didn't mention your product but:
List of fixes in Service Pack 1 for XP:
http://support.microsoft.com/kb/324720
List of fixes in Service Pack 2 for XP:
http://support.microsoft.com/kb/811113
List of fixes in Service Pack 3 for XP:
http://support.microsoft.com/kb/946480
List of fixes in Service Pack 1 for Vista:
http://technet.microsoft.com/en-us/library/cc749061.aspx


Question:
I wrote a sample program at http://codepad.org/ko8vVCDF that uses a template function.

How do I retrict the template function to only use numbers? (int, double etc.)

#include <vector>
#include <iostream>

using namespace std;

    template <typename T>
T sum(vector<T>& a)
{
    T result = 0;
    int size = a.size();
    for(int i = 0; i < size; i++)
    {
        result += a[i];
    }

    return result;
}

int main()
{
    vector<int> int_values;
    int_values.push_back(2);
    int_values.push_back(3);
    cout << "Integer: " << sum(int_values) << endl;

    vector<double> double_values;
    double_values.push_back(1.5);
    double_values.push_back(2.1);
    cout << "Double: " << sum(double_values);

    return 0;
}

Answer:
Why would you want to restrict the types in this case? Templates allow "static duck typing", so anything allowed by what your
```
sum
```
function in this case should be allowed. Specifically, the only operation required of
```
T
```
is add-assignment and initialisation by 0, so any type that supports those two operations would work. That's the beauty of templates.
(If you changed your initialiser to
```
T result = T();
```
or the like, then it would work for both numbers and strings, too.)


Question: Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library.

Answer:
You can use the
```
codecvt
```
locale facet
. There's a specific specialisation defined,
```
codecvt<wchar_t, char, mbstate_t>
```
that may be of use to you, although, the behaviour of that is system-specific, and does not guarantee conversion to UTF-8 in any way.


Question:
I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file.

How do I get sed to replace just the first occurrence of a string in a file rather than replacing every occurrence?

If I use

sed s/#include/#include "newfile.h"\n#include/

it replaces all #includes.

Alternative suggestions to achieve the same thing are also welcome.

Answer:
```
```
# sed script to change "foo" to "bar" only on the first occurrence
 1{x;s/^/first/;x;}
 1,/foo/{x;/first/s///;x;s/foo/bar/;}
 #---end of script---
```
```
or, if you prefer:
Editor's note: works with
GNU
```
sed
```
only.
```
```
sed '0,/foo/s//bar/' file
```
```
Source


Question:
It seems the .NET Regex.Replace method automatically replaces all matching occurrences.  I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me.

What is the most efficient way to stop after the first replacement?

Answer:
From
MSDN
:
```
```
Replace(String, String, Int32)
```
```
Within a specified input string, replaces a specified maximum number of strings that
  match a regular expression pattern with a specified replacement string.
Isn't this what you want?


Question:
I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge.

I want some help working out how to create an iterator for a class I have created.

I have a class 'Shape' which has a container of Points.
I have a class 'Piece' which references a Shape and defines a position for the Shape.
Piece does not have a Shape it just references a Shape.

I want it to seem like Piece is a container of Points which are the same as those of the Shape it references but with the offset of the Piece's position added.

I want to be able to iterate through the Piece's Points just as if Piece was a container itself. I've done a little reading around and haven't found anything which has helped me. I would be very grateful for any pointers.

Answer:
/EDIT: I see, an own iterator is actually necessary here (I misread the question first). Still, I'm letting the code below stand because it can be useful in similar circumstances.
Is an own iterator actually necessary here? Perhaps it's sufficient to forward all required definitions to the container holding the actual Points:
```
```
// Your class `Piece`
class Piece {
private:
    Shape m_shape;

public:

    typedef std::vector<Point>::iterator iterator;
    typedef std::vector<Point>::const_iterator const_iterator;

    iterator begin() { return m_shape.container.begin(); }

    const_iterator begin() const { return m_shape.container.begin(); }

    iterator end() { return m_shape.container.end(); }

    const_iterator end() const { return m_shape.const_container.end(); }
}
```
```
This is assuming you're using a
```
vector
```
internally but the type can easily be adapted.


Question: I have seen a few (old) posts on the 'net about hacking together some support for pre-compiled headers in CMake. They all seem a bit all-over the place and everyone has their own way of doing it. What is the best way of doing it currently?

Answer:
Don't even go there. Precompiled headers mean that whenever one of the headers changes, you have to rebuild
everything
. You're lucky if you have a build system that realizes this. More often than never, your build will just fail until you realize that you changed something that is being precompiled, and therefore you need to do a full rebuild. You can avoid this mostly by precompiling the headers that you are absolutely positive won't change, but then you're giving up a large part of the speed gain as well.
The other problem is that your namespace gets polluted with all kinds of symbols that you don't know or care about in many places where you'd be using the precompiled headers.


Question: I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own?

Answer:
I think you'll find this an incredibly difficult task. The easier path would be to prevent multiple-thread access with a
```
lock
```
:
```
```
void AddItemToList(object o)
{
    lock(myBindingList)
    {
        myBindingList.Add(o);
    }
}
```
```
Look at the
lock statement docs
for more info.


Question:
Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?

I would like to be able to write something like this:

#if ($a lt Long.MAX_VALUE)

but this is apparently not the right syntax.

Answer:
Velocity can only use anything it finds in its context, after e.g.
```
```
context.put("MaxLong", Long.MAX_VALUE);
```
```
You cannot use statics, or access static members of things in Velocity's context due to the way its lookup works (see Velocity's
Property lookup rules
). The best thing to do is add the value you want to check against explicitly in your context.
Edit October 6
on second sight, it seems to be possible to access static members. See the velocity
Developer guide - Support for "Static Classes"
for more information. I have not tried this out, though.


Question: Had anybody found a way to migrate MediaWiki pages over to WSS Wikis? We just put up Sharepoint 2007 and while it appears to meet our needs, it doesn't appear to be any tool provided by Microsoft to migrate MediaWiki pages over to WSS wikis.

Answer:
There is no such tool provided by Microsoft at this time.
There is one being developed though in the
SharePoint Community Kit
.
Wiki Import/Export Tool
The EWE team is at a very early stage of designing an import/export tool for the SharePoint wiki. The goal is for this tool to be able to import from other wiki products such as FlexWiki, MediaWiki, and TWiki, and Confluence and also from Word and OneNote as well as to export to Word via HTML (per page) and MHTML (entire wiki) formats.
For this CKS 2.0 pre-release, the EWE team is making available a fairly stable build of the FlexWiki Import Tool, for which the source code was graciously donated by Michael Cheng, a developer in the SharePoint product group. This is a one-off tool that will ultimately be converted to a plug-in for the Wiki Import/Export Tool, so if you’re currently using FlexWiki, please test the tool and provide feedback.


Question:
i work with sql server, but i must migrate to an application with Oracle DB.
for trace my application queries, in Sql Server i use wonderful Profiler tool. is there something of equivalent for Oracle?

Answer:
Oracle, along with other databases, analyzes a given query to create an execution plan.  This plan is the most efficient way of retrieving the data.
Oracle provides the '
```
explain plan
```
' statement which analyzes the query but doesn't run it, instead populating a special table that you can query (the plan table).
The syntax (simple version, there are other options such as to mark the rows in the plan table with a special ID, or use a different plan table) is:
```
```
explain plan for <sql query>
```
```
The analysis of that data is left for another question, or your further research.


Question:
This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles  providing an explanation would be appreciated.

//The constructor
public Page_Index() {

    //create a local value
    string currentValue = "This is the FIRST value";

    //use the local variable in a delegate that fires later
    this.Load += delegate(object sender, EventArgs e) {
        Response.Write(currentValue);
    };

    //change it again
    currentValue = "This is the MODIFIED value";

}

The value that is output is the second value "Modified". What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later?

[Edit]: Given some of the comments, changing the original sentence some...

Answer:
currentValue is no longer a local variable: it is a
captured
variable. This compiles to something like:
```
```
class Foo {
  public string currentValue; // yes, it is a field

  public void SomeMethod(object sender, EventArgs e) {
    Response.Write(currentValue);
  }
}
...
public Page_Index() {
  Foo foo = new Foo();
  foo.currentValue = "This is the FIRST value";
  this.Load += foo.SomeMethod;

  foo.currentValue = "This is the MODIFIED value";
}
```
```
Jon Skeet has a really good write up of this in
C# in Depth
, and a separate (not as detailed) discussion
here
.
Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers.
This is different to java: in java the
value
of a variable is captured. In C#, the
variable itself
is captured.


Question:
I don't see what all this fuss is about Microsoft's decision to support JQuery within ASP.NET MVC.

There were signs that open-minded people are starting to have some say in the matters of marketing for a while now. And even the way MS does business has started to change. But at it's core it's still acting in response to customers' requests.

I for one don't know what to make of it, except that it brings back to Microsoft's sphere of influence a very visible product.

Answer:
Its the first time MS is shipping an open source component
they didn't write
with one of their products.  This doesn't seem like a big deal, but its almost nuclear in its implications.
Think about it... They are saying "we support this."  In an OSS product, MS has no control over the code.  So, they are putting their livelihood (in some small way) into the hands of people who don't work for MS.
I think jQuery's popularity, the fact that it's not mission critical code, and that the codebase is so small all came together to make for favorable circumstances for MS to dip their toe in the water.


Question:
.NET developers out there! Need your opinion here!

I am now using Visual Assist X, a decent piece of software, indeed. But the .NET bloggers seem to prefer Resharper more. I might want to consider a switch over, but before that I want your guys opinion first.

Answer:
Resharper is much better for C# code (and supposedly VB.Net, but I haven't tried that).
Unfortunately there is no support for C/C++, so if you need that, you might want to keep Visual Assist around.
They don't coexist very well, unfortunately, so you may need to unload one, then load the other, when switching between C/C++ and C#.
To see the magic of Resharper, I would recommend watching the
"Resharper Jedi" video
.


Question:
Is there an iSeries command to export the data in a table to CSV format?

I know about the Windows utilities, but since this needs to be run automatically I need to run this from a CL program.

Answer:
If you want the data to be downloaded directly to a PC, you can use the "Data Transfer from iSeries" function of IBM iSeries Client Access to create a .CSV file. In the file output details dialog, set the file type to
```
Comma Separated Variable (CSV)
```
.
You can save the transfer description to be reused later.


Question:
I'd like to add scrolling capability to a javax.swing.JDesktopPane. But wrapping in a javax.swing.JScrollPane does not produce the desired behavior.

Searching the web shows that this has been an issue for quite some time. There are some solutions out there, but they seem to be pretty old, and I'm not not completely satisfied with them.

What actively maintained solutions do you know?

Answer:
I've used
JavaWorld's solution
by creating my own
```
JScrollableDesktopPane.
```


Question:
I want to be able to intercept the shutdown event in C# for Windows Vista.  Due to the advanced security features with Vista, any applications that are running after the shutdown command is called are halted and displayed in a list, prompting the user to do something with them.

Does anybody know how to overcome this and what events I need to be using in Vista.

Thanks.

Answer:
```
```
System.Environment.HasShutdownStarted
```
```


Question: In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy?

Answer:
DriveInfo.DriveType
should work for you.
```
```
DriveInfo[] allDrives = DriveInfo.GetDrives();

foreach (DriveInfo d in allDrives)
{
    Console.WriteLine("Drive {0}", d.Name);
    Console.WriteLine("  File type: {0}", d.DriveType);
}
```
```


Question:
What is the difference between a framework and a library?

I always thought of a library as a set of objects and functions that focuses on solving a particular problem or a specific area of application development (i.e. database access); and a framework on the other hand as a collection of libraries centered on a particular methodology (i.e. MVC) and which covers all areas of application development.

Answer:
A
library
performs specific, well-defined operations.
A
framework
is a skeleton where the application defines the "meat" of the operation by filling out the skeleton.  The skeleton still has code to link up the parts but the most important work is done by the application.
Examples of libraries:
Network protocols, compression, image manipulation, string utilities, regular expression evaluation, math.  Operations are self-contained.
Examples of frameworks:
Web application system, Plug-in manager, GUI system.  The framework defines the concept but the application defines the fundamental functionality that end-users care about.


Question:
Selecting the union:

select * from table1
union
select * from table1_backup

What is the query to select the intersection?

Answer:
In SQL Server
intersect
```
```
select * from table1
intersect
select * from table1_backup
```
```


Question:
Is there a way to identify unused attributes/methods in Visual C++ 2008 Professional? If it's not possible by default, recommendations of 3rd-party tools are also much appreciated.

Thanks,

Florian

Edit: nDepend only works for .NET assemblies. I'm looking for something that can be used with native C++ applications.

Answer:
nDepend
will do it, along with cleaning your house and taking the dog for a walk. There's a nagware version available for free.
The following code query language statement will get you a list of unused methods
```
```
WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE MethodCa == 0 AND
   !IsPublic AND !IsEntryPoint AND !IsExplicitInterfaceImpl AND
   !IsClassConstructor AND !IsFinalizer
```
```


Question:
Is there a component available list FileUpload which shows files on the server, not the client?

I am basically looking for a clean dialog box to select server side files, like the one used in FileUpload.

Answer:
Nope. There's not.  That said, you can use a listbox, and load the files into it.
```
```
public sub file_DatabindListbox(directoryPath as string)
   for each fName as string in io.directory(directorypath).getfilenames()
     dim li as new listitem
     li.text = io.path.getfilename(fName)
     li.value = fName
     myFileListbox.Items.Add(li)
   next
end sub
```
```


Question: There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?

Answer:
You can use the
```
instanceof
```
keyword in place of C#'s
```
is
```
, but there is nothing like
```
as
```
.
Example:
```
```
if(myThing instanceof Foo) {
   Foo myFoo = (Foo)myThing; //Never throws ClassCastException
   ...
}
```
```


Question:
Will .Net 4.0 use a new version of the CLR (v2.1, 3.0) or will it stick with the existing v2.0?

Supplementary: Is it possibly going to keep with CLR v2.0 and add DLR v1.0?

Update: Whilst this might look like a speculative question which cannot be answered, the VS team appear to be releasing more and more info on VS10 and .Net 4.0 so this may very soon not be the case. (Info available here -> http://msdn.microsoft.com/en-us/vstudio/products/cc948977.aspx)

Answer:
4.0 is going to be another side by side release from what I have read.
http://blogs.msdn.com/wenlong/archive/2008/09/07/net-4-0-wf-wcf-and-oslo.aspx


Question:
I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows?  All the tutorials I've found seem out of date and are for older versions of Apache/Rails.

Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps?

Answer:
EDIT:
At least until there's a Phusion Passenger for Win, Apache + Mongrel is the way to go. You can use Apache + FastCGI without Mongrel, but under real loads you will get (more) zombie processes and (more) memory leaks.
You could also look at proxying to
Thin
in the same way as detailed below. However, I've had some instabilities with Thin on Win, even though it's appreciably quicker. AB (Apache Benchmark) is your friend here!
Configuring Apache + Mongrel on Windows is not significantly different from *nix.
Essentially, you need to proxy requests coming into Apache to Mongrel. What this boils down to is something like this:
```
```
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
<VirtualHost localhost:80>
    ServerName www.myapp.comm
    DocumentRoot "C:/web/myapp/public"
    ProxyPass / http://www.myapp.com:3000/
    ProxyPassReverse / http://www.myapp.com:3000/
    ProxyPreserveHost On
</VirtualHost>
```
```
Stick this in your
```
httpd.conf
```
(or
```
httpd-vhost.conf
```
if you're including it).
It assumes you're going to run mongrel on port 3000, your Rails root is in
```
C:\web\myapp
```
, and you'll access the app at www.myapp.com.
To run the rails app in production mode:
```
```
mongrel_rails start -p 3000 -e production
```
```
And away you go (actually mongrel defaults to port 3000 so you could skip
```
-p 3000
```
if you want).
The main difference is that you cannot daemonize mongrel on Windows (i.e. make it run in the background). Instead you can install it as a service using the
```
mongrel_service
```
gem.
Also, running a cluster is more complicated and you won't be able to use Capistrano. Let me know if you want more info.


Question:
I need to call an external dll from c#. This is the header definition:

enum WatchMode {
   WATCH_MODE_SYSTEM = 0,
   WATCH_MODE_APPLICATION  = 1 };

LONG ADS_API WDT_GetMode ( LONG i_hHandle, WatchMode * o_pWatchMode );

I've added the enum and the call in C#:

public enum WatchMode
{
    WATCH_MODE_SYSTEM = 0,
    WATCH_MODE_APPLICATION = 1
}
[DllImport("AdsWatchdog.dll")]
internal static extern long WDT_GetMode(long hHandle, ref WatchMode watchmode);

This generates an AccessViolationException. I know the dll is 'working' because I've also added a call to GetHandle which returns the hHandle mentioned above. I've tried to change the param to an int (ref int watchmode) but get the same error. Doesn anyone know how I can PInvoke the above call?

Answer:
You're running into a parameter size problem difference between C# and C++.  In the C++/windows world LONG is a 4 byte signed integer.  In the C# world long is a 8 byte signed integer.  You should change your C# signature to take an int.
ffpf is wrong in saying that you should use an IntPtr here.  It will fix this particular problem on a 32 bit machine since an IntPtr will marshal as a int.  If you run this on a 64 bit machine it will marshal as a 8 byte signed integer again and will crash.


Question:
I have been googling for a good time on how to move a file with c# using the TFS API. The idea is to have a folder on which the developers drop database upgrade scripts and the build process get's to the folder creates a build script and moves all the files on the folder to a new folder with the database build version that we just created.

I cannot seriously find any reference about moving files programatically in TFS... (aside of the cmd command line)

does anybody know of a good guide / msdn starting point for learning TFS source control files manipulation via c#?

Answer:
Its pretty simple :).
```
```
Microsoft.TeamFoundation.VersionControl.Client.Workspace workspace = GetMyTfsWorkspace();
workspace.PendRename( oldPath, newPath );
```
```
Then you need CheckIn it of course. Use a "workspace.GetPendingChanges()" and "workspace.CheckIn()" methods to do it.


Question:
In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level.

DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)

I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change.

Answer:
The EXCEPT function will take a set, and remove the members you dont want. In your case you need to say:
```
```
EXCEPT(
{DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)},
{DESCENDANTS([Location].[Whatever].[Redundant],[Location].[Site], SELF_AND_BEFORE)}
)
```
```
This gives you everything in the first set except what you've mentioned in the second. It's easier to understand like this:
```
```
EXCEPT({the set i want}, {a set of members i dont want})
```
```
You shouldnt need to worry about the third (optional) argument:
http://msdn.microsoft.com/en-us/library/ms144900.aspx


Question:
I've always handled optional parameters in JavaScript like this:

function myFunc(requiredArg, optionalArg){
  optionalArg = optionalArg || 'defaultValue';

  // Do stuff
}

Is there a better way to do it?

Are there any cases where using || like that is going to fail?

Answer:
Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative
```
```
if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }
```
```
Or an alternative idiom:
```
```
optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;
```
```
Use whichever idiom communicates the intent best to you!


Question:
I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later?

Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later?

Answer:
There's nothing wrong with following Philip's method, other than it leaves some "cruft" in the revision history. If you wanted to removed them for tidiness sake, and the revisions are at HEAD you could remove them from the repository by following
these instructions
.
Update:
Philip's method is better than the one suggested in the question for the reasons he stated. Mine and Philip's methods would be similar, except that insead of reverting the trunk I propose removing the revisions from the revision history. (as I said, this can only be done if all the revisions you want to remove are at the HEAD of the repository.)


Question:
We let users create ad-hoc queries in our website.  We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel.  I have the application populating a DataTable, then using the datatable to create a tab delimited string.  The problem is getting that to excel.

What is the best way to stream data to Excel?  Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.

Answer:
Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from
here
```
```
//for demo purpose, lets create a small datatable & populate it with dummy data
System.Data.DataTable workTable = new System.Data.DataTable();

//The tablename specified here will be set as the worksheet name of the generated Excel file.
workTable.TableName = "Customers";
workTable.Columns.Add("Id");
workTable.Columns.Add("Name");
System.Data.DataRow workRow;

for (int i = 0; i <= 9; i++)
{
workRow = workTable.NewRow();
workRow[0] = i;
workRow[1] = "CustName" + i.ToString();
workTable.Rows.Add(workRow);
}

//...and lets put DataTable2ExcelString to work
string strBody = DataTable2ExcelString(workTable);

Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
Response.AppendHeader("Content-disposition", "attachment; filename=my.xls");
Response.Write(strBody);
```
```


Question: As I understand it, .bat is the old 16-bit naming convention, and .cmd is for 32-bit Windows, i.e., starting with NT. But I continue to see .bat files everywhere, and they seem to work exactly the same using either suffix. Assuming that my code will never need to run on anything older than NT, does it really matter which way I name my batch files, or is there some gotcha awaiting me by using the wrong suffix?

Answer:
No - it doesn't matter in the slightest.  On NT the .bat and .cmd extension both cause the cmd.exe processor to process the file in exactly the same way.
Additional interesting information about command.com vs. cmd.exe on WinNT-class systems from MS TechNet (
http://technet.microsoft.com/en-us/library/cc723564.aspx
):
This behavior reveals a quite subtle
  feature of Windows NT that is very
  important. The 16-bit MS-DOS shell
  (COMMAND.COM) that ships with Windows
  NT is specially designed for Windows
  NT. When a command is entered for
  execution by this shell, it does not
  actually execute it. Instead, it
  packages the command text and sends it
  to a 32-bit CMD.EXE command shell for
  execution. Because all commands are
  actually executed by CMD.EXE (the
  Windows NT command shell), the 16-bit
  shell inherits all the features and
  facilities of the full Windows NT
  shell.


Question:
I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time.

ex.

function A:

add(new Array("hello", some function));

function B:

public function b(args:Array) {
    var myString = args[0];
    var myFunc = args[1];
}

Answer:
This is very easy in ActionScript:
```
```
function someFunction(foo, bar) {
   ...
}

function a() {
    b(["hello", someFunction]);
}

function b(args:Array) {
    var myFunc:Function = args[1];
    myFunc(123, "helloworld");
}
```
```


Question:
I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree.

XML example:

<?xml version="1.0" encoding="utf-8"?>
<node>
  <attribute/>
  <node>
    <attribute/>
    <node/>
  </node>
</node>

Which is the best way to validate it?  Recursion?

Answer:
XSD does indeed allow for recursion of elements. Here
is a sample for you
```
```
<xsd:element name="section">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element ref="title"/>
      <xsd:element ref="para" maxOccurs="unbounded"/>
      <xsd:element ref="section" minOccurs="0" maxOccurs="unbounded"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>
```
```
As you can see the section element contains a child element that is of type section.


Question:
I have an object that I'm testing that raises an event.  What is the best way of using Rhino Mocks to check that it was raised?

Best I could come up with (I am certain it gets better than this):

public void MyCallback(object sender, EventArgs e) { _flag = true;}

[Test]
public void DoSomethingRaisesEvent() {
  _flag = false;
  using(_mocks.Record()) {
    Expect.Call(delegeate { _obj.DoSomething();});
  }
  using(_mocks.Playback()) {
    _obj = new SomethingDoer();
    _obj.SomethingWasDoneEvent += new EventHandler(MyHandler);
    Assert.IsTrue(_flag);
  }
}

Answer:
I'm not sure how your test actually calls the DoSomething() Method. Maybe you're missing something to fire the event. Other than that, I think you have are on the right track for testing events with Rhino Mocks
In any case, here is another way I like to deal with events:
```
```
[Test]
public void MyEventTest()
{

    IEventRaiser eventRaiser;

    mockView = _mocks.CreateMock<IView>();
    using (_mocks.Record())
    {
      mockView.DoSomethingEvent += null;
      eventRaiser = LastCall.IgnoreArguments();
    }
    using (_mocks.Playback())
    {
       new Controller(mockView, mockModel);
       eventRaiser.Raise(mockView, EventArgs.Empty);
    }
}
```
```


Question: What does the POP3 CAPA UIDL command do?

Answer:
Gives the unique identifier for a message on the POP3 server.
Possible responses: +OK or -ERR


Question:
My questions is simple!

Would you start learning Smalltalk if you had the time? Why? Why not?

Do you already know Smalltalk? Why would you recommend Smalltalk? Why not?

Personally I'm a Ruby on Rails programmer and I really like it. However, I'm thinking about Smalltalk because I read various blogs and some people are calling Ruby something like "Smalltalk Light". The second reason why I'm interested in Smalltalk is Seaside.

Maybe someone has made the same transition before?

EDIT: Actually, what got me most excited about Smalltalk/Seaside is the following Episode of WebDevRadio: Episode 52: Randal Schwartz on Seaside (among other things)

Answer:
I was taught Smalltalk in one of the first graduate college level Object-Orient Programming courses (circa 1988).  The teacher thought it best to start was a "pure" OO langauge,before moving on to a more trendy one (we did a bit of C++ at the end of the semester).
By that measure, it's still best to start with pure OO, although these days we have Java & C#, both of which are "nearly-pure" OO -- close enough that you can get by ignoring the non-OO features of them, and limiting yourself to the Pure-OO subset of the langauges.


Question:
I would like to format a price in JavaScript. I'd like a function which takes a float as an argument and returns a string formatted like this:

"$ 2,500.00"

How can I do this?

Answer:
The main part is inserting the thousand-separators, and that could be done like this:
```
```
<script type="text/javascript">
  function ins1000Sep(val) {
    val = val.split(".");
    val[0] = val[0].split("").reverse().join("");
    val[0] = val[0].replace(/(\d{3})/g, "$1,");
    val[0] = val[0].split("").reverse().join("");
    val[0] = val[0].indexOf(",") == 0 ? val[0].substring(1) : val[0];
    return val.join(".");
  }

  function rem1000Sep(val) {
    return val.replace(/,/g, "");
  }

  function formatNum(val) {
    val = Math.round(val*100)/100;
    val = ("" + val).indexOf(".") > -1 ? val + "00" : val + ".00";
    var dec = val.indexOf(".");
    return dec == val.length-3 || dec == 0 ? val : val.substring(0, dec+3);
  }
</script>

<button onclick="alert(ins1000Sep(formatNum(12313231)));">
```
```


Question:
I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace:

public function PrintStackTrace() {
    try {
        throw new Error('StackTrace');
    } catch (e:Error) {
        trace(e.getStackTrace());
    }
}

I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know.

Thanks!

Answer:
As far as I know, the only way to make the stack trace available to your own code is via the
getStackTrace()
method in the Error class, just like you're already doing. In response to the example in your question, though, I would mention that you don't actually have to throw the Error -- you can just create it and call the method on it:
```
```
var tempError:Error = new Error();
var stackTrace:String = tempError.getStackTrace();
```
```
Also, like the documentation says, this only works in the debug version of Flash Player, so you can wrap this functionality in an if-block that checks the value of
Capabilities.isDebugger
if you want.


Question:
We have been designing our reports around Crystal Reports in VS2008 for our web application and I just discovered the Microsoft provided ReportViewer control.  I've searched around a bit but cannot find a good breakdown of the pros and cons of each method of producing reports.

I'm looking for pros and cons regarding:

Ease of development

Ease of deployment

Ability to export data

Ease of support and finding help on the web

Answer:
Well, I can answer for one side. I have used
ReportViewer
aka Client Side Reporting. I can tell you its easy to use, easy to deploy and easy to develop. If you can create SQL Reporting Services reports, you can create these. They can take any kind of datasource so you have full control.
Here is an excellent book on Client Side reporting
.
There are built in PDF and Excel exports available but you can add your own export handling also. You can use in winforms, Asp.Net in your own services. You can do really anything you can imagine with them.
For Crystal Reports, I do not know much about them.


Question:
I'm getting warnings about CSS3.0 properties like text-overflow.  Is there a way to validate against 3.0?

HTML5 and CSS3 support is coming to VS2010 in SP1.

Link

And now its here.

http://visualstudiogallery.msdn.microsoft.com/7211bcac-091b-4a32-be2d-e797be0db210/view/Reviews/0?showReviewForm=True

Answer:
Apparently, you can define your own Visual Studio Intellisense schema for CSS. I’m not sure if VS will then validate against that, or only use it for code completion.
Might be worth making a minimal one and seeing if it gets used for validation.
Custom CSS Intellisense Schema in Visual Studio 2005 and 2008
I don’t know of an easy way to validate against CSS 3 yet though. CSS 3 is a large, modular spec, and most of it is very much still in flux, despite some decent browser support for some properties.
http://www.w3.org/Style/CSS/current-work


Question:
I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:

I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.

How do I do this without the use of cursors? Should be an easy one for you sql gurus!

Answer:
This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table.  For example:
```
```
CREATE TABLE #t (uniqueid int)
INSERT INTO #t EXEC p_YourStoredProc

UPDATE TargetTable
SET a.FlagColumn = 1
FROM TargetTable a JOIN #t b
    ON a.uniqueid = b.uniqueid

DROP TABLE #t
```
```


Question:
Are there any templates/patterns/guides I can follow for designing a multithreaded server?  I can't find anything terribly useful online through my google searches.

My program will start a thread to listen for connections using TcpListener.
Every client connection will be handled by it's own IClientHandler thread.  The server will wrap the clientHandler.HandleClient in a delegate, call BeginInvoke, and then quit caring about it.

I also need to be able to cleanly shutdown the listening thread, which is something I'm not finding a lot of exampes of online.

I'm assuming some mix of lock/AutoResetEvents/threading magic combined with the async BeginAceptTcpClient and EndAcceptTcpClient will get me there, but when it comes to networking code, to me it's all been done. So I have to believe there's just some pattern out there I can follow and not get totally confused by the myriad multithreaded corner cases I can never seem to get perfect.

Thanks.

Answer:
Oddly enough you may find something on a Computer Science Assignment,
CSC 512 Programming Assignment 4: Multi-Threaded Server With Patterns
. Altough it's C++ voodoo but the theory is quite understandable for someone who can do C#.
Acceptor/ Connector
Monitor Object
Thread Safe Interface
Wrapper Facade
Scoped Locking
Strategized Locking
Reactor
Half Sync/Half-Async
Leaders/Followers
Altough you can get the whole list of nice readings on the
main page
.


Question:
I'm looking for a way to limit the maximum number of running processes in Windows Server 2003.

Is there a registry key somewhere that controls it?
If so, which one is it?

Answer:
if you are talking about processes as in the items listed in task manager, then there is no way to do it natively, and you can do it with a program,
but there should be no real valid reason to do so.
If you are talking about making your application only ever launch one EXE no matter how many times it is called, then you are looking for singleton-ing. Example for .NET at:
http://www.thescarms.com/dotnet/SingleInstance.aspx
--EDIT For another language, google for "singleton" and your language.
If you are asking about something else, please elaborate.


Question:
I'm doing a webapp and need a backup plan. Here's what I've got so far:

nightly encrypted backup of the SQL database to Amazon S3 and my external drive (incremental if possible, not overly familiar with PostgreSQL yet, but that's another thread)

nightly backup of my Mercurial repo (which includes Apache configs, deploy scripts, etc) to S3 (w/ local backups via Time Machine)

Should I add anything else, or will this cover it? For a gauge of how critical the data is/would be, it's a project management app along the lines of Basecamp.

Answer:
Weekly full backup of your database as well as nightly incremental ones as well perhaps?
It means that if one of your old incremental backups gets corrupted then you have lost less than a week of data.
Also, ensure you have a backup test plan to ensure your backups work. There are a lot of horror stories going around about this, from companies that have been doing backups for years, never testing them and then finding out none of them are any good once they need them. (I've also been at a company like this. Thankfully I spotted the backups weren't working before they were required and fixed the problems).


Question:
I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system.

What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me.

I heard Git supports this, please let me know if this is correct.

Answer:
Mercurial can do this with the
record
extension.
It'll prompt you for each file and each diff hunk.  For example:
```
```
% hg record
diff --git a/prelim.tex b/prelim.tex
2 hunks, 4 lines changed
examine changes to 'prelim.tex'? [Ynsfdaq?]
@@ -12,7 +12,7 @@
 \setmonofont[Scale=0.88]{Consolas}
 % missing from xunicode.sty
 \DeclareUTFcomposite[\UTFencname]{x00ED}{\'}{\i}
-\else
+\else foo
 \usepackage[pdftex]{graphicx}
 \fi

record this change to 'prelim.tex'? [Ynsfdaq?]
@@ -1281,3 +1281,5 @@
 %% Local variables:
 %% mode: latex
 %% End:
+
+foo
\ No newline at end of file
record this change to 'prelim.tex'? [Ynsfdaq?]  n
Waiting for Emacs...
```
```
After the commit, the remaining diff will be left behind:
```
```
% hg di
diff --git a/prelim.tex b/prelim.tex
--- a/prelim.tex
+++ b/prelim.tex
@@ -1281,3 +1281,5 @@
 %% Local variables:
 %% mode: latex
 %% End:
+
+foo
\ No newline at end of file
```
```
Alternatively, you may find it easier to use MQ (Mercurial Queues) to separate the individual changes in your repository into patches. There is a MQ variant of record (qrecord), too.
Update:
Also try the
crecord
extension, which provides a curses interface to hunk/line selection.


Question: I have an application that uses Forms Authentication to authenticate one type of user. There is a section in this application that needs to be authenticated for another type of user using a different table in the database. The problem happens if the second type of user's session times out, she is taken to the login page defined in the Forms Authentication section of the main Web.Config instead of the login page for the second type of user. I am looking for solutions to this problem. One idea is to create an application in IIS for the section and create a Web.Config for the folder and add another Forms Authentication section. In my experiments, it seems this doesn't work. Am I missing something obvious? Any insights?

Answer:
IIRC, the authentication works per folder.  So you should be able to do it if all of the pages that require the 2nd type of authentication live in a specific sub-folder with it's own config.
Not 100% sure on this, though, so if someone more knowledgeable can contradict me I'll just delete the response.


Question:
I have a XML response from an HTTPService call with the e4x result format.

<?xml version="1.0" encoding="utf-8"?>
<Validation Error="Invalid Username/Password Combination" />

I have tried:

private function callback(event:ResultEvent):void {
    if(event.result..@Error) {
        // error attr present
    }
    else {
        // error attr not present
    }
}

This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks.

EDIT: I have also tried to compare the attribute to null and an empty string without such success...

Answer:
I have figured out a solution, I'm still interested if there is a better way to do this...
This will work:
```
```
private function callback(event:ResultEvent):void {
    if(event.result.attribute("Error").length()) {
        // error attr present
    }
    else {
        // error attr not present
    }
}
```
```


Question: Does anybody know what hypothetical indexes are used for in sql server 2000?  I have a table with 15+ such indexes, but have no idea what they were created for.  Can they slow down deletes/inserts?

Answer:
Not sure about 2000, but in 2005 hypothetical indexes and database objects in general are objects created by
DTA (Database Tuning Advisor)
You can check if an index is hypothetical by running this query:
```
```
SELECT  *
FROM    sys.indexes
WHERE   is_hypothetical = 1
```
```
If you have given the tuning advisor good information on which to base it's indexing strategy, then I would say to generally trust its results, but if you should of course examine how it has allocated these before you trust it blindly. Every situation will be different.


Question:
I have 7-8 xml files. Each one is approximately 50 MB in size. What is the best way to merge files programmatically in C# without getting System.OutOfMemory Exception?  So far I have tried reading each file in a StringBuilder and than putting it in an array of string builder but I still get system.outofmemoery exception. Any help??
Thank you,
-Nimesh

Answer:
The thing about stringbuilder is you're still trying to keep the entire contents in memory.  You want to only keep a small portion in memory at a time, and that means using filestreams.  Don't read an entire file into memory, open a stream on it and keep reading from the stream.
The problem with xml is that you can't just append them to each other:  you'll break the tag nesting.  So you need to know something about the structure of your xml files so that you can have an idea of what to do at each file boundry.
If you have something that works in theory with StringBuilder, but only fails in practice because of memory constraints, you should be able to translate the StringBuilder's .Append() and .AppendLine() method calls into .Write() and .WriteLine() calls for a filestream.


Question:
I'm slowly getting back into PHP, and now I run into a problem, I want to install some web software on our host and I need to have either the latest Zend (which they don't have) or IonCube on the server and IonCube requires enable_dl to be on in the php.ini. Now a colleague of mine thinks I can update this via an .htaccess file on the server. So I created a s.htaccess on my machine as Windows doesn't like emptiness before the file extension. So I added the line php_flag enable_dl On to the file uploaded it and renamed the file to just .htaccess on the server. When I refresh the file is gone, when I keep it as s.htaccess it's fine but my php info still shows it as Off.

What n00b mistake am I making?

Answer:
The thing about stringbuilder is you're still trying to keep the entire contents in memory.  You want to only keep a small portion in memory at a time, and that means using filestreams.  Don't read an entire file into memory, open a stream on it and keep reading from the stream.
The problem with xml is that you can't just append them to each other:  you'll break the tag nesting.  So you need to know something about the structure of your xml files so that you can have an idea of what to do at each file boundry.
If you have something that works in theory with StringBuilder, but only fails in practice because of memory constraints, you should be able to translate the StringBuilder's .Append() and .AppendLine() method calls into .Write() and .WriteLine() calls for a filestream.


Question: What delphi function asserts that an object is not nil?

Answer:
Not sure what you mean but
```
Assert(Assigned(MyObject));
```
is pretty short and easy to use.


Question: How can I run background tasks on App Engine?

Answer:
GAE is very useful tool to build scalable web applications. Few of the limitations pointed out by many are no support for background tasks, lack of periodic tasks and strict limit on how much time each HTTP request takes, if a request exceeds that time limit the operation is terminated, which makes running time consuming tasks impossible.
How to run background task ?
In GAE the code is executed only when there is a HTTP request. There is a strict time limit (i think 10secs) on how long the code can take. So if there are no requests then code is not executed. One of the suggested work around was use an external box to send requests continuously, so kind of creating a background task. But for this we need an external box and now we dependent on one more element. The other alternative was sending 302 redirect response so that client re-sends the request, this also makes us dependent on external element which is client. What if that external box is GAE itself ? Everyone who has used functional language which does not support looping construct in the language is aware of the alternative ie recursion is the replacement to loop. So what if we complete part of the computation and do a HTTP GET on the same url with very short time out say 1 second ? This creates a loop(recursion) on php code running on apache.
```
<?php
$i = 0;
if(isset($_REQUEST["i"])){
        $i= $_REQUEST["i"];
    sleep(1);
}
$ch = curl_init("http://localhost".$_SERVER["PHP_SELF"]."?i=".($i+1));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_exec($ch);
print "hello world\n";
?>
```
Some how this does not work on GAE. So what if we do HTTP GET on some other url say url2 which does HTTP GET on the first url ? This seem to work in GAE. Code for this looks like this.
```
class FirstUrl(webapp.RequestHandler):
    def get(self):
        self.response.out.write("ok")
        time.sleep(2)
        urlfetch.fetch("http://"+self.request.headers["HOST"]+'/url2')

class SecondUrl(webapp.RequestHandler):
    def get(self):
        self.response.out.write("ok")
        time.sleep(2)
        urlfetch.fetch("http://"+self.request.headers["HOST"]+'/url1')

application = webapp.WSGIApplication([('/url1', FirstUrl), ('/url2', SecondUrl)])
def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()
```
Since we found out a way to run background task, lets build abstractions for periodic task (timer) and a looping construct which spans across many HTTP requests (foreach).
Timer
Now building timer is straight forward. Basic idea is to have list of timers and the interval at which each should be called. Once we reach that interval call the callback function. We will use memcache to maintain the timer list. To find out when to call callback, we will store a key in memcache with interval as expiration time. We periodically (say 5secs) check if that key is present, if not present then call the callback and again set that key with interval.
```
def timer(func, interval):
    timerlist = memcache.get('timer')
    if(None == timerlist):
        timerlist = []
    timerlist.append({'func':func, 'interval':interval})
    memcache.set('timer-'+func, '1', interval)
    memcache.set('timer', timerlist)

def checktimers():
    timerlist = memcache.get('timer')
    if(None == timerlist):
        return False
    for current in timerlist:
        if(None == memcache.get('timer-'+current['func'])):
            #reset interval
            memcache.set('timer-'+current['func'], '1', current['interval'])
            #invoke callback function
            try:
                eval(current['func']+'()')
            except:
                pass
            return True
    return False
```
Foreach
This is needed when we want to do long taking computation say doing some operation on 1000 database rows or fetch 1000 urls etc. Basic idea is to maintain list of callbacks and arguments in memcache and each time invoke callback with the argument.
```
def foreach(func, args):
    looplist = memcache.get('foreach')
    if(None == looplist):
        looplist = []
    looplist.append({'func':func, 'args':args})
    memcache.set('foreach', looplist)

def checkloops():
    looplist = memcache.get('foreach')
    if(None == looplist):
        return False
    if((len(looplist) > 0) and (len(looplist[0]['args']) > 0)):
        arg = looplist[0]['args'].pop(0)
        func = looplist[0]['func']
        if(len(looplist[0]['args']) == 0):
            looplist.pop(0)
        if((len(looplist) > 0) and (len(looplist[0]['args']) > 0)):
            memcache.set('foreach', looplist)
        else:
            memcache.delete('foreach')
        try:
            eval(func+'('+repr(arg)+')')
        except:
            pass
        return True
    else:
        return False

# instead of
# foreach index in range(0, 1000):
#   someoperaton(index)
# we will say
# foreach('someoperaton', range(0, 1000))
```
Now building a program which fetches list of urls every one hour is straight forward. Here is the code.
```
def getone(url):
    try:
        result = urlfetch.fetch(url)
        if(result.status_code == 200):
            memcache.set(url, '1', 60*60)
            #process result.content
    except :
        pass

def getallurl():
    #list of urls to be fetched
    urllist = ['http://www.google.com/', 'http://www.cnn.com/', 'http://www.yahoo.com', 'http://news.google.com']
    fetchlist = []
    for url in urllist:
        if (memcache.get(url) is None):
            fetchlist.append(url)
    #this is equivalent to
    #for url in fetchlist: getone(url)
    if(len(fetchlist) > 0):
        foreach('getone', fetchlist)

#register the timer callback
timer('getallurl', 3*60)
```
complete code is here
http://groups.google.com/group/httpmr-discuss/t/1648611a54c01aa
I have been running this code on appengine for few days without much problem.
Warning: We make heavy use of urlfetch. The limit on no of urlfetch per day is 160000. So be careful not to reach that limit.


Question:
When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work.  As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack.

Edit
When I access the value like so

TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox;

the text box is found, but the .Text is not the user input.

Answer:
You should be able to use the GridViewUpdateEventArgs to retrieve the inputted value, for example:
```
```
TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox;
```
```
I have used that syntax before and it works like a charm.


Question:
Is there a way set flags on a per-file basis with automake?

In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do?

I tried something like:

CXXFLAGS = -WAll ...
bin_PROGRAMS = test
test_SOURCES = main.cpp utility.cpp
utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value

but it didn't work.

EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder).

Answer:
You've got confused - that section is referring to options to automake itself.
It's a way of setting the automake command-line options:
-W CATEGORY
  --warnings=category
      Output warnings falling in category. category can be one of:
```
```
gnu
    warnings related to the GNU Coding Standards (see Top).
obsolete
    obsolete features or constructions
override
    user redefinitions of Automake rules or variables
portability
    portability issues (e.g., use of make features that are known to be not portable)
syntax
    weird syntax, unused variables, typos
unsupported
    unsupported or incomplete features
all
    all the warnings
none
    turn off all the warnings
error
    treat warnings as errors
```
```
A category can be turned off by prefixing its name with ‘no-’.
  For instance, -Wno-syntax will hide the
  warnings about unused variables.
The categories output by default are ‘syntax’ and ‘unsupported’.
  Additionally, ‘gnu’ and ‘portability’
  are enabled in --gnu and --gnits
  strictness.
The environment variable WARNINGS can contain a comma separated list of
  categories to enable. It will be taken
  into account before the command-line
  switches, this way -Wnone will also
  ignore any warning category enabled by
  WARNINGS. This variable is also used
  by other tools like autoconf; unknown
  categories are ignored for this
  reason.
The per-file listed in section 17 refers to per-Makefile not source file.
I'm not aware of any per-source file flag setting, but you can set the option for each result binary with:
```
```
binaryname_CXXFLAGS
```
```


Question: Is there any way to do this in the Powerbuilder properties window for a datawindow's textbox?

Answer:
That kind of depends on how you define "textbox", but in general the only way to mix normal and superscript text is with a richtext control. In PB 11.5, you can even use richtext as a column style.
Good luck,
Terry.


Question:
How does Stackoverflow implement the resizable textarea?

Is that something they rolled themselves or is it a publicly available component that I can easily attach to textareas on my sites?

I found this question and it doesn't quite do what I want.

autosizing-textarea

That talks more about automatically resizing textareas whereas I want the little grab-area that you can drag up and down.

Answer:
At first I believed it was a built-in feature of the
Wysiwym Markdown editor
, but Shog9 is correct: it's not baked-in at all, but is courtesy of the jQuery plugin TextAreaResizer (I was lead astray by the browser was using to check on the
editor demo
because Google Chrome itself adds the expandable functionality on textareas—much like the Safari browser does).


Question:
How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language.

public interface Listener {
  void callBack(Object arg);
}
public class ListenerImpl implements Listener {
  public ListenerImpl(Broadcaster b) { b.register(this); }
  public void callBack(Object arg) { ... }
  public void shutDown() { b.unregister(this); }
}
public class Broadcaster {
  private final List listeners = new ArrayList();
  public void register(Listener lis) { listeners.add(lis); }
  public void unregister(Listener lis) {listeners.remove(lis); }
  public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } }
}

Answer:
I don't see that being a circular dependency.
Listener depends on nothing.
ListenerImpl depends on Listener and Broadcaster
Broadcaster depends on Listener.
```
```
Listener
       ^        ^
      /          \
     /            \
Broadcaster <--  ListenerImpl
```
```
All arrows end at Listener.  There's no cycle.  So, I think you're OK.


Question:
Well, it seems simple enough, but I can't find a way to add a caption to an equation.
The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great.

Answer:
You may want to look at
http://tug.ctan.org/tex-archive/macros/latex/contrib/float/
which allows you to define new floats using
```
\newfloat
```
I say this because captions are usually applied to floats.
Straight ahead equations (those written with
```
$ ... $
```
,
```
$$ ... $$
```
,
```
begin{equation}...
```
) are in-line objects that do not support
```
\caption
```
.
This can be done using the following
snippet
just before
```
\begin{document}
```
```
```
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}
```
```
and when adding an equation use something like
```
```
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
```
```


Question:
I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container).  If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething).  I cannot figure out the syntax of the if statement.  I want to write something like:

Public Function Build(Of T) as T
    If T Is IDoSomething then
        Return New DoSomething()
    ElseIf T Is IAndSoOn Then
        Return New AndSoOn()
    Else
        Throw New WhatWereYouThinkingException("Bad")
    End If
End Sub

But this code does not compile.

Answer:
```
```
Public Function Build(Of T) As T
  Dim foo As Type = GetType(T)

  If foo Is GetType(IDoSomething) Then
    Return New DoSomething()
  ...
  End If
End Function
```
```


Question:
What does the following code do in C/C++?

if (blah(), 5) {
    //do something
}

Answer:
Comma operator is applied and the value 5 is used to determine the conditional's true/false.
It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.
Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious.


Question: Has anyone ever done work to get Ruby to do continuations (like Seaside on Smalltalk)?

Answer:
Yes, in most cases. MRI (1.8) have supported them as far as my memory reaches, Ruby 1.9 (YARV)
does it, too
, so does Rubinius. JRuby and IronRuby don't have continuations, and it's quite unlikely they will get them (JVM and CLR use stack-instrospection for security)
Ruby as a language supports continuations via
```
callcc
```
keyword. They're used, for example, to implement
```
Generator
```
class from standard library.
continuations on ruby-doc
Continuation-based web frameworks (like seaside, or one from Arc's std. library) seem less popular. I've found
wee
that claim to let you do optional continuations, but I've never used it.


Question:
Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.

(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)

Answer:
Look at the
selectedIndex
of the
```
select
```
element. BTW, that's a plain ol' DOM thing, not JQuery-specific.


Question:
Does BeautifulSoup work with Python 3?

If not, how soon will there be a port? Will there be a port at all?

Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)

Answer:
I'm guessing the answer is "No".  According to
Python.org
:
Python 3000 (a.k.a. "Py3k", and
  released as Python 3.0) is a new
  version of the language that is
  incompatible with the 2.x line of
  releases. The language is mostly the
  same, but many details, especially how
  built-in objects like dictionaries and
  strings work, have changed
  considerably, and a lot of deprecated
  features have finally been removed.
  Also, the standard library has been
  reorganized in a few prominent places.
A better place for this particular question might be the
BeautifulSoup forum
.


Question: I was currently developing a desktop application in C# using mono and testing in SuSE and Windows. The concept doesn't matter much, but it is a "web lint" program that will scan a web site and return possible issues with security and/or cross browser compatibility.  However, I want to be able to offer binaries for multiple platforms.  Should I stay with Mono, or is there another platform that would give me a better availablility of platforms, such as on Macs, Windows, Linux, and others (possibly mobile platforms), and make it easier to port?

Answer:
Java will run on Windows, Linux and Macs. Should be easy to transition from C# - use Apache HTTPClient for grabbing the web content you are scanning, and the scanning code should be more or less the same. However the downside is requiring the user to have the Java runtime installed.
Python is another option - you can build stand-alone executables for Windows, and it comes with most Linux distributions by default, and also Mac OS X (citation needed ;) ). This is a lot less hassle for Windows users (language is compiled into the executable, no other downloads required).
If mono runs on Mac OS X then surely that is a good platform as well?


Question: Is there a clean way of cloning a record in SQL that has an index(auto increment).  I want to clone all the fields except the index.  I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time.

Answer:
Not unless you want to get into dynamic SQL.  Since you wrote "clean", I'll assume not.
Edit:
Since he asked for a dynamic SQL example, I'll take a stab at it.  I'm not connected to any databases at the moment, so this is off the top of my head and will almost certainly need revision.  But hopefully it captures the spirit of things:
```
```
-- Get list of columns in table
SELECT INTO #t
EXEC sp_columns @table_name = N'TargetTable'

-- Create a comma-delimited string excluding the identity column
DECLARE @cols varchar(MAX)
SELECT @cols = COALESCE(@cols+',' ,'') + COLUMN_NAME FROM #t WHERE COLUMN_NAME <> 'id'

-- Construct dynamic SQL statement
DECLARE @sql varchar(MAX)
SET @sql = 'INSERT INTO TargetTable (' + @cols + ') ' +
    'SELECT ' + @cols + ' FROM TargetTable WHERE SomeCondition'

PRINT @sql -- for debugging
EXEC(@sql)
```
```


Question:
I am trying to extract a certain part of a column that is between delimiters.

e.g. find foo in the following

test 'esf :foo: bar

So in the above I'd want to return foo, but all the regexp functions only return true|false,
is there a way to do this in MySQL

Answer:
A combination of
LOCATE
and
MID
would probably do the trick.
If the value
"test 'esf :foo: bar"
was in the field
fooField
:
```
```
MID( fooField, LOCATE('foo', fooField), 3);
```
```


Question:
I have several .NET Windows Forms applications that I'm preparing to convert into a ClickOnce/smart-client deployment scenario. I've read the isn't-this-great tutorials, but are there pitfalls or "gotchas" that I should be aware of?

There are several minor applications used off and on, but the main application is in C#, runs 24/7, is quite large, but only changes every few weeks. It also writes to a log file locallly and talks to local hardware devices.

Answer:
Here are a few that I am aware of.
Can't put an icon on the desktop.
You can now.
I can't install for all users.
I need to jump through hoops to move the deployment to a different server. It is not a problem if you are developing internally, and the users can see the server that you are publishing to or if you are deploying to the public web, but it is not great if you need to roll out to multiple customer sites independently.
Since
.NET
3.5 SP1 you do not need to sign the deployment manifest anymore which makes it much easier to move deployments to new servers.
I can't install assemblies in the
GAC
. You can get around this by creating regular install packages that are pre-requisites of the ClickOnce application.


Question:
I'm benchmarking a WPF application on various platforms and I need an easy way to determine if WPF is using hardware or software rendering.

I seem to recall a call to determine this, but can't lay my hands on it right now.

Also, is there an easy, code based way to force one rendering pipeline over the other?

Answer:
Check RenderCapability.Tier
Graphics Rendering Tiers
RenderCapability Class
[
UPDATE
]
RenderCapability.IsPixelShaderVersionSupported
- Gets a value that indicates whether the specified pixel shader version is supported.
RenderCapability.IsShaderEffectSoftwareRenderingSupported
- Gets a value that indicates whether the system can render bitmap effects in software.
RenderCapability.Tier
- Gets a value that indicates the rendering tier for the current thread.
RenderCapability.TierChanged
- Occurs when the rendering tier has changed for the Dispatcher object of the current thread.
RenderCapability.Tier >> 16
Rendering Tier 0
- No graphics hardware acceleration. The DirectX version level is less than version 7.0.
Rendering Tier 1
- Partial graphics hardware acceleration. The DirectX version level is greater than or equal to version 7.0, and lesser than version 9.0.
Rendering Tier 2
- Most graphics features use graphics hardware acceleration. The DirectX version level is greater than or equal to version 9.0.


Question:
Basically the question is how to get from this:

foo_id   foo_name
1        A
1        B
2        C

to this:

foo_id   foo_name
1        A B
2        C

Answer:
```
```
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;
```
```
https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat
From the link above,
```
GROUP_CONCAT
```
: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.


Question:
This question comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this:

insert into MyTable
    select * from MyTable where uniqueId = @Id;

I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field).

I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is.

Answer:
Try this:
```
```
insert into MyTable(field1, field2, id_backup)
    select field1, field2, uniqueId from MyTable where uniqueId = @Id;
```
```
Any fields not specified should receive their default value (which is usually NULL when not defined).


Question:
When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn_click event?

Thanks.

Answer:
This article on the MSDN site clearly explains how to go about
adding a button into a datagrid
. Instead of using the click event of the button you'll use the command event of the DataGrid. Each button will be passing specific commandarguments that you will set.
This article shows
how to use the command event with buttons
. In it you use CommandArguments and CommandNames.


Question:
I ran across the following code in Ely Greenfield's SuperImage from his Book component - I understand loader.load() but what does the rest of do?

loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));

It looks like some kind of crazy inline if statement but still, I'm a little preplexed.  And if it is an if statement - is this way better than a regular if statement?

Answer:
this is using the
ternary ?: operator
.  the first part is the condition, between the ? and : is what to return if the condition is true.  after the : is what to return if the condition is false.
a simpler example
```
```
String str = null;
int x = (str != null) ? str.length() : 0;
```
```
would be the same as
```
```
String str = null;
int x;
if (str != null)
  x = str.length()
else
  x = 0;
```
```


Question:
What is a strong way to protect against sql injection for a classic asp app?

FYI I am using it with an access DB.  (I didnt write the app)

Answer:
Stored Procedures and/or prepared statements:
https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?
Catching SQL Injection and other Malicious Web Requests
With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway.
Here's a link to the technique in Access:
http://www.asp101.com/samples/storedqueries.asp
Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic.  Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code.  Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place.
In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target:
```
```
Conn.Execute("EXEC usp_ImOnlySafeIfYouCallMeRight '" + param1 + "', '" + param2 + "'") ;
```
```
Remember that your database needs to defend its own perimeter, and if various logins have rights to
```
INSERT/UPDATE/DELETE
```
in tables, any code in those applications (or compromised applications) can be a potential problem.  If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior.  (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.)


Question:
I would like to specify a constraint which is another type with a generic argument.

class KeyFrame<T>
{
    public float Time;
    public T Value;
}

// I want any kind of Keyframe to be accepted
class Timeline<T> where T : Keyframe<*>
{
}

But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?:

class Timeline<TKeyframe, TKeyframeValue>
     where TKeyframe : Keyframe<TKeyframeValue>,
{
}

Answer:
As TimeLine is most likely an aggregation of KeyFrames, wouldn't something like:
```
```
class TimeLine<T>
{
private IList<KeyFrame<T>> keyFrameList;
...
}
```
```
fulfill your requirements nicely?


Question:
I would like to do something like
     <test:di id="someService"/`>

    <%
       someService.methodCall();
    %>

where <test:di

 gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example
    <jsp:useBean id="someDate" class="java.util.Date"/>

    <%

       someDate.getYear();

%>

how do i make my own objects available as a scritping variable?

Answer:
I think you're trying to write your own tag library.
Check out the tutorial at:
http://www.ironflare.com/docs/tutorials/taglibs/
Edit:
As Garth pointed out, you want to use the TagExtraInfo class after you've defined your tag lib.
http://www.stardeveloper.com/articles/display.html?article=2001081601&page=2


Question:
Does anyone know of a method to determine when a file copy completes in VBScript?  I'm using the following to copy:

set sa = CreateObject("Shell.Application")
set zip = sa.NameSpace(saveFile)
set Fol = sa.NameSpace(folderToZip)
zip.copyHere (Fol.items)

Answer:
You may have better luck using the Copy method on a
```
FileSystemObject
```
.  I've used it for copying, and it's a blocking call.