Question:
I've been using ISAPI_Rewrite from Helicon (http://www.helicontech.com/isapi_rewrite/) on a Server 2003 box for years and have always had good luck with it.

I'm migrating all the sites on the 2003 box to a new shiny Server 2008 box.  I would prefer to not purchase a new license and I have heard that IIS 7 will have capability built in.

All the rewrites are setup in a .htaccess configuration file just like mod_rewrite for Apache.

Does anyone know if this capability ever got baked into IIS 7 and if so do you know of any good articles that explain how to get it all enabled?

Thanks.

Answer:
IIS7 does have the functionality built in, as you mentioned. You can either use a custom HttpModule, as described in
Tip/Trick: Url Rewriting with ASP.NET
.
Alternatively, you could install the the
IIS7 Rewrite Module
as
described here
.


Question:
I am using Python and the Twisted framework to connect to an FTP site to perform various automated tasks.  Our FTP server happens to be Pure-FTPd, if that's relevant.

When connecting and calling the list method on an FTPClient, the resulting FTPFileListProtocol's files collection does not contain any directories or file names that contain a space (' ').

Has anyone else seen this?  Is the only solution to create a sub-class of FTPFileListProtocol and override its unknownLine method, parsing the file/directory names manually?

Answer:
Firstly, if you're performing automated tasks on a retrieived FTP listing then you should probably be looking at
```
NLST
```
rather than
```
LIST
```
as noted in
RFC 959 section 4.1.3
:
```
NAME LIST (NLST)
 ...
            This command is intended to return information that
            can be used by a program to further process the
            files automatically.
```
The
Twisted documentation
for
```
LIST
```
says:
```
It can cope with most common file listing formats.
```
This make me suspicious; I do not like solutions that "cope".
```
LIST
```
was intended for human consumption not machine processing.
If your target server supports them then you should prefer
```
MLST
```
and
```
MLSD
```
as defined in
RFC 3659 section 7
:
```
7.  Listings for Machine Processing (MLST and MLSD)

   The MLST and MLSD commands are intended to standardize the file and
   directory information returned by the server-FTP process.  These
   commands differ from the LIST command in that the format of the
   replies is strictly defined although extensible.
```
However, these newer commands may not be available on your target server and I don't see  them in Twisted. Therefore
```
NLST
```
is probably your best bet.
As to the nub of your problem, there are three likely causes:
The processing of the returned results is incorrect (Twisted may be at fault, as you suggest, or perhaps elsewhere)
The server is buggy and not sending a correct (complete) response
The wrong command is being sent (unlikely with straight
```
NLST
```
/
```
LIST
```
, but some servers react differently if arguments are supplied to these commands)
You can eliminate (2) and (3) and prove that the cause is (1) by looking at what is sent over the wire. If this option is not available to you as part of the Twisted API or the Pure-FTPD server logging configuration, then you may need to break out a network sniffer such as tcpdump, snoop or WireShark (assuming you're allowed to do this in your environment). Note that you will need to trace not only the control connection (port 21) but also the data connection (since that carries the results of the
```
LIST
```
/
```
NLST
```
command). WireShark is nice since it will perform the protocol-level analysis for you.
Good luck.


Question: Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags.

Answer:
You can use
XPath paths
on the findall method:
The 1.2 release supports simple
  element location paths. In its
  simplest form, a location path is one
  or more tag names, separated by
  slashes (/).
You can also use an asterisk (*)
  instead of a tag name, to match all
  elements at that level. For example,
  */subtag returns all subtag grandchildren.
An empty tag (//) is used to search on
  all levels of the tree, beneath the
  current level. The empty tag must
  always be followed by a tag name or an
  asterisk.
```
```
etree.findall('.//*')
```
```


Question: What Inversion of Control Container framework would you recommend to a beginner in this area?

Answer:
I have done some evaluation of the
Spring.NET port
.  It offers AOP, config-file setup of the container, and other cool stuff.  I think their site is well organized and the docs are well written.


Question:
I have a custom NSTableView subclass which is bound to a data source (an NSArray) which updates asynchronously. When items are added to the array, rows are automatically added to the tableview. Awesome!

My question is this: How can I detect that this magic has happened so that I can perform some other tasks related to the display of my custom tableview? Is there a method that I can override in my subclass which will be called when the tableview is updated?

Answer:
You don't need to subclass NSTableView to change its height based on the number of rows. In your controller, just monitor the data array using KVO and adjust the frame size of the tableview's scrollview (you can find it using
```
enclosingScrollView
```
) when rows are added or removed. I've used this technique before and it's worked well. You can use the tableview's
```
rowHeight
```
and
```
intercellSpacing
```
methods to calculate the height of the frame.


Question:
I've been contacted to see about updating an old legacy web application that was built using ASP and Access. The server is running Windows 2000 Advanced Server and I believe IIS 5.0 (I am trying to get confirmation on that, but the company isn't technical so I highly doubt Apache is running on the server).

What languages would be viable for updating this web app on the above platform? I've never touched classic ASP much less done any web development work against Windows 2000/IIS 5. There are no plans on updating the server to anything new due to budget concerns.

I'm leaning at the moment to moving to an SQLite-based database (customer isn't too keen on installing MySQL at the moment but I'm still in planning stages and this is a relatively low-traffic website) but what language would I pair with that? Does ASP.NET work well under IIS 5? Does PHP perform worth anything under this kind of setup?

Answer:
If the company is concerned with cost, I would be very conservative making changes.  Concentrate on why they want to update- do they want to add new functionality?  What are their mid-to-long term plans for the site?  Are they having trouble maintaining the site?  Going to a custom .NET solution may only complicate things further unless they are willing to make some ongoing investment in development.
If it's a relatively simple site, they may want to consider a platform like DotNetNuke.  There are hosts out there that sell ready-to-configure sites that can do quite a lot with a minimum of configuration.  That combined with a profressionally developed DotNetNuke UI template (TemplateMonster.com offers them) may be a good solution.
If they do want to go with a custom solution, ASP.NET runs fine on IIS 5.0.  I believe you can run the .NET Framework up to at least 2.0, not sure about 3.0 or 3.5.  Language won't make a difference to functionality, so C# or VB.NET are fine, all things being equal.


Question:
<?php
class foo
{
    //this class is always etended, and has some other methods that do utility work
    //and are never overrided
    public function init()
    {
        //what do to here to call bar->doSomething or baz->doSomething
        //depending on what class is actually instantiated?
    }

    function doSomething()
    {
        //intentionaly no functionality here
    }

}

class bar extends foo
{
    function doSomething()
    {
        echo "bar";
    }
}

class baz extends foo
{
    function doSomething()
    {
        echo "baz";
    }
}
?>

Answer:
```
```
public function init() {
    $this->doSomething();
}

$obj = new bar();
$obj->doSomething(); // prints "bar"

$obj2 = new baz();
$obj->doSomething(); // prints "baz"
```
```


Question:
I assume 100 bytes is too small and can slow down larger file transfers with all of the writes, but something like 1MB seems like it may be too much.  Does anyone have any suggestions for an optimal chunk of bytes per write for sending data over a network?

To elaborate a bit more, I'm implementing something that sends data over a network connection and show the progress of that data being sent.  I've noticed if I send large files at about 100 bytes each write, it is extremely slow but the progress bar works out very nicely. However, if I send at say 1M per write, it is much faster, but the progress bar doesn't work as nicely due to the larger chunks being sent.

Answer:
If you can, just let the IP stack handle it; most OSes have a lot of optimization already built in. Vista, for example, will dynamically alter various parameters to maximize throughput; second-guessing the algorithm is unlikely to be beneficial.
This is especially true in higher-order languages, far from the actual wire, like C#; there are enough layers between you and actual TCP/IP packets that I would expect your code to have relatively little impact on throughput.
At worst, test various message sizes in various situations for yourself; few solutions are one-size-fits-all.


Question: The Python datetime.isocalendar() method returns a tuple (ISO_year, ISO_week_number, ISO_weekday) for the given datetime object.  Is there a corresponding inverse function?  If not, is there an easy way to compute a date given a year, week number and day of the week?

Answer:
EDIT: ignore this, the edge cases are a pain. Go with Ben's solution.
Ok, on closer inspection I noticed that
```
strptime
```
has
```
%W
```
and
```
%w
```
parameters, so the following works:
```
```
def fromisocalendar(y,w,d):
   return datetime.strptime( "%04dW%02d-%d"%(y,w-1,d), "%YW%W-%w")
```
```
A couple of gotchas: The ISO week number starts at
```
1
```
, while
```
%W
```
starts at
```
0
```
.  The ISO week day starts at
```
1
```
(Monday), which is the same as
```
%w
```
, so Sunday would probably have to be
```
0
```
, not
```
7
```
...


Question:
I am given a responsibility in my project to develop a Equipment tracking tool with following requirements

New Equipment can be added by admin to a particular user

Once equipment is assigned to a person he will a request to accept the request so he will be responsible

User can transfer his equipment to other users.

At the same time Admin should be sent a mail or message whenever there is a change in status.

It should be deployed locally on a PC( So it is not actually a web app) that is connected to network which can be accessed by everyone

I thought I can use Django for this( I am new to it ), but I do not know much about deployment on a local PC , How can I do this, or is there any better Idea for this?

Answer:
It still sounds like you want a web app, you just won't be deploying it on a traditional web server.  One thing to note, client versions of Windows (XP, Vista) will limit you to 10 incoming connections per computer.
You'll want to follow these
instructions on how to install Django
.  If you haven't installed python yet, I'll recommend that you
install version 2.5
, since that will include sqlite, an embedded database that makes it
very easy
to get started developing with Django.  Django includes its own development web server, which you will come across naturally as you
go through the tutorial
.
Start by installing and then jump right into the tutorial.  Your deployment options will be much easier to understand once you're comfortable with developing in Django.


Question:
I am looking to use Java to get the MD5 checksum of a file.  I was really surprised but I haven't been able to find anything that shows how to get the MD5 checksum of a file.

How is it done?

Answer:
There's an example at
Real's Java-How-to
using the
MessageDigest
class.
Check that page for examples using CRC32 and SHA-1 as well.
```
```
import java.io.*;
import java.security.MessageDigest;

public class MD5Checksum {

   public static byte[] createChecksum(String filename) throws Exception {
       InputStream fis =  new FileInputStream(filename);

       byte[] buffer = new byte[1024];
       MessageDigest complete = MessageDigest.getInstance("MD5");
       int numRead;

       do {
           numRead = fis.read(buffer);
           if (numRead > 0) {
               complete.update(buffer, 0, numRead);
           }
       } while (numRead != -1);

       fis.close();
       return complete.digest();
   }

   // see this How-to for a faster way to convert
   // a byte array to a HEX string
   public static String getMD5Checksum(String filename) throws Exception {
       byte[] b = createChecksum(filename);
       String result = "";

       for (int i=0; i < b.length; i++) {
           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
       }
       return result;
   }

   public static void main(String args[]) {
       try {
           System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));
           // output :
           //  0bb2827c5eacf570b6064e24e0e6653b
           // ref :
           //  http://www.apache.org/dist/
           //          tomcat/tomcat-5/v5.5.17/bin
           //              /apache-tomcat-5.5.17.exe.MD5
           //  0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe
       }
       catch (Exception e) {
           e.printStackTrace();
       }
   }
}
```
```


Question:
Ok, I have one JavaScript that creates rows in a table like this:

  function AddRow(text,rowID) {
    var tbl = document.getElementById('tblNotePanel');
    var row = tbl.insertRow(tbl.rows.length);

    var cell = row.insertCell();
    var textNode = document.createTextNode(text);
    cell.id = rowID;
    cell.style.backgroundColor = "gold";

    cell.onclick = clickTest;

    cell.appendChild(textNode);
  }

In the above function, I set the cell's onclick function to call another JavaScript function called clickTest.  My question is when I assign the onclick event to call clickTest, how do I set parameter information to be sent when the clickTest method is called on the cell's onclick event?  Or, how do I access the cell's ID in the clickTest function?

Thanks,
Jeff

Answer:
In the clickTest function you should have access to a the
```
this
```
variable.  Try this inside of
```
clickTest
```
function:
```
```
alert(this.id);
```
```
This will refer to the DOM element that fired the event.
Basically, there isn't really a way to pass parameters to an event handler function.  The reason for that is that the browser is executing the function based on an event and you are not actually calling the function.
You can use closures which allow you to access local variables (to the closure) when you assign the event handler function.  That would look like this:
```
```
cell.onclick = function() { alert(this.id); alert(cell.id); };
```
```
Were
```
cell.id
```
is the locally scoped variable that is still considered in scope when the event handler is executed.


Question:
What is a security sandbox violation, and how do I override it? I'm making a project in FlashDevelop, and today, it will not load external files, even though it had been previously. It gives the following output:

************* Security Sandbox Violation *********   Connection to
  file:///C|/Documents%20and%20Settings/Kevin.PC885314341208/Desktop/Import%20.txt/StockData/1.txt
  halted - not permitted from
  file:///C|/Documents%20and%20Settings/Kevin.PC885314341208/Desktop/Import%20.txt/import.swf

I hope this isn't a serious problem.

Thanks for any help.

Answer:
You're loading a local file, something that's not permitted. However, as you're developing this you can of course allow this.
Add your project folder to the trusted locations:
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html
Edit: I might add that if you run it with networking disabled it will work (this is for development purposes). This happens for example when you run it from the Flash IDE, which would explain why it may have worked before?


Question:
I`ve read that columns that are chosen for indices should discriminate well among the rows, i.e. index columns should not contain a large number of rows with the same value. This would suggest that booleans or an enum such as gender would be a bad choice for an index.

But say I want to find users by gender and in my particular database, only 2% of the users are female, then in that case it seems like the gender column would be a useful index when getting the female users, but not when getting all the male users.

So would it generally be a good idea to put an index on such a column?

Answer: This is a case where I would let the server statistics inform me of when to create the index.  Unless you know that this query is going to predominate or that running such a query would not meet your performance goals a priori, then creating the index prematurely may just cost you performance rather than increase it.  Also, you may want to think about how you would actually use the query.  In this case, my guess would be that you'd typically be doing some sort of aggregation based on this column rather than simply selecting the users who meet the criteria.  In that event, you'll be doing the table scan anyway and the index won't buy you anything.


Question: Does MySQL index foreign key columns automatically?

Answer:
Yes, see
InnoDB and FOREIGN KEY Constraints
.


Question:
Is there a way I can export my Silverlight DataGrid data to excel or csv?

I searched the web but can't find any examples!

Thanks a lot

Answer:
I don't think Silverlight offers a way to download files.  You can add a button to your app that calls a URL- i.e.
http://www.mysite.com/generateexcelfile.aspx
.  Include as Querystring values the parameters used to generate the data being displayed in your Silverlight app, run your query and use your favorite Excel file generation component to generate the file on the fly.  Redirect to it and it will download to the users' system.


Question:
What is the best way to integrate an external script into the Zend Framework? Let me explain because I may be asking this the wrong way. I have a script that downloads and parses an XML file. This script, which runs as a daily cron job, needs to dump its data into the database.

I am using Zend Framework for the site which uses this script and it seems to me that it would be best to use my subclassed model of Zend_Db_Abstract to do the adding and updating of the database. How does one go about doing this? Does my script go in the library next to the Zend Components (i.e. library/Mine/Xmlparse.php) and thus have access to the various ZF components? Do I simply need to include the correct model files and the Zend DB component in the file itself? What is the best way to handle this sort of integration?

Answer:
I just came across something that may be germane to this question.
This IBM developerWorks article.
The author recommends simply creating a scripts folder in the ZF hierarchy and the using it as one normally would within ZF (though he does set the ini path and call autoload). Is it that simple? Does simply being in the hierarchy of the framework and including the path and autoloader grant your script access to all of the goodies?


Question:
Was wandering if anyone uses ASP .NET membership? If you do, tell me what you think about it.

If you don't use it, Are you planning to use it on future projects? If not, why?

RWendi

Answer:
Yes. Have used it quite a lot, and it will save you a lot of work.
There are some pain points like changing usernames, and administrative reset of passwords, that clients will often ask for, and you will have to hack your way around them.
The role provider is also pretty handy, and there are a lot of prebuilt controls that work with it, although recently hit a bug between role manager and aspnet ajax that has been a PITA.
The model is generally very good, even if you have shop around for some different providers that suit your needs.
Overall, it's not perfect, but if you can live with it and work around it's issues, it will save you heaps of code.
For some situations, it is maybe using a chainsaw when a butter knife would do, but it's there, it works, and there are plenty of other people using it.
Its one kind of hammer, for the price, is ok, but there is no golden hammer.


Question:
I'm looking to get some help on using the cycle library for jQuery. I'm in the beginner demos, and I got the absolute first one completed. This is the second one on the page.

<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery.cycle.all.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {

    $('.pics').cycle({
        fx:      'scrollDown',
        speed:    300,
        timeout:  2000
    });
</script>

My CSS is identical to the one on the page, that's why I put .pics in the quotes.

Answer:
I will take a guess that this is just not working for you.
You need to balance your braces and parentheses.
Please
help others to help you by saying what the actual problem is next time.
Try this:
```
```
$(document).ready(function() {
    $('.pics').cycle({
        fx: 'scrollDown',
        speed: 300,
        timeout: 2000
    });
});
```
```


Question:
How long do you normally test an update for Zend Framework before pushing it out into a productions project.  We can break this question up into minor updates 1.6.0 -> 1.6.1 or maybe a major update 1.6.2 -> 1.7.0.  Obviously you don't release it if it add bugs to your code.

Also, as with most other server software updates normally people have a window of time they like to wait and watch the community before even attempting an update on a development environment.  How long do you even wait to start the process?

Answer:
It seems like the best method would be to have a comprehensive set of tests that exercised all the functionality in your application.  With a good method for testing it seems like you could push it into production pretty quickly.
Another simple thing you can do to help you make your decision would be to simply do a diff against the repository to see what changes where applied to any modules that you use.  If there where no changes, then upgrading shouldn't make any difference.  If something underwent a major re-write, you would probably want to investigate a lot deeper.


Question: How do I compare two images & recognize the pattern in an image irrespective of its size and pattern size, and using .Net C#?  Also, which algorithms are used for doing so from Image Processing?

Answer:
See
Scale-invariant feature transform
,
template matching
, and
Hough transform
. A quick and inaccurate guess may be to make a histogram of color and compare it. If the image is complicated enough, you might be able to distinguish between several sets of images.
To make the matter simple, assume we have three buckets for R, G, and B. A completely white image would have (100%, 100%, 100%) for (R, G, B). A completely red image would have (100%, 0%, 0%). A complicated image might have something like (23%, 53%, 34%). If you take the distance between the points in that (R, G, B) space, you can compare which one is "closer".


Question: In VB.NET, which is better to use: function overloading or default parameters?

Answer:
if the parameters are optional (i.e. the overloads are a subset of the parameters that the full procedure signature accepts) then default or optional parameters would make more sense.
If the overload is allowing a different type for the parameter or is a semantically different parameter that will be interpreted differently by the routine then overloads would make more sense.


Question:
Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?

Note: I am rewriting an existing system that is painfully slow.

Answer:
Use
str_split()
:
```
```
$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
```
```
The output:
```
```
Array
(
    [0] => 0123
    [1] => 4567
    [2] => 8901
    [3] => 2345
)
```
```
Then of course to insert hyphens between the sets you just
implode()
them together:
```
```
echo implode('-', $sets); // echoes '0123-4567-8901-2345'
```
```


Question: One of the appropriate uses for sqlite3 is "in-memory databases".  This sounds like a really useful tool for my C++ applications.  Does anyone have an example of how this is done in C or C++?  I'm specifically looking for a canonical way to slurp several flat-files into an in-memory database, then do some joins.

Answer:
Just open the file :memory: and that should do it (at least it does in PHP).
You mention that you want to read in several flat files and do joins on them. If it's possible to store the flat files as SQLite databases, you can work directly with both by attaching one to the other:
```
```
ATTACH foo.db AS foo
```
```
Then refer to the tables in foo like so:
```
```
SELECT * FROM foo.users
```
```
This way you can do your joins without the need for creating an in-memory database.


Question:
I'm looking for some sample code that will sort the list items in an HTML list by alphabetical order.  Can anyone help?

Here is a sample list for people to work with:

<ul class="alphaList">
    <li>apples</li>
    <li>cats</li>
    <li>bears</li>
</ul>

Answer:
```
```
var items = $('.alphaList > li').get();
items.sort(function(a,b){
  var keyA = $(a).text();
  var keyB = $(b).text();

  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});
var ul = $('.alphaList');
$.each(items, function(i, li){
  ul.append(li); /* This removes li from the old spot and moves it */
});
```
```


Question:
I need to do a join with a table/result-set/whatever that has the integers n to m inclusive. Is there a trivial way to get that without just building the table?

(BTW what would that type of construct be called, a "Meta query"?)

m-n is bounded to something reasonable ( < 1000's)

Answer:
There is no sequence number generator (
CREATE SEQUENCE
) in MySQL. Closest thing is
```
AUTO_INCREMENT
```
, which can help you construct the table.


Question:
I am writing a text editor which has an option to display a bullet in place of any invisible Unicode character.  Unfortunately there appears to be no easy way to determine whether a Unicode character is invisible.

I need to find a text file containing every Unicode character in order that I can look through for invisible characters.  Would anyone know where I can find such a file?

EDIT: I am writing this app in Cocoa for Mac OS X.

Answer:
Its an impossible task, Unicode supports even Klingon, so it's not going to work. However most text editors use the standard ANSI invisible characters. And if your Unicode library is good, it will support finding equivalent characters and/or categories, you can use these two features to do it as well as any editor out there
Edit:
Yes I was being silly about Klingon support, but that doesn't make it not true... of course Klingon is not supported by the Consortium, however there is a movement for Klingon in the Unicode's "Private Use Area" defined for Klingon alphabet (U+F8D0 - U+F8FF).
Link here
for those interested :)
Note:
Wonder what editor Klingon programmers use...


Question: How do I check if a field (textbox) is empty or filled only with white spaces (spaces/enters/tabs etc.), using javascript RegExp?

Answer:
```
```
if (myField.value.match(/\S/)) {
  // field is not empty
}
// or
if (/\S/.test(myField.value)) {
  // field is not empty
}
```
```
Explanation, since other people seem to have some
crazy
different ideas:
```
\s
```
will match a space, tab or new line.
```
\S
```
will match anything but a space, tab or new line.
If your string has a single character which is not a space, tab or new line, then it's not empty.
Therefore you just need to search for one character:
```
\S
```


Question:
I have this piece of code in my PHP code:

while ($row = mysqli_fetch_assoc($result))
{
    extract($row);
    echo "<tr>";
    echo "<td bgcolor='#FFFFFF'><input id='bookArray[]' name='bookArray[]' type='checkbox' value='$book_id' />$book_id</td>";
    echo "<td bgcolor='#FFFFFF'>$threat_name</td>";
    echo "</tr>";
}

In HTML page, I want to use jQuery serialize() method to sent array of selected books in bookArray[]. In my JavaScript,

var selectedbooks = $("book_form").serialize();
alert (selectedbooks);

In the alert message box, i did not get any value (empty string).

Previously when i am using Prototype, it worked nicely.

Answer:
You may need to change your PHP as @Tomalak suggests, but you will also need to change your javascript.  To reference a named element use the #name selector:
```
```
var selectedbooks = $('form#book_form').serialize();;
```
```


Question:
i have two servers a main site and a static server.
i want to get a file's content from ajax in runtime, which is stored in static server.
obviously cross domain problem will occur.

so what i am trying to do is storing that ajax .js in the static server, so that calling the local file wont be a problem.

but after i include that js file from static, still that problem remains...

Any solutions?!

Answer:
Are you sure the path to
```
info.xml
```
is correct?  That gets me sometimes when I am including a file from a subdirectory.


Question:
Ok, I know this is a strange question, but there is a "standard" (fan-wise at least) Unicode support for the Klingon alphabet, and since code can be written in Unicode with no problem, that means it is possible to write Kode with Klingon tokens( vars, function names, etc...).

For the record I've written C++ in Japanese and it works, so K++ in Klingon should work too. But I don't know of any text editor with support for Klingon. Any suggestions?

Answer:
Not likely, especially when you consider rule 9 of the
KLINGON GUIDE To Writing Perfect Code
“Indentation?! I will show you how to indent when I indent your skull!”
and number 7 does not bode well for any editor:
“Klingon function calls do not have ‘parameters.’ They have ‘arguments’ . . . and they ALWAYS WIN THEM!”
```
[
```
Seriously, this is an interesting
Unicode editor problem
```
]
```
After all, ITunes has a license agreement in Klingon!
And you need the right keyboard, off course \o/
Now... may be you can try to "Google it" ;-)


Question:
Simple question:

Can a swing frame be completely modal ( block all others windows ) ?

I tried the following, but I can still click on other apps windows ( like this browser )

JDialog myDialog  = ....
myDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

Plase paste some code if this is possible.

Answer:
I don't know about global modal, but here's an idea.
Take the screenshot of the desktop.
Go full screen.
Pop up your dialog.
Since the desktop is fake screenshot, you can ignore any attempt to click into it.
Full screen sample
:
```
```
private void toggleFullScreenWindow() {
  GraphicsEnvironment graphicsEnvironment
    = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice graphicsDevice
    = graphicsEnvironment.getDefaultScreenDevice();
  if(graphicsDevice.getFullScreenWindow()==null) {
    dialog.dispose(); //destroy the native resources
    dialog.setUndecorated(true);
    dialog.setVisible(true); //rebuilding the native resources
    graphicsDevice.setFullScreenWindow(dialog);
  }else{
    graphicsDevice.setFullScreenWindow(null);
    dialog.dispose();
    dialog.setUndecorated(false);
    dialog.setVisible(true);
    dialog.repaint();
  }
  requestFocusInWindow();
}
```
```
FYI:
Full-Screen Exclusive Mode API
.


Question: Unfortunately I don't have access to a *nix box at work or at home.  The only way I can play with Haskell is on windows.  Anyone here using Haskell on Windows? What's your setup?

Answer:
GHC
is a state-of-the-art, open source, compiler and interactive environment for the functional language Haskell.
There is a
Windows installer for GHC
, but it for Version 6.4.2 .
A Windows
```
.exe
```
(not an
```
.msi
```
installer) for version 6.10.1 is at
http://www.haskell.org/ghc/dist/6.10.1/
It is not clear when the current (GHC 6.10.1) version will offer a Windows installer.


Question:
Assuming the following class stub:

public class Foo<T> {
  private Class<T> type;

  public Foo<T> () {}
}

Can I store the generic type T into the field type in the constructor, without changing the constructor's signature to "public Foo<T> (Class<T> type)"?

If yes, how? If no, why?

"type = T" doesn't seem to work.

Answer:
Does
```
```
type = T.getClass();
```
```
work?


Question:
I am trying to create a custom subclass of NSScroller. I have created the class, and set it as the vertical scroller on an NSScrollView in IB. When I run my project, the drawRect: method is called for my subclass, so I know that it is properly connected.

Now, How do I change the width of my fancy new NSScroller? No matter what I do to its bounds and frame, it always wants to draw in a rectangle 15 pixels wide (the size of the default NSScroller).

Answer:
In your NSScroller subclass, you have to override scrollerWidth:
```
```
+(CGFloat)scrollerWidth
{
    return 30.0;
}
```
```
This is the value that NSScrollView uses to define the frame for your component when it sets it up.


Question:
The performance of a Direct3D application seems to be significantly better in full screen mode compared to windowed mode. What are the technical reasons behind this?

I guess it has something to do with the fact that a full screen application can gain exclusive control for the display. But why the application cannot gain exclusive control for part of the screen (i.e. window) and have the same performance benefits?

Answer:
There's
a bit
on MSDN that says full screen mode uses buffer flipping, if set up correctly, as opposed to blitting. It makes sense.
Of course you can (and in a way, do) give exclusive control for part of the screen to an application, but what happens to the rest of the screen? You still have to blit, do occlusion checking, etc. on the rest of the windows, and I think that's what causes the performance hit.


Question:
i'm using vs installer to build a setup package for my vb6 app.
and the problem is i can see that under the project explorer there's a list of dependencies attached to my exe file.

alt text http://img505.imageshack.us/img505/9696/croppercapture259lr8.png

and under the file system on target machine treeview, i can actually store the dll/ocx on a folder or in the windows system folder itself[the left window].

alt text http://img101.imageshack.us/img101/9224/croppercapture251qm1.png

so what i don't understand is .. is there actually a difference?
if i just set the dependencies and didn't add the dll or ocx to the folder or win sys folder, does the dll automatically get copied over too?

Answer:
It is not guaranteed that all those dlls will be present on the system that the software is being installed on. So they need to be included in your installer. From there you have two choices.
You can install them in your windows system folders or in your application folder. The difference is that if you install them in your application folder you can set things up on XP and Vista so that the different version of the software with different version of the components can be fired up and run side by side. Installing them into the system folder will break any older version that depend on older version of the components.
Installing in the application folder rarely doesn't work if a component depends on other components that can't be updated. When this occurs it is usually with with Microsoft libraries. They have gotten better over the years on this issue.
You can read more about the issues involving side by side execution
here
Finally the dependencies need to be in your installer so that they are registered in the Windows Registry. Unlike most .NET assemblies any ActiveX/COM application needs to have the component registered in order to use it even if you are using CreateObject and Variant types to access it.
I will admit the whole process is idiosyncratic and is one of the sources for the stories about DLL Hell.  Start with the MSDN article, use wikipedia, and of course ask further questions here.


Question: Is there any free IDE for Pl/SQL development

Answer:
I personally like
http://www.allroundautomations.nl/plsqldev.html
Quite usefull for PL/SQL and Oracle in general. But not free.


Question:
We often send emails in HTML for clients (Dont like it but not my choice)

Does anyone have any info or a link on support for the dynscrc attribute or img in email clients?

Answer:
My solution here would be to have a screenshot (perhaps with a 'click to watch' overlay) of your movie that links to a non-mail page that has a player in it.
Dealing with html email, in my experience, isn't so much about having standards as it is learning to compromise.  Web client and (the increasingly rare) desktop clients have differing behaviors that make website browser compliance seem like preschool by comparison.


Question: With which version(s) of VS2008/VSTS can I work with .dbproj files?

Answer:
You can definitely use
Team Edition for Database Professionals
.  The bad news is that it seems you
can only use this
or of course the superset version
Team Suite
but that would set you back a lot for a team.
It would be nice if the whole team could edit these files without having to fork out for these expensive extra licenses.  On the plus side the dbproj projects can be
built using Team Build


Question:
Does using delegates slow down my programs?

I've been avoiding them because I really have no clue if they make my programs any slower.  I know if I cause a (catch) exception, that uses quite a bit of CPU power but I don't know about Delegates and Events and what .NET does to them.

Answer:
Delegates are very, very fast. Not quite as fast as direct method calls, but not far off. The chances of them becoming a bottleneck are miniscule.
(Likewise exceptions, when used properly,
rarely actually cause a performance issue
.)
Would using delegates make your code simpler, more readable, and more robust? If so, use them. Measure your performance carefully, and keep an eye on it. Move away from readability for the sake of performance only when the data is clear.
I'm sure there are some graphs around showing the speed of delegates vs interfaces vs non-virtual method calls etc - I don't know where they are, but you could always run tests yourself if you're really worried.


Question: Is it possible to use CPython to develop Adobe Flash based applications?

Answer:
I guess it would be possible to compile the python interpreter to flash bytecode using this
http://labs.adobe.com/downloads/alchemy.html
and then use it to run python programs. But apart from that the answer is no.


Question:
What is JDBC and where can I start learning about?

I know it's a way to access databases with Java, but what problems does it solve? Is it an ORM (or does it try to be)? Does it abstract away differences between databases, at the syntax level? What does it do? and what does it not do?

Answer:
No, JDBC isn't an ORM. It's the
Java Database Connectivity
API and basically it provides a database-agnostic access layer with a provider model (so that new database drivers can be added easily). Vendors can add more functionality for specific database features if they wish, but developers can ignore those features if they wish to work with multiple databases.
There's no mapping involved - just modeling for connections (and pools), prepared statements, stored procedures, result sets etc.


Question:
I want to let the user draw on an image in a browser. In other words, I need both bitmapped graphics and drawing capabilities, whether vector or bitmapped.

Canvas looks good, but is not supported by IE, and though there is ExCanvas, I wonder if ExCanvas is stable enough for consistent use in IE6 through 8.

Or best of all, is there an open-source image/drawing library that supports all this out of the box? I found two dozen or so Web-based image editors or drawing tools, but none support the requirements. (And I'd like to avoid Flash/Flex/Silverlight/JavaFX.)

Answer: Even though you said you'd like to avoid it I'd suggest Flash. You could easily use Flash 6 or 7 and these have a > 90% adoption rate. I'd be surprised if you could get that level of support with JavaScript. Flash is truly write once run anywhere, which will cut down on your development time.


Question:
I receive some arguments into a stored procedure. These arguments are NVARCHAR's.

I have a problem, when I need to cast some of these values to FLOATS, because they are being received as e.g.

@VALUE1 NVARCHAR(100)

DECLARE @ChangedValue
SET @ChangedValue = CAST(@Value1 AS FLOAT)

E.g. @Value1 = "0,001"

Gives me a problem, as it expects "0.001"

I can't change the format of the input, but can I somehow change it on the SQL-server side? By changing all "," to "." instead?

Best regards, Kenn

Answer:
You could use
```
@VALUE1 = REPLACE(@VALUE1, ',', '.')
```
This does seem a horrible thing to do though!


Question:
I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don't initially know the final number of samples I will actually retrieve.

What is the most efficient way to concatenate these arrays together in C# as I pull them  out of the system?

Answer:
You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a
```
List<T>
```
which can grow as it needs to.
Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.
See
Eric Lippert's blog post on arrays
for more detail and insight than I could realistically provide :)


Question:
Is there a way to detect whether IIS is enabled or not?

I know how to check if it is INSTALLED, but I need to know if it's installed but not enabled.

Also, can this be done natively via InstallShield?  Checking this via .NET would be acceptable as we can write custom actions, but if there is an IS call then that would be ideal.

Any hints/tips are appreciated, thanks

Answer:
You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a
```
List<T>
```
which can grow as it needs to.
Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.
See
Eric Lippert's blog post on arrays
for more detail and insight than I could realistically provide :)


Question:
Did you ever use SQL Server auditing features on a production db?

How did that impact on performances, and are there differences you noticed between different versions of SQL Server.

Also how we need to enable the audit features.

Answer:
I'm afraid there's no such a thing as "audit feature". Instead you need to build it yourself depending on what kind of requirements you have. There are many ways to do this, for example
A trigger fires every time data in audited tables change. An example here:
http://web.archive.org/web/20071006100909/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-audit-changes-to-sql-server-data.html
using your ORM, with NHIbernate
ideas here:
Data Auditing in NHibernate and SqlServer


Question:
Forgive me for probably using the wrong term for this "application mode".

Our application has a problem during start in that it doesn't show a task bar icon until the main window is up, even though there are loading progress windows, logon-windows, etc. on screen before that.

We change the code to fix this, but unfortunately this fix, when running the app through citrix, now shows two icons, one with just the icon and no text.

Is there a way for me to detect that the application is running through citrix? I don't know the right term for this, but only the app window is brought to the users desktop, not the whole remote desktop.

If it matters, the app is written in Delphi.

Answer:
Not sure exactly how to do this in delphi, but if you can call out to the user32.dll, and call the function:
```
```
if (GetSystemMetrics(SM_REMOTESESSION) != 0)
{
   // We are in a remote session
}
```
```
This should tell you if you are running in a Citrix or Terminal Services environment.
SM_REMOTESESSION is defined as:
```
```
#define SM_REMOTESESSION        0x1000
```
```
More info on the GetSystemMetrics api here:
Link to msdn
Edit
The following page describes how to do exactly the above in delphi. What works for Terminal Services should also work for Citrix:
Is your Delphi Application Running under Terminal Services as a Remote Session


Question:
I'm writing this question in the spirit of answering your own questions, since I found a solution to the problem, but if anyone has a better solution I would gladly listen to it.

In the application I am currently working on I am subclassing the ListView control to add some functionality of which some interacts with the ListView SelectedIndices and SelectedItems properties.

The problem is that when I try to unit test my subclass, the SelectedIndices and SelectedItems properties does not update when I add items to the selection. I tried both

item.Selected = true

and

listView.SelectedIndices.Add(...)

But SelectedIndices or SelectedItems simply does not appear to be affected. The unit tests for the other parts of the functionality works fine.

How can I unit test the selection dependent parts of my ListView subclass?

Answer:
The problem seems to be that the SelectedIndices and SelectedItems does not update properly if the ListView has not been drawn, as is stated in this comment from the MSDN documentation of the
ListViewItem.Selected property
:
The Selected property cannot be trusted if your ListView has never been drawn (for example, it's in a TabControl, in a tab that has not been selected yet). In that case, the SelectedItems and SelectedIndices of the parent ListView are not correctly updated and will still be empty.
One solution to this problem is to create a simple dummy form class in your test, add the ListView to the form and simply show the form. After that the SelectedIndices and SelectedItems properties work as expected.
Something like this:
```
```
[Test]
    public void CanGetSelectedItems()
    {
        // simple test to make sure that the SelectedIndices
        // property is updated
        using (var f = new DummyForm(listView))
        {
            f.Show();

            listView.SelectedIndices.Add(0);
            Assert.AreEqual(1, listView.SelectedIndices.Count);
        }
    }

    private class DummyForm : Form
    {
        public DummyForm(ListView listView)
        {
            // Minimize and make it not appear in taskbar to
            // avoid flicker etc when running the tests
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
            this.Controls.Add(listView);
        }
    }
```
```


Question:
I wish to set a usererror string before leaving a function, depending on the return code and variable in the function.

I currently have:

Dim RetVal as RetType

try
...
if ... then
    RetVal = RetType.FailedParse
    end try
endif
...

finally
    select case RetVal
        case ...
            UserStr = ...
    end select
end try

return RetVal

Is it possible to use return RetType.FailedParse, then access this in the finally block?

Answer:
The only real way of doing this in C# would be to declare a variable at the start of the method to hold the value - i.e.
```
```
SomeType result = default(SomeType); // for "definite assignment"
try {
   // ...
   return result;
}
finally {
    // inspect "result"
}
```
```
In VB, you
might
be able to access the result directly - since IIRC it kinda works like the above (with the method name as "result") anyway. Caveat: I'm
really
not a VB person...


Question: Is it good practice to have a unit test that specifies how long a certain function takes to return a value. I'm unit testing a curl function and want to specify that it needs to time out after 5 seconds. Is this in line with the way unit tests work?

Answer:
I don't think, that this is a test of the contract of the method. That's why I would say no, it's not an unit-test. But it sound like some sort of system-test.
Another point that disqualifies your example as unit-test is the fact, that it needs long time (5 seconds) to execute. Typically you should be able to execute the complete suite of unit-tests every time you do a change. You cannot wait long time.
That's why I think your test should be in another set of tests, than the unit-tests. It should be executed in your daily builds/continuous integration but not before every checkin from every programmer.


Question:
I am wondering what is best practice when it comes to dependencies and how releases should be done. In my case I have a library that relies on log4net and I am wondering if I should distribute log4net.dll (set the log4net reference to copy local) along with the release?

Could I simply state that log4net should be installed in the GAC?

Answer:
I don't think, that this is a test of the contract of the method. That's why I would say no, it's not an unit-test. But it sound like some sort of system-test.
Another point that disqualifies your example as unit-test is the fact, that it needs long time (5 seconds) to execute. Typically you should be able to execute the complete suite of unit-tests every time you do a change. You cannot wait long time.
That's why I think your test should be in another set of tests, than the unit-tests. It should be executed in your daily builds/continuous integration but not before every checkin from every programmer.


Question:
We have a number of very old data entry forms that were made in Access that link to our SQL Server database. Each form may have any number of sub-forms.

We'd like to move away from using these access frontends but don't have the time to create a new app or web app to replace every form that we've got.

Is there another option that would link to SQL Server and allow visual design of the form and automatic linkage to the database?

Or if that's too much of an ask, can you think of a way to make hand-coding the forms easier?

Answer:
From experience, I don't think you will find any product, tool or technology any easier than Access for creating forms with a DB behind them.
Do you have a copy of
Access Developer's Handbook
?   In the past, I found this a valuable resource for implementing best practices in quite complex projects with Access as a front-end to SQL Server.
If you want to move to web forms, I would take a look at
IronSpeed Designer


Question:
MS SQL has a convenient workaround for concatenating a column value from multiple rows into one value:

SELECT col1
 FROM table1
 WHERE col2 = 'x'
 ORDER by col3
 FOR XML path('')

and that returns a nice recordset:

XML_F52E2B61-18A1-11d1-B105-00805F49916B
----------------------------------------
<col1>Foo</col1><col1>Bar</col1>

only the column name in the returned recordset is rather nasty!

The column name seems to include random elements (or a GUID), and hence I am reluctant to use it in my application (different instances or different servers might have another GUID).  Unfortunately I cannot use * to select the value, and due to the restrictions in the existing application I cannot iterate through returned columns, either...

Is there a way to force the column name in the returned recordset to something more sensible?

Answer:
That should do:
```
```
select(
SELECT col1
 FROM table1
 WHERE col2 = 'x'
 ORDER by col3
 FOR XML path('')
) as myName
```
```
Not pretty but should give the result that you need


Question:
I was wondering if there was a way to tell if an instance of Oracle on a system has a database installed or not?

This is for an installation script, and I need to verify that there is an actual database in place before proceeding with the loading of my own tablespace onto that database. Has anyone tackled this problem before?

Cheers

Answer:
You could use
```
tnsping
```
to check whether the database listener is active, that would be a good indication. Other than that, why not just simply do a test connection? If it's part of an installer process, you could prompt the user to enter the appropriate connection credentials if you don't know what they'll be in advance.


Question:
The web service endpoint usually is defined in an early stage of a project. Since it follows the "contract first" principle, it shouldn't be changed after communicated to client systems.

Therefore, it is vital to label the web service in a good way.

How would you label web services?

e.g.

http://my.domain.com/businessProcess/services/concreteServiceName

Other ideas?

See this question as a poll... Feel free to vote for the best idea.

Answer:
We decide on names by talking to the developers, business guys, and support guys. We formed a committee called the "interface control committee", and we approach it kind of like you described in the question. We want service names to be descriptive, reflect the processes they support, and fit the needs of the technical and business stakeholders.
When we have ICC meetings, we also talk about schemas and how they should be developed. The business guys are key in this as well since they know what data they want to expose and why.
KA


Question:
I have following situation:
I have loged user, standard authentication with DB table

$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users');
$authAdapter->setIdentityColumn('user_name');
$authAdapter->setCredentialColumn('password');

When user edits his profile, I save it into Db, but I need to update also storage (using standard Zend_Auth_Storage_Session). Is there any easy way how to do it? Many thanks.

Answer:
I have done it like this, it works, but I don't know if there is not some better way,how to do it
```
```
$user_data = User::getUser($user_id)->toArray();
unset($user_data['password']);

$std_user = new stdClass();

foreach ($user_data as $key => $value)
{
   $std_user->$key = $value;
}

$auth = Zend_Auth::getInstance();
$auth->getStorage()->write($std_user);
```
```


Question:
We are currently creating an InfoPath 2007 form is deployed in SharePoint 2007. In the form we populate the repeating tables with more than 60 records. However, when we're submitting the form, an error message appears. Does the number of records in the repeating table affects the submitting of the form? Also provide some workaround to resolve the issue.

Thanks in advance.

Answer:
I have done it like this, it works, but I don't know if there is not some better way,how to do it
```
```
$user_data = User::getUser($user_id)->toArray();
unset($user_data['password']);

$std_user = new stdClass();

foreach ($user_data as $key => $value)
{
   $std_user->$key = $value;
}

$auth = Zend_Auth::getInstance();
$auth->getStorage()->write($std_user);
```
```


Question:
I'm trying to programmatically reject a call on a BlackBerry, with Java + JDE.
I'm intercepting the callIncoming event, and in there I need to do something to reject a call from a specific number.

Does anyone know how to do that?

Answer:
I couldn't find an API for directly rejecting the call in progress. However, you could explore a hack where you inject a keypress of the Hangup/Disconnect button (see
```
EventInjector
```
).
As to determining the phone number, you could use
```
Phone.getCall(callId).getDisplayPhoneNumber()
```
or
```
Phone.getActiveCall().getDisplayPhoneNumber()
```
.


Question:
I have a loader.exe with Main() that loads the 'UI' in WPF, the thing is that I want only one instance of the loader.exe, how can I achieve it?

Is there a way a user clicks loader.exe it should check if an existing loader.exe is running and does nothing.

currently I have

loader.exe

with

main()
....
..
Load UI
...

the loader has no idea what its loading etc so I can't do many things with the loader project...

Any help n code is highly appreciated

Thanks in advance.

Answer:
Have a look at:
http://yogesh.jagotagroup.com/blog/post/2008/07/03/Ways-of-making-a-WPF-application-Single-Instance.aspx
Also, you might find a more detailed answer in the following post here on StackOverflow:
What is the correct way to create a single-instance application?


Question:
I have created a class to dynamically put together SQL function statements within a project. I have found this class to be pretty useful and would like to incorporate into future projects

namespace connectionClass

{

 public class connClass

 {

     NpgsqlConnection conn = new NpgsqlConnection(projectName.Properties.Settings.Default.ConnString);

 }

}

I want to be able to dynamically input the project name without having to do it myself for every different class! the connection string will be defined within the properties settings in VS.

Any help would be greatly appreciated:)

Answer:
One option is to have the connection class use the ConfigurationManager to get the name from the App.Config file - but this still means setting the name in there. Something like
```
```
ConfigurationManager.AppSettings["PROJECT_NAME"];
```
```


Question: Is there an easy way within C# to check to see if a DateTime instance has been assigned a value or not?

Answer:
The only way of having a variable which hasn't been assigned a value in C# is for it to be a local variable - in which case at compile-time you can tell that it isn't definitely assigned by trying to read from it :)
I suspect you really want
```
Nullable<DateTime>
```
(or
```
DateTime?
```
with the C# syntactic sugar) - make it
```
null
```
to start with and then assign a normal
```
DateTime
```
value (which will be converted appropriately). Then you can just compare with
```
null
```
(or use the
```
HasValue
```
property) to see whether a "real" value has been set.


Question: Yes we're talking about ASCII codes. My appologies I'm not the Delphi dev here.

Answer:
It depends what your definition of conversion is. If you want to map the 127 lowest characters to the Unicode equivalent, you can use an explicit cast. But this creates garbage if the string contains higher characters.
If you want mappings like ë -> e and û -> u, you can write your own code. But be aware that there are always characters that can't be converted.


Question:
We have two web servers with load balancing. We need to share some files between those servers. These would be uploaded files, session files, various files that php applications create.

We don't want to use a heavyweight, no longer maintained or a commercial solution. We're looking for some lightweight open-source software that would work as shared file system. It should be really easy to set up, must be HA available, must be very fast. It should work with RedHat Linux.

We looked at such solutions like drbd with synchronous file sharing but we can't use them because it can't work on an underlying filesystem like ext3.

Answer:
DRBD is good for syncing over a network (direct crossover connection if at all possible), but EXT3 is not designed to be aware of changes that occur underneath it, at the block device level. For that reason you need a filesystem designed for such purposes such as the Global File System (GFS). To the best of my knowledge Red Hat has support for GFS.
The DRBD manual will give you an overview of how to use GFS with DRBD.
http://www.drbd.org/users-guide/ch-gfs.html
Don't take this as a final answer - I have not researched or used a multi-master system  before, but at least this might give you something to go on.
Ideally, you would only sync the part of the data that's shared between the webservers.


Question: I am putting together a build system and wanted to know if there is a reliable way to find out if a checked out SVN folder needs updating (i.e. is it out of sync with the repository).  I want to avoid a nightly build unless something has changed.  I could write a script that parses the results of the svn update command I guess, but I wondered if there as a command that would tell me if an update is actually required?

Answer:
Use the
show updates option
of the status command:
```
```
svn status -u
```
```
or
```
```
svn status --show-updates
```
```


Question:
I have an Informix SQL query which returns a set of rows. It was slightly modified for the new version of the site we've been working on and our QA noticed that the new version returns different results. After investigation we've found that the only difference between two queries were in the number of fields returned.

FROM, WHERE and ORDER BY clauses are identical and the column names in the SELECT part did not affect the results. It was only the number of fields which caused the problem.

Any ideas?

Answer:
Adding
```
--+ ORDERED
```
join-order directive fixes the problem by allowing you to get your results in predictable order each time.
The links goes to the description of how the directive works
http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls1144.htm
Use the ORDERED join-order directive
  to force the optimizer to join tables
  or views in the order in which they
  appear in the FROM clause of the
  query.
```
```
SELECT --+ ORDERED
   name, title, salary, dname
FROM dept, job, emp WHERE title = 'clerk' AND loc = 'Palo Alto'
   AND emp.dno = dept.dno
   AND emp.job= job.job;
```
```


Question:
I am using iText to generate PDF invoices for a J2EE web application and included on the page is an image read from a URL constructed from the request URL. In the development and test environments this works fine, but in production I get a java.io.IOException:  is not a recognized imageformat.

If I paste the url into my browser then the correct image is returned, however the request is redirected from http to https. In my code if I hard code the redirect URL then the image is displayed correctly.

So it seems that when retrieving the image using com.lowagie.text.Image.getInstance(URL), the redirects on the URL are not being followed. How can I output an image from a redirected URL using iText?

Answer:
Is there a reason you have to get this using the URL??  Do you have to match the image that the url is pointing to?  What if it changes or gets removed?
I am not sure of your requirement, but it may be easier to save the image from the url and place it somewhere within your project.  Then you can add it to your pdf with:
```
```
Image.getInstance("yourimage.gif");
```
```


Question:
Okay i am working on someone elses code. They do alot of this:

char description[256];
description[0]=0;

I know this would put a \0 in the first spot of the character array. But is this even a safe way to erase a string?

Also visual studio keeps reporting memory leaks, and i've pretty much tied this done to the strings that are used.

Ps. Yes i know about std::string, yes i use that. This isn't my code.

Answer:
This string is allocated on the stack, so there's no way to free the memory it uses until the function that it's called in returns (when it will happen automatically). Unless you're calling this function recursively*, there's no way this will end up being a memory leak, because once the function returns the space is used for future stack frames. And if you're concerned about security, you should just loop through and zero out the elements of the string.
If you want a free()-able memory block, you could do the following and allocate the array on the heap:
```
```
char *str = malloc(256*sizeof(char)); // str now is a pointer to a 256-char array
...
// some code here
...
free(str); // free the memory
```
```
*this is not an acutal memory leak, but some people say "memory leak" when they mean "run out of memory". In any case, stack space is much more limited than heap space, so you have to watch the size of memory blocks you use there.


Question:
Is there an Iterator implementation that merges multiple iterators?

class MergedIterator<T> implements Iterator<T>
{
     MergedIterator(Iterator<T>... iters)
     ....
}

And the next method should move on to iters[1] when !iters[0].hasNext() etc

Answer:
I'd call that a ConcatenatedIterator myself - a MergedIterator should merge the results of several iterators e.g. based on sorting
Naming aside, I'm sure there'll be an implementation in a 3rd party library somewhere. Just off to check
Google collections
...
EDIT: Bingo -
Iterators.concat


Question:
I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don't want it to be restricted to a hardcoded list.
In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do

type(X) in (list, tuple)

but there may be other sequence types I'm not aware of, and no common base class.

-N.

Edit: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.

Answer:
I think what I would do is check whether the object has certain methods that indicate it is a sequence.  I'm not sure if there is an official definition of what makes a sequence.  The best I can think of is, it must support slicing.  So you could say:
```
```
is_sequence = '__getslice__' in dir(X)
```
```
You might also check for the particular functionality you're going to be using.
As pi pointed out in the comment, one issue is that a string is a sequence, but you probably don't want to treat it as one.  You could add an explicit test that the type is not str.


Question:
For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:

.tables
.dump

using the Python sqlite3 API.

Is there anything like that?

Answer:
I'm not familiar with the Python API but you can always use
```
```
SELECT * FROM sqlite_master;
```
```


Question: Is there any way to have a reset button in the SSRS parameter window?

Answer:
No, or i haven't heard how to do it. But you can simulate it.
One way to do this is to create a textbox that has an action set to jump to itself. You can or jump to the default values, or jump to itself with some parameters already assigned.


Question:
I am writing an unit test for a mvc web application that checks if a returned list of anonymous variables(in a jsonresult) is correct. therefore i need to iterate through that list but i cannot seem to find a way to do so.

so i have 2 methods

1) returns a json result . In that json result there is a property called data. that property is of type object but internally it's a list of anonymous variables

2) the method calls method 1 and checks if the returned jsonresult is ok.

if i run the test and i break the debugger i can hover over the result and see the items in it. i just don't find a way to do so in code.(just using a foreach isn't possible because at the point i need it i'm not in the method that created the anonymous method)

Answer:
I think you mean "anonymous type" everywhere you've said "anonymous variable" - but you can still iterate over the list with
```
foreach
```
, just declaring the iteration variable as type
```
object
```
:
```
```
foreach (object o in myList)
{
    // Not sure what you're actually trying to do in here...
}
```
```
If you need to check the contents, you can use the fact that anonymous types override
```
ToString
```
in a useful way. Your test can check the result of projecting each element to a string. Indeed, you could convert your result object to a sequence of strings quite easily:
```
```
var strings = ((IEnumerable) result).Cast<object>.Select(x => x.ToString());
```
```
Then test
```
strings
```
possibly using
```
SequenceEqual
```
.


Question: How do I accomplish text wrapping of table fields in SSRS Report, and proper landscaping when rendering the report to PDF format?

Answer:
To ensure line breaks are inserted correctly, use
```
```
=Replace(Fields!MyField.Value, vbLf, Environment.NewLine)
```
```
Set CanGrow = True.


Question:
If any one can help me with Python code:
If I input a letter, How can I print all the words start with that word?

Answer:
There are many ways of doing this, e.g.:
```
```
words = ["zwei", "peanuts", "were", "walking", "down", "the", "strasse"]
letter = "w"
output = [x for x in words if x[0] == letter]
```
```
The contents of
```
output
```
will be:
```
```
['were', 'walking']
```
```
Some notes:
If the code needs to be
fast
you should put the wordlist in some kind of tree.
If you need more flexibility, you should build a regular expression for matching


Question: I am starting a normal Java SE project and i am planning to use JPA/Hibernate. I was wondering if anyone could enlighten me as to what is considered the best way to interact with Hibernate in this environment (data access layers)?

Answer:
I'm not sure what's considered the best approach to this, but at my workplace, we have based most of our Hibernate interaction on these articles:
Don't let Hibernate steal your identity
and
Generic Data Access Objects
They show you how to make your mapped classes in a smart way, and how to implement a generic DAO that can be reused for any persistent class. This has worked out nicely for us.


Question:
I need to upload a file using C# from a windows mobile app to a website. It's running PHP as the webservice on the other side, though I guess it really doesn't have to if there's another way to be able to get the file up there. There is no server-side ASP support, however. My problem really isn't the PHP, it's the mobile C# code.

Also, System.net.WebClient does NOT exist in the compact framework, so unfortunately, that simple solution is gone.

Let me apologize in advance, because I know this is a relatively commonly asked question, but I just can't seem to find an answer. I've spent an unseemly amount of time on this one particular problem with no solution, so any help at all would be greatly greatly appreciated. Thanks a lot!

Answer:
Have a look at this article
Improving .NET Compact Framework HTTP Communications using HttpWebRequest and Custom ASP.NET Providers
in MSDN. It is specific for ASP technology,
but the Compact Framework remains the same. Basically it uses an HttpWebRequest with a PUT method. If you aren't allowed to do so in the server, you need to create a sequence of POST requests yourself and handle them accordingly.


Question:
Is there a way to query the current DATEFORMAT SQLServer 2005 is currently using with T-SQL?

I have an application that reads pregenerated INSERT-statements and executes them against a database. To make the data to be inserted culture independent I store datetime-values represented in the invariant culture (month/day/year...) . The database server may run under different locales, depending on the system locale (maybe using day/month/year) , so the insert may crash because the datetime cannot be parsed.

I know there are the "SET LANGUAGE" and "SET DATEFORMAT" statements in T-SQL to set the locale to be used.

I do not want to make these changes permanent (are they permanent?), so I'm looking for a way to read the DATEFORMAT from the DB, store it, change the format to my liking and reset it to the stored value after the data has been inserted.

Any ideas where to find that value in the server?

Answer:
Set Language and Set DateFormat only affect the current session.  If you Disconnect from the database and connect again, the language and Dateformat are set back to their default values.
There is a 'trick' you could use to determine if the DateFormat is m/d/y, or d/m/y.
```
```
Select DatePart(Month, '1/2/2000')
```
```
This date is valid either way.  It's Jan 2, or Feb 1.  If this query returns a 1, then you have MDY.  If it returns a 2, you have DMY.


Question:
I have a program in which the user adds multiple objects to a scene. These objects are all represented as a classes.
Now I want the user to be able to save the scenario, so it can be loaded again.

Is there some genereic save method I can use, or do I have to write my own that saves the values of all properties and such and then create new objects and insert the saved values into them when the user loads the scenario again.

/P

Edit: Thanks for the quick replys guys.
I'm actually storing default values for the objects in a SQL compact 3.5 database right now. So if anyone knows how to serialize to SQL, that would be great info.

Edit 2: Thanks again! I'm going to serialize to xml, then store it as a string to the SQL database.

Answer:
Usually one would use a database to do this kind of thing. That's probably the recommended practise.
However if you want a quick and dirty method you can serialise to Xml or Binary with relatively little code. Check out the System.Runtime.Serialization stuff. The trade-off of Xml or Binary is that versioning sucks big time.
Consider a collection of xml files containing objects from your 1.0 app. If you've added fields to those objects since 1.0 then they wont be compatible with any new 1.1 objects. To get around this you have to write a manual update sequence from type 1.0 -> 1.1. Even worse if you use autodiscovery code (which automatically serialises) such as they xml or binary serializer you may even have to name your objects different names Product1 / Product1.1 / etc, it's either that or write your own serialisation code.
If your app starts approaching any level of seriousness I'd say you'll probably want to use a database. SqlLite is very nice and simple for 1 user apps, anything bigger and you'll want a proper RDBMS.


Question:
Access can open DBF (dBase) files, but instead of physically converting the data into MDB format, it has the ability to link to the DBF table itself. This way the DBF is "linked" to the MDB.

Is it possible to attach a DBF file in such manner using C#?

Edit: I would like to use Jet and avoid using MS Access directly.

Answer:
Perhaps this code from
How to quickly copy tables from an ODBC source to MS Access within a C# project
might help:
The VB function you’ll need to put
  into MS Access is quite simple, and
  basically calls the TransferDatabase
  method by passing it a DSN (pointing
  to the source database), a source
  table name and target table name. The
  code is as follows:
```
```
Public Function Import(dsnName As String, sourceTableName As String, targetTableName As String)
‘ if the table already existsm, delete it.
   On Error GoTo CopyTable
   DoCmd.DeleteObject acTable, targetTableName
CopyTable:
   DoCmd.TransferDatabase _
   acImport, _
   "ODBC Database", _
   "ODBC;DSN=" + dsnName, _
   acTable, _
   sourceTableName, _
   targetTableName
End Function
```
```
Changing the VBA to read acLink rather than acImport should allow linking.
And then the C# code:
```
```
object accessObject = null;
try
{
   accessObject = Activator.CreateInstance(Type.GetTypeFromProgID("Access.Application"));

   accessObject.GetType().InvokeMember(
      "OpenCurrentDatabase",
      System.Reflection.BindingFlags.Default  System.Reflection.BindingFlags.InvokeMethod,
      null,
      accessObject,
      new Object[] { "AccessDbase.mdb" });

   accessObject.GetType().InvokeMember(
      "Run",
      System.Reflection.BindingFlags.Default  System.Reflection.BindingFlags.InvokeMethod,
      null,
      accessObject,
      new Object[] { "Import", "DSN Name", "Source table name", "Target table name" });

   accessObject.GetType().InvokeMember(
      "CloseCurrentDatabase",
      System.Reflection.BindingFlags.Default  System.Reflection.BindingFlags.InvokeMethod,
      null,
      accessObject,
      null);

   MessageBox.Show("Copy succeeded.");
}
catch (Exception ex)
{
   string message = ex.Message;
   while (ex.InnerException != null)
   {
      ex = ex.InnerException;
      message += "\r\n----\r\n" + ex.Message;
   }
   MessageBox.Show(message);
}
finally
{
   if (accessObject != null)
   {
      System.Runtime.InteropServices.Marshal.ReleaseComObject(accessObject);
      accessObject = null;
   }
}
```
```
Edit re comments
I cannot help with c#, but here is some VBScript that links a table from
one MDB to another.
```
```
strLinkFile = "C:\Docs\Link.mdb"
strAccessFile = "C:\Docs\LTD.mdb"

'Create Link... '
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
       "Data Source=" & strAccessFile & ";" & _
       "Persist Security Info=False"

Set adoCat = CreateObject("ADOX.Catalog")
Set adoCat.ActiveConnection = cn

Set adoTbl = CreateObject("ADOX.Table")

Set adoTbl.ParentCatalog = adoCat
adoTbl.Name = "LinkTable"

adoTbl.properties("Jet OLEDB:Link Datasource") = strLinkFile
adoTbl.properties("Jet OLEDB:Link Provider String") = "MS Access"
adoTbl.properties("Jet OLEDB:Remote Table Name") = "Table1"
adoTbl.properties("Jet OLEDB:Create Link") = True

'Append the table to the tables collection '
adoCat.Tables.Append adoTbl
```
```
It is modified from:
http://support.microsoft.com/kb/240222


Question:
This question exists because it has
  historical significance, but it is not
  considered a good, on-topic question
  for this site, so please do not use it
  as evidence that you can ask similar
  questions here.

More info: https://stackoverflow.com/faq

Anyone knows if it's possible to find all A records, CNAME or subzone records configured for a domain name?

For example, domain.com:

www IN CNAME domain.com.
subdomain1 IN CNAME domain.com.
subdomain2 IN CNAME domain.com.

subdomain1 IN A 123.4.56.78.
subdomain2 IN A 123.4.56.79.

I want to keep a sub-domain private where I'll run an admin application (it will be password protected and on a special port, but I would prefer to keep it as private as possible).

Answer:
It used to be possible with:
```
```
host -a -l domain.com
```
```


Question:
I wanted to pass calendar1.Selecteddate in a query string from gridview in one page to another gridview (I have written sqlquery in that gridview) in another page. As seen in the below code I tried passing it but this did not work. Can anyone tell me how to pass the selected date from calendar in query string

      <asp:HyperLinkField DataNavigateUrlFields="LocalIP"
                DataNavigateUrlFormatString="DailyResults.aspx?
           Terms={0}&column=LocalIP&
               startdate=Calendar1.SelectedDate.Date.Date.ToShortDateString()
                DataTextField="LocalIP" HeaderText="User" />

Answer:
In the example you've provided it would treat that calendar part of the string as a literal and pass the exact value you have typed.
In order to obtain the data using you would need to do something similar to:
```
```
<asp:HyperLinkField DataNavigateUrlFormatString="<%=GetSelectedDate()%>....
```
```
where this is a method on the code behind class (or you could use a property) that creates the string you intend, including the {0} placeholder for the LocalIP bound data field.


Question:
I am writing a QT application and I need to embed a terminal (we say,xterm) within a QDialog, like some KDE application (see kdevelop/kate/...).

I've been trying with:
- QX11EmbedContainer placed into the QLayout of my QDialog
- QProcess for the program I want to excecute

I expect the QProcess running within the QX11EmbedContainer, but it does not work.

The problem is that I can't put the xterm into the QX11EmbedContainer, the only thing I obtain is an xterm window (unfortunately separated from my QDialog).
Does anybody got the same problem?

Answer:
You need to pass the window ID of the container to the xterm.
If you look at the example in the Qt help for QX11EmbedContainer,  it just passes the window id to the QProcess. Change this to
```
```
QProcess process(&container);
 QString executable(app.arguments()[1]);
 QStringList arguments;
 arguments << "-into" << QString::number(container.winId());
 process.start(executable, arguments);
```
```
where "-into" has been added to the arguments. From the XTerm man page:
-into windowId
Given an X window identifier (a decimal integer), xterm
    will reparent its top-level shell
    widget to that window.  This is  used
    to embed xterm within other applications.


Question:
I'm using SQL Server 2005 and the the Dynamic Management View sys.dm_db_missing_index_details. It continues to tell me that Table1 really needs an index on ColumnX and ColumnY, but that index already exists! I've even dropped and re-created it a couple times to no avail.

More specifics: The view lists Column1 under equality_columns.  Column2 is listed under inequality_columns, so the index I have created is:

create index IndexA on Table1 (Column1 asc, Column2 asc)

Isn't this exactly the index sys.dm_db_missing_index_details is telling me I need?

Answer:
If you have dropped & created the index, sp_update_stats shouldn't affect it (problem is not with statistics)
Perhaps it's because of the DMV data is obsolete already
Does Actual Execution Plan suggest the Missing Index in SSMS as well?
From
Books Online
Information returned by
  sys.dm_db_missing_index_details is
  updated when a query is optimized by
  the query optimizer, and is not
  persisted. Missing index information
  is kept only until SQL Server is
  restarted. Database administrators
  should periodically make backup copies
  of the missing index information if
  they want to keep it after server
  recycling.
To determine which missing index
  groups a particular missing index is
  part of, you can query the
  sys.dm_db_missing_index_groups dynamic
  management view by equijoining it with
  sys.dm_db_missing_index_details based
  on the index_handle column.


Question:
I cannot figure out a way to disable a container AND its children in Swing. Is Swing really missing this basic feature?

If I do setEnabled(false) on a container, its children are still enabled.

My GUI structure is pretty complex, and doing a traversion of all elements below the container is not an option. Neither is a GlassPane on top of the container (the container is not the entire window).

Answer:
JXLayer
might be what you're looking for, according to
this post
:
Wrap your container with the JXLayer and call
```
JXLayer.setLocked(true)
```
after that - all components inside will be disabled
alt text http://www.java.net/download/javadesktop/blogs/alexfromsun/2007.06.25/LayerDemo.PNG


Question:
Greetings to all!  This is my first question here on stackoverflow.  I have a WPF application that I am writing for the fellow developers in my department, and there are a couple of settings that I need to check for at startup and update if they are not set (one is the location of an executable on the users computer, we all have it, just not in the same place).  So when my app starts up for the first time, I need to pop a filechooser to have them select the location.

What I need to do is write the location of that to the appSettings, but I just can't seem to get it, and I searched Google pretty hard last night trying to find a way to do it.  Most answers I saw involved reading the app.config file as straight XML, and that doesn't seem right.

So, I just need a way to update values in the appSettings for my application.  I can read from them just fine, just haven't figured out how to write to them.  Thanks so much!

James

Answer:
Have you looked into the ConfigurationManager class? It provides a more robust interface to the app.config file and you can do something like this:
```
```
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
oConfig.AppSettings.Settings["PreferenceToRemember"].Value = "NewValue";
oConfig.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("appSettings");
```
```
Just remember to import
```
System.Configuration
```
into your project. It isn't added by default.


Question:
I am using LLBL Gen Pro v2.6 and am attempting to create a means of auditing changes made to the database. Now, I know that LLBL Gen has auditing built into it using AuditorBase and dependency injection. The question I have is; I need to track not only the stuff that LLBL Gen exposes as auditable, but also the User who made the changes. From what I've seen there isn't a built in way of gathering this information. Has anyone used LLBL Gen's built in auditing and determined a way to do this?

Wayne E. Pfeffer

Answer:
I have used LLBLGens Auditing classes. Determining the user is really something that you will have to handle. There are too many variables for LLBLGen to actually do this for you. How are your users handled? Is this a winforms or asp.net application?
The best solution would be to store the UserId in a session variable or static variable depending on which is more appropriate for your application. In your implementation of the Auditing class you can just pull the UserId from its storage place.
Another potential solution would be to override the Entity Class or the Data Adapter classes and pass the UserId in to your save methods. However, this would be a lot more work.


Question:
Need to locate the following pattern:

The letter I followed by a space then three alpha numerics followed by a space

"I ALN "
"I H21 "
"I 31M "

these items are also followed by a lat/lon that is trapped by this expression:

Dim regex As New Regex("\d{6} \d{7}")

Can the expressions be combined to return a match that would look like:

"H21 ###### #######"

Thanks,

Dave

Answer:
```
```
I ([a-zA-Z\d]{3} \d{6} \d{7})
```
```
Match group 1 would contain the three alphanumerics plus the numbers you already catch with your other regex.
EDIT: Does not work because the pattern described in the question does not reflect what the author meant in the first place. What really was meant was first clarified in the comments.


Question:
How to get the last selected item in a .Net Forms multiselect ListBox? Apparently if I select an item in the listbox and then select another 10 the selected item is the first one.

I would like to obtain the last element that I selected/deselected.

Answer:
Not sure I understand the question, but the last selected item will be the last in the SelectedItems array, so something like this should work:
```
```
ListItem i = list.SelectedItems[list.SelectedItems.Length-1];
```
```


Question:
Excuting the line of SQL:

SELECT *
  INTO assignment_20081120
  FROM assignment ;

against a database in oracle to back up a table called assignment gives me the following ORACLE error:
ORA-00905: Missing keyword

Answer:
Unless there is a single row in the
```
ASSIGNMENT
```
table and
```
ASSIGNMENT_20081120
```
is a local PL/SQL variable of type
```
ASSIGNMENT%ROWTYPE
```
, this is not what you want.
Assuming you are trying to create a new table and copy the existing data to that new table
```
```
CREATE TABLE assignment_20081120
AS
SELECT *
  FROM assignment
```
```


Question:
I'm writing a simple .bat file and I've run into some weird behavior.  There are a couple places where I have to do a simple if/else, but the code inside the blocks don't seem to be working correctly.

Here's a simple case that demonstrates the error:

@echo off

set MODE=FOOBAR

if "%~1"=="" (
  set MODE=all
  echo mode: %MODE%
) else (
  set MODE=%~1
  echo mode: %MODE%
)
echo mode: %MODE%

The output I'm getting is:

C:\>test.bat test
mode: FOOBAR
mode: test

Why is the echo inside the code block not getting the new value of the variable?  In the actual code I'm writing I need to build a few variables and reference them within the scope of the if/else.  I could switch this to use labels and gotos instead of an if/else, but that doesn't seem nearly as clean.

What causes this behavior?  Is there some kind of limit on variables within code blocks?

Answer:
You are running into the problem of cmd's static variable expansion. The MODE variable is only evaluated once. You can see this if you omit the @echo off line.
From the set /? documentation:
Finally, support for delayed environment variable expansion has
  been added.  This support is always
  disabled by default, but may be
  enabled/disabled via the /V command
  line switch to CMD.EXE.  See CMD /?
Delayed environment variable expansion is useful for getting around
  the limitations of the current
  expansion which happens when a line of
  text is read, not when it is executed.
  The following example demonstrates the
  problem with immediate variable
  expansion:
```
```
set VAR=before
 if "%VAR%" == "before" (
     set VAR=after
     if "%VAR%" == "after" @echo If you see this, it worked
 )
```
```
would never display the message, since
  the %VAR% in BOTH IF statements is
  substituted when the first IF
  statement is read, since it logically
  includes the body of the IF, which is
  a compound statement.  So the IF
  inside the compound statement is
  really comparing "before" with "after"
  which will never be equal.  Similarly,
  the following example will not work as
  expected:
```
```
set LIST=
for %i in (*) do set LIST=%LIST% %i
echo %LIST%
```
```
in that it will NOT build up a list of
  files in the current directory, but
  instead will just set the LIST
  variable to the last file found.
  Again, this is because the %LIST% is
  expanded just once when the FOR
  statement is read, and at that time
  the LIST variable is empty. So the
  actual FOR loop we are executing is:
```
```
for %i in (*) do set LIST= %i
```
```
which just keeps setting LIST to the
  last file found.
Delayed environment variable expansion
  allows you to use a different
  character (the exclamation mark) to
  expand environment variables at
  execution time.  If delayed variable
  expansion is enabled, the above
  examples could be written as follows
  to work as intended:
```
```
set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "!VAR!" == "after" @echo If you see this, it worked
)

set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%
```
```


Question:
Does anyone know of any C container libraries? I am looking for something which gives standard implementations of linked lists, arrays, hash tables etc, much in the same way as the C++ STL does. Key concerns are:

Client code should be able to create containers for multiple different data types without modifying the library.

The interface for creating and using the containers should be intuitive.

Answer:
Chuck Falconer
has a decent hash library written in C that includes a C++ interface, click on hashlib.zip on the webpage to download.
Ben Pfaff
has very nice and extremely well-documented binary and balanced tree library,
GNU libavl
, that implements most major tree structures including binary search trees, AVL trees, red-black trees and threaded versions of each.
libavl is licensed under the LGPL (as of version 2.0.3), hashlib is GPL.
I'm not sure what you are looking for as far as arrays and linked lists go as the former is supported directly by the language and the latter is generally trivial enough to implement without warranting a library.


Question:
What are the advantages/disadvantages to running time based jobs using:

windows services

Application_BeginRequest to start seperate threads / timers.

One disadvantage of running the jobs in the context of a asp.net web appplication is during .net recycling things will have to be setup again, any others?

Answer:
If you have administrative access to the server, I would either run a Windows Service or a scheduled SQL job depending on what you are trying to achieve.
It is nice to be able to stop/start and log these jobs independent of your web application. Also, if you have problems or errors in the job, it could adversely affect your website.
Finally, you are forcing the web application to go through code at
every
request to see if the timer has elapsed, which is an unnecessary overhead.
As I said to start with, the implementation depends on what the job is. If it is simply to update a number of database records, I'd use a scheduled job in SQL Server. If you need file I/O or access to external services, then a Windows Service might be more appropriate.
It is worth noting that you need to build in your own scheduling and thread safety into Windows Services. An alternative is to build a console application and use an application like
FireDaemon
for the scheduling.


Question: I need to signal a running application (Windows service) when certain things happen in SQL Server (2005). Is there a possibility to send a message from a trigger to an external application on the same system?

Answer:
You can send an email from a trigger, but it isn't a recommended practice becasue if the email ssystem is down, no data changes can be made to the table.
Personally if you can live with less than realtime, I would information about the event you are interested in to another table (so the real change of data can go smoothly even if email is down for some reason.) Then I would have a job that checks that table every 5-10 minutes for any new entries and emails those out.


Question:
My application caches some data on disk.  Because the cache may be large, it should not be stored on a network drive.  It should persist between invocations of the application.  I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.

What is the appropriate location for such a cache?  Is there an API for determining the appropriate location?  How do I call it from Python?

Answer:
Perhaps the
```
tempfile
```
module provides what you need. It uses the Windows Temp directory (which probably is not on a network drive) but you can specify a directory if you want to. Also for security reasons this module should be the right tool - if you use
```
tempfile.mkstemp()
```
the file is readable and writable only by the creating user ID.
Oh. I see you have just edited your question and that you need file persistence between invocations of the app. Then
```
tempfile
```
is not that ideal (even though you could choose not to delete your cache between invocations).


Question:
I've seen this syntax a couple times now, and it's beginning to worry me,

For example:

iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();

Answer:
It's calling a generic method - so in your case, the method may be declared like this:
```
```
public T Create<T>()
```
```
You can specify the type argument in the angle brackets, just as you would for creating an instance of a generic type:
```
```
List<Event> list = new List<Event>();
```
```
Does that help?
One difference between generic
methods
and generic
types
is that the compiler can try to infer the type argument. For instance, if your
```
Create
```
method were instead:
```
```
public T Copy<T>(T original)
```
```
you could just call
```
```
Copy(someEvent);
```
```
and the compiler would infer that you meant:
```
```
Copy<Event>(someEvent);
```
```


Question:
I am working on a tool where I need to convert string values to their proper object types. E.g. convert a string like "2008-11-20T16:33:21Z" to a DateTime value. Numeric values like "42" and "42.42" must be converted to an Int32 value and a Double value respectively.

What is the best and most efficient approach to detect if a string is an integer or a number? Are Int32.TryParse or Double.TryParse the way to go?

Answer:
In terms of efficiency, yes, TryParse is generally the preferred route.
If you can know (for example, by reflection) the target type in advance - but don't want to have to use a big
```
switch
```
block, you might be interested in using
```
TypeConverter
```
- for example:
```
```
DateTime foo = new DateTime(2008, 11, 20);
        TypeConverter converter = TypeDescriptor.GetConverter(foo);
        string s = converter.ConvertToInvariantString(foo);
        object val = converter.ConvertFromInvariantString(s);
```
```


Question:
I'm looking to add support for reading and writing video files in my application.  If you had to choose exactly one file format and codec combination that would satisfy the majority of users, which would you choose:

1) MPEG-4/H.264 (.mp4)
2) AVI/DiVX (.avi)
3) Ogg/Theora (.ogg)
4) Windows Media Video (.wmv)

I'm leaning towards MPEG-4/H.264 given that it is supported in Linux, Mac OS X, the Flash player, iPods, Playstation 3, XBox360, and support is forthcoming in Microsoft Silverlight,and Windows Media Player 12.

Am I missing anything?  Is there something better I could be choosing?

Answer:
It depends on what your application is doing.  If you want to process videos recorded from a video capture card, you'll probably need to be able to read .mpg files with mpeg2 embedded.  A large number of videos use the .avi or .wmv container.  Microsoft is pushing .wmv, but .avi has a lot better support amongst free tools.  Not many tools support .mp4 containers on Windows (Mac is probably different).  H.264, mpeg2, and mpeg4 are my favorite codecs.  H.264 is great quality/bitrate-wise but makes precise and fast seeks hard and is extremely CPU-intensive.  mpeg4 is almost as good as h.264 in terms of quality/bitrate, but it is much less CPU-intensive.  mpeg2 requires many more bits to achieve the same quality, but it's supported pretty much everywhere and it's really easy to decode and seek in those files.
If you don't mind using LGPL code, I'd suggest looking at
ffmpeg
's libavcodec and libavformat.  It'll let you do everything you mention on all platforms (though I'm not sure about Ogg & Theora--I haven't used them).


Question: I am just getting started creating an AJAX application using server side push. I am using Grizzly Comet on Glassfish V2. Almost all the sample applications use IFrames for updating content on the client side. I want to stick to using JavaScript only. Are there any such sample applications (preferably ones that do not use a JavaScript library)?

Answer:
The point about the push is that the HTTP request never ends. Not all client implementations handle that correctly. As I see it, it's possible to do it with pure javascript in Firefox with its extensive API, but the XMLHTTPRequest object would timeout and would not be able to stream you the content.
IFrame is good, you could also try the object tag if its about standard compliance.
Before XMLHTTPRequest and Ajax had no name, we used to get data from the servers through IFrames.


Question:
I am porting some queries from Access to T-SQL and those who wrote the queries used the Avg aggregate function on datetime columns.  This is not supported in T-SQL and I can understand why - it doesn't make sense.  What is getting averaged?

So I was about to start reverse engineering what Access does when it aggregates datetime using Avg, but thought I would throw the question out here first.

Answer:
I'd imagine that Access is averaging the numeric representation of the dates.  You could do similar in T-SQL with the following...
```
```
select AverageDate = cast(avg(cast(MyDateColumn as decimal(20, 10))) as datetime)
from    MyTable
```
```