Question:
I have some classes layed out like this

class A
{
    public virtual void Render()
    {
    }
}
class B : A
{
    public override void Render()
    {
        // Prepare the object for rendering
        SpecialRender();
        // Do some cleanup
    }

    protected virtual void SpecialRender()
    {
    }
}
class C : B
{
    protected override void SpecialRender()
    {
        // Do some cool stuff
    }
}

Is it possible to prevent the C class from overriding the Render method, without breaking the following code?

A obj = new C();
obj.Render();       // calls B.Render -> c.SpecialRender

Answer:
You can seal individual methods to prevent them from being overridable:
```
```
public sealed override void Render()
{
    // Prepare the object for rendering
    SpecialRender();
    // Do some cleanup
}
```
```


Question:
Using C# 2.0 what is the best way to implement dynamic form controls?

I need to provide a set of controls per data object, so should i just do it manually and lay them out while increment the top value or is there a better way?

Answer:
What do you mean by “dynamic”? A new, fixed set of controls for each data row in the data set? Then use a
```
UserControl
```
that contains your controls.
Or do you mean that, depending on your data layout, you want to provide the user with a customized set of controls, say, one
```
TextBox
```
for each column?


Question: How to restrict the maximum number of characters that can be entered into an HTML <textarea>? I'm looking for a cross-browser solution.

Answer:
The
```
TEXTAREA
```
tag does not have a
```
MAXLENGTH
```
attribute the way that an
```
INPUT
```
tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be
typed
into a
```
TEXTAREA
```
tag is:
```
```
<textarea onKeyPress="return ( this.value.length < 50 );"></textarea>
```
```
Note:
```
onKeyPress
```
, is going to prevent any button press,
any button
including
the backspace key.
This works because the Boolean expression compares the field's length
before the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more,
```
false
```
if not. Returning false from most events cancels the default action.
So if the current length is already 50 (or more), the handler returns false,
the
```
KeyPress
```
action is cancelled, and the character is not added.
One fly in the ointment is the possibility of pasting into a
```
TEXTAREA
```
,
which does not cause the
```
KeyPress
```
event to fire, circumventing this check.
Internet Explorer 5+ contains an
```
onPaste
```
event whose handler can contain the
check. However, note that you must also take into account how many
characters are waiting in the clipboard to know if the total is going to
take you over the limit or not. Fortunately, IE also contains a clipboard
object from the window object.
1
Thus:
```
```
<textarea onKeyPress="return ( this.value.length < 50 );"
onPaste="return (( this.value.length +
window.clipboardData.getData('Text').length) < 50 );"></textarea>
```
```
Again, the
```
onPaste
```
event and
```
clipboardData
```
object are IE 5+ only. For a cross-browser solution, you will just have to use an
```
OnChange
```
or
```
OnBlur
```
handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly.
Source
Also, there is another way here, including a finished script you could include in your page:
http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html


Question:
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.

Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.

Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.

How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows.

Does the browser add this information when posting the file to the web page?

Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?

Answer:
The
mimetypes module
in the standard library will determine/guess the MIME type from a file extension.
If users are uploading files the HTTP post will contain the MIME type of the file alongside the data.  For example, Django makes this data available as an attribute of the
UploadedFile
object.


Question:
A very niche problem:

I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js).

Now on this page I have a Google Map and I use the Prototype Window library.

The problem occurs in IE7 and FF3.

This is the info FireBug gives:

handler is undefined
? in prototype.js@3871()prototype.js (line 3877)
handler.call(element, event);

I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error...

I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :).

Answer:
I switched to a local version of prototypejs and added some debugging
  in the offending method (createWraper) but the debugging never appears
  before the error...
Actually the offending function being called when the error occurs is "wrapper" which is created inside createWrapper (but not called there). Basically what is happening is that you've attached a function as the event handler for an element, and the function doesn't actually exist.
If you're trying to put any debug information in to try and pinpoint which function "doesn't exist" then add your alert messages or firebug console output inside the wrapper function between lines 3871 and 3878.


Question: I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?

Answer:
First day is always YYYY-MM-01, isn't it? Example:
```
date("Y-M-d", mktime(0, 0, 0, 8, 1, 2008))
```
Last day is the previous day of the next month's first day:
```
```
$date = new DateTime("2008-09-01");
$date->modify("-1 day");
echo $date->format("Y-m-d");
```
```


Question: I understand that there are several ways to blend XNA and WPF within the same application. I find it enticing to use WPF for all GUI and HUD stuff in my XNA games. Does anyone have any practical experience on how well this approach works in real life using .NET 3.5 SP1 ? Any pitfalls (such as the "airspace problem")? Any hint on what appoach works best?

Answer:
There is an addition in 3.5 SP1 that allows better interaction between DirectX and WPF (D3DImage), and one way to get to that is through XNA.
Here are some details:
http://jmorrill.hjtcentral.com/Default.aspx?tabid=428&EntryID=259


Question: I need to select data when a page is viewed and update the 'views' column is there a way to do this in one query, or do I have to use to distinct queries?

Answer:
You would have to do this in two statements in one transaction
```
```
Begin Tran

Update Pages Set Views = Views + 1 Where ID = @ID
Select Columns From Pages Where ID = @ID

Commit Tran
```
```


Question:
I have a line color property in my custom grid control. I want it to default to Drawing.SystemColors.InactiveBorder. I tried:

[DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")]
public Color LineColor { get; set; }

But it doesn't seem to work. How do I do that with the default value attribute?

Answer:
You need to change first argument from
```
SystemColors
```
to
```
Color
```
.
It seems that there is no type converter for the
```
SystemColors
```
type, only for the
```
Color
```
type.
```
```
[DefaultValue(typeof(Color),"InactiveBorder")]
```
```


Question: I have a String representation of a date that I need to create a Date or Calendar object from. I've looked through Date and Calendar APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?

Answer:
Try this:
```
```
DateFormat.parse(String)
```
```


Question:
This is probably a really simple jQuery question, but I couldn't answer it after 10 minutes in the documentation so...

I have a list of checkboxes, and I can get them with the selector 'input[type=checkbox]'. I want the user to be able to shift-click and select a range of checkboxes. To accomplish this, I need to get the index of a checkbox in the list, so I can pass that index to .slice(start, end). How do I get the index when the user clicks a box?

Answer:
The following selector should also work in jQuery:
```
input:checkbox
```
.
You can then string the
```
:gt(index)
```
and
```
:lt(index)
```
filters together, so if you want the 5th to 7th checkboxes, you'd use
```
input:checkbox:gt(4):lt(2)
```
.
To get the index of the currently clicked checkbox, just use
```
$("input:checkbox").index($(this))
```
.


Question:
We are now using NHibernate to connect to different database base on where our software is installed.  So I am porting many SQL Procedures to Oracle.

SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate.

Date parts examples are day, week, month, year, etc. . .

What is the Oracle equivalent?

I have not found one do I have to create my own version of it?

(update by Mark Harrison) there are several nice answers that explain Oracle date arithmetic.  If you need an Oracle datediff() see Einstein's answer.  (I need this to keep spme SQL scripts compatible between Sybase and Oracle.)  Note that this question applies equally to Sybase.

Answer:
Tom's article is very old.  It only discusses the DATE type.  If you use TIMESTAMP types then date arithmetic is built into PL/SQL.
http://www.akadia.com/services/ora_date_time.html
```
```
DECLARE
ts_a timestamp;
ts_b timestamp;
diff interval day to second;
BEGIN
  ts_a := systimestamp;
  ts_b := systimestamp-1/24;
  diff := ts_a - ts_b;
  dbms_output.put_line(diff);
END;
+00 01:00:00.462000
```
```
or
```
```
DECLARE
ts_b timestamp;
ts_a timestamp;
date_part interval day to second;

BEGIN
  ts_a := systimestamp;
  date_part := to_dsinterval('0 01:23:45.678');
  ts_b := ts_a + date_part;
  dbms_output.put_line(ts_b);
END;

04-SEP-08 05.00.38.108000 PM
```
```


Question: Why do I need two of them? When I have to use one or another?

Answer:
Please see:
http://www.sap-img.com/oracle-database/finding-oracle-sid-of-a-database.htm
What is the difference between Oracle
  SIDs and Oracle SERVICE NAMES. One
  config tool looks for SERVICE NAME and
  then the next looks for SIDs! What's
  going on?!
Oracle SID is the unique name that
  uniquely identifies your
  instance/database where as Service
  name is the TNS alias that you give
  when you remotely connect to your
  database and this Service name is
  recorded in Tnsnames.ora file on your
  clients and it can be the same as SID
  and you can also give it any other
  name you want.
SERVICE_NAME is the new feature from
  oracle 8i onwards in which database
  can register itself with listener. If
  database is registered with listener
  in this way then you can use
  SERVICE_NAME parameter in tnsnames.ora
  otherwise - use SID in tnsnames.ora.
Also if you have OPS (RAC) you will
  have different SERVICE_NAME for each
  instance.
SERVICE_NAMES specifies one or more
  names for the database service to
  which this instance connects. You can
  specify multiple services names in
  order to distinguish among different
  uses of the same database. For
  example:
SERVICE_NAMES = sales.acme.com,
  widgetsales.acme.com
You can also use service names to
  identify a single service that is
  available from two different databases
  through the use of replication.
In an Oracle Parallel Server
  environment, you must set this
  parameter for every instance.
In short: SID = the unique name of your DB instance, ServiceName = the alias used when connecting


Question:
I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:

ID   COMPANY_ID   EMPLOYEE
1    1            Anna
2    1            Bill
3    2            Carol
4    2            Dave

and I wanted to group by company_id to get something like:

COMPANY_ID   EMPLOYEE
1            Anna, Bill
2            Carol, Dave

There is a built-in function in mySQL to do this group_concat

Answer:
I claim no credit for the answer because I found it after some searching:
What I didn't know is that PostgreSQL allows you to define your own aggregate functions with
CREATE AGGREGATE
This post
on the PostgreSQL list shows how trivial it is to create a function to do what's required:
```
```
CREATE AGGREGATE textcat_all(
  basetype    = text,
  sfunc       = textcat,
  stype       = text,
  initcond    = ''
);

SELECT company_id, textcat_all(employee || ', ')
FROM mytable
GROUP BY company_id;
```
```


Question:
I have a multiple selection SELECT field which I don't want the end user to be able to change the value of.

For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success.

Can this be done or am I trying to do the impossible?

Answer:
Could you do it with an
```
onchange
```
event?
```
```
<select onfocus="this.oldIndex=this.selectedIndex" onchange="this.selectedIndex=this.oldIndex">
```
```


Question:
A .container can contain many .components, and .components themselves can contain .containers (which in turn can contain .components etc. etc.)

Given code like this:

$(".container .component").each(function(){
  $(".container", this).css('border', '1px solid #f00');
});

What do I need to add to the line within the braces to select only the nested .containers that have their width in CSS set to auto?  I'm sure it's something simple, but I haven't really used jQuery all that much.

Answer:
```
```
$(".container .component").each(function() {
    if ($(".container", this).css('width') === "auto")
        $(".container", this).css('border', '1px solid #f00');
});
```
```


Question:
Suppose I have some code that would, in theory, compile against any version of the .net framework. Think "Hello World", if you like.

If I actually compile the code, though, I'll get an executable that runs against one particular version.

Is there any way to arrange things so that the compiled exe will just run against whatever version it finds? I strongly suspect that the answer is no, but I'd be happy to be proven wrong...

Edit: Well, I'll go to the foot of our stairs. I had no idea that later frameworks would happily run exe's compiled under earlier versions. Thanks for all the responses!

Answer:
Read ScuttGu's post about
VS 2008 Multi-Targeting Support
One of the big changes we are making
  starting with the VS 2008 release is
  to support what we call
  "Multi-Targeting" - which means that
  Visual Studio will now support
  targeting multiple versions of the
  .NET Framework, and developers will be
  able to start taking advantage of the
  new features Visual Studio provides
  without having to always upgrade their
  existing projects and deployed
  applications to use a new version of
  the .NET Framework library.
Now when you open an existing project
  or create a new one with VS 2008, you
  can pick which version of the .NET
  Framework to work with - and the IDE
  will update its compilers and
  feature-set to match this.  Among
  other things, this means that
  features, controls, projects,
  item-templates, and assembly
  references that don't work with that
  version of the framework will be
  hidden, and when you build your
  application you'll be able to take the
  compiled output and copy it onto a
  machine that only has an older version
  of the .NET Framework installed, and
  you'll know that the application will
  work.
That way you can use VS2008 to develop .NET 2.0 projects that will work on both .NET 2.0, 3.0 and 3.5


Question:
Caveat: I'm relatively new to coding as well as TextMate, so apologies if there is an obvious answer I'm missing here.

I do a lot of HTML/CSS markup, there are certain patterns that I use a lot, for example, forms, navigation menus etc. What I would like is a way to store those patterns and insert them quickly when I need them.

Is there a way to do this using TextMate?

Answer:
You can do this very easily in TextMate using
Snippets
. Just add a new snippet in the bundle editor, and set up how you want to trigger it. You can set a key shortcut, or have it pop up when you hit
```
Tab
```
after a certain word/pattern.
There are many things you can do with them—in your case, it would probably be very useful to set so-called "placeholders" in your snippets, which are the parts that change every time (e.g. the names of the fields in the form). Then, as soon as you insert the snippet, you can hit
```
Tab
```
to move between these.


Question:
I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address.  We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall.

So how do I configure sendmail to send all mail through mailrelay.example.com?  Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying.

Answer:
http://www.elandsys.com/resources/sendmail/smarthost.html
Sendmail Smarthost
A smarthost is a host through which
  outgoing mail is relayed. Some ISPs
  block outgoing SMTP traffic (port 25)
  and require their users to send out
  all mail through the ISP's mail
  server. Sendmail can be configured to
  use the ISP's mail server as the smart
  host.
Read the linked article for instruction for how to set this up.


Question:
Handling multiple merges onto branches in Subversion or CVS is just one of those things that has to be experienced. It is inordinately easier to keep track of branches and merges in Mercurial (and probably any other distributed system) but I don't know why. Does anyone else know?

My question stems from the fact that with Mercurial you can adopt a working practice similar to that of Subversions/CVSs central repository and everything will work just fine. You can do multiple merges on the same branch and you won't need endless scraps of paper with commit numbers and tag names.

I know the latest version of Subversion has the ability to track merges to branches so you don't get quite the same degree of hassle but it was a huge and major development on their side and it still doesn't do everything the development team would like it to do.

There must be a fundamental difference in the way it all works.

Answer:
I only have experience with Subversion but I can tell you that the merge screen in TortoiseSVN is horribly complicated.  Luckily they include a dry run button so that you can see if you are doing it right.  The complication is in the configuration of what you want to merge to where.  Once you get that set up for the merge the merge generally goes fine.  Then you need to resolve any and all conflicts and then commit your merged in working copy to the repository.
If Mercurial can make the configuration of the merge easier then I can say that would make merging 100% easier then Subversion.


Question:
I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding.  For example:

declare @value decimal(18,2)

set @value = 123.456

This will automatically round @value to be 123.46, which is good in most cases.  However, for this project, I don't need that.  Is there a simple way to truncate the decimals I don't need?  I know I can use the left() function and convert back to a decimal.  Are there any other ways?

Answer:
```
```
select convert(int,@value)
```
```


Question:
Is it possible to pass a reference to a function to another function in F#?  Specifically, I'd like to pass lambda functions like

foo(fun x -> x ** 3)

More specifically, I need to know how I would refer to the passed function in a function that I wrote myself.

Answer:
Yes, it is possible. The
manual
has this example:
```
```
> List.map (fun x -> x % 2 = 0) [1 .. 5];;

val it : bool list
= [false; true; false; true; false]
```
```


Question:
We've been using "Drip" to try and identify why pages with UpdatePanels in them tend to use a lot of client-side memory.  With a page with a regular postback, we are seeing 0 leaks detected by Drip.  However, when we add an update panel to the mix, every single DOM object that is inside of the update panel appears to leak (according to Drip).

I am not certain is Drip is reliable enough to report these kinds of things - the reported leaks do seem to indicate Drip is modifying the page slightly.

Does anyone have any experience with this?  Should I panic and stop using Microsoft Ajax?  I'm not above doubting Microsoft, but it seems fishy to me that it could be this bad.

Also, if you know of a tool that is better than Drip, that would be helpful as well.

Answer:
According to
ASP.NET AJAX in Action
, p. 257
Just before the old markup is replaced with the updated HTML, all the DOM elements in the panel are examined for Microsoft Ajax behaviours or controls attached to them. To avoid memory leaks, the components associated with DOM elements are disposed, and then destroyed when the HTMl is replaced.
So as far as I know, any asp.net ajax components within the update panel are disposed to prevent memory leaks, but anything else in there will just be replaced with the html received.
So if you don't have any asp.net ajax components in the target container for the response, it would be basically the same as an inner html replacement with any other js framework / ajax request, so i would say that it's just the how the browser handles this, rather than asp.net ajax causing this.
Also, while it may be "leaking", it may be by design, meaning that the browser might not have reclaimed the dom elements yet and released them. Also, drip might be causing those to leak, as it is attaching to those dom elements.


Question:
I am working on a site where users can login to get more private information.
 My client has another site else where that uses nt authentication for accessing it.

What they want to do is have a button on the site I am working on under the private area that will send them to the nt authenticated site, but not require them to log on to that site instead passing the username and password that they used to log into my site to the other site for them.

Is it possible to do this? and how would I accomplish it? Is there a better way to do this?

Answer:
How will the other site validate your username and password?
Ideally your site shouldn't even be remembering the user's password to be able to pass it to another site (you store hashes of the password, not the password itself, and only use the actually password during validation).
What if your site provided a token to the user, who presents that token to the new site, which in turn asks your site to validate the token.  Basically the second site is trusting you to tell them who the user is.
This all breaks down if the second site is actually using the Windows accounts for anything other than just retrieving a user name (for example permissions on the underlying file), since the user is not logged on as the actual Windows user account in this scenario.


Question:
What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes).

I've already seen a few ways to do it, but can't decide on which one is the best.

Answer:
There is an official recommendation on
storing additional information about users
.
The Django Book also discusses this problem in section
Profiles
.


Question:
Does anyone know of a way to alter a computed column without dropping the column in SQL Server. I want to stop using the column as a computed column and start storing data directly in the column, but would like to retain the current values.

Is this even possible?

Answer:
Ok, so let me see if I got this straight.  You want to take a column that is currently computed and make it a plain-jane data column.  Normally this would drop the column but you want to keep the data in the column.
Make a new table with the primary key columns from your source table and the generated column.
Copy the data from your source table into the new table.
Change the column on your source table.
Copy the data back.
No matter what you do I am pretty sure changing the column will drop it.  This way is a bit more complex but not that bad and it saves your data.
[Edit: @SqlMenace's answer is much easier. :)  Curse you Menace!! :)]


Question:
I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown.

The blinking input caret is confusing. How do I hide it?

Answer:
If you disable the text box (set
```
Enable=false
```
), the text in it is still scrollable and selectable. If you don't like the visual presentation of a disabled text box (gray background usually) you can manually override the colors.
Be warned, manually overriding colors is going to make your form/control look weird on systems that do not use the default color/theme settings. Don't assume that because your control is white that everyone's control is going to be white. That's why you should always use the system colors whenever possible (defined in the
```
System.Drawing.SystemColors
```
enumeration) such as
```
SystemColors.ControlLight
```
.


Question:
What is the best way to layout a large django project?  The tutorials provide simple instructions for setting up apps, models, and views, but there is less information about how apps and projects should be broken down, how much sharing is allowable/necessary between apps in a typical project (obviously that is largely dependent on the project) and how/where general templates should be kept.

Does anyone have examples, suggestions, and explanations as to why a certain project layout is better than another?  I am particularly interested in the incorporation of large numbers of unit tests (2-5x the size of the actual code base) and string externalization / templates.

Answer:
This page does a good job of addressing some of my questions:
http://www.b-list.org/weblog/2006/sep/10/django-tips-laying-out-application/
Specifically:
To define custom template tags or filters, you must create a sub-directory in the application’s directory called templatetags, and it must contain a file named __init__.py so that it can be imported as a Python module.
To define unit tests which will automatically be noticed by Django’s testing framework, put them in a module called tests (which can be either a file named tests.py or a directory called tests). The testing framework will also find any doctests in that module, but the preferred place for those is, of course, the docstrings of the classes or functions they’re designed to test.
To provide custom SQL which will be executed immediately after your application is installed, create a sub-directory called sql inside the application’s directory; the file names should be the same as the names of the models whose tables they’ll operate on; for example, if you have an app named weblog containing a model named Entry, then the file sql/entry.sql inside the app’s directory can be used to modify or insert data into the entries table as soon as it’s been created.
The note about tests.py and tests (the directory) also holds for models, which helps address the problem of having way to many tests (or models) for one file.
I would still like to see some examples / suggestions for app/project break down, and  big django sites that work well.


Question: What options do I have to publish Flash video from webcams other than Adobe's Flash Media Server and Red5? I would prefer a solution in .NET, Python or PHP but can't find anything.

Answer:
Besides another commercial product, like
Wowza Media Server
, you could go with a CDN (Content Delivery Network), like
Limelight Networks
or
Voxel.net
.  You might even be able to find a local hosting provider that would serve up live Flash video for you.
(Live Flash video in a non-trivial thing to do, so the options are a bit limited.)


Question: I'm using Hudson and Maven 2 for my automated build/CI.  I can build fine with maven from the command line, but when I run the same goal with Hudson, the build fails complaining of missing artifacts.  I'm running Hudson as a windows XP service.

Answer:
Besides another commercial product, like
Wowza Media Server
, you could go with a CDN (Content Delivery Network), like
Limelight Networks
or
Voxel.net
.  You might even be able to find a local hosting provider that would serve up live Flash video for you.
(Live Flash video in a non-trivial thing to do, so the options are a bit limited.)


Question:
Like the title says: Can reflection give you the name of the currently executing method.

I'm inclined to guess not, because of the Heisenberg problem.  How do you call a method that will tell you the current method without changing what the current method is?  But I'm hoping someone can prove me wrong there.

Update:

Part 2:  Could this be used to look inside code for a property as well?

Part 3:  What would the performance be like?

Final Result

I learned about MethodBase.GetCurrentMethod().  I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want.

To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.

Answer:
I think you should be able to get that from creating a
StackTrace
.  Or, as @
edg
and @
Lars Mæhlum
mention, MethodBase.
GetCurrentMethod
()


Question:
A friend of mine told me there was a way to connect two private IPs without using a proxy server. The idea was that both computers connected to a public server and some how the server joined the private connections and won't use any more bandwidth.

Is this true? How's this technique named?

Answer:
This is true.  It's the way
FogCreek Copilot
works
Take a look at item 2 on Joel's
Copilot 2.0 post
.


Question:
I have a database with two tables (Table1 and Table2). They both have a common column [ColumnA] which is an nvarchar.

How can I select this column from both tables and return it as a single column in my result set?

So I'm looking for something like:

ColumnA in Table1:
a
b
c

ColumnA in Table2:
d
e
f

Result set should be:
a
b
c
d
e
f

Answer:
```
```
SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1
```
```
Also, if you know the contents of Table1 and Table2 will
NEVER
overlap, you can use UNION ALL in place of UNION instead.  Saves a little bit of resources that way.
-- Kevin Fairchild


Question:
I am looking for a simple JavaScript example that updates DOM.

Any suggestions?

Answer:
I believe that this tutorial on jQuery has an example that might help you:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery


Question: I am looking for some advice on what should I concentrate my efforts to get the needed skills to become a Java developer for Oracle applications. I'm bit confused as there are lot of technologies in the Java world. Where should I start? What to avoid? Is JDeveloper a good IDE for a beginner?

Answer:
You should be able to do everything related to Oracle using
JDBC
, so make sure you bone up on that API.  Other than that, it depends on the type of application.  Standalone apps may use Swing (the Java UI toolkit) or in the future JavaFX, which is supposed to make Swing obsolete and may do so in a few years.  Web/enterprisey apps will make use of Java Enterprise Edition, so take a look at the servlet API, and if the app uses Enterprise JavaBeans, look at the
Java Persistence API
, which you would probably be using instead of JDBC.
I haven't used JDeveloper, but I haven't found anything wrong with the free IDEs like
Eclipse
or
Netbeans
, and my personal favorite is JetBrains's
IntelliJ IDEA
.


Question:
This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity.

array(
  0 => '-- SELECT --',
  1 => 'Afghanistan',
  2 => 'Albania',
  3 => 'Algeria',
  4 => 'American Samoa',
  5 => 'Andorra',)

The id's need to stay intact. So making them -1 or -2 will unfortunately not work.

Answer:
My shortcut in similar cases is to add a space at the start of Canada and two spaces at the start of United States. If displaying these as options in a SELECT tag, the spaces are not visible but the sorting still brings them to the front.
However, that may be a little hacky in some contexts. In Java the thing to do would be to extend StringComparator, override the compare() method making the US and Canada special cases, then sort the list (or array) passing in your new comparator as the sort algorithm.
However I would imagine it might be simpler to just find the relevant entries in the array, remove them from the array and add them again at the start. If you are in some kind of framework which will re-sort the array, then it might not work. But in most cases that will do just fine.
[edit] I see that you are using a hash and not an array - so it will depend on how you are doing the sorting. Could you simply put the US into the hash with a key of -2, Canada with -1 and then sort by ID instead? Not having used PHP in anger for 11 years, I don't recall whether it has built-in sorting in its hashes or if you are doing that at the application level.


Question:
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?

string testString = "Test";
string anotherString = "Another";

if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}

(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)

Answer:
From MSDN:
"The CompareTo method was designed primarily for use in sorting or
  alphabetizing      operations. It should not be used when the primary
  purpose of the method call is to     determine whether two strings are
  equivalent. To determine whether two strings are    equivalent, call
  the Equals method."
They suggest using
```
.Equals
```
instead of
```
.CompareTo
```
when looking solely for equality.  I am not sure if there is a difference between
```
.Equals
```
and
```
==
```
for the
```
string
```
class.  I will sometimes use
```
.Equals
```
or
```
Object.ReferenceEquals
```
instead of
```
==
```
for my own classes in case someone comes along at a later time and redefines the
```
==
```
operator for that class.


Question: I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems.  SNMP, WMI, that sort of thing.  With most classes I can mock up objects to test them, but how do you deal with unit testing a real system?  For example, if my class goes out and gets the Win32_LogicalDisk object for a server, how could I possibly unit test it?

Answer:
Assuming you meant "How do I test against things that are hard/impossible to mock":
If you have a class that "goes out and gets the Win32_LogicalDisk object for a server" AND does something else (consumes the 'Win32_LogicalDisk' object in some way), assuming you want to test the pieces of the class that consume this object, you can use
Dependency Injection
to allow you to mock the 'Win32_LogicalDisk' object.  For instance:
```
```
class LogicalDiskConsumer(object):

    def __init__(self, arg1, arg2, LogicalDiskFactory)
        self.arg1=arg1
        self.arg2=arg2
        self.LogicalDisk=LogicalDiskFactory()

    def consumedisk(self):
        self.LogicalDisk.someaction()
```
```
Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32_LogicalDisk'.


Question: In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?

Answer:
Here's one way to do it:
```
```
import inspect

def get_subclasses(mod, cls):
    """Yield the classes in module ``mod`` that inherit from ``cls``"""
    for name, obj in inspect.getmembers(mod):
        if hasattr(obj, "__bases__") and cls in obj.__bases__:
            yield obj
```
```


Question:
I have built a basic data entry application allowing users to browse external content in iframe and enter data quickly from the same page. One of the data variables is the URL.
Ideally I would like to be able to load the iframes current url into a textbox with javascript. I realize now that this is not going to happen due to security issues.

Has anyone done anything on the server side? or know of any .Net browser in browser controls. The ultimate goal is to just give the user an easy method of extracting the url of the page they are viewing in the iframe It doesn't necessarily HAVE to be an iframe, a browser in the browser would be ideal.

Thanks,
Adam

Answer:
Does this help?
http://www.quirksmode.org/js/iframe.html
I only tested this in firefox, but if you have something like this:
```
```
<iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>
```
```
You can get its address by using:
```
```
document.getElementById('myframe').src
```
```
Not sure if I understood your question correctly but anyways :)


Question:
So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests.  I believe it--my code is difficult to test right now.  So how do I avoid global state?

The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments.  For example, I have a static class named "Globals" with a static member called "DBConnectionString."  When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString.  I load file paths, server names, and other information in the Globals class.

Some of my functions rely on the global variables.  So, when I test my functions, I have to remember to set certain globals first or else the tests will fail.  I'd like to avoid this.

Is there a good way to manage state information?  (Or am I understanding global state incorrectly?)

Answer:
Dependency injection is what you're looking for. Rather than have those functions go out and look for their dependencies, inject the dependencies into the functions. That is, when you call the functions pass the data they want to them. That way it's easy to put a testing framework around a class because you can simply inject mock objects where appropriate.
It's hard to avoid some global state, but the best way to do this is to use factory classes at the highest level of your application, and everything below that very top level is based on dependency injection.
Two main benefits: one, testing is a heck of a lot easier, and two, your application is much more loosely coupled. You rely on being able to program against the interface of a class rather than its implementation.


Question:
How do you shade alternating rows in a SQL Server Reporting Services report?

Edit: There are a bunch of good answers listed below--from quick and simple to complex and comprehensive. Alas, I can choose only one...

Answer:
Go to the table row's BackgroundColor property and choose "Expression..."
Use this expression:
```
```
= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
```
```
This trick can be applied to many areas of the report.
And in .NET 3.5+ You could use:
```
```
= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
```
```
Not looking for rep--I just researched this question myself and thought I'd share.


Question:
I use Eclipse, Maven, and Java in my development. I use Maven to download dependencies (jar files and javadoc when available) and Maven's eclipse plug-in to generate the .project and .classpath files for Eclipse. When the dependency downloaded does not have attached javadoc I manually add a link for the javadoc in the .classpath file so that I can see the javadoc for the dependency in Eclipse. Then when I run Maven's eclipse plugin to regenerate the .classpath file it of course wipes out that change.

Is there a way to configure Maven's eclipse plug-in to automatically add classpath attributes for javadoc when running Maven's eclipse plug-in?

I'm only interested in answers  where the javadoc and/or sources are not provided for the dependency in the maven repository, which is the case most often for me. Using downloadSources and/or downloadJavadocs properties won't help this problem.

Answer:
Would having the sources for the dependency help? You can tell the eclipse plugin to download those (and refer to them in the .classpath) with
```
-DdownloadSources=true
```


Question: I would like to generate a random floating point number between 2 values.  What is the best way to do this in C#?

Answer:
```
```
// generate a random number starting with 5 and less than 15
Random r = new Random();
int num = r.Next(5, 15);
```
```
For doubles you can replace Next with NextDouble


Question: Every time I publish the application in ClickOnce I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)?

Answer:
You'll probably need to create a piece of code that updates AssemblyInfo.cs according to the version number stored in the .csproj file. (The ClickOnce deploy version is stored inside an XML tag.)
You'd then change your .csproj file to run this bit of code when Publish|Release build is performed. The MSBuild folks have blogged about how to perform custom actions during certain build types; check the
MSBuild team blog
.


Question:
For this directory structure:

.
|-- README.txt
|-- firstlevel.rb
`-- lib
    |-- models
    |   |-- foo
    |   |   `-- fourthlevel.rb
    |   `-- thirdlevel.rb
    `-- secondlevel.rb

3 directories, 5 files

The glob would match:

firstlevel.rb
lib/secondlevel.rb
lib/models/thirdlevel.rb
lib/models/foo/fourthlevel.rb

Answer:
In Ruby itself:
```
```
Dir.glob('**/*.rb') perhaps?
```
```


Question: How do you generate C# classes for accessing WMI?

Answer:
To generate strongly typed WMI classes, use the Management Strongly typed class generator (MgmtClassGen.exe).  It's usually in C:\Program Files\Microsoft Visual Studio X\SDK\vX\Bin.  The parameters are
at MSDN
and they even have
a page
describing the code generated.  If you have to do a lot of work with WMI, it's a lifesaver.


Question: Are there any tools that will spider an asp.net website and create a static site?

Answer:
http://www.httrack.com/
Have used for this purpose a few times, may need to do a little tidying up of urls, and some css linked images might not make it, depends on how good a job you want to do.
If you have dreamweaver, you can use that to manage the links if you need to clean up the file names afterwards.
Optionally use the link checker extension for firefox to check it all afterwards.


Question:
Do you attach the images?

Use absolute urls?

How do you best avoid getting flagged as spam?

Answer:
Campaign Monitor is a great resources for html email:
http://www.campaignmonitor.com/resources/#building
Also
http://www.email-standards.org/
, but seems down right now.


Question: As Jeff Atwood asked: "What’s your logging philosophy? Should all code be littered with .logthis() and .logthat() calls? Or do you inject logging after the fact somehow?"

Answer:
My logging philosophy is pretty easily summarized in four parts:
Auditing, or business logic logging
Log those things that are required to be logged.  This comes from the application requirements, and may include logging every change made to any database (as in many financial applications) or logging accesses to data (as may be required in the health industry to meet industry regulations)
As this is part of the program requirements many do not include it in their general discussions of logging, however there is overlap in these areas, and for some applications it is useful to consider all logging activities together.
Program logging
Messages which will help developers test and debug the application, and more easily follow the data flow and program logic to understand where implementation, integration, and other errors may exist.
In general this logging is turned on and off as needed for debugging sessions.
Performance logging
Add later logging as needed to find and resolve performance bottlenecks and other program issues which aren't causing the program to fail, but will lead to better operation.  Overlaps with Program logging in the case of memory leaks and some non-critical errors.
Security logging
Logging user actions and interactions with external systems where security is a concern.  Useful for determining how an attacker broke a system after an attack, but may also tie into an intrusion detection system to detect new or ongoing attacks.


Question:
I have never used octal numbers in my code nor come across any code that used it (hexadecimal and bit twiddling notwithstanding).

I started programming in C/C++ about 1994 so maybe I'm too young for this? Does older code use octal? C includes support for these by prepending a 0, but where is the code that uses these base 8 number literals?

Answer:
It's useful for the
```
chmod
```
and
```
mkdir
```
functions in Unix land, but aside from that I can't think of any other common uses.


Question:
I recently downloaded ndepend and ran an analysis on an open source project I participate in.

I did not now where to look next - a bit of visual and information overload and it turned out I don't even know where to start.

Can anyone suggest starting points?

What information should I look for first?

What points out problems in the code (in a BIG way)?

What would the low hanging fruit that can immediately seen?

Answer:
Scott Hanselman / Stuart Celarier / Patrick Cauldwell's
poster
with ndepend metrics has some useful information on it. Rather than trying to break down all the heuristics being used I'd focus on only a few at a time starting with "zone of pain / zone of uselessness" and cyclomatic complexity.
There is also a
podcast
which covers some of the basics of the tool.
Between that and running nDepend on a few different projects you may be able to start gathering useful data that you can make into insights.


Question:
In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?

My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data.

Do I have to choose between performance and data integrity?

If so, is in general better to go one way or is it particular to the case?

Are there other alternatives?

Answer:
Maybe something like this?
```
```
const std::vector<mydata>& getData()
{
  return _myPrivateData;
}
```
```
The benefit here is that it's very, very simple, and as safe as you getin C++.  You can cast this, like RobQ suggests, but there's nothing you can do that would prevent someone from that if you're not copying.  Here, you would have to use
```
const_cast
```
, which is pretty easy to spot if you're looking for it.
Iterators, alternatively, might get you pretty much the same thing, but it's more complicated.  The only added benefit of using iterators here (that I can think of) is that you can have better encapsulation.


Question: How can I create an empty one-dimensional string array?

Answer:
Not sure why you'd want to, but the C# way would be
```
```
string[] newArray = new string[0];
```
```
I'm guessing that VB won't be too dissimilar to this.
If you're building an empty array so you can populate it with values later, you really should consider using
```
```
List<string>
```
```
and converting it to an array (if you really need it as an array) with
```
```
newListOfString.ToArray();
```
```


Question:
I heard on a recent podcast (Polymorphic) that it is possible to cache a user control as opposed to the entire page.

I think my header control which displays static content and my footer control could benefit from being cached.

How can I go about caching just those controls?

Answer:
Take a look
here
You can use
```
VaryByParam
```
and
```
VaryByControl
```
in the output cache.


Question: What actually happens to the file system when you do a Subclipse Share Project on an Eclipse project that was externally checked out from Subversion?  All the .svn folders are already in place.  I get an error when I try to Share Project the right way, and I'd rather not delete and re-checkout the projects from the SVN  Repository browser.

Answer:
Dunno exactly what happens within eclipse, I presume it does some funky stuff in the .metadata directory of the workspace.  That said, I would recommend the following to get eclipse to learn about the svn settings of the project:
Delete the project from the workspace (keep "Delete project contents on disk" unchecked)
File > Import... > General > Existing Projects into Workspace
Browse to the folder containing the original project(s) of interest
Import the projects into your workspace
This seems to have the side effect of subclipse noticing the subversion settings when importing the "new" projects into your workspace.


Question:
Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:

ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"

where subCategory is a page property that looks like this:

protected SubCategory subCategory
{
    get
    {
        var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
        return subCategory;
    }
}

Answer:
I dont' think calling a Generic Method on a webservice is possible.
If you look at the service description of two identical methods, one generic, one not:
```
```
[WebMethod]
public string[] GetSearchList(string prefixText, int count)
{
}

[WebMethod]
public string[] GetSearchList2<T>(string prefixText, int count)
{
}
```
```
They are identical.  It appears that both SOAP 1.x and HTTP POST do not allow this type of operation.


Question:
What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.)

I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.

Answer:
```
```
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
```
```
```
```
'a,b,c,d'
```
```
This won't work if the list contains integers
And if the list contains non-string types (such as integers, floats, bools, None) then do:
```
```
my_string = ','.join(map(str, my_list))
```
```


Question:
I'm on .NET 2.0, running under Medium Trust (so TimeZoneInfo and the Registry are not allowed options).  I'm asking the user for two dates and a time zone, and would really love to be able to automatically determine whether I need to adjust the time zone for DST.

This probably isn't even a valid scenario unless I have some very robust support, a la TimeZoneInfo, to differentiate between all of the different varieties of Time Zones in the first place.

Answer:
Well, since
```
TimeZoneInfo
```
is excluded, you're probably not going to find a solution in the framework itself (but don't quote me on that).
In which case, have you considered reflectoring the
```
TimeZoneInfo
```
class and using what you find there?


Question:
Scenario: Document library in SharePoint with column x of "Person or Group" type.  From within a VBA macro (or VSTO add-in) we're trying to access the MetaProperty on the document to set/get the user name.  Any attempt to access the value via the ContentTypeProperties collection throws a

Type MisMatch error (13).

The Type property of the MetaProperty object says it's msoMetaPropertyTypeUser.  I cannot find any examples of how to work with MetaProperties of this type.  Anyone have any experience with this?

Thanks!

Answer:
Are you executing the programs directly or going through the shell?  If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection.
EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick.  No shell, no shell evaluation.  Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that.


Question: Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications?  If so, any success stories or tragedies to avoid?  If you did use it, how did you handle security?

Answer:
I use WebORB for .NET to do Flex remoting and then use DLINQ on the server. One tricky thing about using LINQ with WebORB is that WebORB uses Reflection to automatically retrieve all the relationships of the object(s) you return to Flex. This causes severe time penalties as LINQ uses lazy loading to load relationships. To prevent this from happening, I do something like the following:
Override your DataContext's constructor and add the following code:
```
```
this.DeferredLoadingEnabled = false;
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Order>(q => q.Payments);
dlo.LoadWith<Order>(q => q.Customer);
this.LoadOptions = dlo;
```
```
This tells the DataContext to disable deferred loading of relationships and specifically instructs it to load just the relationships you want, without lazy loading. That way, WebORB isn't causing any lazy loading to happen through Reflection and the number of relationships being transferred to Flex is kept at a minimum.
Hope this helps you in some way. It's definitely one of those little "gotchas" when working with Flex/WebORB and LINQ.


Question: I see __all__ in __init__.py files. What does it do?

Answer:
It's a list of public objects of that module, as interpreted by
```
import *
```
. It overrides the default of hiding everything that begins with an underscore.


Question: Does the Java language have delegate features, similar to how C# has support for delegates?

Answer:
Short story: no
.
Introduction
The newest version of the Microsoft Visual J++ development environment
supports a language construct called
delegates
or
bound method
references
. This construct, and the new keywords
```
delegate
```
and
```
multicast
```
introduced to support it, are not a part of the Java
TM
programming language, which is specified by the
Java Language
Specification
and amended by the
Inner Classes Specification
included
in the
documentation for the JDKTM 1.1 software
.
It is unlikely that the Java programming language will ever include
this construct. Sun already carefully considered adopting it in 1996,
to the extent of building and discarding working prototypes. Our
conclusion was that bound method references are unnecessary and
detrimental to the language. This decision was made in consultation
with Borland International, who had previous experience with bound
method references in Delphi Object Pascal.
We believe bound method references are
unnecessary
because another
design alternative,
inner classes
, provides equal or superior
functionality. In particular, inner classes fully support the
requirements of user-interface event handling, and have been used to
implement a user-interface API at least as comprehensive as the
Windows Foundation Classes.
We believe bound method references are
harmful
because they detract
from the simplicity of the Java programming language and the
pervasively object-oriented character of the APIs. Bound method
references also introduce irregularity into the language syntax and
scoping rules. Finally, they dilute the investment in VM technologies
because VMs are required to handle additional and disparate types of
references and method linkage efficiently.


Question:
My app has many controls on its surface, and more are added dynamically at runtime.

Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc).

What are your tips and tricks to improve WinForms app performance?

Answer:
Are you making good use of
```
SuspendLayout()
```
and
```
ResumeLayout()
```
?
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx


Question:
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;

vs.

SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;

Answer:
Performance wise, they are exactly the same (at least in SQL Server).
PS: Be aware that the
```
IMPLICIT OUTER JOIN
```
syntax is deprecated since SQL Server 2005. (The
```
IMPLICIT INNER JOIN
```
syntax as used in the question is still supported)
Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing


Question: Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good.

Answer:
Expert .NET 2.0 IL Assembler  by Serge Lidin
There was a 1.1 version of the same book, but I haven't seen anything for the latest .NET release.  It's an excellent book.  I used it to write an OCR component in MSIL, as a learning project.
[Edit] @Curt is right, 3.0 and 3.5 are just extensions to 2.0, I hadn't plugged that in to my head yet.  Now I've thought of a fun geek project... compare the disassembly of standard 2.0 code to the new LINQ/Lambda way of performing common tasks like filtering lists.  For some reason I assumed that the magic was happening in new IL features, not just the compiler.


Question:
Can you cast a List<int> to List<string> somehow?

I know I could loop through and .ToString() the thing, but a cast would be awesome.

I'm in C# 2.0 (so no LINQ).

Answer:
Is C# 2.0 able to do
```
List<T>.Convert
```
? If so, I think your best guess would be to use that with a delegate:
```
```
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Convert(delegate (int i) { return i.ToString(); });
```
```
Something along those lines.
Glenn's answer is probably the correct code ;-)


Question: I've searched on the Internet for comparisons between F# and Haskell but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?

Answer:
Well, for one I'd say a main advantage is that F# compiles against the .NET platform which makes it easy to deploy on windows. I've seen examples which explained using F# combined with ASP.NET to build web applications ;-)
On the other hand, Haskell has been around for waaaaay longer, so I think the group of people who are real experts on that language is a lot bigger.
For F# I've only seen one real implementation so far, which is the Singularity proof of concept OS. I've seen more real world implementations of Haskell.


Question:
Having briefly looked at Haskell recently, what would be a brief, succinct, practical explanation as to what a monad essentially is?

I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.

Answer:
But,
You could have invented Monads!
sigfpe says:
But all of these introduce monads as something esoteric in need of explanation. But what I want to argue is that they aren't esoteric at all. In fact, faced with various problems in functional programming you would have been led, inexorably, to certain solutions, all of which are examples of monads. In fact, I hope to get you to invent them now if you haven't already. It's then a small step to notice that all of these solutions are in fact the same solution in disguise. And after reading this, you might be in a better position to understand other documents on monads because you'll recognise everything you see as something you've already invented.
Many of the problems that monads try to solve are related to the issue of side effects. So we'll start with them. (Note that monads let you do more than handle side-effects, in particular many types of container object can be viewed as monads. Some of the introductions to monads find it hard to reconcile these two different uses of monads and concentrate on just one or the other.)
In an imperative programming language such as C++, functions behave nothing like the functions of mathematics. For example, suppose we have a C++ function that takes a single floating point argument and returns a floating point result. Superficially it might seem a little like a mathematical function mapping reals to reals, but a C++ function can do more than just return a number that depends on its arguments. It can read and write the values of global variables as well as writing output to the screen and receiving input from the user. In a pure functional language, however, a function can only read what is supplied to it in its arguments and the only way it can have an effect on the world is through the values it returns.


Question: Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them?

Answer:
if you set ENV['GEM_PATH'] correctly before using rubygems, then gems will work
sometimes
under IronRuby.  I'm actually looking at fixing this right now.
Also, this kind of question is probably better suited for the
IronRuby mailing list
than it is for StackOverflow.


Question:
How can one determine, in code, how long the machine is locked?

Other ideas outside of C# are also welcome.

I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.

I'll write it up anyway and see if it works. Thanks everyone!

Answer:
Below is the 100% working code to find if the PC is locked or not.
Before using this use the namespace
```
System.Runtime.InteropServices
```
.
```
```
[DllImport("user32", EntryPoint = "OpenDesktopA", CharSet = CharSet.Ansi,SetLastError = true, ExactSpelling = true)]
private static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess);

[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 CloseDesktop(Int32 hDesktop);

[DllImport("user32", CharSet = CharSet.Ansi,SetLastError = true,ExactSpelling = true)]
private static extern Int32 SwitchDesktop(Int32 hDesktop);

public static bool IsWorkstationLocked()
{
    const int DESKTOP_SWITCHDESKTOP = 256;
    int hwnd = -1;
    int rtn = -1;

    hwnd = OpenDesktop("Default", 0, false, DESKTOP_SWITCHDESKTOP);

    if (hwnd != 0)
    {
        rtn = SwitchDesktop(hwnd);
        if (rtn == 0)
        {
            // Locked
            CloseDesktop(hwnd);
            return true;
        }
        else
        {
            // Not locked
            CloseDesktop(hwnd);
        }
    }
    else
    {
        // Error: "Could not access the desktop..."
    }

    return false;
}
```
```


Question:
I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?

string[] sa = {"one", "two", "three"};
sa[1].Dump();

var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'

Answer:
As the comment says, you cannot apply indexing with
```
[]
```
to an expression of type
```
System.Collections.Generic.IEnumerable<T>
```
. The IEnumerable interface only supports the method
```
GetEnumerator()
```
. However with LINQ you can call the extension method
```
ElementAt(int)
```
.


Question:
Given a string of JSON data, how can I safely turn that string into a JavaScript object?

Obviously I can do this unsafely with something like:

var obj = eval("(" + json + ')');

but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.

Answer:
I'm not sure about other ways to do it but here's how you do it in
Prototype (JSON tutorial)
.
```
```
new Ajax.Request('/some_url', {
  method:'get',
  requestHeaders: {Accept: 'application/json'},
  onSuccess: function(transport){
    var json = transport.responseText.evalJSON(true);
  }
});
```
```
Calling
```
evalJSON()
```
with true as the argument sanitizes the incoming string.


Question:
I'm wanting to parse a string into a nullable int in C#.  ie. I want to get back either the int value of the string or null if it can't be parsed.

I was kind of hoping that this would work

int? val = stringVal as int?;

But that won't work, so the way I'm doing it now is I've written this extension method

public static int? ParseNullableInt(this string value)
{
    if (value == null || value.Trim() == string.Empty)
    {
        return null;
    }
    else
    {
        try
        {
            return int.Parse(value);
        }
        catch
        {
            return null;
        }
    }
}

Is there a better way of doing this?

EDIT:  Thanks for the TryParse suggestions, I did know about that, but it worked out about the same.  I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?

Answer:
```
int.TryParse
```
is probably a tad easier:
```
```
public static int? ToNullableInt(this string s)
{
    int i;
    if (int.TryParse(s, out i)) return i;
    return null;
}
```
```
Edit
@Glenn
```
int.TryParse
```
is "built into the framework". It and
```
int.Parse
```
are
the
way to parse strings to ints.


Question: I need to deploy a few files that were checked in sometime ago (can't remember the exact ones), so I'm looking to get a list so I can deploy just those files. What is the svn command to do this?

Answer:
```
svn log
```
has a
```
--verbose
```
parameter. I don't have a repository here to test with, but does that return a list of modified files?
You can also use
```
svn diff -r <revision>
```
to retrieve the full change details, which you can parse or read manually to find out which files were changed.


Question:
Is there a better way to flash a window in Java than this:

public static void flashWindow(JFrame frame) throws InterruptedException {
        int sleepTime = 50;
        frame.setVisible(false);
        Thread.sleep(sleepTime);
        frame.setVisible(true);
        Thread.sleep(sleepTime);
        frame.setVisible(false);
        Thread.sleep(sleepTime);
        frame.setVisible(true);
        Thread.sleep(sleepTime);
        frame.setVisible(false);
        Thread.sleep(sleepTime);
        frame.setVisible(true);
}

I know that this code is scary...But it works alright. (I should implement a loop...)

Answer:
Well, there are a few minor improvements we could make. ;)
I would use a Timer to make sure callers don't have to wait for the method to return. And preventing more than one flashing operation at a time on a given window would be nice too.
```
```
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JFrame;

public class WindowFlasher {

    private final Timer timer = new Timer();
    private final Map<JFrame, TimerTask> flashing
                              = new ConcurrentHashMap<JFrame, TimerTask>();

    public void flashWindow(final JFrame window,
                            final long period,
                            final int blinks) {
        TimerTask newTask = new TimerTask() {
            private int remaining = blinks * 2;

            @Override
            public void run() {
                if (remaining-- > 0)
                    window.setVisible(!window.isVisible());
                else {
                    window.setVisible(true);
                    cancel();
                }
            }

            @Override
            public boolean cancel() {
                flashing.remove(this);
                return super.cancel();
            }
        };
        TimerTask oldTask = flashing.put(window, newTask);

        // if the window is already flashing, cancel the old task
        if (oldTask != null)
            oldTask.cancel();
        timer.schedule(newTask, 0, period);
    }
}
```
```


Question: Ok, I asked a question earlier about Flex and ADO.NET Data Services but didn't get much response so I thought I'd rephrase.  Does anyone have any experience building Adobe Flex applications with a .NET back-end?  If so, what architecture did you use and what third-party tools if any did you employ.  I've read a little about doing Flex remoting with WebORB but it seems more complicated than it should be, are web services an adequate alternative?

Answer:
I've mainly used plain ASP.NET pages that return XML for situations that are mainly one-way (data from ASP.NET --> Flex/Flash) communication. The Flex side just uses a URLLoader to hit the ASP.NET page and loads the result as XML.
If the communication needs to be a little more two-sided (sending more than a couple parameters to ASP.NET lets say), I have used standard ASP.NET webservices.
I've never used WebOrb or Flex remoting because I've never really needed that type of interaction between the server and the SWF.
Hope that helps.


Question: Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share?

Answer:
Don't do it. You're practically guaranteed to fail. Use
```
PreparedStatement
```
(or its equivalent) instead.


Question:
I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces

ISomethingV01
ISomethingV02
etc

and I do this

public interface ISomething{
      void method();
}

then I have to add method 2 so now what I do?

public interface ISomethingV2:ISomething{
      void method2();
}

or same other way?

Answer:
The purpose of an interface is to define an abstract pattern that at type must implement.
It would be better implement as:
```
```
public interface ISomething

public class Something1 : ISomething
public class Something2 : ISomething
```
```
You do not gain anything in the form of code reusability or scalable design by creating multiple versions of the same interface.


Question: Why does the order in which libraries are linked sometimes cause errors in GCC?

Answer:
I have seen this a lot, some of our modules link in excess of a 100 libraries of our code plus system & 3rd party libs.
Depending on different linkers HP/Intel/GCC/SUN/SGI/IBM/etc you can get unresolved functions/variables etc, on some platforms you have to list libraries twice.
For the most part we use structured hierarchy of libraries, core, platform, different layers of abstraction, but for some systems you still have to play with the order in the link command.
Once you hit upon a solution document it so the next developer does not have to work it out again.
My old lecturer used to say, "
high cohesion & low coupling
", it’s still true today.


Question:
Given this HTML:

<ul id="topnav">
    <li id="topnav_galleries"><a href="#">Galleries</a></li>
    <li id="topnav_information"><a href="#">Information</a></li>
</ul>

And this CSS:

#topnav_galleries a, #topnav_information a {
    background-repeat: no-repeat;
    text-indent: -9000px;
    padding: 0;
    margin: 0 0;
    overflow: hidden;
    height: 46px;
    width: 136px;
    display: block;
}
#topnav { list-style-type: none; }
#topnav_galleries a { background-image: url('image1.jpg'); }
#topnav_information a { background-image: url('image2.jpg'); }

How would I go about turning the topnav list into an inline list?

Answer:
Try this:
```
```
#topnav {
    overflow:hidden;
}
#topnav li {
    float:left;
}
```
```
And for IE you will need to add the following:
```
```
#topnav {
    zoom:1;
}
```
```
Otherwise your floated < li > tags will spill out of the containing < ul >.


Question:
I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser.

My IDL file for the COM object has the interface that I am calling into as:

HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);

The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript.

The question is:
What is the proper way to get the array of strings returned to a JavaScript variable?

Answer:
If i recall correctly, you'll need to wrap the
```
SAFEARRAY
```
in a
```
VARIANT
```
in order for it to get through, and then use a
VBArray object
to unpack it on the JS side of things:
```
```
HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray)
{
   // ...

   _variant_t ret;
   ret.vt = VT_ARRAY|VT_VARIANT;
   ret.parray = rgBstrStringArray;
   *pvarBstrStringArray = ret.Detach();
   return S_OK;
}
```
```
then
```
```
var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray();
```
```


Question: Is there a way to always have LF line endings in Visual Studio? I can never seem to find it!

Answer:
Visual Studio 2008 doesn't retain the advanced save options after the solution is closed.  I would be willing to hand edit a lot of files if that would make it work consistently, but I am not willing to change all of the settings every time I open VS.
This is too bad.  Since VS does support forcing the line-endings to whatever is desired in the backend, its just not hooked up properly in the UI.  Maybe Microsoft will fix this isn a service pack.


Question: I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?

Answer:
If your asking what I think your asking, you can find them
Here
... page 476 and on.
It's written around optimization techniques for Python; It's mostly Big-O notation of time efficiencies not much memory.


Question:
I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how?

Oh and all of these machines are running either Ubuntu or OS X.

Answer:
You can use Port Fowarding to do this. Take a look here:
http://portforward.com/help/portforwarding.htm
There are instructions on how to set up your router to port forward request on this page:
http://www.portforward.com/english/routers/port_forwarding/routerindex.htm


Question:
I work on a large Visual C++ (MFC) project in VS.NET 2005.

I have noticed strange behavior in Visual C++ 2005. Often, I will change one line of code in a .CPP file but many .CPP files will compile as a result of this. I have never seen this until VS.NET 2005. Theortically, changing a line of code in a .CPP file should simply require recompilation of that .CPP file and re-linking of the PE file.

What am I not understanding about the build process.

Answer:
This is a strange bug in the VS2005 dependency behavior. To find out one suggestion would be to take the following steps:
Go to
Tools
-> Options ->
Projects and Solutions -> Build and
Run -> MSBuild Project Build output
Verbosity
and select
Detailed
Compile your project.
This will give you a detailed output of the build which
"may"
help you arrive at a solution to your problem.


Question:
I have 1 process that receives incoming connection from port 1000 in 1 linux server. However, 1 process is not fast enough to handle all the incoming request.

I want to run multiple processes in the server but with 1 end-point. In this way, the client will only see 1 end-point/process not multiple.

I have checked LVS and other Load Balancing Solution. Those solutions seem geared towards multiple servers load-balancing.

Any other solution to help on my case?

i am looking something more like nginx where i will need to run multiple copies of my app.

Let me try it out.

Thanks for the help.

Answer:
The question is a little unclear to me, but I suspect the answer you are looking for is to have a single process accepting tasks from the network, and then forking off 'worker processes' to actually perform the work (before returning the result to the user).
In that way, the work which is being done does not block the acceptance of more requests.
As you point out, the term load balancing carries the implication of multiple servers - what you want to look for is information about how to write a linux network daemon.
The two kes system calls you'll want to look at are called
fork and exec
.


Question:
I'm working on a Rails app and am looking to include some functionality from "Getting the Hostname or IP in Ruby on Rails" that I asked.

I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents:

require 'socket'

module GetIP
  def local_ip
    orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off reverse DNS resolution temporarily

    UDPSocket.open do |s|
      s.connect '64.233.187.99', 1
      s.addr.last
    end
  ensure
    Socket.do_not_reverse_lookup = orig
  end
end

I had also tried defining GetIP as a class but when I do the usual ruby script/console, I'm not able to use the local_ip method at all. Any ideas?

Answer:
You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already know.
The methods on a module never come into use unless the module is included into a class.  Instance methods on a class require there to be an instance of the class.  You probably want a class method instead.  And the file itself should be loaded, generally through the require statement.
If the following code is in the file getip.rb,
```
```
require 'socket'

class GetIP
  def self.local_ip
    orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true

    UDPSocket.open do |s|
      s.connect '64.233.187.99', 1
      s.addr.last
    end
  ensure
    Socket.do_not_reverse_lookup = orig
  end
end
```
```
Then you should be able to run it by saying,
```
```
require 'getip'
GetIP.local_ip
```
```


Question:
When an AutoCompleteExtender is displayed in IE6 it seems to ignore z-index and renders below any select controls (like dropdownlists) in IE6.

<asp:TextBox ID="TextBox1" runat="server"  />
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
    TargetControlID="TextBox1" EnableCaching="true" CompletionSetCount="5"
    FirstRowSelected="true" ServicePath="~/Services/Service1.asmx" ServiceMethod="GetSuggestion" />
<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem Text="Item 1" Value="0" />
    <asp:ListItem Text="Item 2" Value="1" />
</asp:DropDownList>

How do I make it render above dropdownlists?

Answer:
Nothing renders below select controls in IE6. It's one of the many "features" microsoft bestowed upon us when they gifted IE to the world
You have to hide them, then re-show them.
Observe the
standard lightbox script
- which does exactly this
(note that link is just to the first thing I found on google which had the source to lightbox.js as a demonstration. It's got nothing to do with anything else)


Question:
I have a scenario where I need to make a call to a telephone(landline/mobile)  or send SMS to a particular set of users only using ASP.NET and C#. The web application is not a mobile application.

How do I go about doing these? What typically would be the hardware requirements? I would be extremely grateful if you could provide me with pointers and reference websites.

Answer:
Not sure if you're looking for hardware solutions to automate yourself, or external services. However, I've used BT's
Web21C
pretty extensively.
They have an excellent .Net API and a host of functionality. Their pricing is the best in the UK, but might fall down with US SMS, which is obviously cheaper - there are plenty of other SMS API providers though.
What BT do offer, which is rare, is an API interface for automating call dialling, conferencing and managing call flow.


Question:
Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page.  I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the .designer file.  I'm using Visual Studio 2008

EDIT: Sorry I should have noted I've already tried:

Closing & re-opening all the files & Visual Studio

Making a change to a runat="server" control on the page

Deleting & re-adding the page directive

Answer:
If you open the .aspx file and switch between design view and html view and
back it will prompt VS to check the controls and add any that are missing to
the designer file.
In VS2013-15 there is a
Convert to Web Application
command under the
Project
menu. Prior to VS2013 this option was available in the right-click context menu for as(c/p)x files. When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control.
PS: This should not be done in debug mode, as not everything is "recompiled" when debugging.
Some people have also reported success by (making a backup copy of your .designer.cs file and then) deleting the .designer.cs file.  Re-create an empty file with the same name.
There are many comments to this answer that add tips on how best to re-create the designer.cs file.


Question:
Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example http://somewhere.overtherainbow.com/userid/123424/

I want you to notice the ending path /userid/123424/

How do you do this in ASP.NET?

Answer: Also, check out ASP.NET MVC or if you're set on webforms, the new System.Web.Routing namespace in ASP.NET 3.5 SP1


Question:
Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).

CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);

Is it possible to have the count column calculated for me whenever I do an insert?

e.g. do something like:

INSERT INTO log (date='foo');

and have count calculated by mysql.

Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.

Answer:
You definitly have to declare what to insert. This should be possible by using the
INSERT ... SELECT
statement.
```
```
INSERT INTO log (date, count)
    SELECT DATE() as date, count(id) as count
    from foo;
```
```
Which should insert a new row into the log table, containing todays date and the number of  rows in the foo table. (Assuming the foo table has an id column.. Use the primary key or another indexed column)


Question:
I've worked on a number of database systems in the past where moving entries between databases would have been made a lot easier if all the database keys had been GUID / UUID values. I've considered going down this path a few times, but there's always a bit of uncertainty, especially around performance and un-read-out-over-the-phone-able URLs.

Has anyone worked extensively with GUIDs in a database? What advantages would I get by going that way, and what are the likely pitfalls?

Answer:
The main advantages are that you can create unique id's without connecting to the database. And id's are globally unique so you can easilly combine data from different databases. These seem like small advantages but have saved me a lot of work in the past.
The main disadvantages are a bit more storage needed (not a problem on modern systems) and the id's are not really human readable. This can be a problem when debugging.
There are some performance problems like index fragmentation. But those are easilly solvable (comb guids by jimmy nillson:
http://www.informit.com/articles/article.aspx?p=25862
)
Edit
merged my two answers to this question
@Matt Sheppard I think he means that you can duplicate rows with different GUIDs as primary keys. This is an issue with any kind of surrogate key, not just GUIDs. And like he said it is easilly solved by adding meaningfull unique constraints to non-key columns. The alternative is to use a natural key and those have real problems..


Question:
What are the main differences (if any) between the box models of IE8 and Firefox3?

Are they the same now?

What are the other main differences between these two browsers? Can a web developer assume that these two browsers as the same since they (seem to) support the latest web standards?

Answer:
The Internet Explorer box model has been "fixed" since Internet Explorer 6 so long as your pages are in standard compliants mode.
See:
Quirks mode
and
Internet Explorer box model bug
.
Until I learnt about doctype declerations getting IE to work properly was a real PAIN, because IE runs in "quirks mode" by default. So having a standards mode doctype will eliminate a whole bunch of the most painful CSS problems.


Question:
How does a virtual machine generate native machine code on the fly and execute it?

Assuming you can figure out what are the native machine op-codes you want to emit, how do you go about actually running it?

Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing?

Or would you generate a temporary shared library (.dll or .so or whatever) and load it into memory using standard functions like LoadLibrary ?

Answer:
As far as i know it compiles everything in memory because it has to run some heuristics to    to optimize the code (i.e.: inlining over time) but you can have a look at the
Shared Source Common Language Infrastructure 2.0
rotor release. The whole codebase is identical to .NET except for the Jitter and the GC.


Question:
I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the Comments tab enabled. The problem is that when I format a document comment that contains:

* @see <a href="test.html">test</a>

the code formatter inserts a space in the closing HTML, breaking it:

* @see <a href="test.html">test< /a>

Why? How do I stop this happening?

This is not fixed by disabling any of the options on the Comments tab, such as Format HTML tags. The only work-around I found is to disable Javadoc formatting completely by disabling both the Enable Javadoc comment formatting and Enable block comment formatting options, which means I then have to format comment blocks manually.

Answer:
I can only assume it's a bug in Eclipse. It only happens with
@see
tags, it happens also for all 3 builtin code formatter settings.
There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for
@see
in the
Eclipse Bugzilla
.


Question:
I'm using Struts 2.

I'd like to return from an Action to the page which invoked it.

Say I'm in page x.jsp, I invoke Visual action to change CSS preferences in the session; I want to return to x.jsp rather than to a fixed page (i.e. home.jsp)

Here's the relevant struts.xml fragment:

<action
   name="Visual"
   class="it.___.web.actions.VisualizationAction">
   <result name="home">/pages/home.jsp</result>
</action>

Of course my VisualizationAction.execute() returns home.

Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick?

Must I use a more involved method (i.e. extracting the request page and forwarding to it)?

T.I.A.

Answer:
```
```
return INPUT;
```
```
will do the trick. INPUT constant is defined in Action interface itself. It indicates that action needs more input.
By calling page if you meant the page that took you to the action input page, then your input page will have to store HTTP header "Referer" in the request scope for the Action.


Question:
I'm generating ICalendar (.ics) files.

Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar BUT NOT in MS Outlook 2007 - it just creates a second event

How do I get them to work for Outlook ?

Thanks

Tom

Answer:
I'm using Entourage, so this may not match up exactly with the behavior you're seeing, but I hope it helps.
Using the iCalendar from your reply, Entourage wouldn't even import the data. Using a known-good file, I got it to import, then successfully update. Comparing the two files, the only structural differences are as follows:
My known-good doesn't have a
```
VERSION
```
element
My known-good doesn't have a
```
PRODID
```
element
My known-good doesn't have a
```
STATUS
```
element
My known-good doesn't have a
```
SEQUENCE
```
element
Since Microsoft's support for open standards tends to lag, I'd suggest trying without the
```
VERSION
```
info.


Question:
Can you suggest some good MVC framework for perl -- one I am aware of is catalyst

The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly.

Answer:
I'll tell you right now that Catalyst has by far the best reputation amongst Perl developers in terms of a rapid application development MVC framework.
In terms of "pure" MVC I'm not sure there are even that many "mature" or at least production-ready alternatives.
If Catalyst doesn't seem right to you, then you could build upon the lightweight framework
CGI::Application
to suit your needs or take a look at some of the lesser known MVC frameworks like
PageKit
and
Maypole
.


Question: How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory?

Answer:
I think it's not possible if you want to use object model (i.e. XElement\XDocument) to query XML. Obviously, you can't build XML objects tree without reading enough data. However you can use
XmlReader
class.
The XmlReader class reads XML data
  from a stream or file. It provides
  non-cached, forward-only, read-only
  access to XML data.


Question:
I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries:

SELECT *
FROM  story_category
WHERE category_id NOT IN (
    SELECT DISTINCT category.id
    FROM category INNER JOIN
       story_category ON category_id=category.id);

I tried to delete them executing:

DELETE FROM story_category
WHERE category_id NOT IN (
    SELECT DISTINCT category.id
    FROM category
      INNER JOIN story_category ON category_id=category.id);

But I get the next error:

#1093 - You can't specify target table 'story_category' for update in FROM clause

How can I overcome this?

Answer:
Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question
In MySQL, you can't modify the same table which you use in the SELECT part.
This behaviour is documented at:
http://dev.mysql.com/doc/refman/5.6/en/update.html
Maybe you can just join the table to itself
If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead.
```
```
UPDATE tbl AS a
INNER JOIN tbl AS b ON ....
SET a.col = b.col
```
```
Alternatively, try nesting the subquery deeper into a from clause ...
If you absolutely need the subquery, there's a workaround, but it's
ugly for several reasons, including performance:
```
```
UPDATE tbl SET col = (
  SELECT ... FROM (SELECT.... FROM) AS x);
```
```
The nested subquery in the FROM clause creates an
implicit temporary
table
, so it doesn't count as the same table you're updating.
... but watch out for the query optimiser
However, beware that from
MySQL 5.7.6
and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the
```
optimizer_switch
```
variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks.
```
```
SET optimizer_switch = 'derived_merge=off';
```
```
Thanks to
Peter V. Mørch
for this advice in the comments.
Example technique was from Baron Schwartz,
originally published at Nabble
, paraphrased and extended here.


Question: If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?

Answer:
You could perhaps take a look at the
software
described
here
. It is a gnome applet, written in Python.
From the web site:
"The gnome wacom applet is a small gnome panel applet that shows how much pressure is being applied to your wacom tablet by the current device. Clicking on the panel icon brings up a dialog allowing you to select a different device and check what pressure and tilt information is being recieved from it. This dialog also contains a small drawing test area to give your pen a quick test."
Google is your friend


Question: I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files.

Answer:
Perhaps the following would work:
Generate your icon image using PIL
Convert the image to .ico format using the python interface to ImageMagick,
PythonMagick
I have not tried this approach. The ImageMagick convert command line program was able to convert a .png file to .ico format, so at least ImageMagick supports the .ico format.


Question:
I want to call a function from a .NET DLL (coded in C#) from an Inno Setup script.

I have:

marked the Register for COM interop option in the project properties,

changed the ComVisible setting in the AssemblyInfo.cs file,

added these lines to the ISS script:

[Files]

Source: c:\temp\1\MyDLL.dll; Flags: dontcopy

[Code]

function MyFunction(): string;

external 'MyFunction@files:MyDLL.dll stdcall setuponly';

but I still get the following error:

Runtime Error (at -1:0):

Cannot Import dll:C:\DOCUME~1\foo\LOCALS~1\Temp\is-LRL3E.tmp\MyDLL.dll.

What am I doing wrong?

Answer:
You're trying to import a C-style function from your .NET dll - this doesn't really have anything to do with COM interop. COM interop allows you to activate your .NET objects as COM objects, it doesn't expose them as C/C++ exported functions/types.
If your function doesn't need to return any data, why not make a simple .exe that calls your function and just run that from your setup?
Also: See the
innosetup support newsgroups
where you might get better support.


Question: I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?

Answer:
That format doesn't exist. You need to do a combination of two things,
```
```
select convert(varchar(4),getdate(),100)  + convert(varchar(4),year(getdate()))
```
```


Question:
I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.

from Tkinter import *
import tkMessageBox

root = Tk()
root.withdraw()

# TODO not if a window with this title exists
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))

Any idea how to check that?

Answer:
I believe you want:
```
```
if 'normal' != root.state():
    tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
```
```


Question: How can I add horizontal scroll capabilities to the asp.net listbox control?

Answer:
If you really, really need it, one idea would be to create a custom
ListBox class whose HTML looks like this: sets the width of the SELECT
to that of your widest value's width (the max width of the scrollbar,
for example). Now wrap that SELECT inside of a DIV of the 'constrained'
size and let it scroll on overflow.
Here's a quick example starting down those lines, here's the type of
HTML you want spit out by a control:
```
```
<div style="width:200px; height:100px; overflow:auto;">
<SELECT size="4">
<OPTION
Value="1">blahblahblahblahblahblahblahblahblahblah blahblah</OPTION>
<OPTION Value="2">2</OPTION>
<OPTION Value="3">3</OPTION>
<OPTION Value="4">4</OPTION>
</SELECT>
</div>
```
```
so in essence I'd recommend creating a composite custom control for
this, which renders this HTML. They're pretty easy to make, Google on
the terms 'composite control asp.net'.
The toughest part will be matching up the div dimensions to that of the
select box, to make the scrollbars work/line up properly. That's why
it's kinda tricky.
Source
Also, take a look at this:
Automatically Adding/Hide Horizontal Scroll bar in the ListBox control
EDIT
: Make sure you have enough height to include the scroll bar height or else you'll get the vertical scroll bar on both controls.


Question: I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.

Answer:
Use this:
```
response.setStatus(403)
```
.