Question: What's the best way to get the last inserted id using sqlite from Java? Google is giving me different answers--some say select the last-insert-rowid; others say call statement.getGeneratedKeys(). What's the best route to take? (I just want to return the id, not use it for other inserts or anything.)

Answer:
Use
```
getGeneratedKeys()
```
if your JDBC driver supports it.  You don't want to muck around trying to get the key yourself after the insert.  If your driver does not support
```
getGeneratedKeys()
```
then I would get the next value from the key before the insert.


Question:
Yes that sounds backwards. I want to create an area or frame in my Silverlight app to host another page from my site. I've seen it done before but I can't seem to find any examples.

This way I can control the entire page layout using SL but still use existing aspx pages.

thanks

Answer:
Yes, it can be done and its quite easy to do. I plan on blogging about my HtmlBrowser control and posting the source. The basics are to make sure the Silverlight control is hosted with the isWindowless parameter enabled and then you can at runtime through the HtmlPage class create an IFRAME element and set the src attribute to the HTML page location. The fun part is getting the sizing right, but its not too difficult.
Follow my blog
http://craign.net/
over the next couple of days as I'll post my control.


Question: I keep wondering how does a debugger work? Particulary the one that can be 'attached' to already running executable. I understand that compiler translates code to machine language, but then how does debugger 'know' what it is being attached to?

Answer:
The details of how a debugger works will depend on what you are debugging, and what the OS is. For native debugging on Windows you can find some details on MSDN:
Win32 Debugging API
.
The user tells the debugger which process to attach to, either by name or by process ID. If it is a name then the debugger will look up the process ID, and initiate the debug session via a system call; under Windows this would be
DebugActiveProcess
.
Once attached, the debugger will enter an event loop much like for any UI, but instead of events coming from the windowing system, the OS will generate events based on what happens in the process being debugged – for example an exception occurring. See
WaitForDebugEvent
.
The debugger is able to read and write the target process' virtual memory, and even adjust its register values through APIs provided by the OS. See the list of
debugging functions
for Windows.
The debugger is able to use information from symbol files to translate from addresses to variable names and locations in the source code. The symbol file information is a separate set of APIs and isn't a core part of the OS as such. On Windows this is through the
Debug Interface Access SDK
.
If you are debugging a managed environment (.NET, Java, etc.) the process will typically look similar, but the details are different, as the virtual machine environment provides the debug API rather than the underlying OS.


Question:
There are some cool and exciting features in .NET 3.5/C# 3.0, and with those features comes some darn interesting ways to write the exact same line of code.

Using the above stated tool set (and by extension .NET 2.0 stuff), what are the different ways the below code snippet could reasonably be rewritten?

        string uploadDirectory = "c:\\some\\path\\";
        if (Directory.Exists(uploadDirectory)) {
            string[] files = Directory.GetFiles(uploadDirectory);
            foreach (string filename in files) {
                if (File.GetLastWriteTime(filename).AddHours(12) < DateTime.Now) {
                    File.Delete(filename);
                }
            }
        }

Answer:
Lambda:
```
```
if (Directory.Exists(uploadDirectory))
  Directory.GetFiles(uploadDirectory)
    .Where(f => File.GetLastWriteTime(file) < DateTime.Now.AddHours(-12))
    .Each(f => File.Delete(f));
```
```
Edit: On 2nd thought, you can avoid the security lookups on each File access by using DirectoryInfo and FileInfo instead of the static File methods:
```
```
var di = new DirectoryInfo(uploadDirectory);
if (di.Exists()) {
   di.GetFiles()
     .Where(f => f.LastWriteTime < DateTime.Now.AddHours(-12))
     .Each(f=> f.Delete());
}
```
```
And for those missing their own Each method:
```
```
void Each<T>(this IEnumerable e, Action<T> action) {
  foreach (T t in e) {
    action(t);
  }
}
```
```
To make this really crazy, and fit the C# 3.0 theme, let's throw in an anonymous type:
```
```
di.GetFiles().Select(f => new() {
   Delete = f.LastWriteTime < DateTime.Now.AddHours(-12) ? f.Delete : () => { }
}).Delete();
```
```
But that just doesn't make any sense. ;)


Question:
I'm currently using the following code to right-trim all the std::strings in my programs:

std::string s;
s.erase(s.find_last_not_of(" \n\r\t")+1);

It works fine, but I wonder if there are some end-cases where it might fail?

Of course, answers with elegant alternatives and also left-trim solution are welcome.

Answer:
In the case of an empty string, your code assumes that adding 1 to
```
string::npos
```
gives 0.
```
string::npos
```
is of type
```
string::size_type
```
, which is unsigned. Thus, you are relying on the overflow behaviour of addition.


Question:
I have a ASP.NET GridView with a column mapped to a boolean. I want do display "Yes"/"No" instead of "True"/"False". Well actually I want "Ja"/"Nej" (in Danish).

Is this possible?

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="false">
    <columns>
        ...
        <asp:boundfield headertext="Active" datafield="Active" dataformatstring="{0:Yes/No}" />
        ...
    </columns>
</asp:gridview>

Answer:
Nope - but you could use a template column:
```
```
<script runat="server">
  TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
     object o = DataBinder.Eval(Container.DataItem, field);
     if (converter == null) {
        return (TResult)o;
     }
     return converter((T)o);
  }
</script>

<asp:TemplateField>
  <ItemTemplate>
     <%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
  </ItemTemplate>
</asp:TemplateField>
```
```


Question:
I'm wondering about the practical use of #undef in C. I'm working through K&R, and am up to the preprocessor. Most of this was material I (more or less) understood, but something on page 90 (second edition) stuck out at me:

Names may be undefined with #undef,
  usually to ensure that a routine is
  really a function, not a macro:

#undef getchar

int getchar(void) { ... }

Is this a common practice to defend against someone #define-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting getchar(), so it shouldn't come up.) With your own function names, do you feel the need to do this? Does that change if you're developing a library for others to use?

Answer:
I only use it when a macro in an
```
#included
```
file is interfering with one of my functions (e.g., it has the same name). Then I
```
#undef
```
the macro so I can use my own function.


Question:
I'm using the following regex to capture a fixed width "description" field that is always 50 characters long:

(?.{50})

My problem is that the descriptions sometimes contain a lot of whitespace, e.g.

"FLUID        COMPRESSOR                          "

Can somebody provide a regex that:

Trims all whitespace off the end

Collapses any whitespace in between words to a single space

Answer:
Is there a particular reason you are asking for a regular expression? They may not be the best tool for this task.
A replacement like
```
```
s/[ \t]+/ /g
```
```
should compress the internal whitespace (actually, it will compress leading and trailing whitespace too, but it doesn't sound like that is a problem.), and
```
```
s/[ \t]+$/$/
```
```
will take care of the trailing whitespace. [I'm using
```
sed
```
ish syntax here. You didn't say what flavor you prefer.]
Right off hand I don't see a way to do it in a single expression.


Question:
One of our providers are sometimes sending XML feeds that are tagged as UTF-8 encoded documents but includes characters that are not included in the UTF-8 charset. This causes the parser to throw an exception and stop building the DOM object when these characters are encountered:

DocumentBuilder.parse(ByteArrayInputStream bais)

throws the following exception:

org.xml.sax.SAXParseException: Invalid byte 2 of 2-byte UTF-8 sequence.

Is there a way to "capture" these problems early and avoid the exception (i.e. finding and removing those characters from the stream)? What I'm looking for is a "best effort" type of fallback for wrongly encoded documents. The correct solution would obviously be to attack the problem at the source and make sure that only correct documents are delivered, but what is a good approach when that is not possible?

Answer:
You should manually take a look at the invalid documents and see what is the common problem to them. It's quite probable they are in fact in another encoding (most probably windows-1252), and the best solution then would be to take every document from the broken system and recode it to UTF-8 before parsing.
Another possible cause is mixed encodings (the content of some elements is in one encoding and the content of other elements is in another encoding). That would be harder to fix.
You would also need a way to know when the broken system gets fixed so you can stop using your workaround.


Question:
What's the best way to pipe the output from an java.io.OutputStream to a String in Java?

Say I have the method:

  writeToStream(Object o, OutputStream out)

Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.

I'm considering writing a class like this (untested):

class StringOutputStream extends OutputStream {

  StringBuilder mBuf;

  public void write(int byte) throws IOException {
    mBuf.append((char) byte);
  }

  public String getString() {
    return mBuf.toString();
  }
}

But is there a better way? I only want to run a test!

Answer:
I would use a
```
ByteArrayOutputStream
```
. And on finish you can call:
```
```
new String( baos.toByteArray(), codepage );
```
```
or better:
```
```
baos.toString( codepage );
```
```
For the
```
String
```
constructor, the
```
codepage
```
can be a
```
String
```
or an instance of
java.nio.charset.Charset
. A possible value is
java.nio.charset.StandardCharsets.UTF_8
.
The method
```
toString()
```
accepts only a
```
String
```
as a
```
codepage
```
parameter (stand Java 8).


Question:
I've been looking around the System.Xml namespace, but don't see anything that would support this. Does anyone know if it's built into .Net, or would I have to obtain a third party library to do it?

NOTE: I wish it were as simple as generating  an xsd, but that won't do for my specific situation.

Answer:
I'm not sure about DTD but you can generate XSD files from an xml file using the
Xsd.exe
tool. It usually lives in the following directory:
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\xsd.exe


Question:
I have sets of values in rows in Excel
First row contains weights of how much each value in each column contributes to weighted total.
Now, I want to mark in each following row the value that contributed to the weighted total the most, by changing its background. I played with conditional formatting, but my Excel skills are modest, to say the least.
So, how do I do that?

Answer:
Here's what I think you are trying to do: You have a list of numbers (they happen to be weights, but that's not important). You want the largest number to be highlighted differently.
Suppose the cells are in the range A1:A8.
Select the range A1:A8.
Select Conditional Formatting (Format | Conditional Formatting)
Enter the condition Cell Value is/Equal To/=MAX(A1:A8)
Click the Format... button and set the Pattern to affect the background.
(Tested on Excel 2003 on Windows.)


Question: I'm new to .Net and do not understand the difference. Can someone point me in the right direction?

Answer:
They are two different frameworks for writing services. WCF is generally more flexible and provides configurable options for what protocols are used, how the service is hosted and a variety of security options. ASMX offers SOAP based services. Generally WCF is also more
performant
. In general ASMX is easier to use and generally has less of a learning curve.
Here
is a MSDN forum discussion on the topic.
Here are the getting started pages for
ASMX
and
WCF
.


Question:
I have a web application with users and their documents. Each user can have many documents:

user.rb:

has_many :documents

document.rb:

belongs_to :user

document_controller.rb:

def index
    @documents = Document.find(:all)
end

I am using the restful_authentication plugin. Here is my question: How do I get the controller to only show documents that belongs to each user? Right now it shows all the documents for all the users.

I am using the latest version of Rails.

Answer:
You set a relationship in your User class to your Document class. This will automatically add a method to your User objects that returns a list of all documents related to a particular user:
```
```
def index
  @documents = @current_user.documents
end
```
```
See the
documentation
for other automatically added methods.


Question: Which types of objects fall into the domain of "subscriptable"?

Answer:
It basically means that the object implements the
```
__getitem__()
```
method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.


Question:
Say I want to copy the contents of a directory excluding files and folders whose names contain the word 'Music'.

cp [exclude-matches] *Music* /target_directory

What should go in place of [exclude-matches] to accomplish this?

Answer:
One solution for this can be found with find.
```
```
$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt
```
```
Find has quite a few options, you can get pretty specific on what you include and exclude.
Edit: Adam in the comments noted that this is recursive.  find options mindepth and maxdepth can be useful in controlling this.


Question: My AS3-heavy project tests fine in the IDE, but some parts don't work in the browser when published. Any ideas what could be causing this?

Answer: It might help if you provide some more specific information on what's not working.  Can you post a link?  Furthermore, are any parts of your project referencing any remote objects?  If so, you might want to make sure your remote objects are located where your app expects them to be.  You may also need to add a crossdomain.xml to your server root if you're doing any cross site scripting.


Question:
Is it possible to see the return value of a method after the line has been run and before the instruction pointer returns to the calling function?

I am debugging code I can't modify (read: don't want to re-compile a third party library), and sometimes it jumps to code I don't have source to or the return expression has side effects that stop me being able to just run the expression in the Display tab.

Often the return value is used in a compound statement, and so the Variables view will never show me the value (hence wanting to see the result before control returns to the calling function).

UPDATE: I can't use the expression viewer as there are side-effects in the statement.

Answer:
Tough one.  My experience, outside of Eclipse, is that if you might need to see the return value, it is best to assign it to a local variable in the function so that the return statement is a simple
```
return varname;
```
and not
```
return(some * expression || other);
```
.  However, that's not dreadfully helpful to you since you say you can't (or don't want to) modify or even recompile the code.  So, I don't have a good answer for you - perhaps you need to reconsider your requirement.


Question:
So I have an Access application, and I'd like some forms to be maximised when they are opened, and others to be medium-sized when they are opened.  However, if I try something like this:

Private Sub Form_Activate()
  DoCmd.Maximize
End Sub

or

Private Sub Form_Activate()
  DoCmd.Restore
End Sub

it has the effect of maximizing or restoring every open window, which isn't what I'm looking for.

Is there any way around this?

I'm using Access 2003.

Answer:
Access is an MDI (Multiple Document Interface) application, and this is how they work: either all sub-windows are maximized, or none.
What you need to do, is find a way to discover the dimensions of the Access application window, and then programmatically set the form's .InsideWidth and .InsideHeight properties. The
```
Application
```
object has a
```
hwndAccessApp
```
that probably can be used with some Windows API call to find out its width and height.
addendum
Thanks to
Philippe Grondier
for finding a relevant code sample, the general idea from the
code sample
is:
declare the following Win32 API elements:
```
struct Rect
```
(
```
Type Rect…
```
in VBA)
```
const SW_SHOWNORMAL = 1
```
(for ShowWindow)
```
GetParent
```
(given a hwnd, get its parent's hwnd)
```
GetClientRect
```
(retrieve position and size from a hwnd)
```
IsZoomed
```
(boolean; true if window is maximized)
```
ShowWindow
```
(change the state of a window)
```
MoveWindow
```
(to change the position and size of a window)
if your form is maximized (
```
IsZoomed(frm.hWnd) = True
```
), then restore it (
```
ShowWindow frm.hWnd, SW_SHOWNORMAL
```
)
get the MDI clients area from your form's hWnd (
```
GetClientRect GetParent(frm.hWnd, rect)
```
)
use the rect data to change the position and size of your window (
```
MoveWindow frm.hWnd, 0, 0, rect.x2-rect.x1, rect.y2-rect.y1
```
)
(The above is basically the explanation of the code sample; I didn't copy-paste the code because I wasn't sure if the author allowed it).


Question:
I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen.

I'd like to do this purely from (Py)GTK+, but I am amenable to calling platform-specific functions.  Ideally I'd like to call functions which have already been wrapped from Python, but if that's not possible, I'm not above a little bit of C or ctypes code, as long as I know what I'm actually looking for.

On Windows I think the function I want is GetLastInputInfo, but that doesn't seem to be wrapped by pywin32; I hope I'm missing something.

Answer:
I got an answer regarding mouse-clicks suggesting to use
pyHook
:
Detecting Mouse clicks in windows using python
Here's some other code I did to detect mouse-position via ctypes:
http://monkut.webfactional.com/blog/archive/2008/10/2/python-win-mouse-position
A more round-about method to accomplish this would be via screen capture and comparing any change in images using PIL.
http://www.wellho.net/forum/Programming-in-Python-and-Ruby/Python-Imaging-Library-PIL.html


Question:
Problem : I have multiple projects checked out in my depot. I also have multiple pending numbered change lists, each change list containing checked out files specific to its project. When I check out a new file, it appears in the default change list instead of in the change list that is relevant to its project and I need to manually move it to the relevant change list. This gets real tedious real quick.

Is there any way to automate this process? Sure, a shell script with regular expressions could work, but I want to know if there is any Perforce feature that does this. For example, is there a way to link my project folder to a numbered change list so that a newly checked out file automatically appears in the relevant change list?

Answer:
The way I handle this is that each project I'm working on has a separate client workspace configuration.
However, this is a 6 of one, half dozen of the other situation - now I have to manage a bunch of workspaces. The problem I run into is that when I'm working on project A and want to do something quick in project B I have to switch my workspace to do it.
Perforce does have methods to help deal with that problem by using config files that you place in the proper parts of your directory hierarchy.  See the
Perforce User's Guide, Chapter 2 - the "Using config files" section
.


Question: I have a revision that has been committed to SVN trunk which I would like to roll back.  However, I would like to retain the changes in some fashion such as a branch or even a patch file.  Any suggestions?

Answer:
Reverse-merge (I think that was the term), commit and that's all.
For the "reverse-merge" part - TSVN has this cool feature called "Revert to this revision" (and "Revert changes from this revision"), accessible through the Log dialogue.
The main purpose of a VCS is to keep history of your changes. You could always go back to this particular revision by using "Update to revision..." or by using the aforementioned "shortcuts".


Question:
Is there a way to make awk (gawk) ignore or skip missing files? That is, files passed on the command line that no longer exist in the file system (e.g. rapidly appearing/disappearing files under /proc/[1-9]*).

By default, a missing file is a fatal error :-(

I would like to be able to do the equivalent of something like this:

BEGIN { MISSING_FILES_ARE_FATAL = 0 }  # <- Wishful thinking!
      { count++ }
END   { print count }

A wrapper script cannot check that files exist befor awk is run as they may disappear between the time they are checked and awk then tries to open them, i.e., it is a race condition. (It is also a race condition to check-and-then-open within awk, although the timing is tighter)

Answer:
In the finest of traditions, I will answer your awk question with a Perl program.
```
```
#!/usr/bin/perl -w

for my $file (@ARGV) {
    open my $fh, $file or next;
    while(<$fh>) {
        ...do your thing here...
    }
}
```
```
(It's not awk, but it is the only solution without a race condition.)


Question:
I'm attempting to display some text in my program using (say) Windows GDI and some of the unicode characters are displayed as question marks? What is up?

See also: What does it mean when my text is displayed as boxes?

Answer:
Basically you have corrupted the text. You are taking Unicode text in one encoding and then have converted it to another encoding without checking that target encoding includes all of the characters in the source text. Having done so you have got a bunch of gibberish.
Ways to do this include:
Treating UTF-8 text as ANSI (without converting into a valid code-page first)
Converting Unicode text into a code-page without checking if the code-page has the right characters in it.


Question: I've run across this sort of thing on multiple websites and was wondering what it was called, does anyone know? Here's a screenshot.

Answer:
I don't see anything obviously out of place.  If you're working with a very large database, you could try increasing your heap size by using the
```
-Xmx n
```
option in your JVM invocation.  This is usually not the best solution - only do with this when you know your working set size is actually bigger than the default heap size.
Are you using any complex data structures?  If you have circular references between objects, you might be preventing the garbage collector from cleaning up unreachable objects.  If you have any hand-written data structures, make sure that you explicitly null out references to objects that are removed instead of doing something like decrementing a size variable.


Question:
I am using pseudo-code here, but this is in JavaScript. With the most efficient algorithm possible I am trying to find the high and low given an array of positive whole numbers. This is what I came up with, but I don't think it is probably best, and was just wondering if anyone has any other suggestions.

var low = 1;
var high = 1;
for ( loop numbers ) {
    if ( number > high ) {
        high = number;
    }
    if ( low == 1 ) {
        low = high;
    }
    if ( number < low ) {
        low = number;
    }
}

Answer:
In python:
```
```
>>> seq = [1, 2, 3, 4, 5, 6, 7]
>>> max(seq)
7
>>> min(seq)
1
```
```


Question:
What kind of collection I should use to convert NameValue collection to be bindable to GridView?
When doing directly it didn't work.

Code in aspx.cs

  private void BindList(NameValueCollection nvpList)
  {
     resultGV.DataSource = list;
     resultGV.DataBind();
  }

Code in aspx

<asp:GridView ID="resultGV" runat="server" AutoGenerateColumns="False" Width="100%">
    <Columns>
         <asp:BoundField DataField="Key" HeaderText="Key" />
         <asp:BoundField DataField="Value" HeaderText="Value" />
    </Columns>
</asp:GridView>

Any tip most welcome. Thanks. X.

Answer:
Can you use Dictionary<string,string> instead of NameValueCollection.  Since Dictionary<T,T> implements IEnumerable you could use LINQ as so:
```
```
resultGV.DataSource = from item in nvpDictionary
                      select new { Key = item.Key, Value = item.Value };
resultGV.DataBind();
```
```
[EDIT] Actually you may be able to use Dictionary directly as:
```
```
resultGV.DataSource = nvpDictionary;
resultGV.DataBind();
```
```
If it doesn't map key/value the way you want you can always go back to LINQ.  LINQ would also allow you to rename the fields to whatever you want.
[EDIT]  If you can't change to use Dictionary<T,T>, make a copy of the NameValueCollection as a Dictionary in the method and bind to it.
```
```
private void BindList(NameValueCollection nvpList)
{
   Dictionary<string,string> temp = new Dictionary<string,string>();
   foreach (string key in nvpList)
   {
      temp.Add(key,nvpList[key]);
   }

   resultGV.DataSource = temp;
   resultGV.DataBind();
}
```
```
If you do this a lot, you could write an extension method to convert to a Dictionary, and use it so.
```
```
public static class NameValueCollectionExtensions
{
   public static Dictionary<string,string> ToDictionary( this NameValueCollection collection )
   {
      Dictionary<string,string> temp = new Dictionary<string,string>();
      foreach (string key in collection)
      {
          temp.Add(key,collection[key]);
      }
      return temp;
   }
}

private void BindList(NameValueCollection nvpList)
{
   resultGV.DataSource = nvpList.ToDictionary();
   resultGV.DataBind();
}
```
```


Question:
Is there a way to spawn a new window via javascript in IE7 that hides the statusbar?

I've added the intranet app as a trusted site. Not sure what else I can use to try. This is my JS

window.open("http:/localhost/start.html", "MyApp", "left=0, top=0, width=" + screen.width + "," +
                              "height=" + screen.height + ", scrollbars=yes, " +
                              "resizable=yes, location=no, menubar=no, titlebar=no, " + "toolbar=no, status=no");

Answer:
Your code worked for me,
and here's a screenshot.
Example of how IE7 renders popup without status bar. http://img511.imageshack.us/img511/7757/workshq7.th.png
Note that experment was done on local filesystem, with "Protected Mode" completly turned off. If it didn't work for you, my guess is that your security settings is somehow still to high. Tinkering with the browser UI trough JavaScript is usually blocked for security reasons and should not be relied on.


Question:
I'm working on a C# program, and right now I have one Form and a couple of classes. I would like to be able to access some of the Form controls (such as a TextBox) from my class. When I try to change the text in the TextBox from my class I get the following error:

An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog'

How can I access methods and controls that are in Form1.cs from one of my classes?

Answer:
you have to have a reference to the form object in order to access its elements
the elements have to be declared public in order for another class to access them
don't do this - your class has to know too much about how your form is implemented; do not expose form controls outside of the form class
instead, make public properties on your form to get/set the values you are interested in
post more details of what you want and why, it sounds like you may be heading off in a direction that is not consistent with good encapsulation practices


Question: Is there a standard way to convert an XSD to an input form (ASP.NET C#) so that later on whenever a new field is added / removed from the XSD the field on the page automatically shows up or goes away respectively, is this something which needs to be developed in-house I assume there must be a way to serializes / deserializes and generates a form? Any hel would be appreciated..

Answer:
Assumption: You're using XML because it is simpler for you at the moment.
Idea: Since you want to create a form to manipulate the data, I'm guessing you might be open to SQL instead of XML. This may not be the case, but you will probably find more tools to help you if you have a database backend instead of an XML/XSD backend. (Plus there are ways you can convert your data from one to another).
There are tools that create forms from databases in ASP.NET. SubSonic, for example, has a auto-scaffolding module that lets you create a database manager knowing only its schema. If the schema changes, just have SubSonic regenerate its files and your forms will have been modified. It isn't perfect, but it may go a long way, depending on your needs.
Option 1) You can create the database schema from the XSD (
How can I create database tables from XSD files?
) and use SubSonic from that point on. This may be even more of a pain than you original question... only you know.
Option 2) Hack the SubSonic scaffolding so that it supports your underlying XSD/XML instead of a database. You can probably re-use lots of their infrastructure (SubSonic is open source) to generate the form from an XSD.
Good luck!


Question:
I have a PHP form (mortgage app) that is about 400 fields, traffic on the site will be low.

What is the ideal Session size for 400 fields going into a MySQL db?

In php.ini what do I set?

Anything I should set that I am missing?

Answer: Well, personally I have had very large sessions before with very little problems. Probably the largest size I've had before is ~10MB. It's not optimal, but I haven't had a problem with slow scripts even with that size. I wouldn't worry about sessions getting to large, but I would try to keep it under control. My theory is, if keeping it in the session makes it much faster than quering the database every time (such as in the case of a search) then I go for it.


Question:
I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

I have the e-mailing of the link, MySQL query, etc. covered.

How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?

I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.

Answer:
To have it send it as a CSV and have it give the file name, use header():
http://us2.php.net/header
```
```
header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');
```
```
As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.


Question:
We are all talking about the efficiency of the algorithms and it depends on input size -basically.

How about the system specifications of current computer that runs the algorithm? does it make any difference to run a different sorting algorithm in a Core 2 Duo 2.6 GHZ, 4 GB RAM-computer or in a P-2, 256 MB RAM-computer?

I am sure that there must be a performance difference. But, I want to know what is the real relationship between algorithms and system specifications...

Answer:
An increase in hardware performance will give you a constant C times the running time of your algorithm.   Meaning if you have computer A which is overall 2 times slower than computer B.  Than your algorithm will be twice as fast on computer B.   Twice as fast though really makes hardly no difference when you consider big input values to an algorithm though.
In big O notation
that is to say you will have something like O(n) compared to C
O(n) = O(c
n) = O(n).  The complexity of the algorithm and general running time for large values will be about the same on both Computer A and Computer B.
If you analyze an algorithm's running time using something like big O notation, then you will have a much better idea about how the algorithm really works.   Computer performance won't give you any kind of advantage when you are comparing an algorithm that is O(logn) compared to O(n^2).
Take a look at some of the data values for n:
I will assume 1 second per operation for the slow computer, and 2 operations for second for the fast computer.  I will compare the better algorithm with the slow computer with the worse algorithm with the fast computer.
for n = 10:
Algorithm 1: O(logn): 4 operations
  Slow computer: 4 seconds
Algorithm 2: O(n^2): 100 operations
  Fast computer: 50 seconds
for n = 100:
Algorithm 1: O(logn): 7 operations
  Slow computer: 7 seconds
Algorithm 2: O(n^2): 10,000
  operations  Fast computer: 1.4 hours
Large difference
for n = 1,000:
Algorithm 1: O(logn): 10 operations
  Slow computer: 10 seconds
Algorithm 2: O(n^2): 1,000,000
  operations  Fast computer: 5.8 days
Huge difference
As n increases, the difference gets bigger and bigger.
Now if you tried to run each of these algorithms on a faster/slower computer for a large input size.  It wouldn't matter.  Hands down the O(logn) would be faster.


Question:
What is appropriate way to integrate SpringSecurity with Capcha ?

I have following use case :
When user will tries to login, if we he failed to login N times, captcha will be displayed, so authentication will be using three parameters : username, password, captcha. But Spring Security doesn't support built in Captcha handling.

I just start thinking about implementation. And have following variants:

Adding separate security filter in Spring Security filter stack,

Entirely rewrite AuthenticationProcessingFilter to support some Captcha

Use some programmatic authentication with interception captcha logic and then transfering username and password to Spring Security

As a Captcha implementation I think about JCaptcha, but what your thougths?

Answer:
As an alternative to using JCaptcha, if you'd like to use the
reCAPTCHA Service
on your site, then check out the free Section 4.4 (
direct PDF link
) of the new
Spring in Practice
book (currently in beta).
This shows you integration with Spring MVC and Spring Validation. Since the integration is on the front-end, w/external APIs, Spring Security doesn't really come into the picture here.
I am not sure what your use case is? Are you hoping to use captchas as an alternative to authentication to prove "human"-ness?


Question:
I'm creating an app that will have to put at max 32 GB of data into my database.  I am using B-tree indexing because the reads will have range queries (like from 0 < time < 1hr).

At the beginning (database size = 0GB), I will get 60 and 70 writes per millisecond.  After say 5GB, the three databases I've tested (H2, berkeley DB, Sybase SQL Anywhere) have REALLY slowed down to like under 5 writes per millisecond.

Questions:

Is this typical?

Would I still see this scalability issue if I REMOVED indexing?

What are the causes of this problem?

Notes:

Each record consists of a few ints

Answer:
Yes; indexing improves fetch times at the cost of insert times. Your numbers sound reasonable - without knowing more.
You can benchmark it. You'll need to have a reasonable amount of data stored. Consider whether or not to index based upon the queries - heavy fetch and light insert? index everywhere a where clause might use it. Light fetch, heavy inserts? Probably avoid indexes. Mixed workload; benchmark it!
When benchmarking, you want as real or realistic data as possible, both in volume and on data domain (distribution of data, not just all "henry smith" but all manner of names, for example).


Question:
How fast is php_uname() say doing php_uname('s n') or php_uname('a'). The reason I ask is because I'd like to use it to determine which server I'm on and therefore the configuration (paths, etc).

This is related to Is there a PHP function or variable giving the local host name?

Answer:
I just did this:
```
```
<?php
  $tstart = microtime(true);

  php_uname('a');

  print 'it took '. sprintf("%f",microtime(true) - $tstart) ." seconds\n";
?>
```
```
And it produced this:
```
```
it took 0.000016 seconds
```
```
That is on a Core2Duo 2.4GHz Debian box.
I know it is an empirical test and all but I think that it shows that it will be fast enough for you.
I did not expect it to take a long time since uname only needs to make a very simple call to the kernel.


Question: I'm trying to create a fast 2D point inside polygon algorithm, for use in hit-testing (e.g. Polygon.contains(p:Point)). Suggestions for effective techniques would be appreciated.

Answer:
The trivial solution would be to divide the polygon to triangles and hit test the triangles as explained
here
If your polygon is
CONVEX
there might be a better approach though. Look at the polygon as a collection of infinite lines. Each line dividing space into two. for every point it's easy to say if its on the one side or the other side of the line. If a point is on the same side of all lines then it is inside the polygon.


Question:
I have several xml files, the names of which are stored in another xml file.

I want to use xsl to produce a summary of the combination of the xml files. I remember there was a way to do this with the msxml extensions (I'm using msxml).

I know I can get the content of each file using select="document(filename)" but I'm not sure how to combine all these documents into one.

21-Oct-08 I should have mentioned that I want to do further processing on the combined xml, so it is not sufficient to just output it from the transform, I need to store it as a node set in a variable.

Answer:
Have a look at the
```
document()
```
function documentation
.
You can use
```
document()
```
to load further XML documents during the transformation process. They are loaded as node sets. That means you would initially feed the XML that contains the file names to load to the XSLT, and take it from there:
```
```
<xsl:copy-of select="document(@href)/"/>
```
```


Question:
I have an existing Perl program that uses Getopt package and Getopt::Long::Configure with permute as one of the options. However, now I need to keep the order of the options entered by the user. There is an option $RETURN_IN_ORDER mentioned in the Long.pm, however doesn't seem to be used anywhere at all.

When I pass return_in_order, I am getting the following error.

Getopt::Long: unknown config parameter "return_in_order" at C:/Program Files/IBM/RationalSDLC/common/lib/perl5/5.8.6/Getopt/Long.pm line 1199.

Can someone please tell me if this is supported at all and if so, the right way to use? If not, I would like to know the other alternatives I have.

Thanks.

Answer:
It's called
```
require_order
```
, according to the manpage I have here. :-)


Question:
I'm a little confused by some PHP syntax I've come across.  Here is an example:

$k = $this->_tbl_key;

if( $this->$k)
{
   $ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls );
}
else
{
    $ret = $this->_db->insertObject( $this->_tbl, $this, $this->_tbl_key );
}

My question is basically what does $this->$k mean?  I figured it might mean the member variable that goes by the name of whatever is in $this->_tbl_key, but how would that work?  Is it possible to add member variables to a class at run-time?

Answer:
It'll look up whatever the value of "k" is, and treat it as a variable name. These two samples are the same:
```
```
echo ($obj->myvar);

####

$k = "myvar";
echo ($obj->$k);
```
```


Question:
Is there any advantage to using __construct() instead of the class's name for a constructor in PHP?

Example (__construct):

class Foo {
    function __construct(){
        //do stuff
    }
}

Example (named):

class Foo {
    function Foo(){
        //do stuff
    }
}

Having the __construct method (first example) is possible since PHP 5.

Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.

Answer:
```
__construct
```
was introduced in PHP5. It is the way you are supposed to do it now. I am not aware of any
advantages
per se, though.
From the PHP manual:
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics
If you're on PHP5 I would recommend using
```
__construct
```
to avoid making PHP look elsewhere.


Question:
I'm using Entity Framework O/R mapper from Microsoft and using entity classes (generated classes that are mapped to DB objects) as a business objects.
Is this OK? Please state your cons or pros. What to do in a case of WCF communication between business layer and presentation, how to send those objects as data members?

Answer:
The Entity framework was designed for the entity objects to be used as business objects, but you should keep in mind that the business objects will be tied to O/R technology as well as the EDM model. In EF 1.0, there wasn't any support for
persistence-ignorance
scenarios, but support was added in 4.0. You can implement
interfaces
, if you don't want to use any of their base classes.
As of .NET 3.5 SP1, they should also be usable as paramater and return types in WCF service methods without any additional code.


Question:
I have faced this problem quite often during the last couple of months, during which I've been building this system. The scenario is this: I have this kind of object that essentially is a list of other objects, but has some other properties specific of its nature. For example:

Class Tests:

Contains many Test objects

Has properties:

DefaultTimeouts

DefaultNumberOfTries

Should I have this class subclass List<Test> or should I have it inheriting from Object, simply having the list as a property beside the other fields?

I know that this may be a bit subjective and personal taste might play a role here, but I'd wholeheartedly like to know your opinion on this.

Answer:
If it literally does everything a
```
List
```
would do, and all the
```
List
```
functions would act on the
```
Tests
```
object in an intuitive way that gives the correct result, then in my opinion it should just subclass
```
List<Test>
```
.
Otherwise, you'll just have a class with a ton of methods which just call a method of the same name on the
```
List<Test>
```
variable in the instance. That'll just be an imperfect extension of the
```
List<Test>
```
class itself.


Question: As you can see this is a question from a non web developer. I would like to have an ASPX page which, under certain circumstances, can generate a 401 error from code. Ideally it would show the IIS standard page.

Answer:
You should be able to just use the following, according to
MSDN
.
```
```
Throw New HttpException(401, "Auth Failed")
```
```
Edit
After seeing the other responses setting the status code would be more appropriate.


Question: Do these two keywords have exactly the same effect, or is there something I should be aware of?

Answer:
According to this site:
http://en.csharp-online.net/CSharp_FAQ:_What_is_the_difference_between_CSharp_lock_and_Java_synchronized
, C#
```
lock
```
and Java
```
synchronized
```
code blocks are "semantically identical", while for methods, Java uses
```
synchronized
```
while C# uses an attribute:
```
[MethodImpl(MethodImplOptions.Synchronized)]
```
.


Question:
What's the best way to format this for readability?

if (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false) {
  createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
  fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}

Answer:
```
```
if ((strpos($file, '.jpg',1) ||
     strpos($file, '.gif',1) ||
     strpos($file, '.png',1))
    && file_exists("$thumbsdir/$file") == false)
{
  createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
  fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}
```
```


Question:
I would really like to annotate a method with a reference to a single property in a property file for injection.

@Resource("${my.service.url}")
private String myServiceUrl;

Of course, this syntax does not work ;) Thats why I'm asking here.

I am aware that I can inject the full properties file, but that just seems excessive, I dont want the property file - I want the configured value.

Edit: I can only see PropertyPlaceholderConfigurer examples where XML is used to wire the property to the given field. I still cannot figure out how this can be achieved with an annotation ?

Answer:
You could try injecting value of property "my.service.url" to a filed in your bean.
Take a look at:
http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer
HTH.


Question:
With the asp.net MVC framework the blogs of the team members (Rob Conery, Phil Haack etc) really helped me on my way and made me feel comfortable the development was going in the right direction.
Is there something similar for Silverlight?

-Edit:
I would like to mention that I would like to find members of the dev team themselves.
Currently the support for Silverlight across OS and browser is just too poor to make me care and invest time in it.
But I would like to keep a spying eye out so I can start caring when the framework fulfils it's potentials.

Answer:
Method ~ of ~ failed by Tim Heuer:
http://feeds.timheuer.com/timheuer-silverlight
Jesse Liberty - Silverlight Geek:
http://feeds.feedburner.com/JesseLiberty-SilverlightGeek
Community Silverlight content:
http://silverlight.net/blogs/community/rss.aspx
Silverlight Tips of the Day
http://silverlight.net/blogs/msnow/default.aspx
Podcasts:
http://www.sparklingclient.com/
Wynapse (Mining the Web for Silverlight so YOU don't have to):
http://geekswithblogs.net/WynApseTechnicalMusings/Default.aspx


Question:
Can I access spring bean that exposed using http invoker (server) from GWT application (client)?

If so is there any example / tutorial for that?

Answer:
There's an application template for Spring-GWT apps available
here
, that you may find useful. I haven't tried it out, but I believe it's implemented as a Maven archetype.
For more background on exactly what this template does for you, and how to integrate GWT with Spring, check out the following (video)
presentation
.


Question:
Anyone have any idea how to get the value of "Language for Non-Unicode Programs" in Control Panel Regional Settings programmatically using c#?

Already tried CultureInfo, RegionInfo and getting the default encoding using the Encoding object, but I can only get the Standards and Formats value or the main code page.

Answer:
IIRC,
```
Thread.CurrentUICulture
```
gets that value.


Question:
What is the most efficient way to write the old-school:

StringBuilder sb = new StringBuilder();
if (strings.Count > 0)
{
    foreach (string s in strings)
    {
        sb.Append(s + ", ");
    }
    sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();

...in LINQ?

Answer:
Have you looked at the Aggregate extension method?
```
```
var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);
```
```


Question: I build VBA applications for both Word and Excel, is there any way to access the progress bar that sometimes appears in the Office status bar.

Answer:
I have not accessed the progress bar, but I have in the past used something like this to place task status text in the status bar...
```
```
Sub StatusBarExample()
    Application.ScreenUpdating = False
    ' turns off screen updating
    Application.DisplayStatusBar = True
    ' makes sure that the statusbar is visible
    Application.StatusBar = "Please wait while performing task 1..."
    ' add some code for task 1 that replaces the next sentence
    Application.Wait Now + TimeValue("00:00:02")
    Application.StatusBar = "Please wait while performing task 2..."
    ' add some code for task 2 that replaces the next sentence
    Application.Wait Now + TimeValue("00:00:02")
    Application.StatusBar = False
    ' gives control of the statusbar back to the programme
End Sub
```
```


Question: Apart from just inserting and parsing text into a blank Word field, is there any way to programmatically build user-defined fields and field codes into my own templates with VBA? Furthermore, is there a way to make these fields show up in the list of available fields?

Answer:
What had you in mind? It is possible to add custom document properties either manually or with VBA. These are the accessible as fields under DOCPROPERTY:
```
```
{ DOCPROPERTY "Test"  \* MERGEFORMAT }
```
```
You can use a macro to ensure that the custom property is added to documents:
```
```
Sub AutoNew()
Dim objCustomProperties As DocumentProperties

Set objCustomProperties = ActiveDocument.CustomDocumentProperties

objCustomProperties.Add Name:="Test", _
   Type:=msoPropertyTypeString, Value:="Blah", _
   LinkToContent:=False

End Sub
```
```
Further Information
Automacros:
http://msdn.microsoft.com/en-us/library/aa263747(office.10).aspx
Understanding Custom Document Properties in Microsoft Office Word 2003:
http://msdn.microsoft.com/en-us/library/aa537154.aspx


Question: We are looking for a open source J2EE Application server for log budget deployments. We are considering JBoss and Glassfish. Which is the best open source application server? Any comparative study available?

Answer:
A comparison table between JBoss, Geronimo and Tomcat for latter 2007.
This article
has many interesting points to aid your decision and is worth reading:
Geronimo 2 is the clear choice if your
  Java application needs are
  particularly extensive or if you just
  want to leverage total Java EE 5
  compliance.
Although JBoss 4.2 is not
  completely compatible with Sun's Java
  EE 5 standard, the JBoss 4.2 team is
  responsible for many of the
  cutting-edge technologies used by all
  of the servers and added to the
  standard Java EE 5 capabilities.
  Tomcat 6 by itself is a lightweight
  solution. It does not come with all
  the Java EE features and additional
  packages found in JBoss and Geronimo,
  but also doesn't require much memory
  and runs fast even on smaller servers.
In conclusion the author says:
Bottom line: JBoss, Geronimo, and
  Tomcat are reliable, fast, and
  definitely able to handle the traffic
  on large-scale enterprise
  applications. Furthermore, many of the
  high-demand Java server technologies
  presented in the features comparison
  originate from the open source world,
  not the commercial one.


Question:
A page executes a number of tasks and takes a long time to process. We want to give the user feedback as each task is completed.

In ASP.NET webforms we used Response.Flush()

What way would you a approach this in ASP.NET MVC?

Answer:
You can make it in client side. In each step, you set some session variable with the current step. Then, You make another action in your controller say called: "GetProgress" and assign a view and URI for it.
In the action, you will check this session and return the current progress of your task. In the client side, make a timer (i.e setTimeOut) and you invoke the URI of the later controller action every specific amount of time - 1 second or so. That is it.


Question:
Could someone explain to me how Any-related annotations (@Any, @AnyMetaDef, @AnyMetaDefs and @ManyToAny) work in practice. I have a hard time finding any useful documentation (JavaDoc alone isn't very helpful) about these.

I have thus far gathered that they somehow enable referencing to abstract and extended classes. If this is the case, why is there not an @OneToAny annotation? And is this 'any' referring to a single 'any', or multiple 'any'?

A short, practical and illustrating example would be very much appreciated (doesn't have to compile).

Edit: as much as I would like to accept replies as answers and give credit where due, I found both Smink's and Sakana's answers informative. Because I can't accept several replies as the answer, I will unfortunately mark neither as the answer.

Answer:
Have you read
the Hibernate Annotations documentation for @Any
? Haven't used that one myself yet, but it looks like some extended way of defining references. The link includes an example, though I don't know if it's enough to fully understand the concept...


Question: In history-books you often have timeline, where events and periods are marked on a line in the correct relative distance to each other. How is it possible to create something similar in LaTeX?

Answer:
The
tikz
package seems to have what you want.
```
```
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}

\begin{document}

  \begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm]
    % draw horizontal line
    \draw (0,0) -- (2,0);
    \draw[snake] (2,0) -- (4,0);
    \draw (4,0) -- (5,0);
    \draw[snake] (5,0) -- (7,0);

    % draw vertical lines
    \foreach \x in {0,1,2,4,5,7}
      \draw (\x cm,3pt) -- (\x cm,-3pt);

    % draw nodes
    \draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$   $};
    \draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};
    \draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};
    \draw (3,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};
    \draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};
    \draw (6,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};
  \end{tikzpicture}

\end{document}
```
```
I'm not too expert with tikz, but this does give a good timeline, which looks like:


Question:
Heres a screenshot to make it clear. I'm trying to figure out a robust way of making the bullet images vertically aligned to my li content. As you can see my content is currently too high.

Many thanks 'over-flowers'...

http://dl.getdropbox.com/u/240752/list-example.gif

Answer:
You can use something like this in your css...
```
```
#content li{

    list-style-image: url(../images/bullet.gif);

}
```
```


Question:
Our 404 error logs show a lot of /SysVol http requests on our Windows Web Server 2008 for our website. It only has a webserver role and I believe that SysVol requests are meant for Domain Controllers? What's causing this and what would be the best solution to deal with these 404 requests?

I'm using code that access employee records via Active Directory (ldap) and the server is not trusted for delegaton in case this is related to the problem.

Answer:
You can use something like this in your css...
```
```
#content li{

    list-style-image: url(../images/bullet.gif);

}
```
```


Question:
What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?

As an example, I need to convert this:

string = "*abc+de?"

to this:

string = ".*abc.+de.?"

Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?

Answer:
I'd use
```
replace
```
:
```
```
def wildcard_to_regex(str):
    return str.replace("*", ".*").replace("?", .?").replace("#", "\d")
```
```
This probably isn't the most efficient way but it should be efficient enough for most purposes. Notice that some wildcard formats allow character classes which are more difficult to handle.


Question:
Is there any good way to use a windows application written in C# to display/control a powerpoint slideshow? Ultimately I would like to show thumbnails in a form and clicking these thumbnails would advance the slides shown on a second monitor (similar to using Powerpoint itself to show a slideshow on a second monitor).

I would like to be able to use Powerpoint Viewer if Powerpoint is not installed.

There seems to be some ActiveX-controls that allows integration of Powerpoint in a form, but most of these seem to cost money, does anyone have experience using one of these controls?

Edit: I know that there is an object model accessable by adding a reference to Microsoft.Office.InterOp.Powerpoint, but I want to be able to distribute the resulting program without having Microsoft Office as a prerequisite, that was why I mentioned Powerpoint Viewer because it can be distributed freely.

Answer:
One of our softwares here at work does that. Initially we used MS Office but recently we switched to use
OpenOffice.org Uno
since it offers better control than MS Office and is easier to work with. It has
.NET CLI-bindings
.
To answer your question, yes it can be done but our engineers would recommend you use OpenOffice.org instead.


Question:
Suppose I have a hash_map and a code like

// i is an iterator
i = hash_map.erase(i)

But GCC's STL doesn't return iterator in erase, but a void. Now is a code like

hash_map.erase(i++)

safe (i.e. does not invalidate the iterator or does any other unexpected or unpleasant things)? Please note this is a hash_map.

Answer:
Yes, this is safe, because the value of
```
i
```
will have been set to the next value, before the current value is erased.
According to the
SGI documentation about hashed containers
invalidation does not occur for non-erased elements, nor even for resizing (there is no word on whether insertions cause resizing, so to be careful I admit that as a possibility)---but in the latter case, the iteration order will be changed. But this doesn't apply here, unless you go out of your way to resize the container during traversal or something. :-)


Question:
i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful

Answer:
Read the
unit testing framework section
of the
Python Library Reference
.
A
basic example
from the documentation:
```
```
import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def testshuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

    def testchoice(self):
        element = random.choice(self.seq)
        self.assert_(element in self.seq)

    def testsample(self):
        self.assertRaises(ValueError, random.sample, self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assert_(element in self.seq)

if __name__ == '__main__':
    unittest.main()
```
```


Question:
Below are lines from "the c++ programming language"

template<class T > T sqrt(T );
template<class T > complex<T> sqrt(complex<T>);
double sqrt(double);
void f(complex<double> z )
{
s q r t (2 ); // sqrt<int>(int)
sqrt(2.0) ; // sqrt(double)
sqrt(z) ; // sqrt<double>(complex<double>)
}

I dont understand why sqrt(z) ; calls sqrt<double>(complex<double>) can any body please explain.

Author says,
T sqrt<complex<T>>  is more specialized than T sqrt <T> but there is a seperate declaration for template<class T > complex<T> sqrt(complex<T>); why not use that?

Answer:
Well, the function used is the one you are talking about
```
sqrt<double>(complex<double>)
```
is an instance of the template
```
template <class T> complex<T> sqrt(complex<T>)
```
.
Your misunderstanding was in the signification of the template instance and not in the overloading process.


Question:
Is there any class in the .NET framework that can read/write standard .ini files:

[Section]
<keyname>=<value>
...

Delphi has the TIniFile component and I want to know if there is anything similar for C#?

Answer:
The creators of the .NET framework want you to use XML-based config files, rather than INI files. So no, there is no built-in mechanism for reading them.
There are third party solutions available, though.
INI handlers can be obtained as
NuGet packages
, such as
INI Parser
.
You can write your own INI handler, which is the old-school, laborious way. It gives you more control over the implementation, which you can use for bad or good. See e.g.
an INI file handling class using C#, P/Invoke and Win32
.


Question:
I am a big fan of letting the compiler do as much work for you as possible.  When writing a simple class the compiler can give you the following for 'free':

A default (empty) constructor

A copy constructor

A destructor

An assignment operator (operator=)

But it cannot seem to give you any comparison operators - such as operator== or operator!=.  For example:

class foo
{
public:
    std::string str_;
    int n_;
};

foo f1;        // Works
foo f2(f1);    // Works
foo f3;
f3 = f2;       // Works

if (f3 == f2)  // Fails
{ }

if (f3 != f2)  // Fails
{ }

Is there a good reason for this?  Why would performing a member-by-member comparison be a problem?  Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?

Answer:
I agree, for POD type classes then the compiler could do it for you. However what you might consider simple the compiler might get wrong. So it is better to let the programmer do it.
I did have a POD case once where two of the fields were unique - so a comparison would never be considered true. However the comparison I needed only ever compared on the payload - something the compiler would never understand or could ever figure out on it's own.
Besides - they don't take long to write do they?!


Question:
I've got a text box bound to an object's property (in fact several text boxes) on a form. This for is an editor for an object. When i'm editing some objects and modify values in the one of the text boxes i can't exit from the text box (neither by tab nor clicking on another text box). However that's not always the case - when editing other objects (of the same type) it works fine.

Here's a code snipet:

txtValue.DataBindings.Add("Text", _SourceObject, "PlannedValue", True, DataSourceUpdateMode.OnPropertyChanged, Nothing, "c")
txtEstPlacements.DataBindings.Add("Text", _SourceObject, "EstimatedPlacementCount")
txtReference.DataBindings.Add("Text", _SourceObject, "Reference")

Any suggestions?

Answer:
Sounds like a data validation issue.  Check if the controls on the form have their CausesValidation properties set to true or false.
Also check the AutoValidate property on the form.  It is probably set to EnablePreventFocusChange (which is the default).
It may also be the case that the value being supplied in the text box can not be converted to the type of the property it is bound to on the source data object.  I believe the Convert class is used for this (though I may be wrong here).
You may want to check out
this article
on MSDN that covers winforms validation in some detail.


Question: Can I have multiple primary keys in a single table?

Answer:
You can only have one primary key, but you can have multiple columns in your primary key.
You can also have Unique Indexes on your table, which will work a bit like a primary key in that they will enforce unique values, and will speed up querying of those values.


Question:
How do I print debug messages in the Google Chrome JavaScript Console?

Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the print command in JavaScript Debugger will not work here. In the JavaScript Console, print() will send the parameter to the printer.

Answer:
Executing following code from the browser address bar:
```
javascript: console.log(2);
```
successfully prints message to the "JavaScript Console" in Google Chrome.


Question:
How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:

http://site/catalogue/BrowseByStyleLevel/1

The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.

For example, these two URLs will take you to the same place:

https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages

https://stackoverflow.com/questions/119323/

EDIT: The friendly part of the url is referred to as a slug.

Answer:
you have a route on the global.asax
```
```
routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = ""}
                    // Parameter defaults )
```
```
you can  define your own route like :
controller is the cs class inside the the controllers folder.
you can define your id - with the name you choose.
the system will pass the value to your actionResult method.
you can read more about this step here :
http://www.asp.net/learn/mvc/tutorial-05-cs.aspx


Question: Is there a way to Deserialize Expressions in C#, I would like to store Expressions in a Database and load them at run time.

Answer:
Not in full; however, the
Dynamic LINQ
sample may help a bit. You can certainly serialize an expression to a string (to an extent - generics look a bit screwy), but there is no inbuilt parser.


Question: I was trying to test code using com class to display Word files but I cannot seem to get the answer and still searching. I get errors and sometimes, programs do not display anything at all. Please give me some ideas. I'm working with PHP 4.

Answer:
Do you mean you want to have the word plugin activated in the browser? Try the
```
<object>
```
tag with the correct mime type.


Question:
In the documentation of hardware that allows us to control it via UDP/IP,
I found the following fragment:

In this communication protocol, DWORD is a 4 bytes data, WORD is a 2 bytes data,
  BYTE is a single byte data. The storage format is little endian, namely 4 bytes (32bits) data is stored as: d7-d0, d15-d8, d23-d16, d31-d24; double bytes (16bits) data is stored as: d7-d0 , d15-d8.

I am wondering how this translates to C#?
Do I have to convert stuff before sending it over?
For example, if I want to send over a 32 bit integer, or a 4 character string?

Answer:
Re little-endian, the short answer (to do I need to do anything) is "probably not, but it depends on your hardware". You can check with:
```
```
bool le = BitConverter.IsLittleEndian;
```
```
Depending on what this says, you might want to reverse portions of your buffers. Alternatively, Jon Skeet has specific-endian converters
here
(look for EndianBitConverter).
Note that itaniums (for example) are big-endian. Most Intels are little-endian.
Re the specific UDP/IP...?


Question:
I quite often see on the Internet various complaints that other peoples examples of currying are not currying, but are actually just partial application.

I've not found a decent explanation of what partial application is, or how it differs from currying. There seems to be a general confusion, with equivalent examples being described as currying in some places, and partial application in others.

Could someone provide me with a definition of both terms, and details of how they differ?

Answer:
Interesting question. After a bit of searching,
"Partial Function Application is not currying"
gave the best explanation I found. I can't say that the
practical
difference is particularly obvious to me, but then I'm not an FP expert...
Another useful-looking page (which I confess I haven't fully read yet) is
"Currying and Partial Application with Java Closures"
.
It does look like this is widely-confused pair of terms, mind you.


Question: If I switch on the generating of debug info with Javac then the class files are 20-25% larger. Has this any performance effects on running the Java program? If yes on which conditions and how many. I expect a little impact on loading the classes because the files are larger but this should be minimal.

Answer:
In any language, debugging information is meta information. It by its nature increases the size of the object files, thus increasing load time. During execution outside a debugger, this information is actually completely ignored. As outlined (although not clearly) in the
JVM spec
the debug information is stored outside the bytecode stream. This means that at execution time there is no difference in the class file. If you want to be sure though, try it out :-).
Ps. Often for debugging there is value in turning off optimization. That
does
have a performance impact.


Question: Guys, can someone give me a brief run through of how to change the background colour of a CEdit control at runtime? I want to be able to change the background to red if the field is zero length and the normal white otherwise.

Answer:
You cannot do it with a plain CEdit, you need to override a few bits.
Implement your own ON_WM_CTLCOLOR_REFLECT handler, then return your coloured CBrush in the handler:
(roughly, you'll need to put the usual resource management in there, rememebr to delete your brush in the destructor)
```
```
class CColorEdit : public CEdit
{
  ....
  CBrush   m_brBkgnd;
  afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor)
  {
    m_brBkgnd.DeleteObject();
    m_brBkgnd.CreateSolidBrush(nCtlColor);
  }
}
```
```


Question: I want to show the publish date in the About dialog.

Answer:
Unfortunately, no. ApplicationDeployment class exposes only the
CurrentVersion
property, not the publish time.
You could use the revision field to store the date of the build to show in the About dialog.


Question: Is there a class in the standard library of .NET that gives me the functionality to create random variables that follow Gaussian distribution?

Answer:
Jarrett's suggestion of using a Box-Muller transform is good for a quick-and-dirty solution.  A simple implementation:
```
```
Random rand = new Random(); //reuse this if you are generating many
double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles
double u2 = 1.0-rand.NextDouble();
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
             Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
double randNormal =
             mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)
```
```


Question:
I've recently searched how I could get the application's directory in Java. I've finally found the answer but I've needed surprisingly long because searching for such a generic term isn't easy. I think it would be a good idea to compile a list of how to achieve this in multiple languages.

Feel free to up/downvote if you (don't) like the idea and please contribute if you like it.

Clarification:

There's a fine distinction between the directory that contains the executable file and the current working directory (given by pwd under Unix). I was originally interested in the former but feel free to post methods for determining the latter as well (clarifying which one you mean).

Answer:
In
Java
, there are two ways to find the application's path. One is to employ
```
System.getProperty
```
:
```
```
System.getProperty("user.dir");
```
```
Another possibility is the use of
```
java.io.File
```
:
```
```
new java.io.File("").getAbsolutePath();
```
```
Yet another possibilty uses reflection:
```
```
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
```
```


Question:
I have a div with overflow:hidden, inside which I show a phone number as the user types it. The text inside the div is aligned to right and incoming characters are added to right as the text grows to left.

But once the text is big enough not to fit in the div, last characters of the number is automatically cropped and the user cannot see the new characters she types.

What I want to do is crop the left characters, like the div is showing the rightmost of its content and overflowing to the left side. How can I create this effect?

Answer:
Have you tried using the following:
```
```
direction: rtl;
```
```
For more information see
http://www.w3schools.com/cssref/pr_text_direction.asp


Question:
Today when I was in computer organization class, teacher talked about something interesting to me. When it comes to talk about Why cache memory works, he said that:

for (i=0; i<M; i++)
   for(j=0; j<N; j++)
      X[i][j] = X[i][j] + K; //X is double(8 bytes)

it is not good to change the first line with the second. What is your opinions on this? And why it is like that?

Answer:
It is like that becauses caches like locality. The same number of memory accessed, but spaced further apart, will hit different "lines" of cache, or might even miss the cache altogether. It is therefore good, whenever you have the choice, to organize data so that accesses that are likely to happen close to each other in time, also do so in space. This increases the chance of a cache hit, and gives you more performance.
There is of course a wealth of information about this topic available, see for instance
this wikipedia entry on locality of reference
. Or, I guess, your own course text book. :)


Question:
I want to deserialize an object but don't know the class up front.  So, consider the following code...

IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);

What could I do if I don't know the class up front?  Say, for example "MyFile.bin" was a MyObject or a MyFoo.  How do I determine which object to instantiate?

Something like...

if (magic happens here == typeof(MyObject))
    MyObject obj = (MyObject) formatter.Deserialize(stream);
else if (more magic happens here == typeof(MyFoo))
    MyFoo foo = (MyFoo)formatter.Deserialize(stream);

Answer:
Just do:
```
```
object result = formatter.Deserialize(stream);
Type t = result.GetType();
```
```


Question:
I'm wrapping up a Javascript widget in a Wicket component.  I want to let the JS side talk to the component.  What I've got so far:

Component in question goes like

talker = new GridAjaxBehavior();
this.add(talker);

in constructor

and then, later on, puts something like

"var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ");";

into the JS.

where GridAjaxBehavior extends AbstractDefaultAjaxBehavior.  I want GridAjaxBehavior to spit back some XML when the JS calls it.

Am I doing this the right way?  What should GridAjaxBehaviour do to spit back the XML?

Thanks

Answer:
I don't really know what Wicket is or what it does, but there is a minor bug in your code (as it appears).
This:
```
"var MyGridTalker = new talker(" + this.talker.getCallbackUrl();
```
You seem to be missing your end parens:
```
"var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ")";
```
Anyway, not a big deal, but didn't know if it was intentional.


Question: If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?

Answer:
I use the
```
ArgumentException
```
(and its “friends”) regularly.
```
NotSupportedException
```
and
```
NotImplementedException
```
are also common.


Question:
To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action.

So, what's the correct way of doing such a thing? I've tried

panel = new CustomJPanelWithComponentsOnIt();
parentFrameJPanelBelongsTo.pack();

but this won't work. What would you suggest?

Answer:
```
```
frame.setContentPane(newContents());
frame.revalidate(); // frame.pack() if you want to resize.
```
```
Remember, Java use 'copy reference by value' argument passing. So changing a variable wont change copies of the reference passed to other methods.
Also note
```
JFrame
```
is very confusing in the name of usability. Adding a component or setting a layout (usually) performs the operation on the content pane. Oddly enough, getting the layout really does give you the frame's layout manager.


Question:
The following code

number=1
if [[ $number =~ [0-9] ]]
then
  echo matched
fi

works. If I try to use quotes in the regex, however, it stops:

number=1
if [[ $number =~ "[0-9]" ]]
then
  echo matched
fi

I tried "\[0-9\]", too. What am I missing?

Funnily enough, bash advanced scripting guide suggests this should work.

Bash version 3.2.39.

Answer:
It was changed
between 3.1 and 3.2
. Guess the advanced guide needs an update.
This is a terse description of the new
  features added to bash-3.2 since the
  release of bash-3.1.  As always, the
  manual page (doc/bash.1) is the place
  to look for complete descriptions.
New Features in Bash
snip
f.  Quoting the string argument to the
  [[ command's  =~ operator now forces
      string matching, as with the other pattern-matching operators.
Sadly this'll break existing quote using scripts unless you had the insight to store patterns in variables and use them instead of the regexes directly. Example below.
```
```
$ bash --version
GNU bash, version 3.2.39(1)-release (i486-pc-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.
$ number=2
$ if [[ $number =~ "[0-9]" ]]; then echo match; fi
$ if [[ $number =~ [0-9] ]]; then echo match; fi
match
$ re="[0-9]"
$ if [[ $number =~ $re ]]; then echo MATCH; fi
MATCH

$ bash --version
GNU bash, version 3.00.0(1)-release (i586-suse-linux)
Copyright (C) 2004 Free Software Foundation, Inc.
$ number=2
$ if [[ $number =~ "[0-9]" ]]; then echo match; fi
match
$ if [[ "$number" =~ [0-9] ]]; then echo match; fi
match
```
```


Question:
Is there a nicer way of styling a <hr /> tag using CSS, that is cross-browser consistent and doesn't involve wrapping a div around it? I'm struggling to find one.

The best way I have found, is as follows:

CSS

.hr {
    height:20px;
    background: #fff url(nice-image.gif) no-repeat scroll center;
}
hr {
    display:none;
}

HTML

<div class="hr"><hr /></div>

Answer:
If you set display to
```
block
```
it should behave more like a
```
<div>
```
.
Your answer you should remove hr altogether and just use the
```
div
```


Question:
As web based designer who has designed web sites using tables but never with css, how can a novice get started with css?

Related SO posts

SO - Css Book & website for CSS

SO - Css blog

Answer:
Get started by reading tutorial web site first. This way, he will see how to create simple CSS and see the benefits.
http://www.w3schools.com/css/
http://www.echoecho.com/css.htm
http://www.csstutorial.net/
http://www.w3.org/Style/Examples/011/firstcss
http://www.westciv.com/style_master/academy/css_tutorial/
Than, I suggest since he knows how to design website to check other website source and see their CSS files.
Zen Garden
is a good start.
If he requires more information, he can always get a book (I do not think it's necessary but if he wants a book), he could try
Core-Css
.


Question:
I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts).

$array1 = array(1 => 'a', 2 => 'b');
$array2 = array(3 => 'c', 4 => 'd');

Essentially I want to combine the two arrays as if it were something like this

$array3 = array(1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd');

Thanks

Answer:
Use
```
```
$array3 = $array1 + $array2;
```
```
See
Array Operators
By the way:
array_merge()
does something different with the arrays given in the example:
```
```
$a1=array(1 => 'a', 2 => 'b');
$a2=array(3 => 'c', 4 => 'd');
print_r($a1+$a2);
Array
(
    [1] => a
    [2] => b
    [3] => c
    [4] => d
)
print_r(array_merge($a1, $a2));
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
```
```
Note the different indexing.


Question: Is there a built-in way to URL encode a string in Excel VBA or do I need to hand roll this functionality?

Answer:
No, nothing built-in (
until Excel 2013 -
see this answer
).
There are three versions of
```
URLEncode()
```
in this answer.
A function with UTF-8 support.
You should probably use this one
(or
the alternative implementation
by Tom) for compatibility with modern requirements.
For reference and educational purposes, two functions without UTF-8 support:
one found on a third party website, included as-is. (This was the first version of the answer)
one optimized version of that, written by me
A variant that supports UTF-8 encoding and is based on
```
ADODB.Stream
```
(include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):
```
```
Public Function URLEncode( _
   ByVal StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String
  Dim bytes() As Byte, b As Byte, i As Integer, space As String

  If SpaceAsPlus Then space = "+" Else space = "%20"

  If Len(StringVal) > 0 Then
    With New ADODB.Stream
      .Mode = adModeReadWrite
      .Type = adTypeText
      .Charset = "UTF-8"
      .Open
      .WriteText StringVal
      .Position = 0
      .Type = adTypeBinary
      .Position = 3 ' skip BOM
      bytes = .Read
    End With

    ReDim result(UBound(bytes)) As String

    For i = UBound(bytes) To 0 Step -1
      b = bytes(i)
      Select Case b
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Chr(b)
        Case 32
          result(i) = space
        Case 0 To 15
          result(i) = "%0" & Hex(b)
        Case Else
          result(i) = "%" & Hex(b)
      End Select
    Next i

    URLEncode = Join(result, "")
  End If
End Function
```
```
This function was
found on freevbcode.com
:
```
```
Public Function URLEncode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim CurChr As Integer
  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    Select Case Asc(Mid(StringToEncode, CurChr, 1))
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case Else
        TempAns = TempAns & "%" & _
          Right("0" & Hex(Asc(Mid(StringToEncode, _
          CurChr, 1))), 2)
    End Select

    CurChr = CurChr + 1
  Loop

  URLEncode = TempAns
End Function
```
```
I've corrected a little bug that was in there.
I would use more efficient (~2× as fast) version of the above:
```
```
Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String

  Dim StringLen As Long: StringLen = Len(StringVal)

  If StringLen > 0 Then
    ReDim result(StringLen) As String
    Dim i As Long, CharCode As Integer
    Dim Char As String, Space As String

    If SpaceAsPlus Then Space = "+" Else Space = "%20"

    For i = 1 To StringLen
      Char = Mid$(StringVal, i, 1)
      CharCode = Asc(Char)
      Select Case CharCode
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Char
        Case 32
          result(i) = Space
        Case 0 To 15
          result(i) = "%0" & Hex(CharCode)
        Case Else
          result(i) = "%" & Hex(CharCode)
      End Select
    Next i
    URLEncode = Join(result, "")
  End If
End Function
```
```
Note that neither of these two functions support UTF-8 encoding.


Question:
I have a Makefile building many C files with long long command lines and we've cleaned up the output by having rules such as:

.c${MT}.doj:

        @echo "Compiling $<";\
         $(COMPILER) $(COPTS) -c -o $@ $<

Now this is great as the @ suppresses the compilation line being emitted.
But when we get an error, all we get is the error message, no command line.
Can anyone think of a "neat" way to emit the command line?
All I can think of doing is echoing it to a file and have a higher level make catch the error and cat the file. Hacky I know.

Answer:
Tested and it worked (GNU make in Linux):
```
```
.c${MT}.doj:
     @echo "Compiling $<";\
          $(COMPILER) $(COPTS) -c -o $@ $<  \
          || echo "Error in command: $(COMPILER) $(COPTS) -c -o $@ $<" \
          && false
```
```


Question:
I need to change in a text input the character '.' to ',' while typing.
In IE I change the keyCode event property in the keypress event, like this

document.getElementById('mytext').onkeypress =
 function (evt) {
  var e = evt || window.event;
  if (e.keyCode && e.keyCode==46)
   e.keyCode = 44;
  else if (e.which && e.which==46) {
   e.which = 44;
  }
 };

but it seemes that in Firefox it's impossible to change characters typed in key events.
Any suggestions?

Answer:
Try this. It works on all browsers:
```
```
window.onload = function () {
    var input = document.getElementById("mytext");

    input.onkeypress = function () {
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is it a period?
        if (char == ".") {
            // Replace it with a comma
            input.value += ",";

            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};
```
```
Update:
Pier Luigi
pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.
The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.


Question:
Is there support in Ruby for (for lack of a better word) non-escaped (verbatim) strings?

Like in C#:

@"c:\Program Files\"

...or in Tcl:

{c:\Program Files\}

Answer:
Yes, you need to prefix your string with
```
%
```
and then a single character delineating its type.
The one you want is
```
%q{c:\program files\}
```
.
The pickaxe book covers this nicely
here,
section is General Delimited Input.


Question: Looking for links to resources that will help me write a user guide for a software application. I'm after something that will help me to structure my guide, give it an appropriate writing style, and ensure that it has an excellent look and feel throughout.

Answer:
This link has some strong points. Each point is presented with clear speech and with inline justifications.
When writing procedures, use the
  active voice (e.g. Click this) and
  address users directly (write "you"
  rather than "the user").
When explaining an action, use the
  "command" form of the verb:
"Choose an option from the menu and
  press [ENTER]."
http://www.klariti.com/technical-writing/User-Guides-Tutorial.shtml
Here is the complete list of the topics covered on the aforementioned article:
Front Page (cover pages)
Cover and Title Page
Disclaimer
Preface
Contents
Body of the guide
Procedures
Writing procedures
Chunking text
Number your steps
Using the If-Then Approach
Reference Materials
Back Matter
Glossary
Index
Establishing Standards
Document Format
Structure Style
Technical Language
Addressing the User
Presenting your material
Special Requirements


Question: Is is possible to write MS SQL Server add-in? I'm thinking of some application integrated with database server available form SQL Server Enterprise Manager.

Answer:
You can include a lot into MS SQL server 2005 and 2008 database. Including .Net code.
But there is no real way to extend (create plugin for) the Management Studio. (Formerly Enterprise Manager.)
However there are database management addins for Visual Studio (especially in Team System). Maybe there you can implement what you need.


Question:
I have a custom class that implements that IComparable.  This class is stored in a Generic List.  I now need to compare to lists to see which objects are in list A but not in list B.

I thought the most simple way of doing this would be to iterate through list B and do A.contains().

I do not know how to get it to use my CompareTo() (or another method that I can override so that I can say if it contains a certain object or not).  I could be wrong but as I understand it the contains checks if the objects are actually the same (i.e. points to the same place in memory).

Could anyone help me please?

Answer:
Why don't you just override the
```
Equals
```
method of your class to be consistent in meaning with
```
CompareTo(other) == 0
```
? This is the simplest way and also the most idiomatic since, as you've noticed,
```
Contains
```
compares equality rather than using
```
CompareTo
```
. However, this check is done via
```
Equals
```
. It does
not
check whether the objects point to the same memory location.
/EDIT: Additionally, if you're using .NET 3.5 you can use the
```
Contains
```
overload that accepts an
```
IEqualityComparer
```
argument. You can use this to provide a class that implements a custom equality relation for your class type. However, I think the first method is more appropriate in your case.


Question:
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

Answer:
```
NullPointerException
```
s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object.  Calling a method on a null reference or trying to access a field of a null reference will trigger a
```
NullPointerException
```
.  These are the most common, but other ways are listed on the
```
NullPointerException
```
javadoc page.
Probably the quickest example code I could come up with to illustrate a
```
NullPointerException
```
would be:
```
```
public class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}
```
```
On the first line inside
```
main
```
, I'm explicitly setting the
```
Object
```
reference
```
obj
```
equal to
```
null
```
.  This means I have a reference, but it isn't pointing to any object.  After that, I try to treat the reference as though it points to an object by calling a method on it.  This results in a
```
NullPointerException
```
because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location.  A null pointer is literally not pointing
anywhere
, which is subtly different than pointing to a location that happens to be invalid.)


Question:
I want to stitch 2 pieces of png side by side. In Cocoa, I would use [NSImage initWithSize], and then just drawInRect.

But UIImage don't have initWithSize class, how would I do this now?

Answer:
Use
```
UIGraphicsBeginImageContext()
```
, draw in it, then use
```
UIGraphicsGetImageFromCurrentImageContext()
```
. Remember to pop the context with
```
UIGraphicsEndImageContext()
```
afterwards.
You should avoid creating an extra image if you simply want to display the two images onscreen, due to the limited memory available on the device. Instead, display them using appropriate
```
drawInRect:
```
calls to avoid copying.


Question:
What's the advantage of passing data as parameters vs part of the URL in an Ajax GET request?

Using parameters:

var ajax = new Ajax.Request('server.php',{
    parameters: 'store=11200&product=Meat',
    onSuccess: function(myData){whatever}
});

Using URL:

var ajax = new Ajax.Request('server.php?store=11200&product=Meat',{
    onSuccess: function(myData){whatever}
});

Answer:
One advantage to using the
```
parameters
```
argument is that you can pass it a
```
Hash
```
-like object instead of as a string. (If you do this, though, make sure so set the
```
method
```
parameter to
```
"GET"
```
, as the default method for Prototype Ajax requests is POST; see
the Prototype Introduction to Ajax
for more details.)
Another advantage, which is more in-line with the example that you gave, is that you can separate the request URL from the options that are sent to it. This might be useful if, for example, you need to send a bunch of similar requests to several different URLs. (In that case, having a common parameters
```
Hash
```
that you modify for each request might be more useful, than using a parameter string, as well.)
For more information, see
the Prototype documentation of Ajax options
.


Question:
I was wondering if there was a good way to monitor a document library on SharePoint for changes (new files added, files changed / checked-in, files deleted, etc.)

Basically, what System.IO.FileSystemWatcher does on local / network directories.

Are there events that get fired when documents are uploaded to document libraries?

Perhaps creating a workflow on the document library that fires onCreate / onModify would be better?

Any suggestions are welcome.

Answer:
Take a look at event receivers for lists/document libraries.  There are both synchronous and asynchronous options built into the object model. (ItemAdded, ItemAdding, ItemUpdated, ItemUpdating ... and so on.)
The following site should give you a good start:
http://www.davehunter.co.uk/Blog/Lists/Posts/Post.aspx?List=f0e16a1a%2D6fa9%2D4130%2Dbcab%2Dbaeb97ccc4ff&ID=69


Question:
Suppose we have the following code:

ExpressionHelper.GetRouteValuesFromExpression<AccountController>(ax => ax.MyAction("a", "b"));

(from ASP.NET MVC Futures assembly). Method is reasonably fast - it executes 10k iterations in 150ms.

Now, we change code to this:

string a = "a";
string b = "b";
ExpressionHelper.GetRouteValuesFromExpression<AccountController>(ax => ax.MyAction(a, b));

This code will execute 10k iterations in 15 seconds

The problem is the following code:

Expression<Func<object>> lambdaExpression = Expression.Lambda<Func<object>>(Expression.Convert(arg, typeof (object)));

Func<object> func = lambdaExpression.Compile();

value = func()

Is there a better way to get value from expression than compiling expression every time? This can greatly affect ASP.NET MVC link generation speed.

Answer:
Why don't you just cache the value of the expression and its compiled value locally if this is such a bottleneck? I imagine a simply Dictionary could do the trick:
```
```
Dictionary<Expression<Action<T>>, Action<T>> m_Cache =
    new Dictionary<Expression<Action<T>>, Action<T>>();

public void GetRouteValuesFromExpression<T>(Expression<Action<T>> expr) {
    Action<T> compiled = null;
    if (!m_Cache.TryGetValue(expr, ref compiled)) {
        compiled = expr.Compile();
        m_Cached.Add(expr, compiled);
    }
    // execute …
}
```
```


Question:
What is the best way to actively monitor if a .NET Windows service is still running (e.g not hung)?  The service needs to periodically respond to events raised by a timer.

Thanks

Jon

Answer:
"Not hung" is always a hard condition to definitively detect, and will depend on the details of your service.
In general any form of interprocess communication can be used.  One simple approach is to create a
named
shared memory mapping and simply write information to it periodically from your service.  Another process can monitor the shared memory and see if its state stops changing.
The advantage of this approach is that you can extend the shared memory block to include other diagnostics which may help diagnose any issues.


Question:
Part of my latest webapp needs to write to file a fair amount as part of its logging. One problem I've noticed is that if there are a few concurrent users, the writes can overwrite each other (instead of appending to file). I assume this is because of the destination file can be open in a number of places at the same time.

flock(...) is usually superb but it doesn't appear to work on NFS... Which is a huge problem for me as the production server uses a NFS array.

The closest thing I've seen to an actual solution involves trying to create a lock dir and waiting until it can be created. To say this lacks elegance is understatement of the year, possibly decade.

Any better ideas?

Edit: I should add that I don't have root on the server and doing the storage in another way isn't really feasible any time soon, not least within my deadline.

Answer:
Another dirty hack would be to
```
flock()
```
a "local" file, and only open / write to the NFS file if you hold the lock on the local file.
Edit: from the
```
flock()
```
page:
flock() will not work on NFS and many
  other networked file systems. Check
  your operating system documentation
  for more details.
Edit 2:
Of course there's always using the database to synchonise access (I'm assuming your app uses a db).  This would be quite a performance hit if you're doing a lot of logging though.
If it's just for logging, do you actually need a centralised log file?  Could you log locally (and even combine the logs when they rotate at the end of the day if needed)?


Question:
I would like to know what is the difference between initializing a static member inline as in:

class Foo
{
    private static Bar bar_ = new Bar();
}

or initializing it inside the static constructor as in:

class Foo
{
    static Foo()
    {
        bar_ = new Bar();
    }
    private static Bar bar_;
}

Answer:
In this case I don't believe there si any practical difference. If you need some logic in initializing the static variables - like if you would want to use different concrete types of an interface given different conditions - you would use the static constructor. Else, the inline initialization is fine in my book.
```
```
class Foo
{
    private static IBar _bar;

    static Foo()
    {
        if(something)
        {
            _bar = new BarA();
        }
        else
        {
            _bar = new BarB();
        }
    }
}
```
```


Question: Specifically, I want to copy a link (with text and location) and then to be able to paste it, e.g., into Word as a link.

Answer:
dig around inside
Download of the Day: AutoCopy Firefox extension
or
Clipboard-Save-As 1.0.4