Question:
When 'val' below is not a bool I get an exception, I believe I can use TryParse but I'm not sure how best to use it with my code below. Can anyone help?

checkBox.Checked = Convert.ToBoolean(val);

Thanks

Answer:
The code is as follows to determine whether the string
```
val
```
is a valid Boolean value and use it to set the
```
Checked
```
property if so. You need to decide what action you would take if it does not represent a valid value.
```
```
bool result;
if (bool.TryParse(val, out result))
{
    // val does represent a Boolean
    checkBox.Checked = result;
}
else
{
    // val does not represent a Boolean
}
```
```


Question:
I heard Microsoft allows use of commercially available Office UI controls, with the exception of competing products, such as a word processor or spreadsheet app, etc.

How true is that?

Also, if it is not true, do you know of any free Ribbon controls?

Answer:
You should look at
Jensen Harris' blog entry about licensing the Office user interface
which explains it in great detail. However I believe the relevant point here is:
There's only one limitation: if you
  are building a program which directly
  competes with Word, Excel, PowerPoint,
  Outlook, or Access (the Microsoft
  applications with the new UI), you
  can't obtain the royalty-free license.


Question:
So, I'm working under the assumption that we have typed languages because we make a lot of mistakes... so typing is one way to have the compiler do a lot of checks for us and help us out a bit (please let me know if it is my assumptions that's incorrect).

However, if we introduce casting to a typed language, don't we re-introduce most the problems we had when were not able to type variables?

I'm also aware that my assumption isn't the only reason why we type variables. Please share some of the other reasons why we have typed languages.

Answer:
so typing is one way to have the
  compiler do a lot of checks for us and
  help us out a bit
Yes.
However, if we introduce casting to a
  typed language, don't we re-introduce
  most the problems we had when were not
  able to type variables?
Yes.
You should avoid it to the extent possible, but sometimes you still need to do dirty work.
Of course, there are plenty of languages that do not enforce strict typing, and plenty of people who like them and get useful work done with them.


Question:
I'm using a vendor API to obtain a JDBC connection to the application's database. The API works when running in the application server or when running in a stand-alone mode. I want to run a series of SQL statements in a single transaction. I'm fine with them occurring in the context of the JTA transaction if it exists. However, if it doesn't then I need to use the JDBC transaction demarcation methods. (Calling these methods on a JDBC connection that is participating in a JTA transaction causes a SQLException.)

So I need to be able to determine whether the Connection came from the JTA enabled DataSource or if it's just a straight JDBC connection.

Is there a straight forward way to make this determination?

Thanks!

Answer:
You could try to check the Connection's autoCommit flag to see if it is in a transaction (regardless of where it came from).
(Apparently, see the accepted answer, this does not work too well. I am not deleting this answer because the following still stands: )
But I think you should really modify your API to depend on external transactions exclusively. If you still want to support plain JDBC, wrap it into a separate API that just starts the transaction.
Update: Just re-read your question and saw that you are not providing an API, but want to use a container-managed connection. But still, can you just mandate (as part of your application's requirements) that JTA be in effect? If not, you could provide a configuration option to fall back to manually managed transactions. For such a critical feature it seems reasonable to require the proper configuration (as opposed to try to guess what would be appropriate).


Question:
How do you iterate over each file in a directory with a .bat or .cmd file?

For simplicity please provide an answer that just echoes the filename or file path.

Answer:
Command line usage:
```
```
for /f %f in ('dir /b c:\') do echo %f
```
```
Batch file usage:
```
```
for /f %%f in ('dir /b c:\') do echo %%f
```
```
Update
: if the directory contains files with space in the names, you need to change the delimiter the
```
for /f
```
command is using. for example, you can use the pipe char.
```
```
for /f "delims=|" %%f in ('dir /b c:\') do echo %%f
```
```
Update 2
: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the
```
usebackq
```
option on the
```
for
```
:
```
```
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f
```
```
And if you need to use output redirection or command piping, use the escape char (
```
^
```
):
```
```
for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f
```
```


Question:
I have an upcoming project which will have to be able to print simple reports from its data. It'll be WPF-based, and I'm wondering which way to go.

I know that WPF introduces its own printing technology (based on XPS) which looks quite easy to use. However, part of me wonders whether it would just be easier to use the ReportViewer control and embed it in a Windows Forms host control, since that will give users the ability to export to a variety of formats as well as print.

Has anyone had any experience with printing/reporting from WPF? Which direction would you recommend?

Answer:
I've reccently accomplished task of developing own reporting system, which basically consist on design enviroment and data Source manager. The first task was to develop WYSWIG-like design enviroment. I've done this using GDI+, without even bothering about printing, as it came out printing/generating print preview was easiest than i expected, In general it  only takes to draw all things on screen to graphics object of printing event.
I think that in case of WPF it would be similar, so all you should worry about is to display you report on screen and printing would be only few lines of code.


Question:
Is there a way to take substrings of a string with .bat/.cmd files?

For example given the string "hello.txt" is there a way to strip the .txt?

EDIT: Also is there a more general way to do this, not under the assumption that it is a file name or file path?

Answer:
If this is a file passed as a parameter, you can use %~n1, like this:
```
```
test.bat
----------
echo %~n1 %~n2

c:\> test.bat myfile.txt my.long.file.bat
  myfile my.long.file
```
```
If you know the length of the string you can use the substring operator:
```
```
echo %variable:0,4%   =>  "test.txt" => "test"
```
```
And to get everything EXCEPT the last 4 characters:
```
```
echo %variable:~0,-4%  => "file...name.txt" => "file...name"
```
```
BatchFiles Website (kind advanced)
Decent forum post
Another Good Post


Question: What are the best free resources for learning advanced batch-file usage?

Answer:
Tried
Wikipedia's batch file entry
? ...or any of
the multitude of answers google gives on advanced batch file usage
?


Question: I have a ListBox which displays items of variable height. I want to show as many items as will fit in the available space, without showing a vertical scrollbar. Other than surgery on the ListBox item template, is there a way to only show the number of items which will fit without scrolling?

Answer:
```
```
<ListBox ScrollViewer.VerticalScrollBarVisibility="Auto" />
```
```
the default is visible


Question:
I have a servlet which is in the same web application as the JSF servlet.
How do I replace (rather than redirect) the servlet response with the JSF response?

Answer:
Not sure I fully understand your question - but if you want to include the output from a JSF page in your servlet response, something like:
```
```
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        // Do stuff
        req.getRequestDispatcher("/blah.jsf").forward(req, res);
        // Do other stuff
}
```
```
Should do the trick


Question:
Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface?

In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter the changed data. Using a better model structure would be one way of reducing the duplication of the data, but there may be situation where the duplicated data needs to be changed on an individual basis in the future.

Answer:
You can
save as
by just enabling adding this to your ModelAdmin:
```
```
save_as = True
```
```
This replaces the "Save and add another" button with a "Save as" button.  "Save as" means the object will be saved as a new object (with a new ID), rather than the old object.


Question:
Here are some gems:

Literals:

var obj = {}; // Object literal, equivalent to var obj = new Object();
var arr = []; // Array literal, equivalent to var arr = new Array();
var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something');

Defaults:

arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:
arg = !!arg ? arg : 'default';

Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:

(function() { ... })(); // Creates an anonymous function and executes it

Question: What other great syntactic sugar is available in javascript?

Answer:
In Mozilla (and reportedly IE7) you can create an XML constant using:
```
var xml = <elem></elem>;
```
You can substitute variables as well:
```
var elem = "html";
var text = "Some text";
var xml = <{elem}>{text}</{elem}>;
```


Question:
I'm the creator (and so far, only developer) of a CodePlex project.  I've writing it on my laptop, using a Subversion repository on my home network.

Submitting my changes to CodePlex via the TeamServer interface is driving me crazy, and I'd really like a simple way of syncing my svn repos with CodePlex via there new SVN interface.  svnsync or synmerge seem to be the way to go, but neither's instructions seem clear to a guy who's only ever used TortoiseSVN. And they seem to also seem need local access to the destination server (which clearly for CodePlex, is impossible)

So, could someone give simple instructions how to do this?

Answer:
As you'll find in the
documentation
, svnsync requires exclusive (but not local) access to the destination server. This makes it unfit for your purpose, as it would render the CodePlex repository inaccessible for commits by other developers (when they come ;)).
You might consider the other way around though: always commit to the CodePlex repo, and use svnsync to keep a local (and read-only) mirror of that.


Question:
How would you reference the models (Accord, CRV, Prius, etc) in this structure?
Is this a bad structure to be able to extract the makes...then use a make to get the models...then use the model to get the options?

var cars = [
    {
        "makes"   : "Honda",
        "models"   : [
            {'Accord' : ["2dr","4dr"]} ,
            {'CRV'    : ["2dr","Hatchback"]} ,
            {'Pilot'  : ["base","superDuper"] }
        ]
    },
    {
        "makes"   : "Toyota",
        "models"  : [
            {'Prius'   : ["green","reallyGreen"]} ,
            {'Camry'   : ["sporty","square"]} ,
            {'Corolla' : ["cheap","superFly"] }
        ]
    }
];

Thanks

Answer:
cars[0].models.Accord
    cars[0].models.CRV
    cars[0].models.Pilot
(See
olliej
's answer)
Though, it may be easier to use the following access concept:
```
```
cars.Honda.Accord
cars.Toyota.Prius
```
```
...using...
```
```
var cars = {
  Honda : {
    Accord : ["2dr", "4dr"],
    CRV    : ["2dr", "Hatchback"],
    Pilot  : ["base", "superDuper"]
  },
  Toyota : {
    Prius : ["green", "reallyGreen"],
    Camry : ["sporty", "square"],
    Corolla : ["cheap", "superFly"]
  }
};
```
```


Question:
What is the maximum length for the text string contained in a CEdit control in MFC? I get a beep when trying to add a character after the character 30001 is this documented anywhere? Can I display longer texts in a CEdit? Should I use another control?

As "Windows programmer" says down below, the text length limit is not the same when the user types as when we programatically set the text using SetWindowText. The limit for setting a text programatically is not mentioned anywhere. The default text lentgth limit for the user typing is wrong. (see my own post below).

I'm guessing that after I call pEdit->SetLimitText(0) the limit for both programatically and user input text length is 7FFFFFFE bytes. Am I right?

In vista, when pasting text longer than 40000 characters into a CEdit, it becomes unresponsive. It does not matter if I called SetLimitText(100000) previously.

Answer:
You can find out what the maximum is for your control by calling
CEdit::GetLimitText()
on your control.  This returns the maximum size for character data in bytes.  You can change the maximum size using the
CEdit::SetLimitText()
function.
The SetLimitText() function is equivalent to sending an
EM_SETLIMITTEXT
message.  The documentation for that message gives the maximum sizes that can be used, but since these are MSDN links that will probably be broken by tomorrow, I'll copy the relevant information :)
The UINT parameter is interpreted as:
The maximum number of TCHARs the user
  can enter. For ANSI text, this is the
  number of bytes; for Unicode text,
  this is the number of characters. This
  number does not include the
  terminating null character. Rich edit
  controls: If this parameter is zero,
  the text length is set to 64,000
  characters.
Edit controls on Windows NT/2000/XP:
  If this parameter is zero, the text
  length is set to 0x7FFFFFFE characters
  for single-line edit controls or –1
  for multiline edit controls.
Edit controls on Windows 95/98/Me: If
  this parameter is zero, the text
  length is set to 0x7FFE characters for
  single-line edit controls or 0xFFFF
  for multiline edit controls.
Also, from the Remarks section:
Before EM_SETLIMITTEXT is called, the
  default limit for the amount of text a
  user can enter in an edit control is
  32,767 characters.
Edit controls on Windows NT/2000/XP:
  For single-line edit controls, the
  text limit is either 0x7FFFFFFE bytes
  or the value of the wParam parameter,
  whichever is smaller. For multiline
  edit controls, this value is either –1
  bytes or the value of the wParam
  parameter, whichever is smaller.
Edit controls on Windows 95/98/Me: For
  single-line edit controls, the text
  limit is either 0x7FFE bytes or the
  value of the wParam parameter,
  whichever is smaller. For multiline
  edit controls, this value is either
  0xFFFF bytes or the value of the
  wParam parameter, whichever is
  smaller.
I assume they meant 0xFFFFFFFF instead of -1 in the second paragraph there...


Question: If a file is set to read only mode, how do I change it to write mode and vice versa from within Emacs?

Answer:
M-x read-only-mode
in very old versions of Emacs, the command was:
M-x toggle-read-only
On my Windows box, that amounts to Alt-x to bring up the meta prompt and typing "read-only-mode" to call the correct elisp function.
If you are using the default keyboard bindings,
C-x C-q
(which you read aloud as "Control-X Control-Q") will have the same effect.  Remember, however, given that emacs is essentially infinitely re-configurable, your mileage may vary.
Following up from the commentary:
you should note that the writeable status of the buffer does not change the writeable permission of the file.  If you try to write out to a read only
file
, you'll see a confirmation message.  However, if you own the file, you can write out your changes
without
changing the permissions on the file.
This is very convenient if you'd like to make a quick change to a file without having to go through the multiple steps of add write permission, write out changes, remove write permission.  I tend to forget that last step, leaving potentially critical files open for accidental changes later on.


Question: Working in Eclipse on a Dynamic Web Project (using Tomcat (v5.5) as the app server), is there some way I can configure things so Tomcat will start with security turned on (i.e. as if I ran catalina.sh start -security)?

Answer:
I'm assuming that you're using Tomcat 5.5.x
after looking at catalina.bat/catalina.sh, all the -security flag does is to set
-Djava.security.policy=="%CATALINA_BASE%\conf\catalina.policy"
Most people have CATALINA_BASE set to TOMCAT_HOME or CATALINA_HOME
So, if you have installed tomcat in the directoryc:\tomcat, then all you need to do is to set an option in the tomcat plugin to include the above policy.
i.e, add this to JAVA_OPTIONS : -Djava.security.policy=="c:\tomcat\conf\catalina.policy".
That's all and restart.


Question:
I want to programmatically create a new column in an MS Access table.  I've tried many permutations of ALTER TABLE MyTable Add  MyField DECIMAL (9,4) NULL; and got:

Syntax Error in Field Definition

I can easily create a number field that goes to a Double type, but I want decimal.  I would very strongly prefer to do this in a single ALTER TABLE statement and not have to create a field and then alter it.

I am using Access 2003.

Answer:
The ALTER TABLE syntax is only supported in Jet 4.0/ACE while in
ANSI-92 Query Mode. Try an ADO connection e.g.
CurrentProject.Connection.Execute "ALTER TABLE myTbl ADD COLUMN myColumn DECIMAL(9,4)"


Question:
I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.

Given this data:

var data = new List<string>();
data.Add("One");
data.Add("Two");
data.Add("Three");

And this code: ** Which is not correct and is what needs to be fixed!! **

var shaped = data.Select(c =>
    new { c = c }
).ToList();

serializer.Serialize(shaped,sb);
string desiredResult = sb.ToString();

I would like desiredResult to be:

{
    "One": "One",
    "Two": "Two",
    "Three": "Three"
}

but it is currently:

{ "c" : "One" },{ "c" : "Two" }, etc.

One problem is that on the left side of the object initializer I want the value of c, not c itself...

Answer:
The ALTER TABLE syntax is only supported in Jet 4.0/ACE while in
ANSI-92 Query Mode. Try an ADO connection e.g.
CurrentProject.Connection.Execute "ALTER TABLE myTbl ADD COLUMN myColumn DECIMAL(9,4)"


Question: Is there a freely available Base64 decoding code snippet in C++?

Answer:
See
Encoding and decoding base 64 with C++
.
Here is the implementation from that page:
```
```
/*
   base64.cpp and base64.h

   Copyright (C) 2004-2008 René Nyffenegger

   This source code is provided 'as-is', without any express or implied
   warranty. In no event will the author be held liable for any damages
   arising from the use of this software.

   Permission is granted to anyone to use this software for any purpose,
   including commercial applications, and to alter it and redistribute it
   freely, subject to the following restrictions:

   1. The origin of this source code must not be misrepresented; you must not
      claim that you wrote the original source code. If you use this source code
      in a product, an acknowledgment in the product documentation would be
      appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and must not be
      misrepresented as being the original source code.

   3. This notice may not be removed or altered from any source distribution.

   René Nyffenegger rene.nyffenegger@adp-gmbh.ch

*/

static const std::string base64_chars =
             "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
             "abcdefghijklmnopqrstuvwxyz"
             "0123456789+/";

static inline bool is_base64(unsigned char c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
  std::string ret;
  int i = 0;
  int j = 0;
  unsigned char char_array_3[3];
  unsigned char char_array_4[4];

  while (in_len--) {
    char_array_3[i++] = *(bytes_to_encode++);
    if (i == 3) {
      char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
      char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
      char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
      char_array_4[3] = char_array_3[2] & 0x3f;

      for(i = 0; (i <4) ; i++)
        ret += base64_chars[char_array_4[i]];
      i = 0;
    }
  }

  if (i)
  {
    for(j = i; j < 3; j++)
      char_array_3[j] = '\0';

    char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
    char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
    char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
    char_array_4[3] = char_array_3[2] & 0x3f;

    for (j = 0; (j < i + 1); j++)
      ret += base64_chars[char_array_4[j]];

    while((i++ < 3))
      ret += '=';

  }

  return ret;

}
std::string base64_decode(std::string const& encoded_string) {
  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;
  unsigned char char_array_4[4], char_array_3[3];
  std::string ret;

  while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
    char_array_4[i++] = encoded_string[in_]; in_++;
    if (i ==4) {
      for (i = 0; i <4; i++)
        char_array_4[i] = base64_chars.find(char_array_4[i]);

      char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
      char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
      char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

      for (i = 0; (i < 3); i++)
        ret += char_array_3[i];
      i = 0;
    }
  }

  if (i) {
    for (j = i; j <4; j++)
      char_array_4[j] = 0;

    for (j = 0; j <4; j++)
      char_array_4[j] = base64_chars.find(char_array_4[j]);

    char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
    char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
    char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

    for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  }

  return ret;
}
```
```


Question: Just updated build server with rc0 and surprise no chiron.  Wondering how you package up a xap file without chiron.

Answer:
Hey Brian, you can get chiron from
http://www.codeplex.com/sdlsdk
-- it was decided to be removed from the SL SDK core tools, but is still a part of the DLR SDK which is available.


Question:
I have many years of experience in Java including Swing, Servlet and JDBC, but have never programmed for a Java EE server.

Many job advertisements from large companies are specifically asking for Java EE experience.  Are there specific skills or development environments that I should learn to qualify for these kinds of jobs?

Answer:
Those jobs are most likely asking that you have experience with one or more of the major app server vendors, i.e. WebLogic, WebSphere, or JBoss. It's a bit different from what you're used to with servlets & JDBC, but it's still just Java. Typically you have to deal with things like JNDI lookups, dependency injection, messaging queues, maintaining application state between transactions, object/relational mapping, etc.
I have found that for most Java EE projects, it's more about knowing how components and systems are configured and how they work together than it is about any specific programming skill. And you also spend a lot more time waiting for the server to start up ;);


Question:
I am getting very frustrated because I cannot seem to figure out why Collections shuffling is not working properly.

Lets say that I am trying to shuffle the randomizer array.

int[] randomizer = new int[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));

For some reason the elements stay sorted exactly the same whether or not I call the shuffle method.  Any ideas?

Answer:
```
Arrays.asList
```
cannot be used with arrays of primitives. Use this instead:
```
```
Integer[] randomizer = new Integer[] {200,300,212,111,6,2332};
Collections.shuffle(Arrays.asList(randomizer));
```
```
The same rule applies to most classes in the collections framework, in that you can't use primitive types.
The original code (with
```
int[]
```
) compiled fine, but did not work as intended, because of the behaviour of the variadic method
```
asList
```
: it just makes a one-element list, with the
```
int
```
array as its only member.


Question: Why does tempuri.org exist?  Why does each XML Webservice require its own namespace, unique from any other on the web?

Answer:
Unfortunately the
```
tempuri.org
```
URL now just redirects to Bing.
You can see what it used to render via
```
archive.org
```
:
https://web.archive.org/web/20090304024056/http://tempuri.org/
To quote:
Each XML Web Service needs a unique namespace in order for client
  applications to distinguish it from other services on the Web.  By
  default, ASP.Net Web Services use
http://tempuri.org/
for this
  purpose.  While this suitable for XML Web Services under development,
  published services should use a unique, permanent namespace.
Your XML Web Service should be identified by a namespace that you
  control.  For example, you can use your company's Internet domain name
  as part of the namespace.  Although many namespaces look like URLs,
  they need not point to actual resources on the Web.
For XML Web Services creating[sic] using ASP.NET, the default namespace can
  be changed using the WebService attribute's Namespace property.  The
  WebService attribute is applied to the class that contains the XML Web
  Service methods.  Below is a code example that sets the namespace to
  "
http://microsoft.com/webservices/
":
C#
```
```
[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
   // implementation
}
```
```
Visual Basic.NET
```
```
<WebService(Namespace:="http://microsoft.com/webservices/")> Public Class MyWebService
    ' implementation
End Class
```
```
Visual J#.NET
```
```
/**@attribute WebService(Namespace="http://microsoft.com/webservices/")*/
public class MyWebService {
    // implementation
}
```
```
It's also worth reading section 'A 1.3 Generating URIs' at:
http://www.w3.org/TR/wsdl#_Toc492291092


Question:
What is the difference between the search() and match() functions in the Python re module?

I've read the Python 2 documentation (Python 3 documentation), but I never seem to remember it.  I keep having to look it up and re-learn it.  I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head.  Or at least I'll have a better place to return with my question and it will take less time to re-learn it.

Answer:
```
re.match
```
is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using
```
^
```
in the pattern.
As the
re.match documentation
says:
If zero or more characters at the
beginning of string
match the regular expression pattern, return a
  corresponding
```
MatchObject
```
instance.
  Return
```
None
```
if the string does not
  match the pattern; note that this is
  different from a zero-length match.
Note: If you want to locate a match
  anywhere in string, use
```
search()
```
instead.
```
re.search
```
searches the entire string, as
the documentation says
:
Scan through string
looking for a
  location where the regular expression
  pattern produces a match, and return a
  corresponding
```
MatchObject
```
instance.
  Return
```
None
```
if no position in the
  string matches the pattern; note that
  this is different from finding a
  zero-length match at some point in the
  string.
So if you need to match at the beginning of the string, or to match the entire string use
```
match
```
. It is faster. Otherwise use
```
search
```
.
The documentation has a
specific section for
```
match
```
vs.
```
search
```
that also covers multiline strings:
Python offers two different primitive
  operations based on regular
  expressions:
```
match
```
checks for a match
only at the beginning
of the string,
  while
```
search
```
checks for a match
anywhere
in the string (this is what
  Perl does by default).
Note that
```
match
```
may differ from
```
search
```
even when using a regular expression
  beginning with
```
'^'
```
:
```
'^'
```
matches only
  at the start of the string, or in
```
MULTILINE
```
mode also immediately
  following a newline. The “
```
match
```
”
  operation succeeds
only if the pattern
  matches at the
start
of the string
regardless of mode, or at the starting
  position given by the optional
```
pos
```
argument regardless of whether a
  newline precedes it.
Now, enough talk. Time to see some example code:
```
```
# example code:
string_with_newlines = """something
someotherthing"""

import re

print re.match('some', string_with_newlines) # matches
print re.match('someother',
               string_with_newlines) # won't match
print re.match('^someother', string_with_newlines,
               re.MULTILINE) # also won't match
print re.search('someother',
                string_with_newlines) # finds something
print re.search('^someother', string_with_newlines,
                re.MULTILINE) # also finds something

m = re.compile('thing$', re.MULTILINE)

print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
               re.MULTILINE) # also matches
```
```


Question: My application has no forms. It runs by calling Application.Run();

Answer:
Call
```
```
System.Windows.Forms.Application.Exit();
```
```


Question: Has anyone been able to implement the JQuery grid plugin, jqGrid? I'm trying to implement the JSON paging, and I feel like I'm getting close, but that I am also being swamped by inconsequential details. If anyone could post some sample code, I would greatly appreciate it.

Answer:
I'm just floundering trying to pull everything together. My first concern is simply generating a correct JSON response. My returned class appears to be serialised as a property named 'd' - is this a JQuery thing, or ASP.Net web method convention? I'm afraid that jqGrid will be looking for the data to be top-level, whereas asp.net will put it in a property called 'd':
```
```
[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object GetData() {
        TestClass tc = new TestClass() { One = "Hello", Two = "World" };
        return tc;
    }

        $("#divResults").click(function() {
            $.ajax({
                type: "POST",
                url: "GridData_bak.aspx/GetData",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(test) {
                    // Replace the div's content with the page method's return.
                    $("#divResults").text(test.d.One);
                },
                error: function(msg) {
                    $("#divResults").text(msg);
                }
            });
        });
```
```


Question:
I installed Ruby and Ruby on Rails yesterday on Vista 32bit using the directions on this site: http://rubyonrails.org/down

So I downloaded the installer, then Gems, then I downloaded rails with Gems.

Now I can't use the Gem or Ruby commands in the command line... so I assume there's something wrong with the environment variables, but I hav eno idea how to set them up in Vista or what to put.

Can anyone help me with this?

Answer:
In the command line window type
```
PATH
```
then hit return, do you see
```
ruby.exe
```
on the
```
PATH
```
environment variable?
If you installed ruby to say
```
c:\ruby
```
then it'll be
```
c:\ruby\bin\
```
.
Looks like it may be missing from the path.


Question:
I am trying to learn some of the basic and advanced features of visual studio, Anyone find sites that have this type of information ?

I see this:

https://stackoverflow.com/questions/86355/best-way-to-learn-visual-studio-power-features

But it seems more related to tips and advanced features.

All three versions ( 2003, 2005, 2008 )

Answer:
In the command line window type
```
PATH
```
then hit return, do you see
```
ruby.exe
```
on the
```
PATH
```
environment variable?
If you installed ruby to say
```
c:\ruby
```
then it'll be
```
c:\ruby\bin\
```
.
Looks like it may be missing from the path.


Question:
With very large amounts of ram these days I was wondering, it is possible to allocate a single chunk of memory that is larger than 4GB? Or would I need to allocate a bunch of smaller chunks and handle switching between them?

Why???
I'm working on processing some openstreetmap xml data and these files are huge. I'm currently streaming them in since I can't load them all in one chunk but I just got curious about the upper limits on malloc or new.

Answer:
it depends on which C compiler you're using, and on what platform (of course) but there's no fundamental reason why you cannot allocate the largest chunk of contiguously available memory - which may be less than you need. And of course you may have to be using a 64-bit system to address than much RAM...
see
Malloc
for history and details
call
HeapMax
in alloc.h to get the largest available block size


Question:
I would like to extract from a general HTML page, all the text (displayed or not).

I would like to remove

any HTML tags

Any javascript

Any CSS styles

Is there a regular expression (one or more) that will achieve that?

Answer:
Using perl syntax for defining the regexes, a start might be:
```
```
!<body.*?>(.*)</body>!smi
```
```
Then applying the following replace to the result of that group:
```
```
!<script.*?</script>!!smi
!<[^>]+/[ \t]*>!!smi
!</?([a-z]+).*?>!!smi
/<!--.*?-->//smi
```
```
This of course won't format things nicely as a text file, but it strip out all the HTML (mostly, there's a few cases where it might not work quite right). A better idea though is to use an XML parser in whatever language you are using to parse the HTML properly and extract the text out of that.


Question:
I wanted to do something like this:

<asp:Label ID="lblMyLabel" onclick="lblMyLabel_Click" runat="server">My Label</asp:Label>

I know that in Javascript I can do:

<span onclick="foo();">My Label</span>

So I'm wondering why I can't do that with a Label object.

Answer:
You can use Attributes to add onclick client side callback.
I didn't know you can do this on span tags, but if it works you can add 'onclick' by
```
lblMyLabel.Attributes.Add("onclick", "foo();");
```
But
```
foo();
```
would need to be a client side javascript function.
```
System.Web.UI.WebControls.Label
```
does NOT have OnClick server event. You could look into using AJAX if you want server callback with example above.
You could also use
```
LinkButton
```
like other say. You can make it not look like a link by using CSS, if it is just that underline you are concerned about.
ASPX:
```
```
<asp:LinkButton ID="LinkButton1" runat="server"
    CssClass="imjusttext" OnClick="LinkButton1_Click">
LinkButton
</asp:LinkButton>
```
```
CSS:
```
```
a.imjusttext{ color: #000000; text-decoration: none; }
a.imjusttext:hover { text-decoration: none; }
```
```


Question:
I have a text file with multiple records. I want to search a name and date, for example if I typed JULIUS CESAR as name then the whole data about JULIUS will be extracted. What if I want only to extract information?

Record number: 1
Date: 08-Oct-08
Time: 23:45:01
Name: JULIUS CESAR
Address: BAGUIO CITY, Philippines
Information:
I lived in Peza Loakan, Bagiou City
A Computer Engineering student
An OJT at TIPI.
23 years old.

Record number: 2
Date: 09-Oct-08
Time: 23:45:01
Name: JOHN Castro
Address: BAGUIO CITY, Philippines
Information:
I lived in Peza Loakan, Bagiou City
A Electronics Comm. Engineering Student at SLU.
An OJT at TIPI.
My Hobby is Programming.

Record number: 3
Date: 08-Oct-08
Time: 23:45:01
Name: CESAR JOSE
Address: BAGUIO CITY, Philippines
Information:
Hi,,
I lived Manila City
A Computer Engineering student
Working at TIPI.

Answer:
If it is one line per entry, you could use a regular expression such as:
```
```
$name = "JULIUS CESAR";
```
```
Then use:
```
```
/$name/i
```
```
to test if each line is about "JULIUS CESAR." Then you simply have to use the following regex to extract the information (once you find the line):
```
```
/Record number: (\d+) Date: (\d+)-(\w+)-(\d+) Time: (\d+):(\d+):(\d+) Name: $name Address: ([\w\s]+), ([\w\s]+?) Information: (.+?)$/i
```
```
$1 = record number
$2-$4 = date
$5-$7 = time
$6 = address
$7 = comments
I would write a code example, but my perl is rusty. I hope this helps :)


Question:
i have a databound GridView in asp.net 2.0 with a row-selection link. When a row is selected, I want to programmatically add a table row below the selected row, in order to nest another grid et al.

I am researching this for a client and for an article, and i think my google-fu is not strong tonight. Any suggestions?

EDIT: I actually had a working solution but Visual Studio was nutted up somehow; closing and re-opening VS and rebuilding everything fixed the problem ;-)

My solution is posted below, please tell me how to make it better if possible. Thanks!

Answer:
I think I figured it out. Here is a solution that seems to work. It could be improved using user controls but this is the gist of it:
```
```
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow &&
        (e.Row.RowState & DataControlRowState.Selected) > 0)
    {
        Table tbl = (Table)e.Row.Parent;
        GridViewRow tr = new GridViewRow(e.Row.RowIndex + 1, -1,
            DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
        TableCell tc = new TableCell();
        tc.ColumnSpan = GridView1.Columns.Count;
        tc.Controls.Add(
            makeChildGrid(Convert.ToInt32(
                ((DataRowView)e.Row.DataItem)["ROW_ID_FIELD"])));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);
    }
}

protected GridView makeChildGrid(int id)
{
    GridView gv = new GridView();
    SqlDataSource sqlds = new SqlDataSource();
    sqlds.DataSourceMode = SqlDataSourceMode.DataSet;
    sqlds.ConnectionString = SqlDataSource1.ConnectionString;
    sqlds.SelectCommand = "SELECT * from MY_TABLE_NAME " +
        "WHERE KEY_FIELD = " + id.ToString();
    DataView dv = (DataView)sqlds.Select(DataSourceSelectArguments.Empty);
    gv.DataSource = dv;
    gv.DataBind();    //not sure this is necessary...?
    return gv;
}
```
```


Question:
I was wondering if you know somewhere where I can find information on how to build a signature file for docuement retrieval.

Do you know if there is some code out there that I can use or look at?

I have to create a signature file in C++ under linux platform.

UPDATE: Sorry, I appreciatte the help but I was refering to signature files not as a way to validate documents but as a way of indexing documents.

http://en.wikipedia.org/wiki/Signature_files

Any help will be greatly appreciated.

Thanks,

Answer:
md5sum
might be what you are looking for. Source code for generating md5 signatures is available if you Google around.
From Wikipedia:
Because almost any change to a file
  will cause its MD5 hash to also
  change, the MD5 hash is commonly used
  to verify the integrity of files
  (i.e., to verify that a file has not
  changed as a result of file transfer,
  disk error, meddling, etc.). The
  md5sum program is installed by default
  in most Unix, Linux, and Unix-like
  operating systems or compatibility
  layers. BSD variants (including Mac OS
  X) have a similar utility called md5.
  Versions for Microsoft Windows do
  exist.


Question:
In VB.NET I often Catch…When:

Try
    …
Catch e As ArgumentNullException When e.ParamName.ToUpper() = "SAMPLES"
    …
End Try

Is there a C# equivalent to Catch…When?

I don't want to resort to using an if statement inside a catch if possible.

Answer:
There's no equivalent to
```
Catch…When
```
in C#. You will really have to resort to an
```
if
```
statement inside your
```
catch
```
, then rethrow if your condition isn't fulfilled:
```
```
try
{
    …
}
catch (ArgumentNullException e)
{
    if ("SAMPLES" == e.ParamName.ToUpper())
    {
        … // handle exception
    }
    else
    {
        throw;  // condition not fulfilled, let someone else handle the exception
    }
}
```
```


Question:
I have an asp.net text form that contains numerous decimal fields that are optional. I want to selectively update the database but not inserting a "0" for fields that do not have data (maintaining the null status).

Typically, I would create multiple functions, each with a different signature to handle this. However, I am inserting the data through a webservice which does not allow a function with the same name to have multiple signatures. I can think of a couple ways to work around this, but none "pragmatically".

Answer:
You could use the
DBNull class
to represent a null value on your web service code.
While you would still have to use a surrogate value (e.g., 0 or -1), and then just evaluate that value to convert it into the
```
DBNull
```
object.


Question:
Is there anyway to build a solution to target 64 bit environment in vs2003? My solution is native c++ not visual c++. Any help would be greatly appreciated.

cheers,

RWendi

Answer:
This page on 2003's lack of 64-bit targeting seems to address your issue:
http://www.toymaker.info/Games/html/64_bit.html
.
The first step was to set up my development environment for 64 bit development. I use Visual Studio 2003 which has little built in support for 64 bit development.
In order to create 64 bit applications you need to install the latest Platform SDK from Microsoft (Microsoft Platform SDK for Windows Server 2003). The SDK, as well as having libraries for 32 bit programming, has 64 bit versions for AMD64 and IA64 (Intel) development.
Getting the correct library and header file paths set up in Visual Studio proved surprisingly difficult. I wanted the choice of developing 32 bit or 64 bit projects. While the platform SDK comes with command files to set up the correct paths they wipe out any other paths. Since T2 uses DirectX I also needed the DirectX paths setting correctly.
Upgrading to a newer edition of Visual Studio looks like the safer, non-hackish solution, if possible.


Question:
Implementing a file upload under html is fairly simple, but I just noticed that there is an 'accept' attribute that can be added to the <input type="file" ...> tag.

Is this attribute useful as a way of limiting file uploads to images, etc? What is the best way to use it?

Alternatively, is there a way to limit file types, preferably in the file dialog, for an html file input tag?

Answer:
Accept attribute was introduced in the
RFC 1867
, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).
Other solutions for advanced file uploading require Flash movies like
SWFUpload
or Java Applets like
JUpload
.


Question: I am using an authentication attribute on some of my actions in an asp.net mvc page to refer people to a login screen if they have not authenticated.  My problem is returning them to the referring page after they have logged in.  I was just keeping track of the referring action and referring controller but that becomes problematic when I also need to keep track of some parameters.  Is there some nifty built in trick about which I don't know?

Answer:
What I did to achieve that result might be overdoing it, and I'd like to see some other methods as well. However, here's my code.
Please note it's using Moq to mock a context... And, I haven't done anything with the querystring yet (my routes don't contain any querystrings).
```
```
var urlReferrer = Request.UrlReferrer;
if (urlReferrer != null)
{
    var url = "~" + Server.UrlDecode(urlReferrer.PathAndQuery);

    // get routecollection
    var routeCollection = new RouteCollection();
    GlobalApplication.RegisterRoutes(routeCollection);

    // mcok context
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    context.Expect(ctx => ctx.Request).Returns(request.Object);

    // mock request
    // TODO: convert querystring to namevaluecollection
    // now it's just stripped
    if (url.IndexOf('?') > 0)
    {
        url = url.Substring(0, url.IndexOf('?'));
    }

    var mock = Mock.Get(context.Object.Request);

    // TODO: insert namevaluecollection of querystring
    mock.Expect(req => req.QueryString).Returns(new NameValueCollection());
    mock.Expect(req => req.AppRelativeCurrentExecutionFilePath).Returns(url);
    mock.Expect(req => req.PathInfo).Returns(string.Empty);

    // get routedata with mocked context
    var routeData = routeCollection.GetRouteData(context.Object);
    var values = routeData.Values;

    return RedirectToAction(routeData.Values["action"].ToString(), values);
}
```
```
As I said, it's maybe a bit overcomplicated :)


Question:
If I have a style defined

.style1
{
   width: 140px;
}

can I reference it from a second style?

.style2
{
   ref: .style1;
}

Or is there a way via javascript/jQuery?

--- Edit

To clarify the problem, I am trying to apply whatever style is defined for a #x and #c to .x and .c without altering the CSS as the CSS is going to have updates that are out of my control.

I used width but really the style would be something more complex with font, border and other style elements being specified.

Specifying multiple class names does work when the style is being applied to a class so I'll mark existing responses as answers, but I need to take the style being applied to an id and also apply it to a class style ... if that makes any sense.

Answer:
There's no way to do it with CSS -- it's an oft-requested feature, but not included in the spec yet. You also can't do it directly with JS, but there's sort of a hacky workaround:
```
```
$('.style2').addClass ('style1');
```
```


Question:
I have a simple iphone app that's based on the CrashLanding sample app.  So basically you tap the title screen and do some stuff... all on the same "view".  I want to add an "options" screen/page/view whatever with a few UISwitches.  What's the easiest way to do this?

Cheers!

Answer:
Dunno if this will help I'm a bit new to objective-c and iPhone api.
Maybe u can do something like this:
Use the interface builder: just type "Interface Builder" on the Spotlight (top right corner) to generate like "myOptions.xib"
And then just implement it: like
```
```
@implementation myOptions

-(void)awakeFromNib
{
...
```
```
You can take a look at the QuartzDemo under the iPhone API to see how to load the interface list of objects. In the previous view controller you just need to add it to the object list.
It will look something like this:
```
```
@implementation previousController
-(void)awakeFromNib
{
    menuList = [[NSMutableArray alloc] init];
    QuartzViewController *controller;

    controller = [[QuartzViewController alloc] initWithTitle:@"Options"];
    controller.quartzViewDelegate = [[[myOptions alloc] init] autorelease];
    [menuList addObject:controller];
    [controller release];
```
```
Hope it helps


Question:
How does TCP/IP report errors when packet delivery fails permanently? All Socket.write() APIs I've seen simply pass bytes to the underlying TCP/IP output buffer and transfer the data asynchronously. How then is TCP/IP supposed to notify the developer if packet delivery fails permanently (i.e. the destination host is no longer reachable)?

Any protocol that requires the sender to wait for confirmation from the remote end will get an error message. But what happens for protocols where a sender doesn't have to read any bytes from the destination? Does TCP/IP just fail silently? Perhaps Socket.close() will return an error? Does the TCP/IP specification say anything about this?

Answer:
The sockets API has no way of informing the writer exactly how many bytes have been received as acknowledged by the peer.  There are no guarantees made by the presence of a successful
```
shutdown
```
or
```
close
```
either.
The TCP/IP specification says nothing about the application interface (which is nearly always the sockets API).
SCTP
is an alternative to TCP which attempts to address these shortcomings, among others.


Question:
Is it a problem if you use the global keyword on variables you don't end up using? Compare:

function foo() {
    global $fu;
    global $bah;
    if (something()) {
        $fu->doSomething();
    } else {
        $bah->doSomething();
    }
}

function bar() {
    if (something()) {
        global $fu;
        $fu->doSomething();
    } else {
        global $bah;
        $bah->doSomething();
    }
}

I'm quite aware that using the second method makes maintaining this code much harder, and that it's generally preferred to put all your globals at the start of functions, so: Ignoring the difference in maintainability and code-styling of the two functions, is there a difference between these two in terms of overhead?

Answer:
If there is, it won't be (humanly) measurable, unless you are literally calling this function millions of times. And even if it was a recursive function with that property, I still wouldn't use your second method for the maintainability aspects you already brought up.
Edit:
For arguments sake, I actually went and benchmarked this, and
```
bar()
```
ended up slower by 0.1s over one million calls. Which means performance wise, you still have a reason to use the cleaner version.


Question: I've installed Oracle XE with APEX, but forgot to write down the URL to access it.  How may I determine the URL?

Answer:
The default is
http://127.0.0.1:8080/apex
If you happen to be on Windows, there will also be an entry in the Start menu (Programs > Oracle XE > Database homepage )


Question:
What is the best way to automatically install an MSI file or installer .exe? We want to do some automated testing from our build system on the installed copy of the product. Our installer has the usual license acceptance screen, install location, etc.

As FryHard pointed out there are two options in particular that seem handy:

"/quiet" - no use interaction

"/passive" - process bar only, unattended mode

Answer:
If you head over to one of your MSI packages in the command prompt and run a:
```
```
Myproduct.MSI /?
```
```
A screen will pop up with all the details of command line parameters that you can pass to the MSI. I am sure that in this way you could install your application via a command prompt and in this way automate it.


Question: Have you refactored from an ActiveRecord to a DataMapper pattern? What conditions prompted the switch? I'm primarily interested in web based applications, but would like to know the challenges that accompany such a move in any environment.

Answer:
I really do like the ActiveRecord pattern for its simplicity.  However, I have been moving away from it for larger web apps.  I find that as an ActiveRecord based project becomes more complex the ActiveRecord objects become large and laden with too much code.
By introducing a Repository pattern (essentially a Data Mapper) the domain model classes become simpler and the data mapping / data access logic is kept separate.
Also, it is quite difficult (impossible?) to mock ActiveRecord objects because of their user of static methods.


Question:
I have been using Ruby for a while now and I find, for bigger projects, it can take up a fair amount of memory.  What are some best practices for reducing memory usage in Ruby?

Please, let each answer have one "best practice" and let the community vote it up.

Answer:
Beware of C extensions which allocate large chunks of memory themselves.
As an example, when you load an image using RMagick, the entire bitmap gets loaded into memory inside the ruby process. This may be 30 meg or so depending on the size of the image.
However
, most of this memory has been allocated by RMagick itself. All ruby knows about is a wrapper object, which is tiny(1).
Ruby only thinks it's holding onto a tiny amount of memory, so it won't bother running the GC. In actual fact it's holding onto 30 meg.
If you loop over a say 10 images, you can run yourself out of memory really fast.
The preferred solution is to manually tell the C library to clean up the memory itself - RMagick has a destroy! method which does this. If your library doesn't however, you may need to forcibly run the GC yourself, even though this is generally discouraged.
(1): Ruby C extensions have callbacks which will get run when the ruby runtime decides to free them, so the memory will eventually be successfully freed at some point, just perhaps not soon enough.


Question: What is the best way to write bytes in the middle of a file using Java?

Answer:
Use
```
RandomAccessFile
```
Tutorial
Javadocs


Question:
I'm making a Stored Procedure that basically concatenates a long string with data from many records.

I want to do:

set @output = @output + 'aaa' + LINEBREAK

How do I specify that line break?

Answer:
```
```
DECLARE @LINEBREAK AS varchar(2)
SET @LINEBREAK = CHAR(13) + CHAR(10)
```
```


Question:
The new awesome Ctrl + . keyboard shortcut to show smart tags has suddenly stopped working, a week or so after I discovered it :(

I am missing it badly, having had to revert back to Ctrl + Alt + F10, which really just isn't the same.

I recently installed F# CTP 1.9.6.2

Has anyone else

installed this CTP and still has Ctrl + .

Lost Ctrl + . without installing F#

Even better, found how to get it back again?

EDIT In attempting John Sheehan recommendation, I have noticed that my available mapping schemes only include Visual C# 2005, should I not have a 2008?

Also the mapped shortcut to this is

OtherContextMenus.FSIConsoleContext.CancelEvaluation

Answer:
From the
documentation
:
Use of NSCalendarDate strongly
  discouraged. It is not deprecated yet,
  however it may be in the next major OS
  release after Mac OS X v10.5. For
  calendrical calculations, you should
  use suitable combinations of
  NSCalendar, NSDate, and
  NSDateComponents, as described in
  Calendars in
Dates and Times
  Programming Topics for Cocoa
.
Following that advice:
```
```
NSDate *today = [NSDate date];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];

NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
components = [gregorian components:unitFlags fromDate:tomorrow];
components.hour = 0;
components.minute = 0;

NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];

[gregorian release];
[components release];
```
```
(I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.)
Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although
```
dateFromComponents:
```
may
tolerate out-of-bounds values, it's not guaranteed to.  You're strongly encouraged not to rely on it.


Question: I need to sort tuples according to the second element of each tuple but apparently usort/1 only works with the first element. So I have to swap the elements, usort them and swap back.Is there an easier way?Also is there a way to sort in descending order (I know sorting and reversing can be done, but just want to know).

Answer:
It shouldn't be too hard to write your own sort function (adapted from a common example):
```
```
qsort([]) -> [];
qsort([Pivot|Tail]) ->
    {PivotFirst, PivotSecond} = Pivot,
    qsort([{FirstElement, SecondElement} || {FirstElement,SecondElement} <- Tail, SecondElement < PivotSecond])
        ++ [Pivot] ++
        qsort([{FirstElement, SecondElement} || {FirstElement,SecondElement} <- Tail, SecondElement >= PivotSecond]).
```
```


Question:
Sometimes I break long conditions in ifs onto several lines. The most obvious way to do this is:

  if (cond1 == 'val1' and cond2 == 'val2' and
      cond3 == 'val3' and cond4 == 'val4'):
      do_something

Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.

For the moment I'm using:

  if (    cond1 == 'val1' and cond2 == 'val2' and
          cond3 == 'val3' and cond4 == 'val4'):
      do_something

But this isn't very pretty. :-)

Can you recommend an alternative way?

Answer:
This doesn't improve so much but...
```
```
allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
                 cond3 == 'val3' and cond4 == 'val4')

if allCondsAreOK:
   do_something
```
```


Question:
I have a text string value that I'd like to persist from one web page to another without using query strings or the session/view states.  I've been trying to get the ASP http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx">HiddenField control to pass information from one web form to a different form.

All the hiddenfield control examples that I've seen is to preserve round trips from the client to the server for the same form.

Is there way for a form to access the ASP controls (and their values) from the previously-rendered form?  Or is the initial form simply disposed of in memory by the time the second form executes it's OnLoad method?

Answer:
I would presume that the Response.Redirect() sends a Location: HTTP header to do a redirect.
As HTTP is stateless, I'd also presume that these variables are inaccessible.
There are however, solutions.
Print a form with hidden fields, and use javascript to submit it
Redirect in the code internally (load up the thing it needs to get to manually)
Store the data in some temporary database table somewhere, and pass along a unique ID
However, from my experience, I can't understand why you might need to do this (other than re-submitting a form after a user authentication - which hopefully you should be able to use method 2 for


Question:
When using py2exe to distribute Python applications with wxPython, some MSVC DLLs are usually needed to make the .exe work on freshly installed machines. In particular, the two most common DLLs are msvcp71.dll and msvcr71.dll

The former can be included in the .exe using this tip. However, the latter is just placed in the dist dir by py2exe and not into the executable, even if I specifically ask to include it.

Any idea how to cause py2exe to include both inside the .exe ?

Answer:
Wouldn't it fail to launch, then? You want
```
msvcr71.dll
```
in the same directory as the exe, so that the library loader will be able to find and link it into the application's memory map.
It's needed for basic operation, so you can't just let
```
py2exe
```
unpack it with the rest of the DLLs.


Question: I've got a bunch of 3D vertex positions & need to generate a convex hull containing them; does anyone know of any QHull bindings for .NET? or native 3D Delaunay triangulation algorithms?

Answer:
A 3d delaunay is tricky, I'm not sure it's even possible to strictly define a delaunay constraint for a 3d surface.
The normal technique if you just want to mesh a surface is to pick a direction and map that onto 2 coordinates and do a 2d delaunay. For a height map it's easy to just use x,y.
Then when you have the nodes forming each triangle you can of course use their 3d coordinates.
The best 2d code is probably
http://www.cs.cmu.edu/~quake/triangle.html
This will also give you the convex hull


Question:
List Comprehension is a very useful code mechanism that is found in several languages, such as Haskell, Python, and Ruby (just to name a few off the top of my head). I'm familiar with the construct.

I find myself working on an Open Office Spreadsheet and I need to do something fairly common: I want to count all of the values in a range of cells that fall between a high and low bounds. I instantly thought that list comprehension would do the trick, but I can't find anything analogous in Open Office. There is a function called "COUNTIF", and it something similar, but not quite what I need.

Is there a construct in Open Office that could be used for list comprehension?

Answer:
CountIf can count values equal to one chosen. Unfortunately it seems that there is no good candidate for such function. Alternatively you can use additional column with If to display 1 or 0 if the value fits in range or not accordingly:
```
```
=If(AND({list_cell}>=MinVal; {list_cell}<=MaxVal); 1; 0)
```
```
Then only thing left is to sum up this additional column.


Question: How do you generate a X.509 public and private key pair and a signing request (CSR file) to be sent to a CA for signing in C#?

Answer:
CountIf can count values equal to one chosen. Unfortunately it seems that there is no good candidate for such function. Alternatively you can use additional column with If to display 1 or 0 if the value fits in range or not accordingly:
```
```
=If(AND({list_cell}>=MinVal; {list_cell}<=MaxVal); 1; 0)
```
```
Then only thing left is to sum up this additional column.


Question:
I'm working on a small project where for the first time I want to use XML as the one and only data source...a file based store suits the need of the project.

When writing the DAL should I have all the get methods static? to aviod and "reading while file open" errors?
Should I use CacheDependency on the file?

Thx

Answer:
I think you were not as clear as you could have been. How big are these files going to be? Would it make sense for the data layer to always keep the XmlDocument in memory and dump to harddisk on every update?
How often are updates going to occur, if at all? How are you going to handle concurrency? Are updates going to be transactional across multiple xml files? How are you going to handle consistency and transactional integrity? If there are no updates, your life will be much simpler.
Methods don't have to be static. The main thing to consider is  that, in the future, you might want to change the DAL provider from XML to DB. To this end, the concrete implementation of the DAL interfaces should talk to an abstract data provider. For you, it would be an Xml provider initially, but you should be able to write a Sql Provider that implements the same interface and easily switch the implementation using dependency injection, config files or what-have-you.
One you have instances of the DAL implementations, you can just use those objects to talk to the data layer.
Hope this is a good start for you.


Question:
How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.

Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc.

Answer:
```
```
int nCol = 127;
string sChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCol = "";
while (nCol >= 26)
{
    int nChar = nCol % 26;
    nCol = (nCol - nChar) / 26;
    // You could do some trick with using nChar as offset from 'A', but I am lazy to do it right now.
    sCol = sChars[nChar] + sCol;
}
sCol = sChars[nCol] + sCol;
```
```
Update
:
Peter
's comment is right. That's what I get for writing code in the browser. :-) My solution was not compiling, it was missing the left-most letter and it was building the string in reverse order - all now fixed.
Bugs aside, the algorithm is basically converting a number from base 10 to base 26.
Update 2
:
Joel Coehoorn
is right - the code above will return AB for 27. If it was real base 26 number, AA would be equal to A and the next number after Z would be BA.
```
```
int nCol = 127;
string sChars = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCol = "";
while (nCol > 26)
{
    int nChar = nCol % 26;
    if (nChar == 0)
        nChar = 26;
    nCol = (nCol - nChar) / 26;
    sCol = sChars[nChar] + sCol;
}
if (nCol != 0)
    sCol = sChars[nCol] + sCol;
```
```


Question: We have a project with many dll files which get loaded when the application starts. The baseaddresses of the dll files do overlap so that the memory image gets relocated. Is there a possibility to assign the baseaddresses automatically or a way to calculate a "good" baseaddress for each dll file?

Answer:
You can use the REBASE utility which ships with the platform SDK and with Visual studio I think to set the base addresses of a whole bunch of DLLS loaded by the appliction
You supply REBASE with a list of the DLLS that make up your program, not including system Dlls, it then performs a dummy load of all the DLLs and assigns them new base addresses.
This can be performed as part of a final build step.
There is a Dr Dobbs article on rebasing
here
and a Microsoft article on rebasing in general
here


Question:
I'm wondering if anyone can recommend a good C++ tree implementation, hopefully one that is
stl compatible if at all possible.

For the record, I've written tree algorithms many times before, and I know it can be fun, but I want to be pragmatic and lazy if at all possible. So an actual link to a working solution is the goal here.

Note: I'm looking for a generic tree, not a balanced tree or a map/set, the structure itself and the connectivity of the tree is important in this case, not only the data within.
So each branch needs to be able to hold arbitrary amounts of data, and each branch should be separately iterateable.

Answer:
I am going to suggest using std::map instead of a tree.
The complexity characteristics of a tree are:
Insert:       O(ln(n))
Removal:  O(ln(n))
Find:         O(ln(n))
These are the same characteristics the std::map guarantees.
Thus as a result most implementations of std::map use a tree (Red-Black Tree) underneath the covers (though technically this is not required).


Question: Let's say I have this model named Product with a field named brand. Suppose the values of brand are stored in the format this_is_a_brand. Can I define a method in the model (or anywhere else) that allows me to modify the value of brand before it is called. For example, if I call @product.brand, I want to get This is a Brand, instead of this_is_a_brand.

Answer:
In your model you can override the method call
```
brand
```
.
```
```
def brand
#code to modify the value that is stored in brand
return modified_brand
end
```
```
This will allow it to be stored as this_is_a_brand.  But, it will be returned as "this is a brand".


Question:
my java application has a loading task which requires two server calls which can be parallelized. So I launch a Thread t1 (doing task1) and a Thread t2 (for task2).
I want then to do a specific task, task3 when both other tasks (1 & 2) are over. Naturally I can't tell which of task1 and task2 will finish first...

Which would be for you the simplest (and safest) way to code this ?

Thank you for your help

Answer:
You can
```
join
```
both
```
t1
```
and
```
t2
```
(in either order), then run task3 after the join.


Question: Has anyone used Mono, the open source .NET implementation on a large or medium sized project? I'm wondering if it's ready for real world, production environments. Is it stable, fast, compatible, ... enough to use? Does it take a lot of effort to port projects to the Mono runtime, or is it really, really compatible enough to just take of and run already written code for Microsoft's runtime?

Answer:
I've used it for a number of internal and commercial projects with great success.  My warnings:
Write lots of unit tests and make sure they ALL pass under Mono -- this will save you a lot of trouble.
Unless you absolutely have to, do NOT use their embedding API.  It's damn easy to use, but it's ungodly easy to garbage collect valid memory or leak all of your memory.
Don't ever, ever, ever even come close to SVN and unless there's no choice, do not compile your own.  Things change so often in SVN that it's highly likely you'll end up implementing something that doesn't work on a release version if your project is significantly large.
Don't try and figure out problems on your own for long, use the IRC channel.  The people there are helpful and you'll save yourself days upon days -- don't make the same mistake I did.
Good luck!
Edit:  The reason I say not to compile your own from source (release or SVN) is that it's easy to configure it differently than release binaries and hide bugs, for instance in the garbage collection.
Edit 2:  Forgot to answer the second part to your question.  In my case, I had no issues with porting code, but I wasn't using any MS-specific libraries (WinForms, ASP.NET, etc).  If you're only using System.* stuff, you'll be fine;  beyond that, you may run into issues.  Mono 2.0 is quite solid, though.


Question:
When I add a breakpoint and hit F5 to run in the debugger (I am using my debug build), a dialog pops up telling my my web.config file does not have debug=true in it (which is does) and I get 2 choices a) run without the debugger or b) let visual studio update my web.config file. If I choose b) the web.config is updated badly and nothing will work. If I choose a) then the site appears and I can test it out, but no debugging.

I am an experienced developer, but I have never used visual studio and asp.net for web development before, so I am feeling rather frustrated by all the walls it is putting up to prevent me working.

So far I have not been able to use the debugger. Is there something totally obvious that I am missing? What would you check if it was happening to you?

Answer:
Open web.config manually and make sure the following line is in there
```
```
<compilation defaultLanguage="c#" debug="true" />
```
```
Now you should be able to debug from VS. If this does not work I suggest that you recreate the project.
EDIT: perhaps from what you say it could be that web.config is screwed up, e.g.contains invalid xml, no closing tag for some element etc.


Question: How do I start a process, such as launching a URL when the user clicks a button?

Answer:
You can use the
System.Diagnostics.Process.Start
method to start a process. You can even pass a URL as a string and it'll kick off the default browser.


Question: i need to get the color at a particular coordinate from a texture. There are 2 ways  i can do this, by getting and looking at the raw png data, or by sampling my generated opengl texture. Is it possible to sample an opengl texture to get the color (RGBA) at a given UV or XY coord? If so, how?

Answer:
The most efficient way I've found to do it is to access the texture data (you should have our PNG decoded to make into a texture anyway) and interpolate between the texels yourself.  Assuming your texcoords are [0,1], multiply texwidth
u and texheight
v and then use that to find the position on the texture.  If they're whole numbers, just use the pixel directly, otherwise use the int parts to find the bordering pixels and interpolate between them based on the fractional parts.
Here's some HLSL-like psuedocode for it.  Should be fairly clear:
```
```
float3 sample(float2 coord, texture tex) {
    float x = tex.w * coord.x; // Get X coord in texture
    int ix = (int) x; // Get X coord as whole number
    float y = tex.h * coord.y;
    int iy = (int) y;

    float3 x1 = getTexel(ix, iy); // Get top-left pixel
    float3 x2 = getTexel(ix+1, iy); // Get top-right pixel
    float3 y1 = getTexel(ix, iy+1); // Get bottom-left pixel
    float3 y2 = getTexel(ix+1, iy+1); // Get bottom-right pixel

    float3 top = interpolate(x1, x2, frac(x)); // Interpolate between top two pixels based on the fractional part of the X coord
    float3 bottom = interpolate(y1, y2, frac(x)); // Interpolate between bottom two pixels

    return interpolate(top, bottom, frac(y)); // Interpolate between top and bottom based on fractional Y coord
}
```
```


Question:
Often when making changes to a VS2008 ASP.net project we get a message like:

BC30560: 'mymodule_ascx' is ambiguous in the namespace 'ASP'.

This goes away after a recompile or sometimes just waiting 10 seconds and refreshing the page.

Any way to get rid of it?

Answer:
I used to have this problem sometimes too.  If I remember correctly it was caused by something like the following:
```
```
<%@ Page Inherits="_Default" %>
```
```
or perhaps
```
```
<%@ Page ClassName="_Default" %>
```
```
Or something like that.  I'm not 100% sure which attribute it was (it's been a while).
But look look for something like _Default in your Page directive and replace them with actual class names in all of your files.  For some reason, ASP.Net doesn't always interpret the _Default correctly, yielding temporary ambiguous references.


Question:
Is there an exact overview what has changed in the SP1 for .NET 3.5? New classes, methods, etc.

For example, I've noticed there is a new WaitOne(TimeSpan) and WaitOne(int) overloads in the WaitHandle class.

Answer: What's New in the .NET Framework Version 3.5 SP1 - MSDN


Question:
I've got a Java client that needs to access a remote database. It is the goal to hide database credentials from the user and not hardcode any credentials within the code. Therefore, the database access will probably have to be on the server side.

I'm restricted to use Ibatis as a data abstraction framework. Apart from that I have JBoss running on the webserver, allowing me to use data sources.

How would you design the remote database access and data serialization/deserialization. would you prefer web services of some kind of data stream over a socket? How would you realize either of both?

Answer:
So you want users to be able to access the database without knowing the credentials? Your only option is server-side database access. Unfortunately there is no way of hiding the username and password in Java -- if you put it into a properties file and encrypt it, a determined attacker could still attach a debugger and see what values are being held in your code.
Also, unless you're connecting to the DB over a secure connection someone could run a packet sniffer such as tcpdump and get the credentials there.
You say that you're running a JBoss server, what might be best is to set up remote EJBs so that your client application doesn't access the database directly - it has to go via your EJB methods. (It doesn't have to be EJB, by the way, you could do something such as web services if you prefer).
The point is, your server talks to the databas directly, and your client's only access is via a limited set of interfaces you define on the server.


Question:
UPDATED: on win2k it seems it works OK. Sorry for the confusion.

MS Windows Vista internal ftp client has a strange behavior.
When redirecting its output and error to a file, the errors do not show up there:

ftp -n -s:commands.txt host >output.log 2>&1

When running it from Task Scheduler inside a batch file, I don't get any error messages if connection refused. Even if echo is on or with the -d option.
Do you have a workaround for it?

Answer:
So you want users to be able to access the database without knowing the credentials? Your only option is server-side database access. Unfortunately there is no way of hiding the username and password in Java -- if you put it into a properties file and encrypt it, a determined attacker could still attach a debugger and see what values are being held in your code.
Also, unless you're connecting to the DB over a secure connection someone could run a packet sniffer such as tcpdump and get the credentials there.
You say that you're running a JBoss server, what might be best is to set up remote EJBs so that your client application doesn't access the database directly - it has to go via your EJB methods. (It doesn't have to be EJB, by the way, you could do something such as web services if you prefer).
The point is, your server talks to the databas directly, and your client's only access is via a limited set of interfaces you define on the server.


Question:
I once had a MySQL database table containing 25 million records, which made even a simple COUNT(*) query takes minute to execute. I ended up making partitions, separating them into a couple tables. What i'm asking is, is there any pattern or design techniques to handle this kind of problem (huge number of records)? Is MSSQL or Oracle better in handling lots of records?

P.S
the COUNT(*) problem stated above is just an example case, in reality the app does crud functionality and some aggregate query (for reporting), but nothing really complicated. It's just that it takes quite a while (minutes) to execute some these queries because of the table volume

Answer:
Many performance issues around large tables relate to indexing problems, or lack of indexing all together. I'd definitely make sure you are familiar with indexing techniques and the specifics of the database you plan to use.
With regards to your slow count(*) on the huge table, i would assume you were using the InnoDB table type in MySQL. I have some tables with over 100 million records using MyISAM under MySQL and the count(*) is very quick.
With regards to MySQL in particular, there are even slight indexing differences between InnoDB and MyISAM tables which are the two most commonly used table types. It's worth understanding the pros and cons of each and how to use them.


Question:
I'm trying to localize my aspx pages. I'm done with content localization using L10n features provided by .net f/w, like resource files. But I'm finding it difficult to set local data in page titles.

Most of the browsers, including IE and FF, shows content on window title with some boxes (FF will show properly localized text in tab, IE doesn't even do that). But its working fine in safari (on windows).

When I did a research it seems like this issue exits ONLY for some of the languages. For example, the Hindi version of BBC shows the title with boxes. But Arabic version shows the localized text in title.

Can somebody please tell me why this is happening? How we can solve this issue?

Note: My site is using Asp.net 2.0 / IIS

Answer:
I suspect this is a typeface issue. The browser title bar and other window ornaments are usually rendered by your OS, not by the browser itself, so if you've configured Windows to use a typeface that doesn't support the additional character glyphs required for Hindi, Arabic, etc., then you'll get the boxes instead. Within your actual pages, you're probably using a typeface which does include support for all these extended characters, which is why you're only seeing the problem on the window titles.
Safari uses its own rendering engine for everything including the window chrome, which is why it doesn't look like a normal Windows app, and why your localized titles are working.
You might want to try changing your Windows "Active Title Bar" font (under Display Properties, Appearance, Advanced) to something like Arial which covers the full set of Unicode characters, and see if this resolves the problem?


Question: What's the difference between absolute path & relative path when using any web server or Tomcat?

Answer:
Absolute paths start with / and refer to a location from the root of the current site (or virtual host).
Relative paths do not start with / and refer to a location from the actual location of the document the reference is made.
Examples, assuming root is
http://foo.com/site/
Absolute path, no matter where we are on the site
```
```
/foo.html
```
```
will refer to
http://foo.com/site/foo.html
Relative path, assuming the containing link is located in
http://foo.com/site/part1/bar.html
```
```
../part2/quux.html
```
```
will refer to
http://foo.com/site/part2/quux.html
or
```
```
part2/blue.html
```
```
will refer to
http://foo.com/site/part1/part2/blue.html


Question:
I have created a Dynamic Web Project in my Eclipse workspace. It is also a Maven project, and under SVN control. But in "Open Resource" (Ctrl+Alt+R) no file from this project appears, unless I check from the window's options (top right drop-down) "Show Derived Resources".

I have checked on some of the project's folders and they are not marked as "Derived".

I have two more (plain Java) projects in the workspace, and all the files from them are visible in "Open Resource".

Do you know what might be wrong with either Eclipse, the Maven plugin or Subclipse (the SVN plugin)?

Answer:
I experienced a similar issue in Eclipse (Ganymede), when using the Maven and Subclipse plugins. I have not determined which plugin caused this problem, but I suspect that it is related to my pom.xml containing nested modules (ie. a
```
<modules><module>main-module</module><module>integration-test</module>
```
). These appear in Eclipse as nested folders with their own pom.xml files (I did not use the Multiple Projects plugin although I have installed it).
I assume that one of the plug-ins has incorrectly set the derived flag on these folders when I checked out the project by SVN and then updated the MVN dependencies and project settings.
When I right click->properties on the top-level nested module directories I can see the Derived flag is checked. By unchecking the derive flag on the module directories (and checking the derive flag on the target directories within each sub-module instead), it fixed the Open Resource functionality.
As the derived flag is inherited from directories, you may need to check all of your directories in the hierarchy to find the 'culprit'.
If it helps the plug-in authors, my top level module directories contain a hyphen '-' in their names. Maybe that is throwing out one of the plugins.


Question:
According to the feedparser documentation, I can turn an RSS feed into a parsed object like this:

import feedparser
d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml')

but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML:

print d.toXML()

but there doesn't seem to be anything in feedparser for going in that direction.  Am I going to have to loop through d's various elements, or is there a quicker way?

Answer:
```
```
from xml.dom import minidom

doc= minidom.parse('./your/file.xml')
print doc.toxml()
```
```
The only problem is that it do not download feeds from the internet.


Question:
After discovering Clojure I have spent the last few days immersed in it.

What project types lend themselves to Java over Clojure, vice versa, and in combination?

What are examples of programs which you would have never attempted before Clojure?

Answer:
Clojure lends itself well to
concurrent programming
.  It provides such wonderful tools for dealing with threading as Software Transactional Memory and mutable references.
As a demo for the Western Mass Developer's Group, Rich Hickey made an ant colony simulation in which each ant was its own thread and all of the variables were immutable. Even with a very large number of threads things worked great. This is not only because Rich is an amazing programmer, it's also because he didn't have to worry about locking while writing his code. You can check out his
presentation on the ant colony here
.


Question:
What are the implications of including a set of visual components released under a Mozilla Public License in a commercial application.

Do I have any obligations?

Answer:
I've found pretty good analysis on MPL (and others) by Frank Hecker here:
http://hecker.org/writings/setting-up-shop
(search for "Mozilla Public License")
This pretty much sums it up:
For MozPL-ed source code considered as
  a set of source files, modifications
  of the original source files are
  considered to also fall under the
  MozPL, as are new source files
  incorporating extracts from the
  original source files. Such modified
  or new files are required to be
  licensed under the same terms as the
  original files, and in particular must
  be made freely and publicly available
  in source form.
...
Thus an open-source product initially
  released under the MozPL may be
  extended with proprietary code to
  create new proprietary products, as
  long as the proprietary code is
  separate (i.e., in separate files) and
  interacts with the open-source code
  using a defined API.
But as usual, read it carefully and consult your lawyers.


Question:
Does anyone know of a nice (and preferably free) way to integrate Prolog and C#?

Im looking to create a Prolog dll or similar to call from my managed code, and retrieve an answer once all the processing has been complete. Im looking for it to be predominantly one sided (c# calls Prolog).

I have seen this question which talks about Prologs real world usage but I was wondering if anyone had either any experience with c# & Prolog? or a nice tutorial/article?

Answer:
Perhaps
P#
will be useful for you


Question:
I want to disable "Alert window" that I get from login page of one HTTPS site with "untrusted certificate".

ServicePointManager is used for WebRequest/WebResponse:

> public static bool
> ValidateServerCertificate(object
> sender, X509Certificate certificate,
> X509Chain chain, SslPolicyErrors
> sslPolicyErrors) {
>     return true; }
>
> ServicePointManager.ServerCertificateValidationCallback
> = new RemoteCertificateValidationCallback(ValidateServerCertificate);

but how can I use it with Webbrowser control?

Answer:
The ServicePointManager is for managed code; WebBrowser is a wrapper around shdocvw, so will almost certainly have a very different programming model.
if
you can automate this (and I'm not sure that you can), I would expect to have to reference the COM version to get the full API (see: AxWebBrowser). WebBrowser only exposes a .NET-friendly subset of the full functionality - enough to get most common jobs done.
One other option might be to get the data yourself (WebClient / WebRequest / etc), and simply push that html into the WebBrowser - but this will mess up external links etc.


Question: Are there any free tools for scripting MSSQL table data?  I'll gladly write one, but am hoping it's been done, and the app matured a bit before/

Answer:
A quick google and hop pointed me to a Stored proc that should be able to help you. Look at
My code library
more specifically the file
generate_inserts.txt
to see if it can help you.
Not really a tool, but the start of one! :)


Question:
When working on a big C/C++ project, do you have some specific rules regarding the #include within source or header files?

For instance, we can imagine to follow one of these two excessive rules:

#include are forbidden in .h files; it is up to each .c file to include all the headers it needs

Each .h file should include all its dependancies, i.e. it should be able to compile alone without any error.

I suppose there is trade-off in between for any project, but what is yours? Do you have more specific rules? Or any link that argues for any of the solutions?

Answer:
The first rule will fail as soon as there are circular dependencies. So it cannot be applied strictly.
(This can still be made to work but this shifts a whole lot of work from the programmer to the consumer of these libraries which is obviously wrong.)
I'm all in favour of rule 2 (although it might be good to include “forward declaration headers” instead of the real deal, as in
```
<iosfwd>
```
because this reduces compile time). Generally, I believe it's a kind of self-documentation if a header file “declares” what dependencies it has – and what better way to do this than to include the required files?
EDIT:
In the comments, I've been challenged that circular dependencies between headers are a sign of bad design and should be avoided.
That's not correct. In fact, circular dependencies
between classes
may be unavoidable and aren't a sign of bad design at all. Examples are abundant, let me just mention the Observer pattern which has a circular reference between the observer and the subject.
To resolve the circularity between classes, you have to employ forward declaration because the order of declaration matters in C++. Now, it is completely acceptable to handle this forward declaration in a circular manner to reduce the number of overall files and to centralize code. Admittedly, the following case doesn't merit from this scenario because there's only a single forward declaration. However, I've worked on a library where this has been much more.
```
```
// observer.hpp

class Observer; // Forward declaration.

#ifndef MYLIB_OBSERVER_HPP
#define MYLIB_OBSERVER_HPP

#include "subject.hpp"

struct Observer {
    virtual ~Observer() = 0;
    virtual void Update(Subject* subject) = 0;
};

#endif
```
```
```
```
// subject.hpp
#include <list>

struct Subject; // Forward declaration.

#ifndef MYLIB_SUBJECT_HPP
#define MYLIB_SUBJECT_HPP

#include "observer.hpp"

struct Subject {
    virtual ~Subject() = 0;
    void Attach(Observer* observer);
    void Detach(Observer* observer);
    void Notify();

private:
    std::list<Observer*> m_Observers;
};

#endif
```
```


Question:
An advantage by using Windows Authentication is that I do not need to provide a username and password to log into the server as the user currently logged into Windows. But in a specific case I would like to log into the SQL Server as another user, using the same Windows Authenticated ODBC connection.

So, the question: Is it possible to log into an SQL Server using Windows Authentication, but not as the user currently logged into Windows (without a dialog asking for username and password)?

Answer:
The simple answer to your question is no, without a dialog being presented, it's not possible to login to SQL Server using another Windows account.
The slightly more complex answer is; You can login as another user (WITH a dialog being presented) by right-clicking the Query Analyser icon and choosing "Run As" (Might require a CTRL or SHIFT key held down to make RUN AS appear.
There's also the RUNAS command line executable which you could look at, so you could create a shortcut that contains the RUNAS command, the credentials and the path to Query Analyser. That would eliminate being asked for a username or password on execution.


Question: In certain areas in my application I need data from several tables in the database (I have  an application, the application has many attributes, each attribute has several definitions, and each definition has a value). I need the data from all these tables for an application. Should I use a view (one that would be rather large) or subqueries for selecting the records? In the case of subqueries is the optimizer able to work efficiently? I'm also interested if caching will work for subqueries.

Answer:
This is an 'It depends' question.  A view might help to make the code more maintainable but complex selection predicates might confuse the optimiser.
Another option is a stored procedure that returns a record set.  If you reuse a subquery several times you may get some mileage from splitting up the query, selecting the subquery into a temporary table and combining the parts in a later step.
Without a more specific description of the problem it's hard to really give a meaningful answer.


Question: I have a webpage (say www.example.com/a.asp) .. I am having an iframe in this page which loads a page from a different website (www.example.net/b.asp)... This b.asp asks few questions to the user and the results are posted to c.asp in my website (www.example.com/c.asp). This page (www.example.com/c.asp) gets loaded in the iframe. Is there any way so that I can reload the entire webpage and redirect to another wbpage when I get the response from www.example.net. Sorry if this question is confusing, Any queries please let me know.

Answer:
This is an 'It depends' question.  A view might help to make the code more maintainable but complex selection predicates might confuse the optimiser.
Another option is a stored procedure that returns a record set.  If you reuse a subquery several times you may get some mileage from splitting up the query, selecting the subquery into a temporary table and combining the parts in a later step.
Without a more specific description of the problem it's hard to really give a meaningful answer.


Question: How can I prevent a user from resizing GridViewColumns withing a ListView control?

Answer:
i found a solution and probably it will help someone else someday ;)
you have to override the GridViewColumnHeader's ControlTemplate (default template is
here
) and remove the
PART_HeaderGripper
from the template in order to prevent resizing of your columns.
there is another solution that comes up with subclassing GridViewColumn described
here
. for representation purposes i prefer xaml only solutions though


Question: I want to use a template engine in a struts application and would like to know if using TILES can be recommended instead of FREEMARKER or VELOCITY.

Answer:
I've used tiles before on a project. It was good for templating, however it can't really be compared to velocity or freemarker: with Tiles you use normal JSPs and are limited to the JSP tags youv'e got.
Velocity (and probably Freemarker although I haven't used it before) provide their own tags or expression language, so you can do thinks like:
```
Hello ${name}
```
Which you can't do in plain JSPs. [updated due to comment: in JSP 2.0, EL is included so you can do things like that. However, I think Velocity or Freemarker are more powerful in terms of what you can do with it.]
If you've got a layout with lots of different components (i.e. header, sidebar, etc) and you want to define various different templates, tiles isn't a bad choice. (Although be warned - it can be quite a lot of XML!)
But if you need something more "advanced" than plain JSPs Velocity or Freemarker might be the way to go.


Question:
the function addresses (Rva+Base) in my MAP-file from visual studio doesn't match the one I see in the debugger (or when I manually inspect my stack frame).

What could be causing this?

/A.B.

Answer:
Is the problem in an executable or a DLL?
If it's a DLL what is its preferred load address? If this clashes with any other DLL then it will be rebased by the loader, and this can lead to what you're seeing.
As part of your build process, you should ensure that all your DLLs are rebased (there's a tool to do this) so that their address spaces don't clash (this frees up some page file space as well as improving load time).


Question: When accessing an object in a DataTable retrieved from a database, are there any reasons not to cast the object into your desired type, or are there reasons to use convert? I know the rule is cast when we know what data type we're working with, and convert when attempting to change the data type to something it isn't. Presuming we know what data type is stored in a column, cast seems appropriate, but are there any DB type issues that mean we can't rely on this?

Answer:
I would always cast, for the reasons you state.  The gotchas I'm aware of that you need to handle are:
You obviously need to be able to handle DBNulls (e.g. by testing with Convert.IsDBNull)
In the case of ExecuteScalar I believe you need to check for null as well as DBNull.
SQL Servers @@IDENTITY and SCOPE_IDENTITY functions return numeric (decimal) even for columns that are declared as INT.  In this case you can cast twice "(int)(decimal)value" or handle it in the T-SQL code, e.g.:
.
INSERT INTO MyTable ...
SELECT AutoIdColumn FROM MyTable WHERE AutoIdColumn = SCOPE_IDENTITY()
or
```
```
INSERT INTO MyTable ...
SELECT CAST(SCOPE_IDENTITY() AS INT)
```
```


Question:
I want to put "random" output from my result set (about 1.5 mil rows) in a file in a sorted manner. I know i can use sort by command in my query but that command is "expensive".
Can you tell me is there any algorithm for writing result set rows in a file so the content would be sorted in the end and can i gain in performance with this?
I'm using java 1.6, and query has multiple joins.

Answer:
Define an index for the sort criteria in your table, then you can use the order by clause without problems and write the file as it comes from the resultset.
If your query has multiple joins, create the proper indexes for the joins and for the sort criteria. You can sort the data on your program but you'd be wasting time. That time will  be a lot more valuable when employed learning how to properly tune/use your database rather than reinventing sorting algorithms already present in the database engine.
Grab your database's profiler and check the query's execution plan.


Question: XP-specific answers preferred, but others are welcome too.

Answer:
From
```
%windir%\System32\Shell32.dll
```


Question:
Can anyone give me an example of what the Artifact paths setting defined for a build configuration could look like if I want to create two artifacts dist and source where I am using the sln 2008 build runner and building my projects using the default bin/Release?

**/Source/Code/MyProject/bin/Release/*.* => dist
**/*.* => source

I get two artifact roots dist and source but under dist I get the whole directory structure (Source/Code/MyProject/bin/Release) which I don't want and under source I get the whole thing along with obj and bin/Release which I do not want.

Can you give some advice on how to do this correctly?

Do I need to change the target location for all the projects I am building to be able to get this thing to work?

Answer:
So you'll just need:
```
```
Source\Code\MyProject\bin\Release\* => dist
Source\**\* => source
```
```
This will put all the files in release into a artifact folder called dist and everything in Source into a artifact folder called source.
If you have subfolders in Release try:
```
```
Source\Code\MyProject\bin\Release\**\* => dist
```
```


Question:
How do I setup a Python environment on windows computer so I can start writing and running Python scripts, is there an install bundle?  Also which database should i use?

I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?

Answer:
Download the Python 2.6 Windows installer from
python.org
(
direct link
). If you're just learning, use the included SQLite library so you don't have to fiddle with database servers.
Most web development frameworks (Django, Turbogears, etc) come with a built-in webserver command that runs on the local computer without Apache.