q:
I have a DataGridView bound to a DataView. The grid can be sorted by the user on any column.

I add a row to the grid by calling NewRow on the DataView's underlying DataTable, then adding it to the DataTable's Rows collection. How can I select the newly-added row in the grid?

I tried doing it by creating a BindingManagerBase object bound to the BindingContext of the DataView, then setting BindingManagerBase.Position = BindingManagerBase.Count. This works if the grid is not sorted, since the new row gets added to the bottom of the grid. However, if the sort order is such that the row is not added to the bottom, this does not work.

How can I reliably set the selected row of the grid to the new row?

[A]
Assuming you have some sort of unique identifier in your data source you could iterate over your collection of rows and compare, as such:
```
```
Dim myRecentItemID As Integer = 3

For Each row As GridViewRow In gvIndividuals.Rows
    Dim drv As DataRowView = DirectCast(row.DataItem, DataRowView)
    If CInt(drv("ItemID")) = myRecentItemID Then
        gvIndividuals.EditIndex = row.RowIndex
    End If
Next
```
```
Hope this helps!


q:
Is there a succinct way to retrieve a random record from a sql server table?

I would like to randomize my unit test data, so am looking for a simple way to select a random id from a table.  In English, the select would be "Select one id from the table where the id is a random number between the lowest id in the table and the highest id in the table."

I can't figure out a way to do it without have to run the query, test for a null value, then re-run if null.

Ideas?

[A]
Is there a succinct way to retrieve a random record from a sql server table?
Yes
```
```
SELECT TOP 1 * FROM table ORDER BY NEWID()
```
```
Explanation
A
```
NEWID()
```
is generated for each row and the table is then sorted by it. The first record is returned (i.e. the record with the "lowest" GUID).
Notes
GUIDs are generated as pseudo-random numbers since version four:
The version 4 UUID is meant for generating UUIDs from truly-random or
  pseudo-random numbers.
The algorithm is as follows:
Set the two most significant bits (bits 6 and 7) of the
  clock_seq_hi_and_reserved to zero and one, respectively.
Set the four most significant bits (bits 12 through 15) of the
  time_hi_and_version field to the 4-bit version number from
  Section 4.1.3.
Set all the other bits to randomly (or pseudo-randomly) chosen
  values.
—
A Universally Unique IDentifier (UUID) URN Namespace - RFC 4122
The alternative
```
SELECT TOP 1 * FROM table ORDER BY RAND()
```
will not work as one would think.
```
RAND()
```
returns one single value per query, thus all rows will share the same value.
While GUID values are pseudo-random, you will need a better PRNG for the more demanding applications.
Typical performance is less than 10 seconds for around 1,000,000 rows — of course depending on the system. Note that it's impossible to hit an index, thus performance will be relatively limited.

s: huggingface

c: devops

d: intermediate


q:
I am trying to rename all the files present in a Windows directory using FOR command as follows at the command prompt:

for %1 in (*.*) do ren %1 test%1

E.g. This renames a file enc1.ctl to testenc1.ctl enc2.ctl  to testenc2.ctl

Thats not what i want. What i want is
enc1.ctl renamed to test1.ctl   enc2.ctl renamed to test2.ctl

How do i do that?

@Akelunuk:
Thanks, that w kind of works but i have files names as

h263_enc_random_pixels_1.ctl , h263_enc_random_pixels_2.ctl which i want to rename to

test1.ctl and test2.ctl respectively

Then how?

[A]
If you know the number of files, (say 10), you can use
```
```
for /L %1 in (1,1,10) do ren enc%1.ctl test%1.ctl
```
```


q:
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.

I'd like to do the equivalent of:

iconv -t utf-8 $file > converted/$file # this is shell code

Thanks!

[A]
You can use the
codecs module
, like this:
```
```
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
```
```
EDIT
: added
```
BLOCKSIZE
```
parameter to control file chunk size.


q:
Trying to debug an issue with a server and my only log file is a 20GB log file (with no timestamps even! Why do people use System.out.println() as logging? In production?!)

Using grep, I've found an area of the file that I'd like to take a look at, line 347340107.

Other than doing something like

head -<$LINENUM + 10> filename | tail -20

... which would require head to read through the first 347 million lines of the log file, is there a quick and easy command that would dump lines 347340100 - 347340200 (for example) to the console?

update I totally forgot that grep can print the context around a match ... this works well. Thanks!

[A]
with GNU-grep you could just say
```
grep --context=10 ...
```


q:
I can reset FPU's CTRL registers with this:

http://support.microsoft.com/kb/326219

But how can I save current registers, and restore them later?

It's from .net code..

What I'm doing, is from Delphi calling an .net dll as an COM module. Checking the Ctrl registers in delphi yield one value, checking with controlfp in the .net code gives another value.
What I need, is in essential is to do this:

_controlfp(_CW_DEFAULT, 0xfffff);

So my floatingpoint calculations in the .net code does not crash, but I want to restore the Ctrl registers when returning.

Maybe I don't? Maybe Delphi is resetting them when needed?
I blogged about this problem here.

[A]
Same function you use to change them:
```
_controlfp()
```
. If you pass in a mask of 0, the current value won't be altered, but it
will
be returned - save it, and use a second call to
```
_controlfp()
```
to restore it later.


q:
Our situation is as follows, but I'm curious about this problem in any situation.

We have a framework consisting of 4 projects:

beans

util

framework

web

We also have modules that need a version and depend on a version of beans and util.

Finally we have a customer project that consists of a specific version of the core projects and one or more modules.

Is there a standard way to version these projects?

What seems simple to me is becoming really complicated as we try to deliver releases to QA and then manage our ongoing development with the maintenance of the release (release = tag and possible branch).

I kind of prefer the following:

1.2.0 - major and minor versions + release.

1.2.1 - next release

1.2.0_01 - bug fix in 1.2.0 release (branch)

etc.

Any ideas?

[A]
There are no standard version number systems. Common themes are to have a major, minor and build number, and occasionally a point number as well (1.2.2.1 for example, for version 1.2 point release 2 build 1). The meaning of the version numbers is highly flexible. A frequent choice is to have backwards compatibility between minor versions or point releases though.
Releases are probably best done by labeling a set of source controlled files as long as your source control allows this. Recreating a release is then as simple as syncing to the label and building, which is very useful :)


q:
I'm about to inherit a rather large Java enterprise project that has a large amount of third party dependencies. There is at least seventy JARs included and some of them would seem to be unused e.g. spring.jar which I know isn't used.

It seems that over the years as various developers have touched upon the code base they have all tried out new project-of-the-month type libraries.

How does one go about getting rid of these? Within reason of course, as clearly some dependencies are helpful to not have to re-invent the wheel.

I'm obviously interested in java based projects but I'm welcome to answers across languages that people think will be helpful.

[A]
Personally, I think you have to start by assessing the scale of the problem.  It's going to be fairly painful, but I'd make a list of the dependencies and work out exactly which parts of the project use which ones.
Then I'd work out exactly what features of each you're actually making use of (in many cases, you'll end up having a massive third party library which you're using a tiny part of).
Once you have this information, you'll at least know what you're dealing with.
My next step would be to look at all of the dependencies that you only use to a small extent.  Checking around might uncover things that you could use from other libraries that would eliminate the lesser used libraries.
I'd also have a look around to see if there's anything small that you could just re-write and include in your own code-base.
Finally, I'd have a look around at the vendors of your dependencies and their competitors to see if the latest versions contain more functionality that will allow you to eliminate a few others.
Then you're just left wondering whether it's better to be highly dependent on a few vendors, or less dependent on a lot of vendors!!  ;o)


q:
How do I change the Read-only file attribute for each file in a folder using c#?

Thanks

[A]
```
```
foreach (string fileName in System.IO.Directory.GetFiles(path))
{
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);

    fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
    // or
    fileInfo.IsReadOnly = true;
}
```
```


q:
I have around 25 worksheets in my workbook (Excel spreadsheet).
Is there a way I can protect all the 25 worksheets in single click ? or this feature is not available and I will have to write a VBA code to accomplish this. I need very often to protect all sheets and unprotect all sheets and doing individually is time consuming

[A]
I don't believe there's a way to do it without using VBA.  If you are interested in a VBA solution, here is the code:
```
```
Dim ws as Worksheet
Dim pwd as String

pwd = "" ' Put your password here
For Each ws In Worksheets
    ws.Protect Password:=pwd
Next ws
```
```
Unprotecting is virtually the same:
```
```
Dim ws as Worksheet
Dim pwd as String

pwd = "" ' Put your password here
For Each ws In Worksheets
    ws.Unprotect Password:=pwd
Next ws
```
```


q:
I have been asking myself this question for a long time now. Thought of posting it. C# doesn't support Multiple Inheritance(this is the fact). All classes created in C# derive out of 'Object' class(again a fact).

So if C# does not support Multiple inheritance, then how are we able to extend a class even though it already extends Object class?

Illustating with an example:

class A : object - Class A created.

class B : object - Class B created.

class A : B - this again is supported. What happens to the earlier association to object.

We are able to use object class methods in A after step 3. So is the turned to multi level inheritance. If that is the case, then

class A : B

class C : B

class A : C - I must be able to access class B's methods in A. Which is not the case?

Can anyone please explain?

[A]
You're confusing mutliple inheritance with an inheritance tree.  You can inherit from something other than Object.  It's just that Object is sitting way up there at the top of your tree.  And someone can inherit your class, but because Object is still up there at the top that class will also inherit from object.  Your "Multi-level" inheritance is not multiple inheritance.
Multiple inheritance is when you inherit from two different trees, and .Net actually does support this after a fashion via interfaces.


q:
Is it possible to change the language of system messages from PostgreSQL?

In MSSQL for instance this is possible with the SQL statement SET LANGUAGE.

[A]
```
```
SET lc_messages TO 'en_US.UTF-8';
```
```
More info on requirements and limitations
here
.


q:
I'm trying to build a similar 'slider' as demoed here http://ui.jquery.com/repository/real-world/product-slider/ but I'm trying to use interior divs inside of the list items (<li>).  it seems as if this demo breaks if you're not using an image or block element (<p>,<div>,etc.)

Anyone have any quick solutions to this?  I basically want to use text and possibly images inside of a <div> instead of using images.

I did find jCarousel which seems as if it works, but I was looking for something a little more lightweight?  Any ideas?

[A]
I think I
sort of
have a working example of what you're trying to do, but there are a couple issues.
Using the example you posted as a base, you can replace the HTML markup of the LI's in a UL to be DIV's in a container DIV. For example:
```
```

Some text!

Some text!

Some text!

            ...

```
```
Then you modify the jQuery code in the page to target that container DIV instead of the UL:
```
```
window.onload = function () {
        var container = $('div.sliderGallery');
        var divThatGetsCropped = $('div.div-that-gets-cropped', container);
        var itemsWidth = divThatGetsCropped.innerWidth() - container.outerWidth();
        $('.slider', container).slider({
            minValue: 0,
            maxValue: itemsWidth,
            handle: '.handle',
            stop: function (event, ui) {
                divThatGetsCropped.animate({'left' : ui.value * -1}, 500);
            },
            slide: function (event, ui) {
                divThatGetsCropped.css('left', ui.value * -1);
            }
        });
    };
```
```
Then you have some non-trivial CSS changes to make...  The original example relied on the LI's being styled to display: inline, inside of a container with overflow hidden. It's going to be a headache to try to get everything to show up correctly if you just style these "text-and-images-chunk" DIV's to be displayed inline. You probably want to float them all.
BUT
, floated elements won't play very nicely with the container "div-that-gets-cropped" DIV because of the way it's being "revealed" by the "sliderGallery" DIV (at least that's what I'm experiencing in Firefox 3.03). I got around this by setting a really big width for the "div-that-gets-cropped" DIV (10000 px):
```
```
.sliderGallery div.div-that-gets-cropped {
          position: absolute;
          list-style: none;
          overflow: none;
      white-space: nowrap;
      padding: 0;
          margin: 0;
          width: 10000px;
        }

        .sliderGallery div.div-that-gets-cropped div.text-and-images-chunk {
      float: left;
      margin-right: 24px;
        }
```
```
And you'll have to tweak the "left" values for .slider-lbl1, .slider-lbl2 to match up whatever the widths end up being (this might be tricky if the size of your text ends up changing the width of the "text-and-images-chunk" elements).
The one issue I noticed is that when you have the images in a block-level element, there isn't a good way to get them to "hug" the bottom, as they do in the example using inline. You might be able to get this working by playing around with the positioning of the elements (I couldn't), but hopefully this won't be a big deal in your specific usage.
All of that said, jCarousel seems like it's
intended for exactly what you're doing
, even if it does add a little code bulk.


q:
I want to display the results of a searchquery in a website with a title and a short description. The short description should be a small part of the page which holds the searchterm. What i want to do is:
1 strip tags in page
2 find first position of seachterm
3 from that position, going back find the beginning (if there is one) of that sentence.
4 Start at the found position in step 3 and display ie 200 characters from there

I need some help with step 3. I think i need an regex that finds the first capital or dot...

[A]
The way I would do it is, I would parse the page...
Skip over all the things starting with '<'
When you encounter a "." or [A-Z], start putting it into a buffer till you find another "."
If the buffered string has the search keyword, thats your string! Else. start buffering at the "." you encountered and repeat.
EDIT: As James Curran pointed out, this strategy would fail in some cases... So heres the solution:
What you can do, is to start X number of characters from start of page (after tags)
and then search for your keyword, buffering 2 previous words. When you find it,
do something like this:
{X} ... {prev-2}  {next-2}
Example:
This planet has - or rather had - a problem, which was this: most of the people living on it were unhappy for pretty much of the time. Many solutions were suggested for this problem, but most of these were largely concerned with the movement of small green pieces of paper, which was odd because on the whole it wasn't the small green pieces of paper that were unhappy.
Search Keyword: "suggested"
Result:
This planet has - or rather had - a problem ... Many solutions were
suggested
for this problem...


q:
I often need to design a dialog in Delphi/C++Builder that allows various properties of an object to be modified, and the code to use it typically looks like this.

Dialog.Edit1.Text := MyObject.Username;
Dialog.Edit2.Text := MyObject.Password;
// ... many more of the same

if (Dialog.ShowModal = mrOk)
begin
  MyObject.Username := Dialog.Edit1.Text;
  MyObject.Password := Dialog.Edit2.Text;
  // ... again, many more of the same
end;

I also often need similar code for marshalling objects to/from xml/ini-files/whatever.

Are there any common idioms or techniques for avoiding this kind of simple but repetitive code?

[A]
Delphi at least have 'With', though it doesn't solve the problem completely.
```
```
if (Dialog.ShowModal = mrOk)
begin
  with MyObject do
  begin
    Username := Dialog.Edit1.Text;
    Password := Dialog.Edit2.Text;
    // ... again, many more of the same
  end;
end;
```
```
And builder AFAIK has nothing alike.


q:
I found this:

http://www.evolt.org/failover-database-connection-with-php-mysql

and similar examples. But is there a better way?

I am thinking along the lines of the Automatic Failover Client in the MS SQL Native Client.

[A]
No, it does not have that build in. I think an easy way is to employ
MySQL Proxy
. Otherwise, but the
logic
(
```
if (fails) { connect to another }
```
) in your application, but that's not so pretty and great in terms of performance.


q:
We have a custom collection of objects that we bind to a listbox control. When an item is added to the list the item appears in the listbox, however when one selects the item the currency manager position will not go to the position. Instead the currency manager position stays at the existing position. The listbox item is high lighted as long as the mouse is press however the cm never changes position.

If I copy one of the collection objects the listbox operates properly.

One additional note the collection also has collections within it, not sure if this would be an issue.

[A]
Collections don't have a sense of "current item". Perhaps your custom collection does, but the
```
ListBox
```
is not using that. It has its own "current item" index into the collection. You need to handle
```
SelectedIndexChanged
```
events to keep them in sync.


q:
I wish to search a database table on a nullable column.  Sometimes the value I'm search for is itself NULL.  Since Null is equal to nothing, even NULL, saying

where MYCOLUMN=SEARCHVALUE

will fail.  Right now I have to resort to

where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL))

Is there a simpler way of saying that?

(I'm using Oracle if that matters)

[A]
Try
```
```
WHERE NVL(mycolumn,'NULL') = NVL(searchvalue,'NULL')
```
```


q:
I'm architecting a new app at the moment, with a high read:write ratio. At my current employer we have lots of denormalised data on our tables for performance reasons. Is it better practice to have totally 3NF tables and then use indexed views to do all the denormalisation? Should I run queries against the tables or views?

An example of some of the things I am interested are aggregates of columns child tables (e.g. having user post count stored somewhere).

[A]
From your description, if you're looking for a pattern that matches better than Factory, try Strategy:
Strategy Pattern
Your
context
could be a custom class which encapsulates and abstracts the different report inputs (you could use the AbstractFactory pattern for this part)
Your
strategy
could implement any number of different query filters or additional logic needed.  And if you ever need to change the system in the future, you can switch between report tools by simply creating a new strategy.
Hope that helps!


q: I installed wxWidgets 2.8.9 on a Windows XP SP2 box and built the library according to the directions and now I'm trying to get the Hello World! tutorial app to build from within Eclipse and I'm just missing something apparently.  Any idea how to get Cygwin, Eclipse and wxWidgets to play nice together?

[A]
This
answer
was posted by Lars Uffmann to the comp.soft-sys.wxwindows newsgroup.  In a nutshell:
Add c:/cygwin/usr/local/bin to the path in the Eclipse project configuration
Add ``wx-config --cxxflags`‘ to the GCC C++ Compiler command
Move the ${FLAGS} variable to the
end of the GCC C++ Linker Command
Line Pattern
Add ``wx-config --libs`‘ to the GCC
C++ Linker flags.
Thank goodness for Mr. Uffmann sharing this information; this problem has been giving me headaches for days.
EDIT: Note that there is a literal backtick at each end of the wx-config strings.  The method of escaping the backtick doesn't seem to work correctly. Refer to the linked answer for more details on exact syntax.


q:
In our industrial automation application, we need to capture and display the data in the milliseconds.

We have data binding between data grid control and a DataTable object. We have around three hundred records which needs to be display in the grid. So we update the 300 records every time we get the records.

Example

       TabularViewTable tvt = _presenter.WorkItem.Items.Get<TabularViewTable> ("TabularViewTable");

        foreach (DataRow row in tvt.Rows)
        {
            row["Value"] = GetDataFast(row["Name"]);
        }

After connecting 10 devices, the CPU usage goes 15%. How to improve the performance using DataTable or using some custom data source

Regards,

Krishgy

[A]
You should seriously reconsider your user interface:
Is it really necessary to display 300 values? Ordinary human cannot concentrate on more than 7 things simultaneously,
Even if you lower number of parameters, there is frequency of refresh that seems to high to be practical.
You probably should do following:
create a dashboard with graphical representation of most important data (graphs, gauges, ...)
create drill down forms and reports, so that user can see what happened with system in any given period


q:
I want to use regular expressions (Perl compatible) to be able to find a pattern surrounded by two other patterns, but not include the strings matching the surrounding patterns in the match.

For example, I want to be able to find occurrences of strings like:

Foo Bar Baz

But only have the match include the middle part:

Bar

I know this is possible, but I can't remember how to do it.

[A]
Parentheses define the groupings.
```
```
"Foo (Bar) Baz"
```
```
Example
```
```
~> cat test.pl
$a = "The Foo Bar Baz was lass";

$a =~ m/Foo (Bar) Baz/;

print $1,"\n";
~> perl test.pl
Bar
```
```


q:
I'm passing /file:c:\myfile.doc and I'm getting back "/file:c:\myfile.doc" instead of "C:\myfile.doc", could someone please advise where I am going wrong?

            if (entry.ToUpper().IndexOf("FILE") != -1)
            {
                //override default log location
                MyFileLocation = entry.Split(new char[] {'='})[1];
            }

[A]
You are splitting on "=" instead of ":"
Try
```
```
if (entry.ToUpper().IndexOf("FILE:") == 0)
    {
         //override default log location
         MyFileLocation location = entry.Split(new char[] {':'},2)[1];
    }
```
```


q:
Given the following HTML:

<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>

How do I grab the string "displayed text 1" using Javascript/the DOM?

[A]
The displayed text is a child node of the option node.  You can use:
```
```
myOptionNode.childNodes[0];
```
```
to access it, assuming the text node is the only thing inside the option (and not other tags).
EDIT:
Oh yeah, as others mentioned, I completely forgot about:
```
```
myOptionNode.text;
```
```


q:
When I get a java.io.InvalidClassException, it gives me the serialVersionUID that it wants, and the serialVersionUID that it got.  Is there an easy way to tell which of my dozens of jars using the wrong serialVersionUID?

Update: I should mention that our intention is to update everything at the same time, but I'm trying to debug a problem in our build and deploy process.

[A]
The best way to deal with this kind of trouble is to update jars on the server and client side at the same time. This will guarantee the same version of your classes on both sides and you'll not have trouble when serializing / deserializing. Tracking serial UIDs each time you have this problem is not going to solve anything, you're only going to waste considerable time and resources. Its much better to spend some time and implement a proper deployment / packaging strategy.
If you really don't have any other choice, you can write a tool that loads a class from each jar (using a URLClassLoader) and then use
```
java.io.ObjectStreamClass.getSerialVersionUID()
```
to obtain the information you need.


q:
I am hoping to find a way to do this in vb.net:

Say you have function call getPaint(Color).  You want the call to be limited to the parameter values of (red,green,yellow). When they enter that parameter, the user is provided the available options, like how a boolean parameter functions.

Any ideas?

[A]
Hope I am not missing something from your question. Use an enumeration like this:
```
```
Enum Color
    Red = 1
    Green = 2
    Yellow = 3
End Enum
```
```
When you write
```
getPaint(Color
```
followed by a . (period) the Intellisense system will automatically suggest the three options declared in the enumeration (Red, Green, Yellow).


q:
Quite a few comments to answers in a different post, Where are the best locations to write an error log in Windows?, gave me the impression that a lot of things regarding standard folders (%APPDATA%; %TEMP%) in Windows Vista are different from Windows XP, which should of course be taken into account when developing software that will have to run under Windows  at some point.

But in my company, I do not see that happen in this decade, and maybe not in the next either. I mean, the central IT deployed SP2 only eight months ago, and any question about SP3 is met with disregard (well, if you're lucky...)

So what is your advice? Should I rewrite two modules in my current project to make them ready for Windows Vista, or should I not bother about it at all, until it is really needed?

[A] Is your company going to upgrade to Windows Vista at all? A lot of companies are ignoring Windows Vista and are planning to upgrade to the next Windows version when it comes out in the hopes that it will suck less than Windows Vista. If this is the case, it would be a complete waste of time.  Who knows what will change in the next version of Windows. It is better to rewrite once for the new Windows than to rewrite once for Windows Vista and then again for the next Windows version.


q:
How can I create a custom property for my .Net assembly which would then be visible under the Details tab in Windows explorer?

Something to sit parallel with "File Description", "Type", "Product Version"... etc

Update: To quote my comment to Lars ... "Whilst I would have liked to do this from within Visual studio, that is certainly not my priority. Actually I hope to integrate any solution into an existing nant build process. So affecting the assemblies post compile is entirely acceptable. Have you ever heard of such a tool?"

Further Update: I'm not sure if what I'm talking about is an attribute or not, to clarify a little what I would like to creat in an entry in the following property page...

[A]
Its not the answer yet, but one 1/2 way hack is to use:
```
```
[assembly: AssemblyDescription("One Line of Content Here")]
```
```
And that shows up under "Comments".
(still researching, this is something I've wanted for a while.)


q:
Can pipes be used across LAN computers?

In particular I'm looking for Windows, but if you have more info on other platforms, that will also help others who find this thread later.

[A]
Yes they can.
Named pipes can be used to provide
  communication between processes on the
  same computer or between processes on
  different computers across a network.
  If the server service is running, all
  named pipes are accessible remotely
http://msdn.microsoft.com/en-us/library/aa365590.aspx


q:
We are using a WCF service layer to return images from a repository.  Some of the images are color, multi-page, nearly all are TIFF format.  We experience slowness - one of many issues.

1.) What experiences have you had with returning images via WCF
2.) Do you have any suggestions tips for returning large images?
3.) All messages are serialized via SOAP correct?

4.) Does wcf do a poor job of compressing the large tiff files?

Thanks all!

[A]
In a previous project I worked we had a similar issue. We had a Web Service in C# that received requests for medias. A media can range from files to images and was stored in a database using BLOB columns. Initially the web method that handled media retrieval requests read the chunk from the BLOB and returned in to the caller. This was one round trip to the server. The problem with this approach is that the client has no feedback of the progress of the operation.
There is no problem in computer
  science that cannot be solved by an
  extra level of indirection.
We started by refactoring the method in three methods.
Method1
setup the conversation between caller and the web service. This includes information about the request (like media Id) and capabilities exchange. The web service responded with a ticked Id which is used for the caller for future requests. This initial call is used for resource allocation.
Method2
is called consecutively until there is more that to be retrieved for the media. The call includes information about the current offset and the ticked Id that was provided when
Method1
was called. The return updates the current position.
Method3
is called to finish request when
Method2
reports that the reading of the request media has completed. This frees allocated resources.
This approach is practical because you can give immediate feedback to the user about the progress of the operation. You have a bonus that is to split the requests to
Method2
in different threads. The progress than can be reported by chunk as some BitTorrent clients do.
Depending on the size of the BLOB you can choose to load it from the database on one go or
reading it also by chunks
. This means that you could use a balanced mechanism that based on a given watermark (BLOB size) chooses to load it in one go or by chunks.
If there is still a performance issue consider packaging the results using
GZipStream
or read about
message encoders
and specifically pay attention to the binary and Message Transmission Optimization Mechanism (MTOM).


q:
I am getting ready to completely overhaul my web server. I use it for both development and to present product to clients. It also hosts my company website.  I will be loading MS Server 2008 and MS SQL 2008. I want it to have the latest .NET Framework as well as the latest MVC templates. I want it to use SubSonic. I also want to start using some sort of SourceSafe (or whatever a good one is).I plan to use VS 2008 as my development tool.

I figure there are a lot of people out there who have recently gone through this and will have good suggestions.

It is a good stout machine with lots of memory and storage, so, please let me know anything that will help me become a better developer.

Scott and the Dev Team

[A]
Well, sounds like you've already got a good list going. Though I'd recommend against SourceSafe.
See here for details
. SubVersion is a free alternative. Or perhaps git or something like that if you're up for a challenge.
[edit to add]
If you can afford it, TFS is a nice product that gives you bug tracking, version control, and a build environment. All of those will help you be a better developer.
To pimp one of this site's founders, check out the
Joel Test
and see what you should implement.


q: If I have a native C++ windows program (i.e. the entry point is WinMain) how do I view output from console functions like std::cout?

[A]
Since there's no console window, this is
impossible
difficult. (Learn something new every day - I never knew about the console functions!)
Is it possible for you to replace your output calls?  I will often use TRACE or OutputDebugString to send information to the Visual Studio output window.


q:
I have a Java array such as:

String[] arr = new String[] {"123","doc","projectReport.doc"};

In my opinion the natural way to access would be:

 #set($att_id = $arr[0])
 #set($att_type = $arr[1])
 #set($att_name = $arr[2])

But that it is not working. I have come with this workaround. But it a bit too much code for such an easy task.

#set($counter = 0)
#foreach($el in $arr)
    #if($counter==0)
        #set($att_id = $el)
    #elseif($counter==1)
        #set($att_type = $el)
    #elseif($counter==2)
         #set($att_name = $el)
    #end
    #set($counter = $counter + 1)
#end

Is there any other way?

[A]
You could wrap the array in a
```
List
```
using
```
Arrays.asList(T... a)
```
.  The new List object is backed by the original array so it doesn't wastefully allocate a copy.  Even changes made to the new List will propagate back to the array.
Then you can use
```
$list.get(int index)
```
to get your objects out in Velocity.
If you need to get just one or two objects from an array, you can also use
```
Array.get(Object array, int index)
```
to get an item from an array.


q: If I have added/removed/modified a large number of files in my local ClearCase view, how can I be certain that all the files have been added to source control?

[A]
Use
```
cleartool ls -view_only -r
```
from the your local view VOB directory.
To add any files recursively to source control that are only in the local view, see
How can I use ClearCase to “add to source control …” recursively?
.


q:
Eg.

ConnectionDetails cd = new ConnectionDetails ();
cd.ProviderName = "System.Data.OleDb";
cd.DataSource = "serverAddress";
cd.Catalog = "database";
cd.UserId = "userId";
cd.Password = "password";

string connectionString = cs.CreateConnectionString();
// Should return:
// "Provider=SQLOLEDB;Data Source=serverAddress;Initial Catalog=database;User Id=userId;Password=password;"

I'd write my own class but I'm not sure how to retrieve a connection string provider property (SQLOLEDB in this example) programmatically from an invariant db provider name (System.Data.OleDb).

Edit:

You can do a

DbProviderFactories.GetFactory("System.Data.OleDB").CreateConnectionStringBuilder()

But the DBConnectionStringBuilder that is returned still doesn't know it's connection string provider property, even though in this case it the derived class has a "Provider" property.

[A]
The closest thing I know of is
DbConnectionStringBuilder
.
Because the properties required by different providers vary, it uses an associative array (name value collection) rather than fixed properties.
So your example would look like
```
```
DbConnectionStringBuilder csb = new DbConnectionStringBuilder();
csb["ProviderName"] = "System.Data.OleDb";
csb["DataSource"] = "serverAddress";
csb["Catalog"] = "database";
csb["UserId"] = "userId";
csb["Password"] = "password";

string connectionString = csb.ConnectionString;
```
```


q:
I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

My specific situation: I have an array defined as shown below:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...

and I need to turn this into a string to pass to $.ajax() like this:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: "{'countries':['ga','cd']}",
...

[A]
I haven't used it but you might want to try the
jQuery plugin written by Mark Gibson
It adds the two functions:
```
$.toJSON(value)
```
,
```
$.parseJSON(json_str, [safe])
```
.


q:
I want to be able to do the following:

$normal_array       = array();
$array_of_arrayrefs = array( &$normal_array );

// Here I want to access the $normal_array reference **as a reference**,
// but that doesn't work obviously. How to do it?
end( $array_of_arrayrefs )["one"] = 1; // choking on this one

print $normal_array["one"]; // should output 1

Regards

/R

[A]
The line:
end( $array_of_arrayrefs )["one"] = 1; // choking on this one
throws a parse error:
Parse error: syntax error, unexpected '[' in /file.php on line 65
Make sure you have
```
error_reporting
```
and
```
display_error
```
activated.
I'm not sure what you want to do but this works:
```
```
$normal_array       = array();
$array_of_arrayrefs = array( &$normal_array );
// Here I want to access the $normal_array reference **as a reference**,
// but that doesn't work obviously. How to do it?
$array_of_arrayrefs[0]["one"] = 1;
//end($array_of_arrayrefs )["one"] = 1; // choking on this one
print $normal_array["one"]; // should output 1
```
```


q:
I have an XML file loaded into a DOM document,
I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via

$element = $dom->getElementsByTagName('foo')->item(0);
foreach($element->childNodes as $node){
    $data[$node->nodeName] = $node->nodeValue;
}

However, what I'm trying to do, is from an XML like,

<stuff>
  <foo>
    <bar></bar>
      <value/>
    <pub></pub>
  </foo>
  <foo>
    <bar></bar>
    <pub></pub>
  </foo>
  <foo>
    <bar></bar>
    <pub></pub>
  </foo>
  </stuff>

iterate over every foo tag, and get specific bar or pub, and get values from there.
Now, how do I iterate over foo so that I can still access specific child nodes by name?

[A]
Not tested, but what about:
```
```
$elements = $dom->getElementsByTagName('foo');
$data = array();
foreach($elements as $node){
    foreach($node->childNodes as $child) {
        $data[] = array($child->nodeName => $child->nodeValue);
    }
}
```
```


q:
Is it possible to define a class in C# such that

class GenericCollection<T> : SomeBaseCollection<T> where T : Delegate

I couldn't for the life of me accomplish this last night in .NET 3.5. I tried using

delegate, Delegate, Action<T> and Func<T, T>

It seems to me that this should be allowable in some way. I'm trying to implement my own EventQueue.

I ended up just doing this [primitive approximation mind you].

internal delegate void DWork();

class EventQueue {
    private Queue<DWork> eventq;
}

But then I lose the ability to reuse the same definition for different types of functions.

Thoughts?

[A]
A number of classes are unavailable as generic contraints - Enum being another.
For delegates, the closest you can get is ": class", perhaps using reflection to check (for example, in the static constructor) that the T
is
a delegate:
```
```
static GenericCollection()
{
    if (!typeof(T).IsSubclassOf(typeof(Delegate)))
    {
        throw new InvalidOperationException(typeof(T).Name + " is not a delegate type");
    }
}
```
```


q: Is there a CIL instruction to exchange the first two elements in the stack?

[A]
There is no single instruction exchange. However, using
stloc
,
pop
, and
ldloc
, you should be able to accomplish your exchange.


q:
In my project I have a class that is inherited by many other classes. We'll call it ClassBase.

public class ClassInheritFromBase : ClassBase

When ClassBase is being inherited, ReSharper throws an "Ambiguous reference" warning on the ClassBase, and anything inside the new class that inherited from ClassBase does not have IntelliSense and gets warnings that it cannot find it.

The project compiles and runs fine.

If I change the namespace ClassBase is in and then change the inheriting classes, they find it fine and ReSharper has no problem, IntelliSense works ... until it is compiled. After the compile it goes back to having the ambiguous reference warnings and everything else.

Has this been seen before and how can it be fixed? I saw an entry in JetBrains bug tracking for an issue just like this, but they closed it as unable to reproduce.

[A] I've seen this bug in ReSharper 4.1. It happens when the base class is in the App_Code directory. I don't know how to fix it; it is very annoying, but the code still compiles though.


q:
If I have the following Linq code:

context.Table1s.InsertOnSubmit(t);
context.Table1s.InsertOnSubmit(t2);
context.Table1s.InsertOnSubmit(t3);

context.SubmitChanges();

And I get a database error due to the 2nd insert, Linq throws an exception that there was an error.  But, is there a way to find out that it was the 2nd insert that had the problem and not the 1st or 3rd?

To clarify, there are business reasons that I would expect the 2nd to fail (I am using a stored procedure to do the insert and am also doing some validation and raising an error if it fails).  I want to be able to tell the user which one failed and why.  I know this validation would be better done in the C# code and not in the database, but that is currently not an option.


q:
What is the correct way to do this? For example, how would I change a stored procedure with this signature:

CREATE PROCEDURE dbo.MyProcedure
  @Param BIT = NULL
AS
  SELECT *
  FROM dbo.SomeTable T
  WHERE T.SomeColumn = @Param

So that giving @Param with a value of 1 or 0 performs the filter, but not specifying it or passing NULL performs no filtering?

[A]
Assuming that NULL means "don't care" then use
```
```
CREATE PROCEDURE dbo.MyProcedure
   @Param BIT = NULL
AS
   SELECT *
   FROM dbo.SomeTable T
   WHERE T.SomeColumn = @Param OR @Param IS NULL
```
```


q: Should I create two CFile objects and copy one into the other character by character?  Or is there something in the library that will do this for me?

[A]
I would just use the
```
CopyFile
```
Win32 API function, but the example code in the
```
CFile::Open
```
documentation shows how to copy files with
```
CFile
```
(using pretty much the method you suggest).


q:
I asked this question a while back and basically the project almost consists of reproducing excel in the browser.  We want people to input data in an excel-like way.  The question i have is, what is the best control to use?  Should i use a regular table, and then append columns to it, or should i use a datagrid and flip it XtoY?  What approach would you take?

Thanks for any help.

[A]
Option 1: Check out the Silverlight option to develop your application. And it had a good Excel like DataGrid which is rendered at the Browser lever and you can have async  calls to server at any point of time you want to persit a change.
Option 2: There are many
datagrids
available in WPF and you can get a high performance application using .NET3.5, and it is possible to host this as XBAP application.
Option 3: Typical ASP.NET with AJAX enabled Datagrid


q:
I am trying to use concat_ws inside a group_concat command. With a query, which simplified looks like:

SELECT item.title, GROUP_CONCAT( CONCAT_WS(  ',', attachments.id, attachments.type,     attachments.name ) )  as attachments
FROM story AS item
LEFT OUTER JOIN story_attachment AS attachments ON item.id = attachments.item_id
GROUP BY item.id

I get the attachments column as a Blob type. is it it possible to get it as a string instead of Blob?

[A]
You need to cast as a char..
```
```
SELECT item.title, GROUP_CONCAT( CAST(CONCAT_WS(',', attachments.id,
attachments.type, attachments.name ) as CHAR ) ) as attachments
FROM story AS item
LEFT OUTER JOIN story_attachment AS attachments
ON item.id = attachments.item_id GROUP BY item.id
```
```


q: Shouldn't this be a pretty straightforward operation? However, I see there's neither a size() nor length() method.

[A]
```
```
ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
  rowcount = rs.getRow();
  rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
while (rs.next()) {
  // do your standard per row stuff
}
```
```


q:
I have a .asp application where image files (.PDF) are stored in a directory (fed by a copier/scanner). The created file names are stored in a database table.  When a query is launched from  the web page a link to the file is created. When clicked the image should be displayed.
This functionality works 100% in Internet Explorer. No such luck in Firefox (and I have some Firefox users). The created hyperlink looks like this file://Server/Scanner/XYZ.pdf

The Firefox helps suggest the reason is this:

Links to local or network pages do not work. As a security precaution, Firefox forbids sites on the Internet to link to files that are stored in your local computing environment. These files may include files on your computer, mapped network drives, and UNC network paths

None of the suggestions for a workaround seem to work (or I am not understanding the steps to create the image display)
Any Suggestions?

[A]
shouldn't you really store the pages in your application directory and reference them this way.
http://SITENAME/Server/scanner/XYZ.pdf
.
We do something similar with files stored all in one directory and just store the file name. we then create the link using the known folder name and append the file name. this works quite well.
Finally firefox is a lot more anal about the directions of the slashes in file names as well. Make sure they are all '/' rather than '\'.
Hope this helps.


q:
We have PHP 5.2.6 deployed to c:\php and in that folder there is the php.ini file. On Windows, can a website override these settings similar to the way that apache has .htaccess? e.g.

DirectoryIndex index.php index.html
<IfModule mod_php5.c>
php_flag magic_quotes_gpc off
  php_flag register_globals off
</IfModule>
<IfModule mod_php4.c>
  php_flag magic_quotes_gpc off
 php_flag register_globals off
</IfModule>

Update:

I was aware of ini_set() but wondered if there was a declarative way to do this in a configuration file in the website rather than in script.

[A]
I would recommend doing all you can to avoid changing r
```
egister_globals
```
to on as it's a major security hole.
But you can try using
```
init_set()
```
to change the settings within your PHP code, although some settings cannot be changed once PHP has started running. (These are somewhat server dependent I believe.)


q:
I am writing a diagnostic page for SiteScope and one area we need to test is if the connection to the file/media assets are accesible from the web server.  One way I think I can do this is load the image via code behind and test to see if the IIS status message is 200.

So basically I should be able to navigate to within the site to a folder like this: /media/1/image.jpg and see if it returns 200...if not throw exception.

I am struggling to figure out how to write this code.

Any help is greatly appreciated.

Thanks

[A]
Just use HEAD.  No need to download the entire image if you don't need it.  Here some boilerplate code.
```
```
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url");
request.Method = "HEAD";

bool exists;
try
{
    request.GetResponse();
    exists = true;
}
catch
{
   exists = false;
}
```
```


q:
From day 1 of my programming career, I started with object-oriented programming. However, I'm interested in learning other paradigms (something which I've said here on SO a number of times is a good thing, but I haven't had the time to do). I think I'm not only ready, but have the time, so I'll be starting functional programming with F#.

However, I'm not sure how to structure much less design applications. I'm used to the one-class-per-file and class-noun/function-verb ideas in OO programming. How do you design and structure functional applications?

[A]
Given that modern functional languages (i.e. not lisps) by default use early-bound polymorphic functions (efficiently), and that object-orientation is just a particular way of arranging to have polymorphic functions, it's not really very different, if you know how to design properly encapsulated classes.
Lisps use late-binding to achieve a similar effect. To be honest, there's not much difference, except that you don't explictly declare the structure of types.
If you've programmed extensively with C++ template functions, then you probably have an idea already.
In any case, the answer is small "classes" and instead of modifying internal state, you have to return a new version with different state.


q:
When calling php via cli, the current directory is NOT changed to the one of the script. All the scripts i have running in crontab run via the CLI, so this is an issue.

I'm currently fixing the problem by doing a chdir() with the absolute path where the script is, but i REALLY dont like hardcoding paths into stuff like that.

I'm looking for the most portable/reliable method for ensuring that the current working directory is the one where the script it is at.

[A]
You can use
```
__FILE__
```
to get the full absolute path to the executing file itself:
```
```
<?php
echo "I'm here: ".__FILE__."\n";
?>
```
```
See
the documentation
for more info.


q:
So what I'm looking for here is something like PHP's print_r function.

This is so I can debug my scripts by seeing what's the state of the object in question.

[A]
You can use the "dir()" function to do this.
```
```
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>
```
```
Another useful feature is help.
```
```
>>> help(sys)
Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://www.python.org/doc/current/lib/module-sys.html

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known
```
```


q:
I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable.  But when I try this:

DateTime? d;
bool success = DateTime.TryParse("some date text", out (DateTime)d);

the compiler tells me

'out' argument is not classified as a variable

Not sure what I need to do here.  I've also tried:

out (DateTime)d.Value

and that doesn't work either.  Any ideas?

[A]
```
```
DateTime? d=null;
DateTime d2;
bool success = DateTime.TryParse("some date text", out d2);
if (success) d=d2;
```
```
(There might be more elegant solutions, but why don't you simply do something as above?)


q: I need specifically to load a JPG image that was saved as a blob. GDI+ makes it very easy to retrieve images from files but not from databases...

[A]
First fetch your blog into a byte array then use something like this:
```
```
public static Image CreateImage(byte[] pict)
{
   System.Drawing.Image img = null;
   using (System.IO.MemoryStream stream = new System.IO.MemoryStream(pict)) {
    img = System.Drawing.Image.FromStream(stream);
   }
   return img;
}
```
```


q:
I am working on an Actionscript 2 project - trying to use the XML object to find a url which is returned as a 302 redirect.  Is there a way to do this in actionscript 2?

code:

var urlone:XML = new XML();
urlone.load("http://mydomain.com/file.py");
urlone.onLoad = function (success) {
    trace("I want to print the 302 redirect url here, how do I access it?");
};

[A]
You can use SqlMethods.Like
e.g.
```
```
Where SqlMethods.Like(t.country, "%Sweden%")
```
```


q:
I have to check some code and run it. I have the URL:

svn+ssh://myuser@www.myclient.com/home/svn/project/trunk

I have a file with their private key. What do I do to get this code?

[A]
Add the private key to your
```
~/.ssh/
```
folder and then run
```
ssh-agent $SHELL; ssh-add;
```
, and then the
```
svn co
```
of that URL should work.


q:
I would like to access the Rails session secret programmatically (I am using it to generate a sign-on token).

Here's what I've come up with:

ActionController::Base.session.first[:secret]

This returns the session secret. However, every time you call ActionController::Base.session it adds another entry to an array so you end up with something like this:

[{:session_key=>"_new_app_session", :secret=>"totally-secret-you-guys"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]

This strikes me as being no good.

Is there a better way to access the session secret?

[A]
```
```
ActionController::Base.session_options_for(request,params[:action])[:secret]
```
```


q:
I have to do a cross site POST (with a redirection, so not using a XMLHTTPRequest), and the base platform is ASP.NET. I don't want to POST all of the controls in the ASP.NET FORM to this other site, so I was considering dynamicly creating a new form element using javascript and just posting that.

Has anyone tried this trick? Is there any caveats?

[A]
I do this all the time.  Works really well.  You will have to look through the Request's parameters manually, though, unless you get creative with what you pass as the parameters won't map onto controls on that page.  You could also do this in a REST way by passing the parameters in the query string, but I prefer the forms approach to keep my URLs clean.  Note that ASP.NET ignores all forms but it's own on postback so I don't bother removing them.
Example from a GridView template field for below code:
```
```
<asp:TemplateField HeaderText="Station" SortExpression="Name">
   <ItemTemplate>
      <a href="javascript:void(0);" onclick='Redirector.redirect_with_id("StationDetail.aspx", <%# Eval("StationID") != null ? Eval("StationID") : "-1" %>);return false;'>
      <asp:Label ID="nameLabel" runat="server" Text='<%# Bind("Name") %>' />
   </ItemTemplate>
   </asp:TemplateField>
```
```
Code below -- requires Prototype:
```
```
// JScript File

   var Redirector = Class.create();

   Redirector.prototype = {
       initialize: function(url,target) {
           this.url = url;
           this.parameters = new Hash();
           this.target = target;
       },

    addParameter: function(id,value) {
        this.parameters.set(id, value);
    },

    redirect: function() {
        var form = document.createElement('form');
        document.body.appendChild(form);
        form.action = this.url;
        form.method = "post";
        if (this.target) {
            form.target = this.target;
        }
        this.parameters.each( function(pair) {
            var input = document.createElement('input');
            input.id = pair.key;
            input.name = pair.key;
            input.value = pair.value;
            input.style.display = 'none';
            form.appendChild(input);
        });
        form.submit();
    }
};

Redirector.redirect_with_id = function(url,id,target) {
    var redirector = new Redirector( url, target );
    redirector.addParameter( 'ID', id );
    redirector.redirect();
};

Redirector.redirect_with_tag = function(url,tag_name,tag,target) {
    var redirector = new Redirector( url, target );
    redirector.addParameter( tag_name, tag );
    redirector.redirect();
};

Redirector.redirect_with_tags = function(url,tag_names_comma_separated,tag_values_comma_separated,target) {
    var redirector = new Redirector( url, target );
    var tags = tag_names_comma_separated.split( "," );
    var values = tag_values_comma_separated.split( ",");
    for( var i = 0; i< tags.length; i++ )
    {
        redirector.addParameter( tags[i], values[i] );
    }
    redirector.redirect();
};
```
```


q:
How do I do this

Select top 10 Foo from MyTable

in Linq to SQL?

[A]
In VB:
```
```
from m in MyTable
take 10
select m.Foo
```
```
This assumes that MyTable implements IQueryable.  You may have to access that through a DataContext or some other provider.
It also assumes that Foo is a column in MyTable that gets mapped to a property name.
See
http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx
for more detail.


q:
This is the SQL that I want to accomplish:

WHERE domain_nm + '\' + group_nm in ('DOMAINNAME\USERNAME1','DOMAINNAME2\USERNAME2')

I can't for the life of me find an appropriate Expression for this. And I don't think I can use two expressions as the domain name and the group name need to be concatenated.

Thanks!

[A]
Can you not use two Expressions?
```
```
criteria
  .Add(Expression.In("DomainName", new string[] { "DOMAINNAME", "DOMAINNAME2" }))
  .Add(Expression.In("GroupName", new string[] { "USERNAME1", "USERNAME2" })
```
```
The other option is to use Expression.Sql.


q:
I'm not much of a coder, but I need to write a simple preg_replace statement in PHP that will help me with a WordPress plugin.  Basically, I need some code that will search for a string, pull out the video ID, and return the embed code with the video id inserted into it.

In other words, I'm searching for this:

[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1]

And want to replace it with this (keeping the video id the same):

param name="movie" value="http://www.youtube.com/v/VIDEO_ID_HERE&hl=en&fs=1&rel=0

If possible, I'd be forever grateful if you could explain how you've used the various slashes, carets, and Kleene stars in the search pattern, i.e. translate it from grep to English so I can learn. :-)

Thanks!

Mike

[A]
```
```
$str = preg_replace('/\[youtube=.*?v=([a-z0-9_-]+?)&.*?\]/i', 'param name="movie" value="http://www.youtube.com/v/$1&hl=en&fs=1&rel=0', $str);

         /     - Start of RE
         \[    - A literal [  ([ is a special character so it needs escaping)
         youtube= - Make sure we've got the right tag
         .*?   - Any old rubbish, but don't be greedy; stop when we reach...
         v=    - ...this text
         ([a-z0-9_-]+?) - Take some more text (just z-a 0-9 _ and -), and don't be greedy.  Capture it using ().  This will get put in $1
         &.*?\] - the junk up to the ending ]
         /i - end the RE and make it case-insensitive for the hell of it
```
```


q:
Say, I have a script that gets called with this line:

./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile

or this one:

./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile

What's the accepted way of parsing this such that in each case (or some combination of the two) $v, $f, and  $d will all be set to true and $outFile will be equal to /fizz/someOtherFile?

[A]
```
getopt()
```
/
```
getopts()
```
is a good option.  Copied from
here
:
The simple use of "getopt" is shown in this mini-script:
```
```
#!/bin/bash
echo "Before getopt"
for i
do
  echo $i
done
args=`getopt abc:d $*`
set -- $args
echo "After getopt"
for i
do
  echo "-->$i"
done
```
```
What we have said is that any of -a,
-b, -c or -d will be allowed, but that -c is followed by an argument (the "c:" says that).
If we call this "g" and try it out:
```
```
bash-2.05a$ ./g -abc foo
Before getopt
-abc
foo
After getopt
-->-a
-->-b
-->-c
-->foo
-->--
```
```
We start with two arguments, and
"getopt" breaks apart the options and
puts each in its own argument. It also
added "--".


q:
Using something like this:

try:
   # Something...
except Exception as excep:
   logger = logging.getLogger("component")
   logger.warning("something raised an exception: " + excep)
   logger.info("something raised an exception: " + excep)

I would rather not have it on the error-level cause in my special case it is not an error.

[A]
From the
logging documentation
:
There are three keyword arguments in
```
kwargs
```
which are inspected:
```
exc_info
```
,
```
stack_info
```
, and
```
extra
```
.
If
```
exc_info
```
does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by
```
sys.exc_info()
```
) or an exception instance is provided, it is used; otherwise,
```
sys.exc_info()
```
is called to get the exception information.
So do:
```
```
logger.warning("something raised an exception:", exc_info=True)
```
```


q:
The way you would normally include a script is with "source"

eg:

main.sh:

#!/bin/bash

source incl.sh

echo "The main script"

incl.sh:

echo "The included script"

The output of executing "./main.sh" is:

The included script
The main script

... Now, if you attempt to execute that shell script from another location, it can't find the include unless it's in your path.

What's a good way to ensure that your script can find the include script, especially if for instance, the script needs to be portable?

[A]
I tend to make my scripts all be relative to one another.
That way I can use dirname:
```
```
#!/bin/sh

my_dir="$(dirname "$0")"

"$my_dir/other_script.sh"
```
```


q:
I have the following two models:

class Activity(models.Model):
    name = models.CharField(max_length=50, help_text='Some help.')
    entity = models.ForeignKey(CancellationEntity)
    ...

class Cancellation(models.Model):
    activity = models.ForeignKey(Activity)
    date = models.DateField(default=datetime.now().date())
    description = models.CharField(max_length=250)
    ...

I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated).

What is the best way to go about this?

[A]
What you want to look into is
Django's signals
(check out
this page
too), specifically the model signals--more specifically, the
post_save
signal. Signals are Django's version of a plugin/hook system. The post_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if it was created). This is how you'd use signals to get notified when an Activity has a Cancellation
```
```
from django.db.models.signals import post_save

class Activity(models.Model):
    name = models.CharField(max_length=50, help_text='Some help.')
    entity = models.ForeignKey(CancellationEntity)

    @classmethod
    def cancellation_occurred (sender, instance, created, raw):
        # grab the current instance of Activity
        self = instance.activity_set.all()[0]
        # do something
    ...

class Cancellation(models.Model):
    activity = models.ForeignKey(Activity)
    date = models.DateField(default=datetime.now().date())
    description = models.CharField(max_length=250)
    ...

post_save.connect(Activity.cancellation_occurred, sender=Cancellation)
```
```


q:
Is it possible to programmatically force a full garbage collection run in ActionScript 3.0?

Let's say I've created a bunch of Display objects with eventListeners and some of the DO's have been removed, some of the eventListeners have been triggered and removed etc... Is there a way to force garbage collection to run and collect everything that is available to be collected?

[A]
Yes, it's possible, but it is generally a bad idea. The GC should have a better idea of when is a good time to run than you should, and except for a very specific case, like you just used 500MB of memory and you need to get it back ASAP, you shouldn't call the GC yourself.
In Flash 10, there is a
```
System.gc()
```
method you can call (but please don't, see above) - keep in mind System.gc() only works in the debugging version of Flash player 10+.
In Flash 9, there is an unsupported way to force it via an odd LocalConnection command, but it may not work in all versions. See
this post
by Grant Skinner.


q:
When using before_filter :login_required to protect a particular page, the link_to_unless_current method in the application layout template renders the "Login" link for the login page as a hyperlink instead of just text.

The "Login" text/link problem only occurs when redirected to the Login Page via the before_filter machinery, otherwise, the link_to_unless_current method operates as expected.

It seems that link_to_unless_current is using the old page data as the "current" instead of the login page (when redirecting).

[A]
Appreciate the responses and you can tell by the nature of the question that we're new to rails. By the way, we posted the same question on this site:
http://railsforum.com
(not sure if it's the official rails forum) with no response yet. StackOverflow so far seems to be creating a great community of helpers willing to reach out to the programmatically challenged.
I think part of the problem is that we were mixing restful urls with standard routes. The login page is mapped to the restful route "/login" but the page redirection was using "/sessions/new" (Rick Olson's restful authentication module)
In application.rb, we forced the filter to "/login" and that solved the problem:
```
before_filter :login_required

protected

def login_required
  return true if logged_in?
  session[:return_to] = request.request_uri
  flash[:error] = "Please log in first"
  redirect_to "/login" and return false
end
```
Comments on the technical merits of this approach appreciated as it may be helpful to other newbs.
Thanks,
Joe


q:
I have a RichTextBox where I need to update the Text property frequently, but when I do so the RichTextBox "blinks" annoyingly as it refreshes all throughout a method call.

I was hoping to find an easy way to temporarily suppress the screen refresh until my method is done, but the only thing I've found on the web is to override the WndProc method.  I've employed this approach, but with some difficulty and side effects, and it makes debugging harder, too.  It just seems like there's got to be a better way of doing this.  Can someone point me to a better solution?

[A]
Try this out:
```
```
myRichTextBox.SuspendLayout();
DoStuff();
myRichTextBox.ResumeLayout();
```
```


q:
Personally, I find the range of functionality provided by java.util.Iterator to be fairly pathetic. At a minimum, I'd like to have methods such as:

peek() returns next element without moving the iterator forward

previous() returns the previous element

Though there are lots of other possibilities such as first() and last().

Does anyone know if such a 3rd party iterator exists? It would probably need to be implemented as a decorator of java.util.Iterator so that it can work with the existing java collections. Ideally, it should be "generics aware".

Thanks in advance,
Don

[A]
You can get
```
previous()
```
easily by just using a
```
java.util.ListIterator
```
.
Peek at that point is easily implemented by doing a
```
```
public <T> T peek(ListIterator<T> iter) throws NoSuchElementException {
    T obj = iter.next();
    iter.previous();
    return obj;
}
```
```
Unfortunately it will be easier to have it as a utility method since each collection class implements their own iterators. To do a wrapper to get a peek method on each collection on some interface such as
```
MyListIterator
```
would be quite a lot of work.


q:
I have TortoiseSVN set up to use KDiff3 as the conflict resolution tool (I find it shows more information useful to the merge than the built-in TortoiseMerge does).

When I open a file with Tortoise's "Edit Conflicts" command it shows me the three files and I have to select "Merge->Merge Current File" manually. The problem is that KDiff3 saves the result to source_file.working instead of to source_file. So without doing a Save As, the real file with the conflict doesn't get modified. Is there a way around doing this manual Save As every time?

I know this isn't strictly a programming question but it's about an ancillary process common enough to programmers that it should be useful here. I couldn't find the answer to this elsewhere.

[A]
Turns out I just needed a more specific command line. I had it set simply to the path to
```
kdiff3.exe
```
, and hoped the default arguments passed from TortoiseSVN would be enough. Not so. Here's the one needed (the key being the
```
-o
```
argument):
```
```
C:\Program Files\KDiff3\kdiff3.exe %base %theirs %mine -o %merged
```
```


q:
I would like to set the log file name for a log4j and log4net appender to have the current date.  We are doing Daily rollovers but the current log file does not have a date.  The log file name format would be

logname.2008-10-10.log

Anyone know the best way for me to do this?

edit:  I forgot to mention that we would want to do this in log4net as well.  Plus any solution would need to be usable in JBoss.

[A]
DailyRollingFileAppender is what you exactly searching for.
```
```
<appender name="roll" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="File" value="application.log" />
    <param name="DatePattern" value=".yyyy-MM-dd" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern"
          value="%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n  %-5p %m%n"/>
    </layout>
  </appender>
```
```


q:
I am currently in the process of making a new ASP.net MVC website, and find myself using Html.Encode all over the place, which is good practice, but gets pretty messy. I think a good way to clean this up would be if I could overload an operator to automatically do Html encoding.

Previously:

<%= Html.Encode( ViewData['username'] ) %>

Would be equivalent to:

<%=h ViewData['username'] %>

Anyone have any ideas how I could do this, maybe using an extension method or something?

[A]
NOTE: This is an ugly and untested hack, I don't think I'd ever do this
```
```
public static String h (this System.Object o, System.Object viewData)
{
    return Html.Encode(viewData);
}
```
```
I'm not sure what type ViewData is, so I used Object here, it would be best to actually change the type in the real code.
this works by hanging an extension method off System.Object, so it is always available on all types...ugly, but it may do the job:
```
```
<%=h(ViewData['username']) %>
```
```


q: How do I transfer the users of a vBulletin forum to a new installation of IceBB?

[A] This is a rather random guess, but I wonder if the user is using an add-on like NoScript to control script execution and is not allowing scripts from Google Analytics to run.  I know this is possible because it's what I do :) I don't know if that would show up as the error you're seeing.


q: We use a lot of of python to do much of our deployment and would be handy to connect to our TFS server to get information on iteration paths, tickets etc. I can see the webservice but unable to find any documentation. Just wondering if anyone knew of anything?

[A]
The web services are not documented by Microsoft as it is not an officially supported route to talk to TFS.  The officially supported route is to use their
.NET API
.
In the case of your sort of application, the course of action I usually recommend is to create your own web service shim that lives on the TFS server (or another server) and uses their API to talk to the server but allows you to present the data in a nice way to your application.
Their object model simplifies the interactions a great deal (depending on what you want to do) and so it actually means less code over-all - but better tested and testable code and also you can work around things such as the NTLM auth used by the TFS web services.
Hope that helps,
Martin.


q:
I have a listbox that is databound to a Collection of objects.  The listbox is configured to display an identifier property of each object.  I would like to show a tooltip with information specific to the item within the listbox that is being hovered over rather than one tooltip for the listbox as a whole.

I am working within WinForms and thanks to some helpful blog posts put together a pretty nice solution, which I wanted to share.

I'd be interested in seeing if there's any other elegant solutions to this problem, or how this may be done in WPF.

[A]
There are two main sub-problems one must solve in order to solve this problem:
Determine which item is being hovered over
Get the MouseHover event to fire when the user has hovered over one item, then moved the cursor within the listbox and hovered over another item.
The first problem is rather simple to solve.  By calling a method like the following within your handler for MouseHover, you can determine which item is being hovered over:
```
```
private ITypeOfObjectsBoundToListBox DetermineHoveredItem()
{
    Point screenPosition = ListBox.MousePosition;
    Point listBoxClientAreaPosition = listBox.PointToClient(screenPosition);

    int hoveredIndex = listBox.IndexFromPoint(listBoxClientAreaPosition);
    if (hoveredIndex != -1)
    {
        return listBox.Items[hoveredIndex] as ITypeOfObjectsBoundToListBox;
    }
    else
    {
        return null;
    }
}
```
```
Then use the returned value to set the tool-tip as needed.
The second problem is that normally the MouseHover event isn't fired again until the cursor has left the client area of the control and then come back.
You can get around this by wrapping the
```
TrackMouseEvent
```
Win32API call.
In the following code, the
```
ResetMouseHover
```
method wraps the API call to get the desired effect: reset the underlying timer that controls when the hover event is fired.
```
```
public static class MouseInput
{
    // TME_HOVER
    // The caller wants hover notification. Notification is delivered as a
    // WM_MOUSEHOVER message.  If the caller requests hover tracking while
    // hover tracking is already active, the hover timer will be reset.

    private const int TME_HOVER = 0x1;

    private struct TRACKMOUSEEVENT
    {
        // Size of the structure - calculated in the constructor
        public int cbSize;

        // value that we'll set to specify we want to start over Mouse Hover and get
        // notification when the hover has happened
        public int dwFlags;

        // Handle to what's interested in the event
        public IntPtr hwndTrack;

        // How long it takes for a hover to occur
        public int dwHoverTime;

        // Setting things up specifically for a simple reset
        public TRACKMOUSEEVENT(IntPtr hWnd)
        {
            this.cbSize = Marshal.SizeOf(typeof(TRACKMOUSEEVENT));
            this.hwndTrack = hWnd;
            this.dwHoverTime = SystemInformation.MouseHoverTime;
            this.dwFlags = TME_HOVER;
        }
    }

    // Declaration of the Win32API function
    [DllImport("user32")]
    private static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);

    public static void ResetMouseHover(IntPtr windowTrackingMouseHandle)
    {
        // Set up the parameter collection for the API call so that the appropriate
        // control fires the event
        TRACKMOUSEEVENT parameterBag = new TRACKMOUSEEVENT(windowTrackingMouseHandle);

        // The actual API call
        TrackMouseEvent(ref parameterBag);
    }
}
```
```
With the wrapper in place, you can simply call
```
ResetMouseHover(listBox.Handle)
```
at the end of your MouseHover handler and the hover event will fire again even when the cursor stays within the control's bounds.
I'm sure this approach, sticking all the code in the MouseHover handler must result in more MouseHover events firing than are really necessary, but it'll get the job done.  Any improvements are more than welcome.


q: SqlDataReader is a faster way to process the stored procedure. What are some of the advantage/disadvantages of using SQLDataReader?

[A]
It depends on what you need to do.  If you get back a page of results from the database (say 20 records), it would be better to use a data adapter to fill a DataSet, and bind that to something in the UI.
But if you need to process many records, 1 at a time, use SqlDataReader.


q:
In @mmalc's response to this question he states that "In general you should not use accessor methods in dealloc (or init)." Why does mmalc say this?

The only really reasons I can think of are performance and avoiding unknown side-effects of @dynamic setters.

Discussion?

[A]
It's basically a guideline to minimize the potential for bugs.
In this case there is the (possibility) that your setter/getter may inadvertently make direct or indirect assumptions about the state of the object. These assumptions could be a problem when the object is in the midst of being setup or destroyed.
For example in the code below the observer does not know that 'Example' is being destroyed and could assume that other properties, which have already been freed, are valid.
(You could argue that your object should remove all observers before tearing itself down, which would be good practice, and another guideline to prevent inadvertent problems).
```
```
@implementation Example

-(void) setFoo:(Foo*)foo
{
   _foo = foo;
  [_observer onPropertyChange:self object:foo];
}

-(void) dealloc
{
   ...
   self.foo = nil;
}

@end
```
```


q:
What's proper way to connect ODBC datasources and execute some SQL statements?

TQuery and other BDE components can do it, but if I understood correctly they are now deprecated?

[A]
You can use the ADO components:
1) Drag a TAdoConnection from the dbGo tab.
2) Right click and choose Edit connection string.
3) Click build
4) Select Microsoft OLE DB Provider for ODBC
5) Click Next
Then you will be able to select a database.
You can drag a TAdoQuery and connect it to the TAdoConnection to execute some queries.
The rest should be straight forward.


q:
Suppose I have an M-file that calculates, for exampleת d=a+b+c (The values on a, b, c were given earlier).

What command should I use in order to produce an output M-file showing the result of this sum?


q:
Can I ignore a folder on svn checkout? I need to ignore DOCs folder on checkout at my build server.

edit: Ignore externals isn't an option. I have some externals that I need.

[A]
No, ignore is only for adding files.
You can use sparse checkouts (if you use svn 1.5)


q: Can you get the distinct combination of 2 different fields in a database table?  if so, can you provide the SQL example.

[A]
How about simply:
```
```
select distinct c1, c2 from t
```
```
or
```
```
select c1, c2, count(*)
from t
group by c1, c2
```
```


q: I am trying to build a homebrew web brower to get more proficient at Cocoa. I need a good way to validate whether the user has entered a valid URL. I have tried some regular expressions but NSString has some interesting quirks and doesn't like some of the back-quoting that most regular expressions I've seen use.

[A]
You could start with the
```
+ (id)URLWithString:(NSString *)URLString
```
method of
```
NSURL
```
, which returns
```
nil
```
if the string is malformed.
If you need further validation, you can use the
```
baseURL
```
,
```
host
```
,
```
parameterString
```
,
```
path
```
, etc methods to give you particular components of the URL, which you can then evaluate in whatever way you see fit.


q:
What's the fastest way to get a framebuffer and render to in software on the iPhone?

Basically getting into a mode 13h style thing going so I can make some effects? :)

[A]
You need to create a
```
CGImageContext
```
, in a bitmap format that you can directly manipulate. Then, you can draw that image on the screen, use it as a GL texture, or whatever.
Pretty simple stuff - check the Core Graphics documentation. I don't think there's a good way to get actual raw
```
frameBuffer
```
access, but that's probably not what you really want, anyway.


q: If I define a constant in a Perl module, how do I use that constant in my main program?  (Or how do I call that constant in the main program?)

[A]
Constants can be exported just like other package symbols. Using the standard
Exporter
module, you can export constants from a package like this:
```
```
package Foo;
use strict;
use warnings;

use base 'Exporter';

use constant CONST => 42;

our @EXPORT_OK = ('CONST');

1;
```
```
Then, in a client script (or other module)
```
```
use Foo 'CONST';
print CONST;
```
```
You can use the
```
%EXPORT_TAGS
```
hash (see the Exporter documentation) to define groups of constants that can be exported with a single import argument.
Update: Here's an example of how to use the
```
%EXPORT_TAGS
```
feature if you have multiple constants.
```
```
use constant LARRY => 42;
use constant CURLY => 43;
use constant MOE   => 44;

our @EXPORT_OK = ('LARRY', 'CURLY', 'MOE');
our %EXPORT_TAGS = ( stooges => [ 'LARRY', 'CURLY', 'MOE' ] );
```
```
Then you can say
```
```
use Foo ':stooges';
print "$_\n" for LARRY, CURLY, MOE;
```
```


q:
Languages like C and even C# (which technically doesn't have a preprocessor) allow you to write code like:

#DEFINE DEBUG
...

string returnedStr = this.SomeFoo();
#if DEBUG
    Debug.WriteLine("returned string =" + returnedStr);
#endif

This is something I like to use in my code as a form of scaffolding, and I'm wondering if PHP has something like this. I'm sure I can emulate this with variables, but I imagine the fact that PHP is interpreted in most cases will not make it easy to strip/remove the debugging code (since its not needed) automatically when executing it.

[A]
PHP doesn't have anything like this. but you could definitely whip up something quickly (and perhaps a regex parse to strip it out later if you wanted). i'd do it as such:
```
```
define('DEBUG', true);
...
if (DEBUG):
  $debug->writeLine("stuff");
endif;
```
```
of course you'd have to write your own debug module to handle all that. if you wanted to make life easier on regex parsing, perhaps you could use a ternary operator instead:
```
```
$str = 'string';
DEBUG ? $debug->writeLine("stuff is ".$str) : null;
```
```
which would make removing debug lines pretty trivial.


q:
I'm building a .NET client application (C#, WinForms) that uses a web service for interaction with the database. The client will be run from remote locations using a WAN or VPN, hence the idea of using a web service rather than direct database access.

The issue I'm grappling with right now is how to handle database concurrency. That is, if two people from different locations update the same data, how do I deal with it? I'm considering using timestamps on each database record and having that as part of the update where clauses, but that means that the timestamps have to move back and forth through the web service interface, which seems kind of ugly.

What is the best way to approach this?

[A]
I don't think you want your web service to talk directly to the database.  You probably want your service to interact with some type of business components who in turn interact with a data access layer.  Any concurrency exceptions can be passed from the DAL up to the business layer where they can be handled so that the web service never has to see the timestamps.
But if you are passing something like a data table up to the client and you want to avoid timestamps, you can do concurrency checking by comparing field by field.  The Table Adapter wizards generate this type of concurrency checking by default if you ask for optimistic concurrency checking.


q:
I am just starting to fiddle with Excel via C# to be able to automate the creation, and addition to an Excel file.

I can open the file and update its data and move through the existing worksheets. My problem is how can I add new sheets?

I tried:

Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excelApp.ThisWorkbook.Worksheets.Add(
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

But I get below COM Exception and my googling has not given me any answer.

Exception from HRESULT: 0x800A03EC Source is: "Interop.Excel"

I am hoping someone maybe able to put me out of my misery.

[A]
You need to add a COM reference in your project to the
"
```
Microsoft Excel 11.0 Object Library
```
"
- or whatever version is appropriate.
This code works for me:
```
```
private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
    Microsoft.Office.Interop.Excel.Application xlApp = null;
    Workbook xlWorkbook = null;
    Sheets xlSheets = null;
    Worksheet xlNewSheet = null;

    try {
        xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
            return;

        // Uncomment the line below if you want to see what's happening in Excel
        // xlApp.Visible = true;

        xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
                false, XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);

        xlSheets = xlWorkbook.Sheets as Sheets;

        // The first argument below inserts the new worksheet as the first one
        xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
        xlNewSheet.Name = worksheetName;

        xlWorkbook.Save();
        xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
        xlApp.Quit();
    }
    finally {
        Marshal.ReleaseComObject(xlNewSheet);
        Marshal.ReleaseComObject(xlSheets);
        Marshal.ReleaseComObject(xlWorkbook);
        Marshal.ReleaseComObject(xlApp);
        xlApp = null;
    }
}
```
```
Note that you want to be very careful about
properly cleaning up and releasing your COM object references
. Included in that StackOverflow question is a useful rule of thumb:
"Never use 2 dots with COM objects"
. In your code; you're going to have real trouble with that.
My demo code above does NOT properly clean up the Excel app, but it's a start!
Some other links that I found useful when looking into this question:
Opening and Navigating Excel with C#
How to: Use COM Interop to Create an Excel Spreadsheet (C# Programming Guide)
How to: Add New Worksheets to Workbooks
According to MSDN
To use COM interop, you must have
  administrator or Power User security
  permissions.
Hope that helps.


q:
I am using Oracle SQL (in SQLDeveloper, using the SQL Worksheet).  I would like to print a statement before my select, such as

PRINT 'Querying Table1';
SELECT * from Table1;

What do I use to Print / show text output?  It's not Print, because that gives me the error: Bind Variable Table1 is NOT DECLARED.  DBMS_OUTPUT.PUT_LINE is an unknown command.  (Obviously, I'm an inexperienced SQLDeveloper and Oracle user.  There must be some synonym for Print, but I'm having trouble finding help on it without knowing what it is.)

[A]
You could
set echo
to on:
```
```
set echo on
REM Querying table
select * from dual;
```
```
In SQLDeveloper, hit F5 to run as a script.


q:
I have been scouring the web for a code sample that shows how to use pbuffer with GLUT but I could not find anything...

I am puzzled with the context switching between pbuffer and the rendering window. I guess that I will have to use glutSetWindow to switch between the two rendering surface but I am not too sure about the details.

Can someone explain me how to use a pbuffer with GLUT?

[A]
The short answer is that there's no
good
way of doing it.
The longer answer is that pbuffers are not cross-platform, so you necessarily have to use platform-specific APIs to access them. How you switch between rendering surfaces depends on your platform; on Windows you'd use wglMakeCurrent() and the like.
The meta-answer is that you should avoid pbuffers if at all possible -
FBO
s provide similar functionality but without this kind of problem, and with better performance too.


q:
I need to have my iPhone Objective-C code catch Javascript errors in a UIWebView.  That includes uncaught exceptions, syntax errors when loading files, undefined variable references, etc.

This is for a development environment, so it doesn't need to be SDK-kosher.  In fact, it only really needs to work on the simulator.

I've already found used some of the hidden WebKit tricks to e.g. expose Obj-C objects to JS and to intercept alert popups, but this one is still eluding me.

[NOTE: after posting this I did find one way using a debugging delegate.  Is there a way with lower overhead, using the error console / web inspector?]

[A]
I have done this in firmware 1.x but not 2.x.
Here is the code I used in 1.x, it should at least help you on your way.
```
```
// Dismiss Javascript alerts and telephone confirms
/*- (void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button
{
    if (button == 1)
    {
        [sheet setContext: nil];
    }

    [sheet dismiss];
}*/

// Javascript errors and logs
- (void) webView: (WebView*)webView addMessageToConsole: (NSDictionary*)dictionary
{
    NSLog(@"Javascript log: %@", dictionary);
}

// Javascript alerts
- (void) webView: (WebView*)webView runJavaScriptAlertPanelWithMessage: (NSString*) message initiatedByFrame: (WebFrame*) frame
{
    NSLog(@"Javascript Alert: %@", message);

    UIAlertSheet *alertSheet = [[UIAlertSheet alloc] init];
    [alertSheet setTitle: @"Javascript Alert"];
    [alertSheet addButtonWithTitle: @"OK"];
    [alertSheet setBodyText:message];
    [alertSheet setDelegate: self];
    [alertSheet setContext: self];
    [alertSheet popupAlertAnimated:YES];
}
```
```


q: Is there a way to tell Enterprise Library to use prepared statements?  If so, how?

[A]
You should be able to obtain the sqlConnection / Command being executed -> can't you set the relevant setting here before executing ??
Hope I've got the right end of the stick...


q:
SQL Server (2005/2008)

Each of the below statements have the same result. Does anyone know if one outperforms the other?

insert into SOMETABLE
  values ('FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000')

insert into SOMETABLE
  select 'FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000'

insert into SOMETALBE
  Select
    Field1 = 'FieldOneValue',
    Field2 = 'FieldTwoValue',
    Field3 = 3,
    Field4 = 4.55,
    Field5 = '10/10/2008 16:42:00.000'

Assuming of course that the data types match the table appropriately...

[A]
It looks like you're just mimicking
```
```
INSERT into SOMETABLE
(
SELECT * FROM SOMEOTHERTABLE
)
```
```


q:
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy?

Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.

In particular:

Where do you put the source?

Where do you put application startup scripts?

Where do you put the IDE project cruft?

Where do you put the unit/acceptance tests?

Where do you put non-Python data such as config files?

Where do you put non-Python sources such as C++ for pyd/so binary extension modules?

[A]
Doesn't too much matter.  Whatever makes you happy will work.  There aren't a lot of silly rules because Python projects can be simple.
```
/scripts
```
or
```
/bin
```
for that kind of command-line interface stuff
```
/tests
```
for your tests
```
/lib
```
for your C-language libraries
```
/doc
```
for most documentation
```
/apidoc
```
for the Epydoc-generated API docs.
And the top-level directory can contain README's, Config's and whatnot.
The hard choice is whether or not to use a
```
/src
```
tree.  Python doesn't have a distinction between
```
/src
```
,
```
/lib
```
, and
```
/bin
```
like Java or C has.
Since a top-level
```
/src
```
directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.
```
/foo
```
```
/bar
```
```
/baz
```
I recommend putting all of this under the "name-of-my-product" directory.  So, if you're writing an application named
```
quux
```
, the directory that contains all this stuff is named
```
/quux
```
.
Another project's
```
PYTHONPATH
```
, then, can include
```
/path/to/quux/foo
```
to reuse the
```
QUUX.foo
```
module.
In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file.  I actually put that in the top-level
```
/quux
```
directory, and omit adding it to SVN.


q: Is there any way to get own phone number by standard APIs from iPhone SDK?

[A]
No, there's no legal and reliable way to do this.
If you find a way, it will be disabled in the future, as it has happened with every method before.


q: What is the best way to display and print XPS files in a Windows Forms application?

[A]
I think the easiest way is to use WPF, you can host a WPF control inside a WinForms application - you don't have to rewrite your GUI in WPF or anything like that.
more information here :
http://msdn.microsoft.com/en-us/library/ms745781.aspx


q:
Assuming a Read Committed Snapshot transaction isolation setting, is the following statement "atomic" in the sense that you won't ever "lose" a concurrent increment?

update mytable set counter = counter + 1

I would assume that in the general case, where this update statement is part of a larger transaction, that it wouldn't be. For example, I think this scenario is possible:

update the counter within transaction #1

do some other stuff
in transaction #1

update the counter
with transaction #2

commit
transaction #2

commit transaction #1

In this situation, wouldn't the counter end up only being incremented by 1? Does it make a difference if that is the only statement in a transaction?

How does a site like stackoverflow handle this for its question view counter? Or is the possibility of "losing" some increments just considered acceptable?

[A]
No, it's not. The value is read in shared mode and then updated in exclusive mode, so multiple reads can occur.
Either use Serializable level or use something like
```
```
update t
set counter = counter+1
from t with(updlock, <some other hints maybe>)
where foo = bar
```
```


q:
I am creating a tool that will check dynamically generated XHTML and validate it against expected contents.

I need to confirm the structure is correct and that specific attributes exist/match. There may be other attributes which I'm not interested in, so a direct string comparison is not suitable.

One way of validating this is with XPath, and I have implemented this already, but I would also like something less verbose - I want to be able to use CSS Selectors, like I can with jQuery, but on the server - within CFML code - as opposed to on the client.

Is there a CFML or Java library that allows me to use CSS Selectors against an XHTML string?

[A]
I don't know of a Java library itself, but there is a Ruby library called
Hpricot
that does exactly what you're looking for. In conjunction with the Ruby implementation on the Java platform,
JRuby
, it should be relatively straightforward to call Ruby methods from your Java code (using BSF,
JSR-222 Scripting APIs
, or
an internal API
).
Are you using Coldfusion 8? Coldfusion 8, being based on Java 6, supports JSR-222 Scripting APIs "javax.scripting".
Take a look at
this blog entry on embedding PHP within CFML
. You should be able to do
the same with Ruby
. There is ZIP file example code linked from this blog posting, and if you crack open the CFML, you'll see a good example of embedding Ruby within CFML.
Although it might take a bit of work to make all the pieces work together, but with a bit of investment, it should give you the robust parsing/CSS selector querying that you're looking for.


q:
I'm making a dynamic image for a forum that doesn't allow dynamic images.

I tried using .htacess to redirect all *.png files to image.png... which works perfectly, but from here I can't seem to be able to get the filename of the .png that was requested to generate the content.

For example:

user puts in banana.png

htaccess forwards to image.php

I need a way of getting that banana into my php script.

Using $_SERVER['REQUEST_URI'] and $_SERVER["SCRIPT_NAME"] just returns that of the PHP file.

Is there a way of redirecting it to image.php?=bananana for example?

[A]
For SVN:  In commandline tool, there is the option
-x
which you can set to "
b
" or "
w
" to ignore space changes resp. all spaces.
You can also supply a third party tool for doing the merges. So if you have a merger which ignores whitespaces, you can use this one.
TortoiseSVN, as always, is a frontend to all parameters, so it will support for ignoring whitespaces as well.
The svn merge command is described
here
. The option you need is
--diff3-cmd


q:
What are the benefits of upgrading from Visual Studio 2005 to 2008?

Any thoughts on whether it's worth the jump, or is it better to wait for whatever's coming next?

[A]
There are tons of improvements. The best part is you can continue to target .Net 2.0 with VS 2008 (
Multi-Targeting
) and use all the new IDE features.
Posting couple of screencasts but you can find more on web:
Script intellisense and debugging in Visual Studio 2008
Multi-threading Debugging Enhancements in Visual Studio 2008


q:
I've been reading about Ocaml's consistent speed, rapid prototyping ability, and excellent memory management, and decided to take it up.

As I've already got Ruby, *lisp, Haskell, and Erlang under my belt, I'm interested specifically in what KISS-violating features I should look out for in Ocaml.

If you've started Ocaml with a background in the above languages, what was the most frustrating thing to grok? How did you get around this difficulty? What analogies helped you get into the flow of the language?

I'd also be interested in knowing whether you have done more than simply learn Ocaml, and have actually converted to it for a large percentage of your coding problems.

[A]
I found an excellent resource on Ocaml and its relation to most other languages:
http://www.soton.ac.uk/~fangohr/software/ocamltutorial/lecture1.html
Not only does it explain the why, it also explains many of the little quirks likely to snag you as you begin.
Ah, I found a
cheatsheet
highlighting almost all of its syntactic weirdnesses.


q:
Is it possible to break at runtime when a particular file has been modified?

ie. monitor the file and break into a debugger once a change has been made to it.

This is for a windows app...is this possible in visual studio or windbg?

edit:  i should have mentioned that this is for a Win32 app..

[A]
Assuming this is .NET, the System.IO.
FileSystemWatcher
class is what you need.
```
```
FileSystemWatcher watcher = new FileSystemWatcher("c:filename.txt");
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
//
void watcher_Changed(object sender, FileSystemEventArgs e)
{
    // put a breakpoint here
}
```
```


q: I would like to hear about interesting projects which made use of Amazon's Mechanical Turk.

[A] I haven't done anything with it yet but I've been meaning to use it for music search by having an app that accepted recordings of people humming or singing a tune and then using the Turk to identify the tune.