Question:
It's rare that I hear someone using Inversion of Control (Ioc) principle with .Net. I have some friends that work with Java that use a lot more Ioc with Spring and PicoContainer.

I understand the principle of removing dependencies from your code... but I have a doubt that it's so much better.

Why do .Net programmers not use (or use less) those types of frameworks? If you do, do you really find a positive effect in the long term?

Answer:
Lots of people use IOC in .NET, and there are several frameworks available to assist with using IoC.  You may see it less in the WinForms side of things, because it's harder to just let the container wire everything together when you are designing forms in Visual Studio, but I can say that for server-side .NET applications, where I work at least, IoC is used very successfully.
Why use it in .NET?  For the same reason you use it everywhere else.  The 2 biggest things I like are:
Designing for IoC tends to enforce good coding practice - designing to interfaces, low coupling, high cohesion.  This also leads to classes that are very easy to unit-test.
System configuration can often be changed without recompiling.
Some other posts discussing the different IoC/DI frameworks available for .NET:
Which C#/.net Dependency Injection frameworks are worth looking into?
Which Dependency Injection Tool Should I Use?


Question:
We're running a lightweight web app on a single EC2 server instance, which is fine for our needs, but we're wondering about monitoring and restarting it if it goes down.

We have a separate non-Amazon server we'd like to use to monitor the EC2 and start a fresh instance if necessary and shut down the old one. All our user data is on Elastic Storage, so we're not too worried about losing anything.

I was wondering if anyone has any experience of using EC2 in this way, and in particular of automating the process of starting the new instance? We have no problem creating something from scratch, but it seems like it should be a solved problem, so I was wondering if anyone has any tips, links, scripts, tutorials, etc to share.

Thanks.

Answer:
You should have a look at
puppet
and its support for
AWS
. I would also look at the
RightScale AWS library
as well as this post about
starting a server with the RightScale scripts
. You may also find this article on
web serving with EC2
useful. I have done something similar to this but without the external monitoring, the node monitored itself and shut down when it was no longer needed then a new one would start up later when there was more work to do.


Question:
If this question has already been asked I appologies, please point me in the right direction.

I was wondering if anyone has any insight into how StackOverflow pops up the "n new answers have been posted, load new answers" thing at the top of a question when you are adding a post. This seems like a very useful function for my forum web-site and I would like to know how it is done. I assume some ajax or advanced javascript of some kind.

Answer:
Look at this SO blog post:
https://blog.stackoverflow.com/2008/10/solving-the-fastest-gun-in-the-west-problem/
That said, the one implementable
recommendation that came out of this
discussion is an active, GMail like
notification when you are composing an
answer. We agreed with this feature
request, so Jarrod implemented it.
Here’s how it works:
When you start composing a reply, a timer is created.
Every minute, the page checks itself to see if new answers have
arrived.
If new answers arrive, the notification bar will tell you how
many, and offer to update the page for
you.
Answer updates are performed AJAX style, so they don’t interrupt
your current answer.


Question:
I have an SQL database with multiple tables, and I am working on creating a searching feature.  Other than having multiple queries for the different tables, is there a different way to go about said searching function?

I should probably add that a lot of my content is database driven to make upkeep easier.  Lucene will not work for this, correct?

Answer:
Different approaches to consider:
1) Multiple queries pre-baked, like you described.
2) Dynamic sql that you put together on the fly based on user-entered criteria.
3) If text is involved, based on SQL Server full text search or Lucene.
In my open source app BugTracker.NET, I do both 2 and 3 (using Lucene.NET).
I documented how I use Lucene.NET here:
http://www.ifdefined.com/blog/post/2009/02/Full-Text-Search-in-ASPNET-using-LuceneNET.aspx


Question:
I made a class that derives from Component:

public class MyComponent: System.ComponentModel.Component
{

}

I saw that Visual Studio put this code in for me:

protected override void Dispose(bool disposing)
{
    try
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
    }
    catch
    {
        throw;
    }
    finally
    {
        base.Dispose(disposing);
    }
}

MyComponent has a member that is a DataSet and maybe there's some other members that implement IDisposable.  What, if anything, do i need to modify with the Dispose() method to make sure things are cleaned up properly?  Thanks for helping.

Answer:
Change:
```
```
if (disposing && (components != null))
{
     components.Dispose();
}
```
```
to be:
```
```
if (disposing && (components != null))
{
    _dataset.Dispose();
    components.Dispose();
}
```
```


Question: Is there a way that you can have SERVEROUTPUT set to ON in sqlplus but somehow repress the message "PL/SQL procedure successfully completed" that is automatically generated upon completed execution of a plsql procedure?

Answer:
Use the command:
```
```
SET FEEDBACK OFF
```
```
before running the procedure.  And afterwards you can turn it back on again:
```
```
SET FEEDBACK ON
```
```


Question: I see many different Java terms floating around.  I need to install the JDK 1.6.  It was my understanding that Java 6 == Java 1.6.  However, when I install Java SE 6, I get a JVM that reports as version 11.0!  Who can solve the madness?

Answer:
JDK - Java Development Kit
JRE - Java Runtime Environment
Java SE - Java Standard Edition
SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).
The JDK includes the compiler and other tools needed to develop Java applications; JRE does not.  So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.
Edited
:
As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's
Java
web site, and in particular from the
Java SE
section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).
Edited 2011-04-06:
The world turns, and Java is now managed by Oracle, which bought Sun.  Later this year, the
```
sun.com
```
domain is supposed to go dark.  The new page (based on a redirect) is this
Java
page at the Oracle Tech Network.  (See also
java.com
.)
Edited 2013-01-11:
And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support.
Oracle
says no more public updates to Java 6 after February 2013.
Within a given version of Java, this answer remains valid.  JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on.  But the version 6 (1.6) is becoming antiquated.
Edited 2015-04-29:
And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too.  In April 2015, Oracle
affirmed
that it was no longer providing public updates to Java SE 7.  The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).


Question:
Does anyone know of any specific DSL implementations used to import legacy Oracle database schemas. I have tried to just run db:schema:dump on my existing db I want to port to a new ruby app. However, the rake dies about halfway through with out any error. It kinda just locks up. I started looking for the best way to tackle this and found examples of how to override some stuff for SQLServer but not much for Oracle.

I basically want to pull in the schema and generate a scaffold and model from it.

Is there a more simple way to do this or will I have to invent the wheel?

Answer:
did you try
```
rake --trace
```
?
By the way Oracle legacy schemas is a small cottage industry.
http://github.com/rsim/legacy_oracle_sample.git/README.txt
http://blog.rayapps.com/2008/06/28/activerecord-oracle-enhanced-adapter-version-111-released/
http://www.oracle.com/technology/pub/articles/saternos-rails.html
http://redsquirrel.com/cgi-bin/dave/dynamic/rails.multiple.oracle.dbs.html


Question:
I'd like something like

int minIndex = list.FindMin(delegate (MyClass a, MyClass b) {returns a.CompareTo(b);});

Is there a builtin way to do this in .NET?

Answer:
Try looking at these:
Min
Max
As long as your class implements IComparable, all you have to do is:
```
```
List<MyClass> list = new List();
//add whatever you need to add

MyClass min = list.Min();
MyClass max = list.Max();
```
```


Question:
What is the best plugin for Rails that gzips my webpage output?

Edit:
The company I am hosting with has stated they will not install mod_deflate.

Answer:
Have you tried enabling compression in apache via
mod_deflate
?


Question:
I have an Ant script with a junit target where I want it to start up the VM with a different working directory than the basedir. How would I do this?

Here's a pseudo version of my target.

<target name="buildWithClassFiles">
    <mkdir dir="${basedir}/UnitTest/junit-reports"/>
    <junit fork="true" printsummary="yes">
        <classpath>
            <pathelement location="${basedir}/UnitTest/bin"/>
            <path refid="classpath.compile.tests.nojars"/>
        </classpath>
        <jvmarg value="-javaagent:${lib}/jmockit/jmockit.jar=coverage=:html"/>
        <formatter type="xml" />
        <test name="GlobalTests" todir="${basedir}/UnitTest/junit-reports" />
    </junit>

</target>

Answer:
Have you tried:
```
```
<junit fork="true" printsummary="yes" dir="workingdir">
```
```


Question: I have a WPF TreeView with just 1 level of items.  The TreeView is data bound to an ObservableCollection of strings.  How can I ensure that the same icon appears to the left of each node in the TreeView?

Answer:
I think the best approach is to set a Style on the TreeView that will change the Template of the TreeViewItems to have the Image that you want.
The Template will probably need to be a StackPanel with an Image and a label control, you bind the image to your icon, and the label text to the strings from the Observable collection.
I've copied the relevant code snippet from a
Code Project article
, which covers this in more detail, but I think the below is all you'll need (This code goes in the TreeView.Resources element).
```
```
<Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="HeaderTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Name="img"
                           Width="20"
                           Height="20"
                           Stretch="Fill"
                           Source="image.png"/>
                    <TextBlock Text="{Binding}" Margin="5,0" />
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
```
```


Question:
I'd trying to style my ComboBoxes to match the rest of the UI but I'm having problems with the IsMouseOver highlighting. It highlights with the color I specify for a second and then fades back to the default color, kind of a cool effect but not what I'm going for. Here is my style:

<Style TargetType="ComboBox">
    <Style.Triggers>
        <Trigger Property="ComboBox.IsMouseOver" Value="True">
            <Setter Property = "Background" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

What can I do to make the background color stay?

Answer:
The problem is indeed due to the default template for the ComboBox. If you use
Reflector
to open the PresentationFramework.Aero assembly you can take a look at the ButtonChrome class. There is a method called OnRenderMouseOverChanged that is hiding the Red background.
Even though it is a lot of work, for ComboBox at least, you probably will want to override the default template for the ComboBox. You can get the basic idea of what the ComboBox temlpate is like by using
Show Me The Template
or
Blend
.
You can use your same style to override the template.
```
```
<Style TargetType="{x:Type ComboBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <!-- Template Here -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
```
```


Question:
I want to attach a 'click' event handler to the first child of an element with ID 'foo' using jQuery. I understand that the syntax for doing this is:

$('#foo:first-child').bind('click', function(event) {
    // I want to access the first child here
})

Within the handler body I want to access the element which caused the event to be fired. I've read somewhere that you can't simply refer to it via 'this', so how can I access it?

Answer:
```
```
$(this).doStuff()
```
```


Question:
I use _vimrc to configure my vim 7.2 (windows) default settings. One setting "set number" will display line numbers on the left side. My vim background color is white (I cannot find setting for this. Maybe the default is white. Anyway I accept this setting).

I would like the background color for line numbers to be Grey or dimmed color. What is the command I can put in my _vimrc to configure this default setting?

Answer:
```
```
highlight LineNr ctermfg=grey ctermbg=white
```
```


Question:
I'm having trouble getting a rails app on Dreamhost's Passenger to see compiled libraries in my ~/opt/lib directory.  I have to put them here because I don't have root access.

I can boot up my app in ./script/console and it sees them libraries just fine because I updated my .bash_profile's LD_LIBRARY_PATH environment variable to include ~/opt/lib.

I've tried putting ENV['LD_LIBRARY_PATH'] = '~/opt/lib' in my environment.rb file but it doesn't seem too help.  I get the following error from Passenger when I navigate to my site:
libodbcinst.so.1: cannot open shared object file: No such file or directory - /home/username/opt/lib/odbc.so

Anyone have experience with this?

Thanks

Answer:
I had similar issue with Passenger that I described in
http://blog.rayapps.com/2008/05/21/using-mod_rails-with-rails-applications-on-oracle/
But in your case this migth not work as you will not be able to change Dreamhost's httpd.conf file.
Other thing that you can try is to set LD_LIBRARY_PATH in .bashrc - according to
http://www.wavethenavel.com/jonathanpenn/2008/09/08/bootstrapping-a-dreamhost-account-for-rails-and-git/
this has worked in Dreamhost's case. Have not verified that Passenger will execute .bashrc before launching ruby.


Question:
I have the following HTML node structure:

<div id="foo">
  <div id="bar"></div>
  <div id="baz">
    <div id="biz"></div>
  </div>
  <span></span>
</div>

How do I count the number of immediate children of foo, that are of type div? In the example above, the result should be two (bar and baz).

Answer:
```
```
$("#foo > div").length
```
```
Direct children of the element with the id 'foo' which are divs. Then retrieving the size of the wrapped set produced.


Question:
I'm building a class library that will have some public & private methods. I want to be able to unit test the private methods (mostly while developing, but also it could be useful for future refactoring).

What is the correct way to do this?

Answer:
Declare them
```
internal
```
, and then use the
```
InternalsVisibleToAttribute
```
to allow your unit test assembly to see them.


Question:
I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:

sudo mod args

where mod is a perl script; so in python I would do

proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE)

The problem is that this mod script needs a few questions answered. For this I thought that the traditional

(stdout, stderr) = proc.communicate(input='y')

would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?

Answer:
The simplest thing to do would be the run the controlling script (the Python script) via
```
sudo
```
. Are you able to do that, or is that not an option?


Question: I need to implement an OpenID Provider in .Net and wondered....Is there's any OpenSource code already written and available?

Answer:
I just found
http://code.google.com/p/dotnetopenid/
Apologies for not search properly first.....
I don't seem to be able to delete this question (strange)
Instead, as penance, this question and answer will be marked community property so I don't benefit in any way from my stupidity..


Question:
We have a software product that evolves at the rhythm of clients' needs and of a more general roadmap.

Because we are in a SCRUM project environment, it happens very regurlarly that a new feature makes its way to the product, and then we are confronted with the choice of:

implementing this feature in an already released branch (not really the point of having a branch, then)

making a new branch - but then we have a branch every three weeks, and it is just not maintanable anymore

Not releasing the new feature is not an option, the clients don't want to wait for a long term milestone plan to get the features they want, and it's not always faisible to move the feature in a client module - sometimes we need to change the core of the product...

Has anyone any feedback on a good practice given those kind of constraints ?

Answer:
A new branch like( 'new_feature_branch') is there to materialize a
development effort
which is not compatible with the current branch (like 'release_branch')
So if your current release_branch is not very active, you can use it for the new feature (provided you define a label
before
developing this new feature, in case you need to cancel that process and go back to the state previous this new feature)
Making a new branch can be a good solution provided it is merged back on a regular basis (every 3 weeks) on the release branch, and then left out. It is especially recommended if you have some activities on the release_branch (like some hot bug-fixing). then the two efforts need to be kept separated.
Basically, it all comes down to your
merge workflow
definition.
Leave comments if you want me to detail some options you feel I did not address enough in depth.


Question:
I'm trying to export a Crystal Report to an HTML file, but when I call the Export method, I immediately get this error:

Source: Crystal Reports ActiveX Designer

Description: Failed to export the report.

I have tried both crEFTHTML40 and crEFTHTML32Standard as export format types - and both result in the same error.

Here is a highly simplified version of what I'm doing:

Dim objCRReport As CRAXDRT.Report
[...]
objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40
objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile
objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html"
objCRReport.Export False '<--- "Failed to export the report" error here

Please note that I am referencing the "Crystal Reports 9 ActiveX Designer Runtime Library" specifically.

Answer:
I'm not sure what you have in the
```
[...]
```
section but your code should include a call to open the report with an instance of the CRAXDRT Application.
```
```
Dim objCRReport As CRAXDRT.Report

'***********************************
Dim objCRApp As New CRAXDRT.Application

objCRReport = objCRApp.OpenReport("<YOUR REPORT FILENAME>", 1)
'***********************************

[...]
objCRReport.ExportOptions.FormatType = 32 'crEFTHTML40
objCRReport.ExportOptions.DestinationType = 1 'crEDTDiskFile
objCRReport.ExportOptions.DiskFileName = "C:\reportInHtmlFormat.html"
objCRReport.Export False '<--- "Failed to export the report" error here
```
```


Question:
It turns out install shield doesn't support file download resuming.

Is there a .net component that provides this functionality?

Answer:
I don't think so,but it's not that hard to write one . There are a lot of
HTTP Clients
already . All that you would need to do is checking to see if the web server actually supports resuming . Check this blog entry for a little info about HTTP and download resuming :
http://www.west-wind.com/WebLog/posts/244.aspx
All you would need to do is store the number of bytes read so far somewhere ( file , database ) , and read that when you're starting your application again . Be sure to check the md5 for the file ( if it has one ) , to ensure no errors occured .


Question:
I want to make some passages of a standard tooltip bold in a WinForms application. Is this possible?

If not, is there a (free) tooltip component that allows me to style them (preferably also border and background)?

Thanks!

Answer:
You can use this type :
Balloon tool tip
. This let you have some bold title and some color option. You might be able to modify the source to get underline, italic and bold inside the message.
Update:
You can modify the drawing of the ToolTip (and the FONT object of the text).
This is how to do it
. The code in this link is for the normal ToolTip, not the Balloon I posted above.


Question:
I'm currently running Lucene.net in a web application and am wondering about the best method, performance-wise.

I currently have it set up so that all index writes get processed together in a scheduled process, along with optimizing the index.

However for searching - I'm currently opening and closing the searcher per search, which I know isn't ideal.

What do you think would be the best approach in this situation?

I'll need to close and reopen the index searcher once the updates/optimization is processed so the scheduled process (which is a windows console app) needs to communicate it's finished to the web application.

Answer:
I just integrated Lucene.NET into BugTracker.NET.  I'm not sure that what I did is the best, but it seems to be working well.
I create the index at app startup.
I create a searcher and keep it around so that the index isn't reloaded with each search.  All threads share the same searcher.  When the searcher searches, it grabs a lock.
Meanwhile, I have an IndexWriter that updates the index when there is a data change.  It is just changing a little bit so it does its task quick.   When it runs, it grabs the same lock, destroys the searcher, updates the index, and the re-recreates the searcher.   The new searcher stays around until the next update of the index.   The searcher always is working with an up-to-date index.
You can get the BugTracker.NET source and look at the files my_lucene.cs and search_text.aspx.   It's all in those two files, and there isn't that much code.


Question:
I have a CSV data file with rows that may have lots of columns 500+ and some with a lot less.  I need to transpose it so that each row becomes a column in the output file.  The problem is that the rows in the original file may not all have the same number of columns so when I try the transpose method of array I get:

`transpose': element size differs (12 should be 5) (IndexError)

Is there an alternative to transpose that works with uneven array length?

Answer:
I would insert nulls to fill the holes in your matrix, something such as:
```
```
a = [[1, 2, 3], [3, 4]]

# This would throw the error you're talking about
# a.transpose

# Largest row
size = a.max { |r1, r2| r1.size <=> r2.size }.size

# Enlarge matrix inserting nils as needed
a.each { |r| r[size - 1] ||= nil }

# So now a == [[1, 2, 3], [3, 4, nil]]
aa = a.transpose

# aa == [[1, 3], [2, 4], [3, nil]]
```
```


Question:
So I'm creating some HTML using javascript based on where the user clicks on the page. On page load the script replaces an empty div with a ul and some data. The user clicks on that data to receive more and so on. Now when the user navigates off the page and then hits the back button to go back to the page, IE displays a blank page with the replaced divs, in all other browsers, FF, Opera, Safari, the page either reloads to the initial ul or goes back to the last state with the dynamic data in it.

Anyone have an idea as to what might be happening here? Any help is appreciated.

Answer:
I would insert nulls to fill the holes in your matrix, something such as:
```
```
a = [[1, 2, 3], [3, 4]]

# This would throw the error you're talking about
# a.transpose

# Largest row
size = a.max { |r1, r2| r1.size <=> r2.size }.size

# Enlarge matrix inserting nils as needed
a.each { |r| r[size - 1] ||= nil }

# So now a == [[1, 2, 3], [3, 4, nil]]
aa = a.transpose

# aa == [[1, 3], [2, 4], [3, nil]]
```
```


Question:
We're looking for a way to log any call to stored procedures in Oracle, and see what parameter values were used for the call.

We're using Oracle 10.2.0.1

We can log SQL statements and see the bound variables, but when we track stored procedures we see bind variables B1, B2, etc. but no values.

We'd like to see the same kind of information we've seen in MS SQL Server Profiler.

Thanks for any help

Answer:
You could take a look at the
DBMS_APPLICATION_INFO package
.  This allows you to "instrument" your PL/SQL code with whatever information you want - but it does entail adding calls to each procedure to be instrumented.
See also
this AskTom thread
on using DBMS_APPLICATION_INFO to monitor PL/SQL.


Question:
A client has asked whether or not I can provide some support for his intranet which runs on Oracle Application Server Portal. Not having used this technology before I thought I'd ask if anyone else has and what they thought of developing for it.

I'm a c#/ASP.NET developer so I note with apprehension that there's no mention of .NET in the developers guide. Anyone tried to make the two work together and lived to tell the tale?

Answer:
The only experience I've had with an Oracle Portal was obliquely, when I inherited a system that used one for a relatively simple maintenance web application.  A large part of my opinion of Oracle's stuff comes from my background with SQL Server/ASP.NET, but Oracle is just plain harder to set up and administer and keep running, and that applies not just to the database but also to auxiliary stuff like Oracle Portal, their SOA suite, their Mobility Server etc.  Even experienced Oracle people tend to agree with this, so hopefully I won't piss anyone off.
I would definitely not provide support for an Oracle Portal application (or any other Oracle product, for that matter) unless I had a lot of experience with the tools.


Question:
How do I find a stored procedure in a Sybase database given a text string that appears somewhere in the proc? I want to see if any other proc in the db has similar logic to the one I'm looking at, and I think I have a pretty unique search string (literal)

Edit:

I'm using Sybase version 11.2

Answer:
In SQL Anywhere and Sybase IQ:
```
```
select * from SYS.SYSPROCEDURE where proc_defn like '%whatever%'
```
```
I'm not that familiar with ASE, but according to the docs (available from sybooks.sybase.com), it's something like:
```
```
select * from syscomments where texttype = 0 and text like '%whatever%'
```
```


Question:
I am loading some data from an XML document, modifying it, and writing back out to XML.  The reading is done using a SAX parser library and the writing is done with a piece of custom code.  Sometimes, the file is modified externally, and extra elements are added (such as references to stylesheets).  Rather than losing these extra elements when I load and save the file, I would like to pass through any unknown tags so that they appear

When unknown elements are separate from interpreted elements, it should be straightforward to save unknown elements and attributes as strings and output these afterwards, but when they are interspersed and nested inside interpreted elements, it becomes less obvious.

Can anybody suggest a succinct way to do this?  Would it be simpler to switch to a DOM parser?  Performance is not an issue.

NB. I am working in C++ with the Gnome Glib::Markup::Parser, but would prefer language/library agnostic answers.

Answer:
I don't know how you've written your content handler, but it's methods should be called on all events, including on the external modifications you want to preserve.  Your
```
startElement()
```
and
```
endElement()
```
callbacks could test element name and attributes to decide whether to call specialized methods on the elements to be modified, but by default just reconstruct and output the event on which the callback was called.  In that way, any elements you don't specifically handle specially just get output by default.
You could also do the same kind of thing in XSLT.  Take an identity transform (a stylesheet that outputs exactly what it is given for input) and add to it templates with more specific match expressions for the custom modifications.  I find XSLT easier to work with for most applications than either SAX or DOM.


Question:
Similar to the one here on StackOverFlow, I would be needing to implement a way for people to vote up and vote down comments in a forum like site.

However instead of having a generic overall score, we will display the total amount of "thumbs up" and "thumbs down". The overall score will be needed for filtering purposes, such as "sort by highest rated", "show only ratings with + 3"

What is the best implementation strategy?

As a user suggested, I would also be storing the information who casted the vote

Answer:
Well you'll need to store ratings (Comment ID, UserID, Vote-Value) so you can calculate and stop duplicate voting but I would strongly suggest you also add a VotesUp and VotesDown fields on your main comment entity.
Why the duplication? Speed. You're going to be doing disgusting amounts of
```
SUM-WHERE
```
statements otherwise and they'll run your database server into the ground. A few extra bytes on the header record and you'll be able to sort and filter to your heart's content.
Edit: If you're going to also sort by overall score in some cases, you might want to add a third field (VoteTotal).
Edit 2: The duplication is pointless if you're able to cache all the comment headers in memory. That's a lot of data though and you'd need a ton of memory to effectively cache it. If you're not a billionaire, I'd just duplicate the data.


Question: How do implement the iterator pattern in VB.NET, which does not have the yield keyword?

Answer:
Hmm, looks like you might be
out of luck
:
I was struggling with an issue today when converting some C# to VB.NET. C# has a really cool "yield return" statement that is used in an iterator block to provide a value to the enumerator object. VB.NET does not have the "yield" keyword. So, there are a few solutions (none of which are really clean) to get around this. You could use a return statement to return the value if you are looping through and would like to break an enumerator and return a single value. However, if you'd like to return the entire enumeration, create a List() of the child type and return the list. Since you are usually using this with an IEnumerable, the List() will work nice.
That was written a year ago, not sure if anyone has come up with anything else better since then..
Edit: this will be possible in the version 11 of VB.NET (the one after VS2010), support for iterators is planned.  The spec
is available here
.


Question:
I have a QDirModel whose current directory is set. Then I have a QListView which is supposed to show the files in that directory. This works fine.

Now I want to limit the files shown, so it only shows png files (the filename ends with .png). The problem is that using a QSortFilterProxyModel and setting the filter regexp will try to match every parent of the files as well. According to the documentation:

For hierarchical models, the filter is
  applied recursively to all children.
  If a parent item doesn't match the
  filter, none of its children will be
  shown.

So, how do I get the QSortFilterProxyModel to only filter the files in the directory, and not the directories it resides in?

Answer:
We ran into something similar where I work, and ended up making our own proxy model to do our filtering.  However, looking through the documentation for what you want (which seems like it would be a more common case), I came across two possibilities.
You might be able to set a name filter on the QDirModel and filter things that way.  I have no idea if this will work like you want, or if the name filters apply to directories also.  The documentation is kind of sparse on these.
Subclass the QSortFilterProxyModel and override the
```
filterAcceptsRow
```
function.  From the documentation:
Custom filtering behavior can be achieved by reimplementing the filterAcceptsRow() and filterAcceptsColumn() functions.
Then you could presumably use the model index to check if the index item is a directory (automatically accept) or a file (filter on filename).


Question: I was wondering what would be the best approach you guys would take to relocate an entire Eclipse workspace? Assuming it's either versioned and exported, what would you do? Import the file? Checkout the whole thing from the repo? Thanks much in advance!

Answer:
Maybe I'm missing something, but wouldn't you just start Eclipse, and either select the new workspace to use or select
```
Switch workspace
```
from the
```
File
```
menu?


Question:
I have an SQLite table that contains a BLOB I need to do a size/length check on. How do I do that?

According to documentation length(blob) only works on texts and will stop counting after the first NULL. My tests confirmed this. I'm using SQLite 3.4.2.

Answer:
I haven't had this problem, but you could try
```
length(hex(glob))/2
```
Update (Aug-2012):
For SQLite 3.7.6 (released April 12, 2011) and later,
```
length(blob_column)
```
works as expected with both text and binary data.


Question:
I am in a process of designing a custom SharePoint application. On a previous project, all the data was kept in SharePoint lists and that's the way I've been trying now. But, I'm getting to the point where the data model grows and I feel a need to normalize it and split one logical entity into several physical lists. I'm wondering if I should switch from the SP lists to a classic database. On one hand, I am happy with the SharePoint out-of-box New Item, Edit Item, All Items forms; on the other hand I'm worried that the performance will suffer once I have to query joined data (if it stays in SPLists).

If you have any insight or experience with this problem, please share. Thanks.

Answer:
If you have complex queries, I suggest you put them into a separate database. Lists are good when the data model doesn't grow that often.
Extending the amount of fields inside the columns of a list includes updating the ContentTypes directly with an STSADM that you will have to code. However, querying the data directly from the database (with some cache of course) will lead to a faster development without having to update all ContentTypes linked to every lists associated with it.
Of course, if you activate the Caching, the data queryied from the database will be cached at the page output level.


Question:
In this question, I was given a really cool answer to alternating an image and its description between left and right, respectively.  Now I want to apply styling to both, e.g. padding-top, padding-bottom etc. How do I apply a style to both the RowStyle and AlternatingRowStyle in this scenario.

<AlternatingRowStyle CssClass="ProductAltItemStyle" />
<RowStyle CssClass="ProductItemStyle" />
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <div class="Image"><asp:Image runat="server" ID="productImage" ImageUrl='<%# Eval("imageUrl") %>' /></div>
            <div class="Description"><asp:Label runat="server" ID="lblProductDesc" Width="100%" Text='<%# Eval("productDesc") %>'></asp:Label></div>
        </ItemTemplate>
    </asp:TemplateField>

Answer:
Here's how you do it:
```
```
.ProductAltItemStyle, .ProductItemStyle {
    // CSS Rules that apply to both go here
}
```
```


Question:
How can I convert a varchar field of the form YYYYMMDD to a datetime in T-SQL?

Thank you.

Answer:
```
```
select convert(datetime, '20081030')
```
```


Question: I like Vim's visual mode. v for highlight/select chars or lines, Ctrlv for rectangle highlighting, as far as I know (I am a beginner). Is there any way to use visual mode to highlight last two chars, for example, on each line for some selected lines? The selected lines are in different length. Basically, I would like to find a quick way to remove the last two chars for some selected lines. Not sure I can use visual mode to highlight irregular area.

Answer:
I can't think of a way to do this in visual mode, but you could use a command like this to do it...
```
```
:10,20 normal $xx
```
```
This would go to each line between line number 10 and 20, use $ to go to the end of the line, and then use x twice to delete two characters.  Normal just tells vim to use the following symbols as if they were keyboard shortcuts entered in normal mode (i.e after hitting esc).
Does that help?


Question:
I tried this:

ALTER TABLE My.Table DROP MyField

and got this error:

-MyField is not a constraint.

-Could not drop constraint. See previous errors.

There is just one row of data in the table and the field was just added.

EDIT:
Just to follow up, the sql was missing COLUMN indeed.
Now I get even more seriously looking errors though:

The object 'some_object__somenumbers' is dependent on column 'MyField'

ALTER TABLE DROP COLUMN MyField failed because one or more objects access this column.

EDIT:

ALTER TABLE TableName DROP Constraint ConstraintName

worked, after that I was able to use the previous code to remove the column. Credit goes to both of you, thanks.

Answer:
I think you are just missing the COLUMN keyword:
```
```
ALTER TABLE TableName DROP COLUMN ColumnName
```
```
You will also need to make sure that any constraint that is depending on ColumnName is dropped first.
You can do this by:
```
```
ALTER TABLE TableName DROP ConstraintName
```
```
For each constraint that you have.
If you have indexes based on the column, you will also need to drop those indexes first.
```
```
DROP INDEX TableName.IndexName
```
```


Question:
I have a DTS package that drops a table then creates it and populates it but sometimes something happens and the package fails after the drop table.  If it's rerun it fails cuz the table hasn't been created yet.

Is there something like "if exists" for SQLServer 2000 like in MySQL?

thanks.

Answer:
```
```
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))
DROP TABLE TableName;
GO
```
```
You can check a
list of type definitions in the sys.objects table here
if you want to check if other objects in your database exist.


Question:
I am developing a C# program, and i have one function that consumes too much CPU. I would like to know a way to control this by code (not with any external application) and restrict the percentage of CPU usage.
For example, if it uses 90% of the CPU usage, to make my app consume only a 20%, even if it becomes slower. It must be done automatically and from within the app.
If you provide a class, it would be fantastic.

Answer:
I don't know if you can do that, but you can change the thread priority of the executing thread via the
Priority
property.  You would set that by:
```
```
Thread.CurrentThread.Priority = ThreadPriority.Lowest;
```
```
Also, I don't think you really want to cap it.  If the machine is otherwise idle, you'd like it to get busy on with the task, right?  ThreadPriority helps communicate this to the scheduler.


Question: I want to fade out an element and all its child elements after a delay of a few seconds. but I haven't found a way to specify that an effect should start after a specified time delay.

Answer:
```
```
setTimeout(function() { $('#foo').fadeOut(); }, 5000);
```
```
The 5000 is five seconds in milliseconds.


Question: Sometimes you need to upgrade the database with many rows that you have in a datatable or you have an array full of data, instead of putting all this data together in a string and then splitting in SQL SERVER, or instead of iterating the datatable in the code row by row and updating database, is there any other way? Is there other type of variables besides the traditional ones in SQL SERVER 2005?

Answer:
There's a few ways to do this.
If you're simply inserting rows, then I would create a DataTable object with the information in it, then use the SqlBulkCopy object:
```
```
SqlBulkCopy copier = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.Default);
copier.BatchSize = 500; //# of rows to insert at a time
copier.DestinationTableName = "dbo.MyTable";
copier.WriteToServer(myDataTable);
```
```
Another option is to wrap your data in xml (however you want to do that), and send it to your stored procedure (which does whatever you need it to do) using the sql 2005 'xml' data type


Question:
I have a User object that has a Country object on it. I map this with a many-to-one tag in the User mapping file:

<many-to-one name="Country" column="CountryID" cascade="none"/>

How do I update a User's country?

At the moment my UI has a dropdown of countries and the ID of the new country is passed to the controller. The controller then sets the ID of the User's country from that value. So:

var user = session.Get<User>(userID);
user.Country.ID = Convert.ToInt32(Request.Form["Country_ID"]);

But when I call:

session.SaveOrUpdate(user);

I get an error saying that "identifier of an instance of Country was altered from 7 to 8". Presumably this is because the Country object is marked as dirty by NHibernate? I don't want to update the country object though, just the ID reference in the User. Is it possible to do it this way?

Thanks,
Jon

Answer:
```
```
var user = session.Get<User>(userID);
user.Country = session.Get<Country>(Convert.ToInt32(Request.Form["Country_ID"]));
```
```
You must retrieve the country from the database and then set it to the user


Question:
My co-founder is currently asking on our blog for an embeddable code widget.

http://devver.net/blog/2008/10/someone-please-build-an-awesome-embeddable-code-widget/

Basically we want something like http://pastie.org/ or http://codepad.org/ but we really want to embed the code section in our blog. We know there are plugins for common blogs and server side solutions, but it would be great to be able to just embed a little javascript and have nicely formatted code anywhere...

Does something like this exist? Have we just missed it?

Answer:
I think you want a javascript syntax highlighter
http://code.google.com/p/syntaxhighlighter/
http://shjs.sourceforge.net/
http://www.google.com/search?q=javascript+syntax+highlighter
Sometimes you just keep thinking in the wrong keywords ;-)


Question:
I noticed the specificaition for Collections.sort:

public static <T> void sort(List<T> list, Comparator<? super T> c)

Why is the "? super" necessary here?  If ClassB extends ClassA, then wouldn't we have a guarantee that a Comparator<ClassA> would be able to compare two ClassB objects anyway, without the "? super" part?

In other words, given this code:

List<ClassB> list = . . . ;
Comparator<ClassA> comp = . . . ;
Collections.sort(list, comp);

why isn't the compiler smart enough to know that this is OK even without specifying "? super" for the declaration of Collections.sort()?

Answer:
Josh Bloch had a talk at Google I/O this year, called
Effective Java Reloaded
, which you may find interesting. It talks about a mnemonic called "Pecs" (producer
```
extends
```
, consumer
```
super
```
), which explains why you use
```
? extends T
```
and
```
? super T
```
in your input parameters (only; never for return types), and when to use which.


Question:
Suppose you want to make an async request in JavaScript, but you want to pass some state along to the callback method. Is the following an appropriate use of closures in JavaScript?

function getSomethingAsync(someState, callback) {
    var req = abc.createRequestObject(someParams);
    req.invoke(makeCallback(someState, callback));
}

function makeCallback(someState, callback) {
    return function getSomethingCallback(data) {
        var result = processDataUsingState(data, someState);
        callback(result); // alternately/optionally pass someState along to result
    }
}

If not, is there a better or more idiomatic way?

Answer:
its better (nicer) to use anonymous functions:
```
```
function getSomethingAsync (someState, callback) {
    req.invoke (function (data) {
       var result = processDataUsingState (data, someState);
       callback (result);
    });
}
```
```


Question:
When I try to use curl or file_get_contents to read something like http://example.com/python/json/ from http://example.com/ I should be getting a JSON response, but instead I get a 404 error. Using curl or any other method outside my own domain works perfectly well.

echo file_get_contents('http://example.com/python/json/'); => 404
echo file_get_contents('http://google.com'); => OK

The same script works on my laptop, but I can't figure out what the difference is.

Answer:
It looks like example.com is not the default domain for the IP address and that file_get_contents uses HTTP/1.0 instead of HTTP/1.1 and/or does not send a Host: header. Try the curl support in PHP instead:
```
```
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
```
```
Alternatively the /etc/hosts file sets the wrong IP address for example.com.


Question:
How do I discover classes at runtime in the classpath which implements a defined interface?

ServiceLoader suits well (I think, I haven't used it), but I need do it in Java 1.5.

Answer:
There is no reliable way to know what classes are in the classpath. According to its
documentation
, ServiceLoader relies on external files to tell it what classes to load; you might want to do the same. The basic idea is to have a file with the name of the class(es) to load, and then use reflection to instantiate it/them.


Question:
I want to get the size of a drive (or UNC path pointing to a partition would be nice, but not required), as well as free space for said drive (or UNC path).  This doesn't need to work cross platform; only in Windows.

I know it's easy to do in Java 6, but that's not an option; I'm stuck with Java 5.

I can get the free space available by doing:

cmd.exe /c Z:\ /-c

or

cmd.exe /c \\server\share /-c

and just parsing out the resulting bytes free.  However I can't seem to find a way to get the total drive size.

Any suggestions?

Answer:
One way to do it would be to use fsutil on the command line.  It returns something like this:
```
```
D:\>fsutil fsinfo ntfsinfo c:
NTFS Volume Serial Number :       0xd49cf9cf9cf9ac5c
Version :                         3.1
Number Sectors :                  0x0000000004a813ff
Total Clusters :                  0x000000000095027f
Free Clusters  :                  0x00000000002392f5
Total Reserved :                  0x0000000000000490
Bytes Per Sector  :               512
Bytes Per Cluster :               4096
Bytes Per FileRecord Segment    : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length :           0x000000000e70c000
Mft Start Lcn  :                  0x00000000000c0000
Mft2 Start Lcn :                  0x0000000000000010
Mft Zone Start :                  0x0000000000624ea0
Mft Zone End   :                  0x0000000000643da0
```
```
Multipy your number of sectors times the bytes per sector to get your size.


Question:
Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I've seen all sorts of bits all over the internet where verbatim LIKE SQL clauses are used - but from what I've heard that isn't the 'correct' way of doing it.

Is there a 'proper' Rails way?

Answer:
If you're looking to do the search in the database then you'll need to use SQL.
And, of course, you'll need to do the search in the database otherwise you need to load
all
the objects into Ruby (which isn't a good thing).
So, you will need something like
```
```
MyModel.find(:all, :conditions => ["field LIKE ?", "#{prefix}%"])
```
```
where
```
prefix
```
is a variable with the string you're looking for.
In Rails 3.0+ this becomes:
```
```
MyModel.where("field LIKE :prefix", prefix: "#{prefix}%")
```
```


Question:
What would be the best hashing algorithm if we had the following priorities (in that order):

Minimal hash collisions

Performance

It doesn't have to be secure. Basically I'm trying to create an index based on a combination of properties of some objects. All the properties are strings.

Any references to c# implementations would be appreciated.

Answer:
There is no one single optimum hashing algorithm.  If you have a known input domain you can use a perfect-hashing generator such as
gperf
to generate a hashing algorithm that will get a 100% rate on that particular input set.  Otherwise, there is no 'right' answer to this question.


Question:
I've been a C# programmer for about 2 years total, and professionally for a little more than 1. I work at a company as a developer on an application that began before the days of .NET 2. My question is this:

What is the benefit to use databinding from sql queries directly to a control over querying and manually adding items to the control? Is this approach generally considered cleaner, and simpler in terms of deploying? Will there still be cases where manually adding would give more fine grained control over the display / value of the data?

I'm asking because I've been assigned some bugs that deal with some controls that populate themselves based off query results, and would love to clean up unnecessary logic and push that off to the libraries to handle instead of me.

Note: We are using .NET 2.0

Answer:
I personally find that using the
```
```
control.DataSource = YourSource;
control.DataBind();
```
```
process is much easier, you don't have to do the iteration, and overall reduces LOC.
If working with DropDownLists and other controls you will most likely set the DataValueField and DataTextField properties as well.


Question:
The MSDN documentation says that

public class SomeObject
{
  public void SomeOperation()
  {
    lock(this)
    {
      //Access instance variables
    }
  }
}

is "a problem if the instance can be accessed publicly". I'm wondering why? Is it because the lock will be held longer than necessary? Or is there some more insidious reason?

Answer:
Because if people can get at your object instance (ie: your
```
this
```
) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on
```
this
```
internally, so this may cause problems (possibly a deadlock)
In addition to this, it's also bad practice, because it's locking "too much"
For example, you might have a member variable of
```
List<int>
```
, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.


Question:
Is there a library out there which I can use in my current ASP.NET app, to validate queryStrings?

Edit ~ Using Regex to look for patterns, like string, only, numeric only, string with length x,...etc

Thanks

Answer:
Don't know about a library, but you can use to check if the querystring exists:
```
```
if (!String.IsNullOrEmpty(Request.Querystring["foo"]))
{
   // check further
}
else
{
   // not there, do something else
}
```
```
If you want to use Reglar Expressions to further validate, you can create a class that accepts the string and return a boolean.
```
```
public static Boolean IsValid(String s)
{
    const String sRegEx = @"regex here";

    Regex oRegEx = new Regex(sRegEx , RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
    MatchCollection oMatches = oRegEx.Matches(s);

    return (oMatches.Count > 0) ? true : false;
}
```
```
This is a good free program to help you build the regluar expressions:
Expresso


Question:
Does anyone know of any DLLs (preferably .net) that encapsulate the lua 5.1 compiler?  I'm working on a .net project where part of it needs to compile lua scripts, and i would rather have a DLL that i could send script code to instead of sending the script to a temporary file and running luac.exe.

Edit: I'd need a .NET library that implements luac in such a way that it outputs standard lua bytecode (not a lua library that compiles to the CLR).  Compiling the lua c source code didn't work, as when i went to include a reference to the dll in a c# project, visual studio complained that it wasnt a valid assembly.  My searches so far haven't found anything.

Answer:
Have you looked into using something like Spring's proxy functionality?  You tell it a bit about the webservice in a spring config file, and all your client code has to deal with is an interface that you create - it doesn't even have to know that there is a web service on the other side!
Example Spring config:
```
```
<bean id="myService" class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean">
    <property name="serviceFactoryClass" value="org.apache.axis.client.ServiceFactory"/>
    <property name="wsdlDocumentUrl" value="classpath://META-INF/myService.wsdl"/>
    <property name="namespaceUri" value="http://com/myService"/>
    <property name="endpointAddress" value="http://server/MyService"/>
    <property name="serviceName" value="MyService"/>
    <property name="portName" value="MyService"/>
    <property name="serviceInterface" value="com.IMyService"/>
    <property name="lookupServiceOnStartup" value="false"/>
</bean>
<bean id="myClient" class="com.MyServiceClient">
    <property name="myService" ref="myService"/>
</bean>
```
```
Java:
```
```
public interface IMyService {
    Foo getFoo();
}

public class MyServiceClient {
    private IMyService myService;
    public void setMyService(IMyService myService) {
        this.myService = myService;
    }

    public void DoStuff() {
        Foo foo = myService.getFoo();
        ...
    }
}
```
```
For custom objects, you may need to subclass JaxRpcPortProxyFactoryBean:
```
```
public class MyServiceFactoryBean extends JaxRpcPortProxyFactoryBean {
protected void postProcessJaxRpcService(Service service) {
    TypeMappingRegistry registry = service.getTypeMappingRegistry();
    TypeMapping mapping = registry.createTypeMapping();
            QName qName = new QName("http://com/myService", "Foo");
    mapping.register(Foo.class, qName,
            new BeanSerializerFactory(Foo.class, qName),
            new BeanDeserializerFactory(Foo.class, qName));
    }
}
```
```
What I love about this is that code that
shouldn't
care about the implementation of the service
doesn't
.  Testing becomes a breeze, and the cohesion of your classes is
much
better.


Question:
I want to have a map that has a homogeneous key type but heterogeneous data types.

I want to be able to do something like (pseudo-code):

boost::map<std::string, magic_goes_here> m;
m.add<int>("a", 2);
m.add<std::string>("b", "black sheep");

int i = m.get<int>("a");
int j = m.get<int>("b"); // error!

I could have a pointer to a base class as the data type but would rather not.

I've never used boost before but have looked at the fusion library but can't figure out what I need to do.

Thanks for your help.

Answer:
How can I build a <favorite container> of objects of different types?
You can't, but you can fake it pretty well. In C/C++ all arrays are homogeneous (i.e., the elements are all the same type). However, with an extra layer of indirection you can give the appearance of a heterogeneous container (a heterogeneous container is a container where the contained objects are of different types).
There are two cases with heterogeneous containers.
The first case occurs when all objects you want to store in a container are publicly derived from a common base class. [...]
The second case occurs when the object types are disjoint — they do not share a common base class.
The approach here is to use a handle class. The container is a container of handle objects (by value or by pointer, your choice; by value is easier). Each handle object knows how to "hold on to" (i.e., maintain a pointer to) one of the objects you want to put in the container. You can use either a single handle class with several different types of pointers as instance data, or a hierarchy of handle classes that shadow the various types you wish to contain (requires the container be of handle base class pointers). The downside of this approach is that it opens up the handle class(es) to maintenance every time you change the set of types that can be contained. The benefit is that you can use the handle class(es) to encapsulate most of the ugliness of memory management and object lifetime. Thus using handle objects may be beneficial even in the first case.


Question:
In MS SQL 2005 or T-SQL, you can do something like:

SELECT T.NAME, T.DATE
  FROM (SELECT * FROM MyTable WHERE ....) AS T

I failed to try the similar SQL on Oracle 9i DB. In MS SQL, the nested SQL is treated as a temporary/dynamic view created on fly and destroyed afterward. How can I do the similar thing in Oracle? I really don't want to create a view to do it.

Answer:
I believe it chokes on the "as".
```
```
SELECT T.NAME, T.DATE
  FROM (SELECT * FROM MyTable WHERE ....)  T
```
```
should work.


Question:
Basically, I have an iframe embedded in a page and the iframe has some JavaScript routines I need to invoke from the parent page.

Now the opposite is quite simple as you only need to call parent.functionName(), but unfortunately, I need exactly the opposite of that.

Please note that my problem is not changing the source URL of the iframe, but invoking a function defined in the iframe.

Answer:
Quirksmode had a
post on this
.
Since the page is now broken, and only accessible via archive.org, I reproduced it here:
IFrames
On this page I give a short overview of accessing iframes from the page they’re on. Not surprisingly, there are some browser considerations.
An iframe is an inline frame, a frame that, while containing a completely separate page with its own URL, is nonetheless placed inside another HTML page. This gives very nice possibilities in web design. The problem is to access the iframe, for instance to load a new page into it. This page explains how to do it.
Frame or object?
The fundamental question is whether the iframe is seen as a frame or as an object.
As explained on the
Introduction to frames
pages, if you use frames the browser creates a frame hierarchy for you (
```
top.frames[1].frames[2]
```
and such). Does the iframe fit into this frame hierarchy?
Or does the browser see an iframe as just another object, an object that happens to have a src property? In that case we have to use a standard
DOM call
(like
```
document.getElementById('theiframe'))
```
to access it.
In general browsers allow both views on 'real' (hard-coded) iframes, but generated iframes cannot be accessed as frames.
NAME attribute
The most important rule is to give any iframe you create a
```
name
```
attribute, even if you also use an
```
id
```
.
```
```
<iframe src="iframe_page1.html"
    id="testiframe"
    name="testiframe"></iframe>
```
```
Most browsers need the
```
name
```
attribute to make the iframe part of the frame hierarchy. Some browsers (notably Mozilla) need the
```
id
```
to make the iframe accessible as an object. By assigning both attributes to the iframe you keep your options open. But
```
name
```
is far more important than
```
id
```
.
Access
Either you access the iframe as an object and change its
```
src
```
or you access the iframe as a frame and change its
```
location.href
```
.
document.getElementById('iframe_id').src = 'newpage.html';
frames['iframe_name'].location.href = 'newpage.html';
The frame syntax is slightly preferable because Opera 6 supports it but not the object syntax.
Accessing the iframe
So for a complete cross–browser experience you should give the iframe a name and use the
```
```
frames['testiframe'].location.href
```
```
syntax. As far as I know this always works.
Accessing the document
Accessing the document inside the iframe is quite simple, provided you use the
```
name
```
attribute. To count the number of links in the document in the iframe, do
```
frames['testiframe'].document.links.length
```
.
Generated iframes
When you generate an iframe through the
W3C DOM
the iframe is not immediately entered into the
```
frames
```
array, though, and the
```
frames['testiframe'].location.href
```
syntax will not work right away. The browser needs a little time before the iframe turns up in the array, time during which no script may run.
The
```
document.getElementById('testiframe').src
```
syntax works fine in all circumstances.
The
```
target
```
attribute of a link doesn't work either with generated iframes, except in Opera, even though I gave my generated iframe both a
```
name
```
and an
```
id
```
.
The lack of
```
target
```
support means that you must use JavaScript to change the content of a generated iframe, but since you need JavaScript anyway to generate it in the first place, I don't see this as much of a problem.
Text size in iframes
A curious Explorer 6 only bug:
When you change the text size through the View menu, text sizes in iframes are correctly changed. However, this browser does not change the line breaks in the original text, so that part of the text may become invisible, or line breaks may occur while the line could still hold another word.


Question:
Is it possible to typedef long types that use templates?  For example:

template <typename myfloat_t>
class LongClassName
{
    // ...
};

template <typename myfloat_t>
typedef std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > LongCollection;

LongCollection<float> m_foo;

This doesn't work, but is there a way to achieve a similar effect?  I just want to avoid having to type and read a type definition that covers almost the full width of my editor window.

Answer:
No, that isn't possible currently. It will be made possible in C++0X AFAIK.
The best I can think of is
```
```
template<typename T> struct LongCollection {
    typedef std::vector< boost::shared_ptr< LongClassName<T> > > type;
};

LongCollection<float>::type m_foo;
```
```


Question:
Looking up LINQ and Or in google is proving somewhat difficult so here I am.

I want to so the following:

(from creditCard in AvailableCreditCards
where creditCard.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant())
**or creditCard.CardNumber.().Contains(txtFilter.Text)**
orderby creditCard.BillToName
select creditCard)

Answer:
You can use the .Where() function to accomplish this.
```
```
var cards = AvailableCreditCards.Where(card=> card.CardNumber.Contains(txtFilter.Text) || card.BillToName.ToLowerInvariant().Contains(txtFilter.Text.ToLowerInvariant());
```
```


Question: In AJAX applications that need to poll the server in regular intervals (like a chat applications), what is the recommended minimum time between two calls, so that the update is done as quickly as possible? What times are considered as hogs for the server and the client?

Answer:
The answer to this question is very much dependent on:
How much data is sent in each poll
How many users you will have online at a time
How much bandwidth your server can handle
How "fresh" the data on your client needs to be
Without knowing any of these specifics for your app, it's going to be hard to give a good recommendation. Have you looked into a method where the client connects to the server, and the server holds the connection open until there is data available? Then the server delivers the data, and the client immediately reconnects and waits again. That can be tricky to get working, but you might be able to maximize both efficiency of bandwidth AND responsiveness that way.


Question:
How do I get a function's name as a string?

def foo():
    pass

>>> name_of(foo)
"foo"

Answer:
```
```
my_function.func_name
```
```
There are also other fun properties of functions. Type
```
dir(func_name)
```
to list them.
```
func_name.func_code.co_code
```
is the compiled function, stored as a string.
```
```
import dis
dis.dis(my_function)
```
```
will display the code in
almost
human readable format. :)


Question:
An easy jQuery question.

I have several identical forms ( except their name ) on one page with a few hidden inputs in each. I want to refer to them by using the form name and  then the input name. ( the input names are not unique in my page )

So for instance:

var xAmt = $('#xForm'+num).('#xAmt');

I really want to supply these values to an AJAX POST

    $.ajax({
      url: "X.asp",
      cache: false,
      type:  "POST",
      data:  "XID=xID&xNumber=xNum&xAmt=xAmt",

...

If I can get the values in the AJAX call even better.

Answer:
Looks like you want
```
formSerialize()
```
(or even
```
ajaxSubmit()
```
) from the
jQuery forms plugin
.


Question:
I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this:

myvalue = CType(value, "String, Integer or Boolean")

The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database.

Is this possible?

Answer:
Sure, but
```
myvalue
```
will have to be defined as of type
```
Object
```
, and you don't necessarily want that. Perhaps this is a case better served by generics.
What determines what type will be used?


Question:
Is there a way to dynamically invoke a method in the same class for PHP? I don't have the syntax right, but I'm looking to do something similar to this:

$this->{$methodName}($arg1, $arg2, $arg3);

Answer:
Just omit the braces:
```
```
$this->$methodName($arg1, $arg2, $arg3);
```
```


Question:
I have a program that will calculate the minimal area taken by fitting rectangles together.

Input: Rectangles of different height and width.

Output: One rectangle that contains all these rectangles.

Rules: One cannot turn or roll the rectangles around and they cannot overlap.

I understand that this is related or is possibly defined as a bin packing problem (NP-hard). However the algorithms i found for those often set a limit on for example width. I have no such limits, the only goal is to get the resulting area as small as possible.

Any pointers on what algorithm is appropriate to get a decent solution?

Answer:
I'd start by skimming through
http://mathworld.wolfram.com
- they're awesome for stuff like this.
Second, I could envision a dopey algorithm that would put the longest (in the X dimension) box on the bottom, then the tallest (in the Y dimension) on top of it on one side or the other. Then continue stacking them in this "stair-stepped" fashion going right wards and upwards (for example go right until you can't, then go up, etc, etc).
That's probably non-ideal, and may very well give you bad results, but it's what popped to mind first.


Question:
I need to echo a string containing angle brackets (< and >) to a file on a Windows machine.  Basically what I want to do is the following:

echo some string < with angle > brackets >>myfile.txt

This doesn't work since the command interpreter gets confused with the angle brackets.  I could quote the whole string like this:

echo "some string < with angle > brackets" >>myfile.txt

But then I have double quotes in my file that I don't want.

Escaping the brackets ala unix doesn't work either:

echo some string \< with angle \> brackets >>myfile.txt

Ideas?

Answer:
The Windows escape character is ^, for some reason.
```
```
echo some string ^< with angle ^> brackets >>myfile.txt
```
```


Question:
I'm invoking one of SharePoint's web service APIs that returns a CAML fragment. I've searched the interweb far and wide but I've been unable to figure out how to make this CAML fragment to render as "normal" HTML that I can render in a more sane environment like Plumtree, WLP, Liferay or any other portal besides SharePoint.

Without a way to do this, I'm wondering why Microsoft wrote SharePoint web service calls that return CAML in the first place. Web services are for interoperability and it seems the CAML is only valid within a WebPart running within SharePoint. [Note to Bill and Steve: that's not interoperability.]

If I can't do anything with the CAML that comes back, I'm just going to call a different web service that returns only data and then write my own UI. I was hoping for an easier path. Any suggestions would be greatly appreciated.

Answer:
You could send the CAML through an XSLT stylesheet to generate HTML or XHTML.
Edit:
Considering your first question (why SharePoint returns CAML from some of its web services)... who knows?  It may be there to support authoring tools such as SharePoint designer.  But it seems clear from the dearth of documentation and tools that CAML is a more-or-less internal SharePoint thing. At present, performing CAML-to-HTML conversion would require either somehow accessing the CAML rendering engine within SharePoint, or re-implementing it. Neither option is attractive.
I think that your conclusion (calling data-returning web services and rendering the HTML yourself) is probably your best bet.


Question: How do you rename a file to include the datetime using the windows command line?

Answer:
Check out
StampMe.cmd
at
http://www.ss64.com/nt/syntax.html
.


Question:
ExtJS has Ext.each() function, but is there a map() also hidden somewhere?

I have tried hard, but haven't found anything that could fill this role. It seems to be something simple and trivial, that a JS library so large as Ext clearly must have.

Or when Ext really doesn't include it, what would be the best way to add it to Ext. Sure, I could just write:

Ext.map = function(arr, f) { ... };

But is this really the correct way to do this?

Answer:
Since
```
map
```
is more of a utility than anything, I don't see why there would be any special way of plugging it into the Ext namespace; the way you propose would work well enough, though you might want to do it thusly:
```
```
if(Ext && typeof(Ext.map) == "undefined") { // only if Ext exists & map isn't already defined
   Ext.map = function(arr, f) { ... };
}
```
```
Seems like that would be fine...but then, I don't use ExtJS, so I don't know. I did take a gander at their docs and it doesn't seem like there is anything special to do in this case.


Question: Anyone know where to find a reference that describes how to output color on the Windows CLI interfaces using API and/or stdout?

Answer:
At least there is the color command:
```
```
color bg fg
```
```
where:
```
```
0: Black
1: Blue
2: Green
3: Cyan
4: Red
5: Purple
6: Yellow
7: Gray
8: Silver
9: Light blue
A: Lime
B: Light cyan
C: Light red
D: Light purple
E: Light yellow
F: White
```
```
Example:
```
```
color 80
```
```
Gives a silver background with black text.


Question:
I have a requirement to produce a Web User Control (in C#) which will exhibit different behaviour when clicked depending on whether the shift (or control) key is pressed at the time. The control itself will contain an ImageButton and/or Hyperlink.

Is this possible?

Basically, if the logged in user is an Admin then I need to allow them access to update the associated URL. I don't want to have a separate page for this admin as it will cause confusion.

Thanks in advance

Answer:
How about
here
?
To implement the
Ctrl
/
Alt
/
Shift
detection, you can use the properties
```
event.ctrlKey
```
,
```
event.altKey
```
,
```
event.shiftKey
```
and the deprecated Navigator-specific property
```
event.modifiers
```
.


Question:
Does anybody knows how can I get the max and min value of the 2nd and 3rd columns in PHP?

$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));

Output should be like:

max(12.9)
min(10)

Answer:
```
```
<?php
$ar = array(array(1,  10,   9.0,   'HELLO'),
            array(1,  11,  12.9,   'HELLO'),
            array(3,  12,  10.9,   'HELLO'));
function col($tbl,$col){
    $ret = array();
    foreach ($tbl as $row){
        $ret[count($ret)+1] = $row[$col];
    }
    return $ret;
}
print (max(col($ar,2))."\n");
print (min(col($ar,1))."\n");
?>
```
```
is this what you look for? I guess its not the most efficient way.


Question:
Here is my situation: I know almost nothing about Perl but it is the only language available on a porting machine. I only have permissions to write in my local work area and not the Perl install location. I need to use the Parallel::ForkManager Perl module from CPAN

How do I use this Parallel::ForkManager without doing a central install? Is there an environment variable that I can set so it is located?

Thanks

JD

Answer:
From
perlfaq8:  How do I keep my own module/library directory?
:
When you build modules, tell Perl where to install the modules.
For C-based distributions, use the INSTALL_BASE option
when generating Makefiles:
```
```
perl Makefile.PL INSTALL_BASE=/mydir/perl
```
```
You can set this in your CPAN.pm configuration so modules automatically install
in your private library directory when you use the CPAN.pm shell:
```
```
% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit
```
```
For C-based distributions, use the --install_base option:
```
```
perl Build.PL --install_base /mydir/perl
```
```
You can configure CPAN.pm to automatically use this option too:
```
```
% cpan
cpan> o conf mbuild_arg --install_base /mydir/perl
cpan> o conf commit
```
```
INSTALL_BASE tells these tools to put your modules into
F.  See L for details on how to run your newly
installed moudles.
There is one caveat with INSTALL_BASE, though, since it acts
differently than the PREFIX and LIB settings that older versions of
ExtUtils::MakeMaker advocated. INSTALL_BASE does not support
installing modules for multiple versions of Perl or different
architectures under the same directory. You should consider if you
really want that , and if you do, use the older PREFIX and LIB
settings. See the ExtUtils::Makemaker documentation for more details.


Question:
We've had an ongoing need here that I can't figure out how to address using the stock Maven 2 tools and documentation.

Some of our developers have some very long running JUnit tests (usually stress tests) that under no circumstances should be run as a regular part of the build process / nightly build.

Of course we can use the surefire plugin's exclusion mechanism and just punt them from the build, but ideally we'd love something that would allow the developer to run them at will through Maven 2.

Answer:
Normally you would add a profile to your maven configuration that runs a different set of tests:
run this with mvn -Pintegrationtest install
```
```
<profile>
        <id>integrationtest</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <argLine>-client -Xmx896m -XX:MaxPermSize=192m</argLine>
                        <forkMode>once</forkMode>
                        <includes>
                            <include>**/**/*Test.java</include>
                            <include>**/**/*IntTest.java</include>
                        </includes>
                        <excludes>
                            <exclude>**/**/*SeleniumTest.java</exclude>
                        </excludes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        <activation>
            <property>
                <name>integrationtest</name>
            </property>
        </activation>
    </profile>
```
```


Question:
I want to create a class that takes string array as a constructor argument and has command line option values as members vals. Something like below, but I don't understand how the Bistate works.

import scalax.data._
import scalax.io.CommandLineParser

class TestCLI(arguments: Array[String]) extends CommandLineParser {
    private val opt1Option = new Flag("p", "print") with AllowAll
    private val opt2Option = new Flag("o", "out") with AllowAll
    private val strOption = new StringOption("v", "value") with AllowAll
    private val result = parse(arguments)
    // true or false
    val opt1 = result(opt1Option)
    val opt2 = result(opt2Option)
    val str = result(strOption)
}

Answer:
I'm not personally familiar with Scalax or
```
Bistate
```
in particular, but just looking at the scaladocs, it looks like a left-right disjunction.  Scala's main library has a monad very much like this (
```
Either
```
), so I'm surprised that they didn't just use the standard one.
In essence,
```
Bistate
```
and
```
Either
```
are a bit like
```
Option
```
, except their "
```
None
```
-equivalent" can contain a value.  For example, if I were writing code using
```
Either
```
, I might do something like this:
```
```
def div(a: Int, b: Int) = if (b != 0) Left(a / b) else Right("Divide by zero")

div(4, 2) match {
  case Left(x) => println("Result: " + x)
  case Right(e) => Println("Error: " + e)
}
```
```
This would print "
```
Result: 2
```
".  In this case, we're using
```
Either
```
to simulate an exception.  We return an instance of
```
Left
```
which contains the value we want, unless that value cannot be computed for some reason, in which case we return an error message wrapped up inside an instance of
```
Right
```
.


Question: Are there, in the canonical Gang of Four list, any design patterns that you often find misused, misunderstood or overused (other than the highly debated Singleton)? In other words, is there a design pattern you would advise to think twice before using? (And why?)

Answer:
Factory Patterns...
I was parachuted into a project before where every single
```
MyObject
```
in the system had an equivalent
```
MyObjectFactory
```
for generating new instances. There was no concept of abstraction or extended classes... just plain old ClassX & ClassXFactory.
And no-one could explain why... "It was just the way things had always been done"


Question:
I have a interface that defines some methods with attributes.  These attributes need to be accessed from the calling method, but the method I have does not pull the attributes from the interface.  What am I missing?

public class SomeClass: ISomeInterface
{
    MyAttribute GetAttribute()
    {
        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase methodBase = stackFrame.GetMethod();
        object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true);
        if (attributes.Count() == 0)
            throw new Exception("could not find MyAttribute defined for " + methodBase.Name);
        return attributes[0] as MyAttribute;
    }

    void DoSomething()
    {
        MyAttribute ma = GetAttribute();
        string s = ma.SomeProperty;
    }
}

Answer:
The methodBase will be the method on the class, not the interface. You will need to look for the same method on the interface. In C# this is a little simpler (since it must be like-named), but you would need to consider things like explicit implementation. If you have VB code it will be trickier, since VB method "Foo" can implement an interface method "Bar". To do this, you would need to investigate the interface map:
```
```
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
interface IFoo
{
    void AAA(); // just to push Bar to index 1
    [Description("abc")]
    void Bar();
}
class Foo : IFoo
{
    public void AAA() { } // just to satisfy interface
    static void Main()
    {
        IFoo foo = new Foo();
        foo.Bar();
    }
    void IFoo.Bar()
    {
        GetAttribute();
    }

    void GetAttribute()
    { // simplified just to obtain the [Description]

        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase classMethod = stackFrame.GetMethod();
        InterfaceMapping map = GetType().GetInterfaceMap(typeof(IFoo));
        int index = Array.IndexOf(map.TargetMethods, classMethod);
        MethodBase iMethod = map.InterfaceMethods[index];
        string desc = ((DescriptionAttribute)Attribute.GetCustomAttribute(iMethod, typeof(DescriptionAttribute))).Description;
    }
}
```
```


Question:
Given a Generic List of objects that contain a member variable that is a string, what is the best way to get the object that contains the string with the longest length?

ie.
assuming val1 is the string I'm comparing:

0 : { val1 = "a"   }
1 : { val1 = "aa"  }
2 : { val1 = "aba" }
3 : { val1 = "c"   }

what needs to be returned is object 2 because "aba" has the greatest length.

Answer:
Sorry, I'll try again. You can use the following aggregation:
```
```
Dim result = elements.Aggregate(Function(a, b) If(a.val1.Length > b.val1.Length, a, b))
```
```


Question:
I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox,  but that will try to validate the input against both the ranges, an AND condition,if you will. CustomValidator is an option, but how would I pass the 2 ranges values from the server-side. Is it possible to extend the RangeValidator to solve this particular problem?

[Update]
Sorry I didn't mention this, the problem for me is that range can vary. And also the different controls in the page will have different ranges based on some condition. I know i can hold these values in some js variable or hidden input element, but it won't look very elegant.

Answer:
You can use the RegularExpressionValidator with the ValidationExpression property set to
Edit: (whoops, 650 and 201 etc. were valid with the old pattern)
```
```
^(1\d{2}|200|5\d{2}|600)$
```
```
This will test the entered text for 100-200 and 500-600.


Question:
I am a rookie was using the Visual Studio 2008 built-in Unit Testing components, what would be the best way to record or display your results in a unit test?

I want to test my service method when it returns a System.GUID and an empty System.GUID

[TestMethod]
public void GetGUID()
{
   MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient();
   string name = "HasGuid";

   System.GUID guid = proxy.GetGUID(name);
}

[TestMethod]
public void GetEmptyGUID()
{
    MyWcfServiceService.MyWcfServiceClient proxy = new MyWcfServiceService.MyWcfServiceClient();
   string name = "HasEmptyGuid";

   System.GUID guid = proxy.GetGUID(name);
}

Answer:
I used this for a few months last year, IIRC isn't there an
```
Assert
```
class?
```
Assert.IsTrue(...)
```
?
I've dropped VS test stuff in favor of other unit test frameworks (better IMO) so my memory is likely clouded.


Question:
What commands in Emacs can I use to insert into the text buffer of a file the current date and time?

(For example, the equivalent in Notepad is simply pressing F5 which is about the only useful feature for Notepad!)

Answer:
Put in your .emacs file:
```
```
;; ====================
;; insert date and time

(defvar current-date-time-format "%a %b %d %H:%M:%S %Z %Y"
  "Format of date to insert with `insert-current-date-time' func
See help of `format-time-string' for possible replacements")

(defvar current-time-format "%a %H:%M:%S"
  "Format of date to insert with `insert-current-time' func.
Note the weekly scope of the command's precision.")

(defun insert-current-date-time ()
  "insert the current date and time into current buffer.
Uses `current-date-time-format' for the formatting the date/time."
       (interactive)
       (insert "==========\n")
;       (insert (let () (comment-start)))
       (insert (format-time-string current-date-time-format (current-time)))
       (insert "\n")
       )

(defun insert-current-time ()
  "insert the current time (1-week scope) into the current buffer."
       (interactive)
       (insert (format-time-string current-time-format (current-time)))
       (insert "\n")
       )

(global-set-key "\C-c\C-d" 'insert-current-date-time)
(global-set-key "\C-c\C-t" 'insert-current-time)
```
```
Reference


Question:
Lists in C# have the .ToArray() method. I want the inverse, where an array is transformed into a list. I know how to create a list and loop through it but I would like a one liner to swap it back.

I am using the String.Split method in the .NET 2.0 environment, so LINQ, etc. is not available to me.

Answer:
```
```
return new List<string>(stringArray);
```
```


Question:
I'm in javascript, running this in the console

d = new Date();
d.setMonth(1);
d.setFullYear(2009);
d.setDate(15);
d.toString();

outputs this:

"Sun Mar 15 2009 18:05:46 GMT-0400 (EDT)"

Why would this be happening? It seems like a browser bug.

Answer:
```
```
d = new Date();
d.setDate(15);
d.setMonth(1);
d.setFullYear(2009);
d.toString();
```
```
This works.


Question:
I have a site that creates images for some bit of content after the content is created.  I'm trying to figure out what to do in between the time the content is created and the image is created.  My thought is that I might be able to set a custom image to display on a 404 error on the original image.  However, I'm not sure how to do this with lighttpd.  Any ideas or alternatives?

EDIT:  The issue is the user isn't the one creating the content, it's being created by a process.  Basically we are adding items to a catalog and we want to create a standardized catalog image from an image supplied by the product provider.  However, I don't want a slow server on the provider end to slow down the addition of new products.  So a separate process goes through and creates the image later, where available.  I guess I could have the system create a default image when we create the product and then overwrite it later when we create the image from the provider supplied image.

Answer:
Use the
```
<object>
```
tag in HTML with a fallback to the default image.
```
```

<OBJECT title="The Earth as seen from space"
        classid="http://www.observer.mars/TheEarth.py">

  <OBJECT data="TheEarth.mpeg" type="application/mpeg">

    <OBJECT data="TheEarth.gif" type="image/gif">

     The Earth as seen from space.
    </OBJECT>
  </OBJECT>
</OBJECT>

```
```
(Example from w3.org)


Question:
I often accidentally create a branch that contains more code than it needs to. When that happens, I delete the branch files, the branch tag, and then start over. The thing that stinks is having to sync the huge pile of data just so I can delete it.

Is there a way to delete server-side?

Answer:
Yes, use sync -k.
Add the path you want to delete to your client, e.g.
```
```
//depot/oops/... //your-client/oops/...
```
```
Then sync that location using the -k option:
```
```
p4 sync -k oops/...
```
```
This will tell Perforce that your client has the files without actually transferring them.  Then you can do:
```
```
p4 delete oops/...
p4 submit oops/...
```
```
etc.


Question:
We are developing a small in-house application that will run on monitor having multi resolutions. Now we want that the application should adjust itself and remain consistent over all monitors.

I came from a Java background too where we used different layouts to accomplish the task. I experimented in .NET with different layouts like UniGrid (which provide the consistency but very restrictive), Grid, etc. but failed in the required task.

What are some possible layout model or some other solution?

I think if we can specify percentage width or height as we do in CSS/HTML then we can adopt this cross-resolution policy. I found Infergistics have such controls, but can this can be achieved via default controls?

P.S.: I am actually trying in WPF (preferably WPF native application).

Answer:
It would completely depend on the content / context of your application, but the .NET Form designer provides you with some useful tools while designing your UI.
Most controls have an
```
Anchor
```
property that allows you specify that a control should stay anchored the specified distance from the top/left/bottom/right of the form during resizing.
Likewise the form itself exposes
```
Resize
```
and
```
SizeChanged
```
events that you can use to customise the UI when the form is resized.
There's some information here as well regarding layouts,
http://msdn.microsoft.com/en-us/library/ms951306.aspx
.


Question:
I have a couple of questions about generic wildcards in Java:

What is the difference between List<? extends T> and List<? super T>?

What is a bounded wildcard and what is an unbounded wildcard?

Answer:
In your first question,
```
<? extends T>
```
and
```
<? super T>
```
are examples of bounded wildcards.  An unbounded wildcard looks like
```
<?>
```
, and basically means
```
<? extends Object>
```
.  It loosely means the generic can be any type.  A bounded wildcard (
```
<? extends T>
```
or
```
<? super T>
```
) places a restriction on the type by saying that it either has to
extend
a specific type (
```
<? extends T>
```
is known as an upper bound), or has to be an ancestor of a specific type (
```
<? super T>
```
is known as a lower bound).
The Java Tutorials have some pretty good explanations of generics in the articles
Wildcards
and
More Fun with Wildcards
.


Question: Using .Net how do I use the Sort method to sort an Array in reverse i.e. Z to A?

Answer:
You need to pass a
IComparer
object or
Comparison
delegate to the Sort function.
Here is a sample code from C# 2.0
```
```
Array.Sort(array,delegate(string a, string b)
    {
        return b.CompareTo(a);
    });
```
```
EDIT: missed the array bit.


Question:
I am building a ASP.NET website, and when I click the START DEBUGGING icon, it runs Internet Explorer as the account that I ran Visual Studio with.

I would like to run IE as a different user when debugging.

Answer:
You can use the runas command to run IE as a different user for running your app. Later attach to the asp.net worker process when you want to debug.
If you want to just change the credentials for Integrated Authentication, try the setting in the update below.
Update
: If you want IE to prompt for a user name and password, try this setting:
For IE 7, set this option for your zone:
Tools> Internet Options > Security > custom level (for your zone)> User Authentication> Logon > prompt for user name and password


Question:
I'm trying to get my head around AMQP. It looks great for inter-machine (cluster, LAN, WAN) communication between applications but I'm not sure if it is suitable (in architectural, and current implementation terms) for use as a software bus within one machine.

Would it be worth pulling out a current high performance message passing framework to replace it with AMQP, or is this falling into the same trap as RPC by blurring the distinction between local and non-local communication?

I'm also wary of the performance impacts of using a WAN technology for intra-machine communications, although this may be more of an implementation concern than architecture.

War stories would be appreciated.

Answer:
AMQP is a specification so you'd be comparing apples with oranges really. There are not that many production ready AMQP providers out there really; none of the major messaging providers or vendors support AMQP at the time of writing (e.g. IBM, Tibco, Sonic, BEA, Oracle, SwiftMQ, MS, Apache ActiveMQ, openmq from Sun) - so all the available AMQP providers are pretty new.
So I'd recommend comparing whatever AMQP provider you are interested in with your message passing framework. There's no point ripping something out that is working fine just because of the way it reads & writes bytes to a socket :)


Question:
Is there any way to insert a text (string, may or may not have html tags) to a div?

It has to be a div and not a textarea.

First of all, I need to get the cursor position, then insert the text in that position. It's similar to function insertAdjacentText, but it can only insert before or after a tag, and only works in IE.

Refer to this URL: http://yart.com.au/test/iframe.aspx. Note how you can position the cursor in the div, we need to add text at the cursor location.

Answer:
The Range and Selection Objects
Use the
selection
and
range objects
.  These contain all kinds of information about the current selection, and where it lies within the node tree.
Fair Warning:
It's not entirely impossible to do what you're describing, but if you get very fancy, you'll be in pretty deep water of
browser quirks and incompatibilities
.  You're going to have to do a lot of
object detection
, checking to make sure you've got consistent values and methods. Incrementally check all of your browsers as you develop.  Good luck!


Question:
Is there any way to disable a system device from C#.NET.

Basically emulating when you go to Device Manager and disable a device that way?

I am assuming there is a WinAPI function that I can invoke, but I don't know which one it is?

The reason I need to do this is that I need to disable and straight after enable the device again.

I need to work in Windows XP and Vista (x86 & x64). I had a look at something called "DevCon" but it doesn't seem to work on Vista x64.

Thanks.

For the answer see here: How do I disable a system device programatically?

Answer:
To futher Mel Green's answer, the hardware helper library uses interop to call the Windows API (setupapi), specifically the SetupDiSetClassInstallParams method. Of course there are other calls here which are used to look up the device details etc.
One thing to consider that if you are running as a standard user or unprivileged account you will not be able to use this to control (enable/disable etc) hardware devices.
For more details have a look at
http://www.pinvoke.net
(and for the specific call:
http://pinvoke.net/default.aspx/setupapi.SetupDiSetClassInstallParam
)


Question:
What's the best way to unify several overlapping id systems into a unified one while maintaining the old id system.

I have several different ids on my website... (E.g /publisher/1234 and /designer/1234) I would like to unify the ids into a new system, but want to preserve the functionality of the older system.

Answer:
You can try using
Microsoft's Sign Tool
You download it as part of the Windows SDK for Windows Server 2008 and .NET 3.5. Once downloaded you can use it from the command line like so:
signtool sign /a MyFile.exe
This signs a single executable, using the "best certificate" available. (If you have no certificate, it will show a SignTool error message.)
Or you can try:
signtool signwizard
This will launch a wizard that will walk you through signing your application. (This option is not available after Windows SDK 7.0.)
If you'd like to get a hold of certificate that you can use to test your process of signing the executable you can use the .NET tool
Makecert
.
Certificate Creation Tool (Makecert.exe)
Once you've created your own certificate and have used it to sign your executable, you'll need to manually add it as a Trusted Root CA for your machine in order for
UAC
to tell the user running it that it's from a trusted source.
Important
.
Installing a certificate as ROOT CA will endanger your users privacy. Look what happened with DELL.
You can find more information for accomplishing this both in code and through Windows in:
Stack Overflow question
Install certificates in to the Windows Local user certificate store in C#
Installing a Self-Signed Certificate as a Trusted Root CA in Windows Vista
Hopefully that provides some more information for anyone attempting to do this!


Question:
is there any good Ruby audio libraries that we can build upon?

Need to manage/edit mp3 files!!!

Answer:
There's an
interface
to a C++ mp3 editor, and an active
pure ruby
project.


Question:
Specifically, I have a model that has a field like this

pub_date = models.DateField("date published")

I want to be able to easily grab the object with the most recent pub_date. What is the easiest/best way to do this?

Would something like the following do what I want?

Edition.objects.order_by('pub_date')[:-1]

Answer:
```
```
obj = Edition.objects.latest('pub_date')
```
```
You can also simplify things by putting
```
get_latest_by
```
in the model's Meta, then you'll be able to do
```
```
obj = Edition.objects.latest()
```
```
See
the docs
for more info.  You'll probably also want to set the
```
ordering
```
Meta option.