Question:
I want to set a background image for a div, in a way that it is in the upper RIGHT of the div, but with a fixed 10px distance from top and right.

Here is how I would do that if wanted it in the upper LEFT of the div:

background: url(images/img06.gif) no-repeat 10px 10px;

Is there anyway to achieve the same result, but showing the background on the upper RIGHT?

Answer:
I don't know if it is possible in pure css, so you can try
```
```
background: url(images/img06.gif) no-repeat top right;
```
```
and modify your image to incorporate a 10px border on the top and right in a transparent color


Question:
Eg. can I write something like this code:

public void InactiveCustomers(IEnumerable<Guid> customerIDs)
{
    //...
    myAdoCommand.CommandText =
        "UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)";
    myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs;
    //...
}

The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string.

Answer:
Nope. Parameters are like SQL values in obeying
first normal form
, basically, there can only be one...
As you are probably aware, generating SQL strings is risky business: you leave yourself open to an
SQL injection attack
. As long as you're dealing with bona fide GUID's you should be fine, but otherwise you need to be sure to cleanse your input.


Question:
Possible Duplicate:

  JavaScript: var functionName = function() {} vs function functionName() {}

What's the difference between:

function sum(x, y) {
  return x+y;
}

// and

var sum = function (x, y) {
    return x+y;
}

Why is one used over the other?

Answer:
The first one is a named function statement, the second one assigns an anonymous function expression to a variable.
The function statement is added to its scope immediately - you don't need to run it before being able to call it, so this works:
```
```
var y = sum(1, 2);

function sum(x, y) {
   return x + y;
}
```
```
But the function expression is only assigned to the variable when the code is executed, so this doesn't work:
```
```
// Error here because the function hasn't been assigned to sum yet.
var y = sum(1, 2);

var sum = function(x, y) {
   return x + y;
}
```
```
An advantage of the expression form is that you can use it to assign different functions to the expression at different points - so you can change the function, or use a different one under different conditions (such as depending on the browser being used).
An advantage of a named function statement, is that debuggers will be able to display the name. Although, you can name function expressions:
```
```
var sum = function sum(x, y) {
   return x + y;
}
```
```
But this can be confusing since the two names are actually in different scopes and refer to different things.


Question:
How can I horizontally center a <div> within another <div> using CSS?

<div id="outer">
  <div id="inner">Foo foo</div>
</div>

Answer:
You can apply this CSS to the inner
```
<div>
```
:
```
```
#inner {
  width: 50%;
  margin: 0 auto;
}
```
```
Of course, you don't have to set the
```
width
```
to
```
50%
```
. Any width less than the containing
```
<div>
```
will work. The
```
margin: 0 auto
```
is what does the actual centering.
If you are targeting
Internet Explorer 8
(and later), it might be better to have this instead:
```
```
#inner {
  display: table;
  margin: 0 auto;
}
```
```
It will make the inner element center horizontally and it works without setting a specific
```
width
```
.
Working example here:
```
```
#inner {
  display: table;
  margin: 0 auto;
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%
}
```
```
```
```

Foo foo

```
```
EDIT
With
```
flexbox
```
it is very easy to style the div horizontally and vertically centered.
```
```
#inner {
  border: 0.05em solid black;
}

#outer {
  border: 0.05em solid red;
  width:100%;
  display: flex;
  justify-content: center;
}
```
```
```
```

Foo foo

```
```
To align the div vertically centered, use the property
```
align-items: center
```
.


Question:
I'm fairly new to the world of versioning but would like to introduce Subversion into our small development team as we're finding that more and more we are working on the same projects/files. We primarily code in PHP on a LAMP environment (Red Hat Enterprise).

What I'm looking for are some starting points to get me up and running such as installation/configuration guides for Red Hat. I use Dreamweaver CS3 (I see that Subversion functions will be introduced in CS4) so would be willing to look at other PHP IDEs with Subversion integration, do you have any preferences? I'm open to suggestions.

Answer:
It depends on what version of RHEL you are running.  Setting up Subversion in general is very easy you just have to install the binaries and run svnserve or adapt the Apache configuration.
Get it:
http://subversion.tigris.org/getting.html
Install it
```
svnadmin create --fs-type=fsfs
```
After that you have a repository which you can serve via apache or svnserve.  I can recommend Apache because it scales better, is easier to maintain and allows you to access the repository via DAV.
Example configurations are here:
http://svnbook.red-bean.com/en/1.0/ch06s04.html


Question: What is the smartest way to design a math parser? What I mean is a function that takes a math string (like: "2 + 3 / 2 + (2 * 5)") and returns the calculated value? I did write one in VB6 ages ago but it ended up being way to bloated and not very portable (or smart for that matter...). General ideas, psuedo code or real code is appreciated.

Answer:
A pretty good approach would involve two steps. The first step involves
converting the expression from infix to postfix
(e.g. via
Dijkstra's shunting yard
) notation. Once that's done, it's pretty trivial to write a
postfix evaluator
.


Question: I'm a bit lost here and I can't find much documentation.

Answer:
.NET workflows or ones created using SharePoint designer?
I've only got latter experience and they aren't really easy to debug, you really just have to do them 1 step at a time and test up to each step.
You can view the workflow state as well in SharePoint when you go to the List Settings (sorry I don't have a WSS machine to look at currently).


Question:
I'm using ReportViewer WinForms, and since it is no easy way to create an coversheet, then I wonder, is it possible to render two reports and have them concatenated?, so they appear as one report?

If I was to print only, then I could execute two reports after each other, but since the user want to see the report before printing (you know, no environment waste here) then they have to appear in the same viewer.

OR, is there other ways of creating coversheets?
Today I use an subreport, but there are some issues with margins etc. which is not easy to fix.

To clarify, we are talking about
  ReportViewer using RDLC files, no
  Crystal Reports involved.

Answer:
I've created a report that sounds like what you are attempting to do...first to clarify, I'm going to guess your using Crystal Reports within VS2005/2008.
If that's the case, all you need to do in the main report is create an additional section after your section that contains the "Cover Sheet" layout/data. In the section expert for the "Cover Sheet" section (in layout view, right click on section header bar, pick section expert in pop up menu..), check off the "New Page After" option.
Edit: After your update, I see you are using RDLC reports, and from my limited exposure to those, I can't recall an easy way to get to where you want to be. Though I'm pretty sure you may be able to pass multiple reports to the same report viewer in code.


Question:
I need to present the user with a matrix of which one column is editable. What is the most appropriate control to use?

I can't use a ListView because you can only edit the first column (the label) and that's no good to me.

Is the DataGridView the way to go, or are there third party alternative components that do a better job?

Answer: DataGridView is the best choice as it is free and comes with .NET WinForms 2.0. You can define editable columns or read-only. Plus you can customize the appearance if required.


Question:
One of my DBs have grown closer to permitted size.

Inorder to find out the table containing the max data, i used the following query:

exec sp_MSforeachtable @command1="print '?' exec sp_spaceused '?'"

It returned the culprit table comprising the max data.

As a next step, i want to cleanup the rows based on the size. For this, i would like to order the rows based on size.

How to achieve this using a query? Are there any tools to do this?

Answer:
An easier approach for all table sizes is to use the stored procedure at
this site
.
You could alter the select statement of that stored procedure to:
```
```
SELECT *
FROM #TempTable
Order by dataSize desc
```
```
to have it ordered by size.
How do you want to cleanup? Cleanup the biggest row of a specific table? Not sure I understand the question.
EDIT
(response to comment)
Assuming your eventlog has the same layout as mine (DNN eventlog):
```
```
SELECT     LEN(CONVERT(nvarchar(MAX), LogProperties)) AS length
FROM         EventLog
ORDER BY length DESC
```
```


Question:
Consider these classes.

class Base
{
   ...
};

class Derived : public Base
{
   ...
};

this function

void BaseFoo( std::vector<Base*>vec )
{
    ...
}

And finally my vector

std::vector<Derived*>derived;

I want to pass derived to function BaseFoo, but the compiler doesn't let me. How do I solve this, without copying the whole vector to a std::vector<Base*>?

Answer:
one option is to use a template
```
```
template<typename T>
void BaseFoo( const std::vector<T*>& vec)
{
 ...
}
```
```
The drawback is that the implementation has to be in the header and you will get a little code bloat. You will wind up with different functions being instantiated for each type, but the code stays the same. Depending on the use case it's a quick and dirty solution.
Edit, I should note the reason we need a template here is because we are trying to write the same code for unrelated types as noted by several other posters. Templates allow you do solve these exact problems. I also updated it to use a const reference. You should also pass "heavy" objects like a vector by const reference when you don't need a copy, which is basically always.


Question: One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type.  Is this implemented internally as a hash table?  If not, what is it?

Answer:
Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters,
here
.
That's why you can't use something 'not hashable' as a dict key, like a list:
```
```
>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
```
```
You can
read more about hash tables
or
check how it has been implemented in python
and
why it is implemented that way
.


Question: How should I determine what to use for a listening socket's backlog parameter?  Is it a problem to simply specify a very large number?

Answer:
From the
docs
:
A value for the backlog of SOMAXCONN is a special constant that instructs the underlying service provider responsible for socket s to set the length of the queue of pending connections to a maximum reasonable value.


Question:
I'm firing off a Java application from inside of a C# .NET console application. It works fine for the case where the Java application doesn't care what the "default" directory is, but fails for a Java application that only searches the current directory for support files.

Is there a process parameter that can be set to specify the default directory that a process is started in?

Answer:
Yes!
ProcessStartInfo Has a property called
WorkingDirectory
, just use:
```
```
...
using System.Diagnostics;
...

var startInfo = new ProcessStartInfo();

  startInfo.WorkingDirectory = // working directory
  // set additional properties

Process proc = Process.Start(startInfo);
```
```


Question:
I'm writing a photo gallery webapp for a friend's wedding and they want a photo gallery for guests to submit the digital photos they take on the day.

After evaluating all the options, I've decided the easiest thing for users would be to let them use a familiar interface (their email) and just have them send in the pictures as attachments.

I've created an mailbox but now I need to connect and retrieve these attachments for automated processing for adding to the gallery system. But how? Are there any tutorials or prefab classes you've seen for doing this?

Answer:
I think you want a MIME message parser.
I've used
this one
before and it seems to work fine, although I haven't tested it on really big attachments (i.e. 2-3MB files you might get from digital cameras).
Have you already got a system for reading POP3 / IMAP mailboxes? There is
another class
on the same site which also works on POP3 (I believe there is also an IMAP one) - however if you will be downloading a fair volume maybe you'll want to investigate a few C-based solutions as I believe that one is pure PHP.


Question:
I have some NSViews that I'm putting in one of two layouts depending on the size of my window.

I'm adjusting the layout when the relevant superview receives the resizeSubviewsWithOldSize method.

This works, but I'd like to animate the change.  So naturally I tried calling the animator proxy when I set the new frames, but the animation won't run while the user is still dragging.  If I release the mouse before the animation is scheduled to be done I can see the tail end of the animation, but nothing until then.   I tried making sure kCATransactionDisableActions was set to NO, but that didn't help.

Is it possible to start a new animation and actually have it run during the resize?

Answer:
This really isn't an answer, but I would advise against animating anything while dragging to resize a window. The screen is already animating (from the window moving) - further animations are likely going to be visually confusing and extraneous.
CoreAnimation effects are best used to move from one known state to another - for example, when a preference window is resizing to accompany a new pane's contents, and you know both the old and new sizes, or when you are fading an object in or out (or both). Doing animation while the window is resizing is going to be visually confusing and make it harder for the user to focus on getting the size of the window where they want it to be.


Question:
Given:

DateTime.UtcNow

How do I get a string which represents the same value in an ISO 8601-compliant format?

Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:

yyyy-MM-ddTHH:mm:ssZ

Answer:
```
```
DateTime.UtcNow.ToString("s")
```
```
Returns something like 2008-04-10T06:30:00
```
UtcNow
```
obviously returns a
UTC
time so there is no harm in:
```
```
string.Concat(DateTime.UtcNow.ToString("s"), "Z")
```
```


Question:
How can we connect a PHP script to MS Access (.mdb) file?

I tried by including following PHP code:

$db_path = $_SERVER['DOCUMENT_ROOT'] . '\WebUpdate\\' . $file_name . '.mdb';
$cfg_dsn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" . $db_path;
$odbcconnect = odbc_connect($cfg_dsn, '', '');

But it failed and I received following error message:

 Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect in C:\web\WebUpdate\index.php on line 41

Answer:
Here's a sample for a connect and a simple select...
```
```
<?php
$db_conn = new COM("ADODB.Connection");
$connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("./Northwind.mdb").";";
$db_conn->open($connstr);
$rS = $db_conn->execute("SELECT * FROM Employees");
$f1 =  $rS->Fields(0);
$f2 =  $rS->Fields(1);
while (!$rS->EOF)
{
    print $f1->value." ".$f2->value."<br />\n";
    $rS->MoveNext();
}
$rS->Close();
$db_conn->Close();
?>
```
```


Question:
How to print line numbers to the log. Say when outputting some information to the log, I also want to print the line number where that output is in the source code. As we can see in the stack trace, it displays the line number where the exception has occurred. Stack trace is available on the exception object.

Other alternative could be like manually including the line number when printing to the log. Is there any other way?

Answer:
From
Angsuman Chakraborty
(archived) :
```
```
/** Get the current line number.
 * @return int - Current line number.
 */
public static int getLineNumber() {
    return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
```
```


Question:
After you start tracking the source of a bunch of open source software, how do you keep your code in sync? Run svn update every time you want to look at or play with the code?

It strikes me that it would be better to essentially start mirroring the code with (say) a cron job every night. Have people set up workflows to do this sort of thing? (With alerts when/if any changes you make to the code end up conflicting with the latest update?)

Or am I on my own? (I'm running Mac OS X but interested in general as well as specific solutions.)

Answer:
If your repository sends you an email every time someone checks in, why not have a program that checks for those emails and then updates the working copy at that time? This way you're always up to date. Caveats include needlessly burning bandwidth and the possibility of getting odd conflicts when a file you're working on gets updated.
Just updating once a day, or once every few days, is only useful when there are a limited number of people working on a project, all in disparate areas of it. When you've got more than five people, and the possibility that they are working in similar parts of the code, updating once an hour, or more frequently, is much better.


Question:
If i make a label in TFS, and later make a new label with the same name... then the old label is replaced by the new one.

How do I prevent TFS from overwriting a label?

Answer:
The following MSDN article covers
using the Scope of a label to try and minimize the occurrences of these mishaps
:
Using the /Child Option to Avoid Labeling Mishaps
If you issue a label command together with a pre-existing label name and an itemspec that includes files that are already marked by the same label, the value of the /child option determines whether the marked files are updated with new revision information. That is, the files are labeled by the same name, but have different scope.


Question:
Is VBA going to go away any time soon, like VB6 has?  Should I not develop new Office applications with VBA?  Or should I be developing all new Office Apps with VSTO?

Update:  Recently read this article.

Answer:
Office VSTO offers a great deal of additional functionality over Office VBA, and while I don't believe Microsoft has signaled that it's going to terminate VBA (in fact,
they've said explicitly
that it will be around at least until Office 14; Office 2007 = Office 12), I think it's well worth the effort to move your applications to VSTO to take advantage of the additional flexibility and power.
I actually don't think that deprecating VBA would be feasible, since a fair amount of Office programming takes place at the macro level by business users and I don't think that's going to go away any time soon.  Those folks don't generally have access to a VSTO-capable IDE.


Question:
Has anyone had success automating testing directly on embedded hardware?

Specifically, I am thinking of automating a battery of unit tests for hardware layer modules. We need to have greater confidence in our hardware layer code. A lot of our projects use interrupt driven timers, ADCs, serial io, serial SPI devices (flash memory) etc..

Is this even worth the effort?

We typically target:

Processor: 8 or 16 bit microcontrollers (some DSP stuff)

Language: C (sometimes c++).

Answer:
Sure.  In the automotive industry we use $100,000 custom built testers for each new product to verify the hardware and software are operating correctly.
The developers, however, also build a cheaper (sub $1,000) tester that includes a bunch of USB I/O, A/D, PWM in/out, etc and either use scripting on the workstation, or purpose built HIL/SIL test software such as MxVDev.
Hardware in the Loop (HIL) testing is probably what you mean, and it simply involves some USB hardware I/O connected to the I/O of your device, with software on the computer running tests against it.
Whether it's worth it depends.
In the high reliability industry (airplane, automotive, etc) the customer specifies very extensive hardware testing, so you have to have it just to get the bid.
In the consumer industry, with non complex projects it's usually not worth it.
With any project where there's more than a few programmers involved, though, it's
really
nice to have a nightly regression test run on the hardware - it's hard to correctly simulate the hardware to the degree needed to satisfy yourself that the software testing is enough.
The testing then shows immediately when a problem has entered the build.
Generally you perform both black box and white box testing - you have diagnostic code running on the device that allows you to spy on signals and memory in the hardware (which might just be a debugger, or might be code you wrote that reacts to messages on a bus, for instance).  This would be white box testing where you can see what's happening internally (and even cause some things to happen, such as critical memory errors which can't be tested without introducing the error yourself).
We also run a bunch of 'black box' tests where the diagnostic path is ignored and only the I/O is stimulated/read.
For a much cheaper setup, you can get $100 microcontroller boards with USB and/or ethernet (such as the Atmel UC3 family) which you can connect to your device and run basic testing.
It's especially useful for product maintenance - when the project is done, store a few working boards, the tester, and a complete set of software on CD.  When you need to make a modification or debug a problem, it's easy to set it all back up and work on it with some knowledge (after testing) that the major functionality was not affected by your changes.
-Adam


Question:
I am evaluating WF for use in line of business applications on the web, and I would love to hear some recent first-hand accounts of this technology.

My main interest here is in improving the maintainability of projects and maybe in increasing developer productivity when working on complex processes that change frequently.

I really like the idea of WF, however it seems to be relatively unknown and many older comments I've come across mention that it's overwhelmingly complex once you get into it.

If it's overdesigned to the point that it's unusable (or a bad tradeoff) for a small to medium-sized project, that's something that I need to know.

Of course, it has been out since late 2006, so perhaps it has matured. If that's the case, that's another piece of information that would be very helpful!

Thanks in advance!

Answer: It really depends on what you want to do with it.  I've only used it a little, but compared to more mature products like MetaStorm (I know technically it's a BPM, but there is still a workflow component), Process Choriographer and IBM MQ workflow, there's no comparison.  It's just not mature enough.  On the other hand it's free where the others are not and can probably get the job done.  I don't know if I would place a multi-million dollar operation on it, but with smaller ones, I'd give it another shot.  The real hurdle you are going to face is the change in thought process it requires.  If you don't have developers that have worked with state systems before that can be a real hurdle.


Question:
If I'm deploying to servers with WebSphere 6.1 (Java 1.5), should I use IBM's JDK on my build box?  Or will Sun's JDK compile to the same binary?

If I should use IBM's, where can I get the Windows x64 version?

Answer:
It should not make any difference. It will probably not be exactly the same binary but 100% compatible. I assume you're using external libraries anyways like log4j or maybe hibernate or whatever and those are not built using the IBM JDK.
There are differences in the JREs, however. For example, I remember that when I listed methods or fields of a class using reflection, the IBM JRE used to give them to me in a different order than the Sun one.


Question:
I'm processing some data files that are supposed to be valid UTF-8 but aren't, which causes the parser (not under my control) to fail. I'd like to add a stage of pre-validating the data for UTF-8 well-formedness, but I've not yet found a utility to help do this.

There's a web service at W3C which appears to be dead, and I've found a Windows-only validation tool that reports invalid UTF-8 files but doesn't report which lines/characters to fix.

I'd be happy with either a tool I can drop in and use (ideally cross-platform), or a ruby/perl script I can make part of my data loading process.

Answer:
Use python and str.encode|decode functions.
```
```
>>> a="γεια"
>>> a
'\xce\xb3\xce\xb5\xce\xb9\xce\xb1'
>>> b='\xce\xb3\xce\xb5\xce\xb9\xff\xb1' # note second-to-last char changed
>>> print b.decode("utf_8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 6: unexpected code byte
```
```
The exception thrown has the info requested in its .args property.
```
```
>>> try: print b.decode("utf_8")
... except UnicodeDecodeError, exc: pass
...
>>> exc
UnicodeDecodeError('utf8', '\xce\xb3\xce\xb5\xce\xb9\xff\xb1', 6, 7, 'unexpected code byte')
>>> exc.args
('utf8', '\xce\xb3\xce\xb5\xce\xb9\xff\xb1', 6, 7, 'unexpected code byte')
```
```


Question: I am using Visual Studio, developing a native application, I have a programmatical breakpoint (assert) in my code placed using __asm int 3 or __debugbreak.  Sometimes when I hit it, I would like to disable it so that successive hits in the same debugging session no longer break into the debugger. How can I do this?

Answer:
x86 / x64
Assuming you are writing x86/x64 application, write following in your watch window:
x86:
```
*(char *)eip,x
```
x64:
```
*(char *)rip,x
```
You should see a value 0xcc, which is opcode for INT 3. Replace it with 0x90, which is opcode for NOP. You can also use the memory window with eip as an address.
PPC
Assuming you are writing PPC application (e.g. Xbox 360), write following in your watch window:
```
*(int *)iar,x
```
You should see a value 0xfeNNNNNN, which is opcode for trap (most often 0x0fe00016 = unconditional trap). Replace it with 0x60000000, which is opcode for NOP.


Question: I am using 3D maths in my application extensively. How much speed-up can I achieve by converting my vector/matrix library to SSE, AltiVec or a similar SIMD code?

Answer:
Most likely you will see only very small speedup, if any, and the process will be more complicated than expected. For more details see
The Ubiquitous SSE vector class
article by Fabian Giesen.
The Ubiquitous SSE vector class: Debunking a common myth
Not that important
First and foremost, your vector class is probably not as important for the performance of your program as you think (and if it is, it's more likely because you're doing something wrong than because the computations are inefficient). Don't get me wrong, it's probably going to be one of the most frequently used classes in your whole program, at least when doing 3D graphics. But just because vector operations will be common doesn't automatically mean that they'll dominate the execution time of your program.
Not so hot
Not easy
Not now
Not ever


Question:
I have the following class

public class Car
{
   public Name {get; set;}
}

and I want to bind this programmatically to a text box.

How do I do that?

Shooting in the dark:

...
Car car = new Car();
TextEdit editBox = new TextEdit();
editBox.DataBinding.Add("Name", car, "Car - Name");
...

I get the following error

"Cannot bind to the propery 'Name' on the target control.

What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development.

Answer:
Without looking at the syntax, I'm pretty sure it's:
```
```
editBox.DataBinding.Add("Text", car, "Name");
```
```


Question:
How to get an instance's member's values?

With propertyInfos there is a propertyInfo.GetValue(instance, index), but no such thing exists in memberInfo.

I searched the net, but it seems to stop at getting the member's name and type.

Answer:
I think what you need is
```
FieldInfo
```
.


Question:
Aside from trying

perldoc <module name>

individually for any CPAN module that takes my fancy or going through the file system and looking at the directories I have no idea what modules we have installed.

What's the easiest way to just get a big list of every CPAN module installed? From the command line or otherwise.

Answer:
```
```
perldoc perllocal
```
```
Edit: There's a (little) more info about it in the
CPAN FAQ


Question:
I am looking to convert a MySQL timestamp to a epoch time in seconds using PHP, and vice versa.

What's the cleanest way to do this?

Answer:
There are two functions in MySQL which are useful for converting back and forth from the unix epoch time that PHP likes:
from_unixtime()
unix_timestamp()
For example, to get it back in PHP unix time, you could do:
```
SELECT unix_timestamp(timestamp_col) FROM tbl WHERE ...
```


Question:
Suppose I have some XAML like this:

<Window.Resources>
  <v:MyClass x:Key="whatever" Text="foo\nbar" />
</Window.Resources>

Obviously I want a newline character in the MyClass.Text property, but the XAML parser constructs the object with the literal string "foo\nbar".

Is there (a) a way to convince the parser to translate escape sequences, or (b) a .NET method to interpret a string in the way that the C# compiler would?

I realize that I can go in there looking for \n sequences, but it would be nicer to have a generic way to do this.

Answer:
Off the top of my head, try;
A custom binding expression perhaps?
```
<v:MyClass x:Key="whatever" Text="{MyBinder foo\nbar}"/>
```
Use a string static resource?
Make Text the default property of your control and;
```
```
<v:MyClass x:Key="whatever">
foo
bar
</v:MyClass>
```
```


Question:
How to customize the color of the symbol inserted in the "glasses mode" in Emacs?
I have not found the option for this. Can anyone suggest anything?

Answer:
There's no option to set the face for the inserted separator (and from a brief study of the docs for emacs overlays, I don't think it's simple to add).
You can customize the face used for the capital letters that glasses-mode splits on; it's called
```
glasses-face
```
.


Question:
I recently asked a question about Oracle Encryption.  Along the way to finding a solution for myself I decided to move the encryption (well, obfuscation) to the application side for certain tasks.

My problem is that the database is already encrypting data a certain way and I need Java code to duplicate that functionality, so that text encrypted by one system can be decrypted by the other and vice versa.

I want the encryption to be compatible with what the DB was already doing but couldn't find the documentation that describes exactly what Oracle is doing.  How do I replicate this in Java?

dbms_obfuscation_toolkit.DESEncrypt(
  input_string => v_string,
  key_string => key_string,
  encrypted_string => encrypted_string );
RETURN UTL_RAW.CAST_TO_RAW(encrypted_string);

No matter what I try, it seems as if the Java DES encryption is different than Oracle's.

Answer:
I found this works:
```
```
KeySpec ks = new DESKeySpec(new byte[] {'s','e','c','r','e','t','!','!'});
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(ks);
Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
IvParameterSpec ips = new IvParameterSpec(new byte[] {0,0,0,0,0,0,0,0});
c.init(Cipher.ENCRYPT, sk, ips);
// or
c.init(Cipher.DECRYPT, sk, ips);
```
```
The missing piece was the Initialization Vector (ips) which must be 8 zeros.  When you use null in Java you get something different.


Question:
I'm running an c# .net app in an iframe of an asp page on an older site. Accessing the Asp page's session information is somewhat difficult, so I'd like to make my .net app simply verify that it's being called from an approved page, or else immediately halt.

Is there a way for a page to find out the url of it's parent document?

Answer:
```
```
top.location.href
```
```
But that will only work if both pages (the iframe and the main page) are being served from the same domain.


Question:
I have to restore a database that has been inadvertently DROPped in MySQL 5.0.  From checking the backup files, I only seem to have .FRM files to hold the database data.

Can anyone advise whether this is all I need to perform a database restore/import from the backup, or are there other files I should have to hand to complete this?

Answer:
.frm files are not the data files, they just store the "data dictionary information" (see
MySQL manual
). InnoDB stores its data in ib_logfile* files. That's what you need in order to do a backup/restore. For more details see
here
.


Question: Is there a command in classic ASP I can use to tell the browser not to pull the page from it's cache, or, to not cache, or clear the cache of my page?

Answer:
If you put
```
```
Response.Expires = -1
```
```
in you classic ASP-page it will instruct the browser not to cache the contents. If the user clicks "back" or navigating to the page in another way, the browser will refresh the page from the server.


Question:
I have an application for Tomcat which needs to offer/consume web services. Since Java web services are a nightmare (xml, code generation, etc.) compared with what is possible in Python, I would like to learn from your experience using jython instead of java for offerring/consuming web services.

What I have done so far involves adapting http://pywebsvcs.sourceforge.net/ to Jython. I still get errors (namespaces, types and so), although some of it is succesful for the simplest services.

Answer:
PyServlet
helps you configure Tomcat to serve up Jython scripts from a URL.  You could use this is a "REST-like" way to do some basic web services without much effort.  (It is also described
here
.)
We used a similar home grown framework to provide a variety of data services in a large multiple web application very successfully.


Question:
I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.

The calendar object just has a method that adds events as they get parsed.

Now I want to create a factory function that creates a calendar from a file object, path, or URL.

I've been using the iCalendar python module, which implements a factory function as a class method directly on the Class that it returns an instance of:

cal = icalendar.Calendar.from_string(data)

From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.

The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?

Answer:
It's pythonic not to think about esoteric difference in some pattern you read somewhere and now want to use everywhere, like the factory pattern.
Most of the time you would think of a @staticmethod as a solution it's probably better to use a module function, except when you stuff multiple classes in one module and each has a different implementation of the same interface, then it's better to use a @staticmethod
Ultimately weather you create your instances by a @staticmethod or by module function makes little difference.
I'd probably use the initializer ( __init__ ) of a class because one of the more accepted "patterns" in python is that the factory for a class is the class initialization.


Question:
I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address?

Edit: to make it clear, I currently don't have a config file at all.

Answer:
That depends on how you are running the cherrypy init.
If using cherrypy 3.1 syntax, that wold do it:
```
```
cherrypy.server.socket_host = 'www.machinename.com'
cherrypy.engine.start()
cherrypy.engine.block()
```
```
Of course you can have something more fancy, like subclassing the server class, or using config files. Those uses are covered in
the documentation
.
But that should be enough. If not just tell us what you are doing and cherrypy version, and I will edit this answer.


Question:
It's my understanding that nulls are not indexable in DB2, so assuming we have a huge table (Sales) with a date column (sold_on) which is normally a date, but is occasionally (10% of the time) null.

Furthermore, let's assume that it's a legacy application that we can't change, so those nulls are staying there and mean something (let's say sales that were returned).

We can make the following query fast by putting an index on the sold_on and total columns

Select * from Sales
where
Sales.sold_on between date1 and date2
and Sales.total = 9.99

But an index won't make this query any faster:

Select * from Sales
where
Sales.sold_on is null
and Sales.total = 9.99

Because the indexing is done on the value.

Can I index nulls?  Maybe by changing the index type?  Indexing the indicator column?

Answer:
I'm no DB2 expert, but if 10% of your values are null, I don't think an index on that column alone will ever help your query.  10% is too many to bother using an index for -- it'll just do a table scan.  If you were talking about 2-3%, I think it would actually use your index.
Think about how many records are on a page/block -- say 20.  The reason to use an index is to avoid fetching pages you don't need.  The odds that a given page will contain 0 records that are null is (90%)^20, or 12%.  Those aren't good odds -- you're going to need 88% of your pages to be fetched anyway, using the index isn't very helpful.
If, however, your select clause only included a few columns (and not *) -- say just salesid, you could probably get it to use an index on (sold_on,salesid), as the read of the data page wouldn't be needed -- all the data would be in the index.


Question:
I'm not sure about what's the difference between opening a JS script with

<SCRIPT language='JavaScript'>

or with:

<SCRIPT type="text/JavaScript">

Should JavaScript always be quoted (either with " " or with ' ') or that's not really important?

Thank you for any clarification on this topic!

Answer:
Use both:
```
```
<script language="javascript" type="text/javascript">
```
```


Question: Convert mysql timestamp to epoch time in python - is there an easy way to do this?

Answer:
Why not let MySQL do the hard work?
```
```
select unix_timestamp(fieldname) from tablename;
```
```


Question: I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#.

Answer:
Use the Windows API. Call
```
GetForegroundWindow()
```
.
```
GetForegroundWindow()
```
will give you a handle (named
```
hWnd
```
) to the active window.
Documentation:
GetForegroundWindow function | Microsoft Docs


Question:
A product that I am working on collects several thousand readings a day and stores them as 64k binary files on a NTFS partition (Windows XP).  After a year in production there is over 300000 files in a single directory and the number keeps growing.  This has made accessing the parent/ancestor directories from windows explorer very time consuming.

I have tried turning off the indexing service but that made no difference.  I have also contemplated moving the file content into a database/zip files/tarballs but it is beneficial for us to access the files individually; basically, the files are still needed for research purposes and the researchers are not willing to deal with anything else.

Is there a way to optimize NTFS or Windows so that it can work with all these small files?

Answer:
If you can calculate names of files, you might be able to sort them into folders by date, so that each folder only have files for a particular date.  You might also want to create month and year hierarchies.
Also, could you move files older than say, a year, to a different (but still accessible) location?
Finally, and again, this requires you to be able to calculate names, you'll find that directly accessing a file is much faster than trying to open it via explorer.  For example, saying
notepad.exe "P:\ath\to\your\filen.ame"
from the command line should actually be pretty quick, assuming you know the path of the file you need without having to get a directory listing.


Question:
I'm trying to run a LINQ to SQL query that returns a result in a grid view in a search engine style listing.

In the simplified example below, is it possible to populate the collection with a comma-separated list of any children that the parent has (NAMESOFCHILDREN) in a single query?

var family = from p in db.Parents
             where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"])
             join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId
             join c in db.Children on pcl.ChildId equals c.ChildId
             select new
             {
                 Family = "Name: " + p.ParentName + "<br />" +
                          "Children: " + NAMESOFCHILDREN? + "<br />"
             };

Thanks in advance.

Answer:
Your joins are going to screw up your cardinality!  You don't have a list of Parents!
Here's some untested free-hand code.  Adding the relationships in the Linq designer gives you relationship properties.  String.Join will put the list together.
I've added two optional method calls.
Where ... Any
will filter the parents to only those parents that have children.  I'm unsure of string.Join's behavior on an empty array.
ToList
will yank Parents into memory, the children will be accessed by further database calls.  This may be necessary if you get a runtime
string.Join is not supported by SQL translator
exception.  This exception would mean that LINQ tried to translate the method call into something that SQL Server can understand - and failed.
```
```
int parentID = Convert.ToInt32(Request.QueryString["parentId"]);

List<string> result =
  db.Parents
  .Where(p => p.ParentId == parentID)
  //.Where(p => p.ParentChildLookup.Children.Any())
  //.ToList()
  .Select(p =>
    "Name: " + p.ParentName + "
" +
    "Children: " + String.Join(", ", p.ParentChildLookup.Children.Select(c => c.Name).ToArray() + "
"
)).ToList();
```
```
Also note: generally you do not want to mix data and markup until the data is properly escaped for markup.


Question:
I'm getting an error message when I try to build my project in eclipse:

The type weblogic.utils.expressions.ExpressionMap cannot be resolved. It is indirectly referenced
 from required .class files

I've looked online for a solution and cannot find one (except for those sites that make you pay for help).  Anyone have any idea of a way to find out how to go about solving this problem?  Any help is appreciated, thanks!

Answer:
Have you Googled for "weblogic ExpressionMap"?  Do you know what it is and what it does?
Looks like you definitely need to be compiling alongside Weblogic and with Weblogic's jars included in your Eclipse classpath, if you're not already.
If you're not already working with Weblogic, then you need to find out what in the world is referencing it.  You might need to do some heavy-duty grepping on your jars, classfiles, and/or source files looking for which ones include the string "weblogic".
If I had to include something that was relying on this Weblogic class, but couldn't use Weblogic, I'd be tempted to try to reverse-engineer a compatible class.  Create your own weblogic.utils.expressions.ExpressionMap class; see if everything compiles; use any resultant errors or warnings at compile-time or runtime to give you clues as to what methods and other members need to be in this class.  Make stub methods that do nothing or return null if possible.


Question: I got this flash application where you can click a link while watching a video. It will open a new tab and pause the video. Now when you come back to the flash application it would be nice if the video would start playing again. Is there a way, an event or so to do this ?

Answer:
Flash is probably a no-go, but you might have some luck with pure javascript and have that communicate with your Flash Movie. I suggest you play around with the Window's onFocus event.
I've never used it before, so it might not trigger on any/all browsers.
This
worked in FF3. It's not valid or good code but it's a stepping stone for you:
```
```

```
```
It's also really annoying because clicking okay ok the alert, re-triggers the focus. Control+W will close the tab for you and allow you to break the cycle.


Question: Which approach do you all think is better?

Answer: Next to each field, highlighting each field in a distinctive color or with an easily distinguishable mark, so it's self evident where the problems are, especially on a long form. Also place a help icon next to each failure providing more information in case it's needed by some users. In addition, do not forget to preserve the data that's correct in between failures.


Question:
Has anyone experienced issues with Java's default garbage collector while running apps on VmWare instances?

I am experiencing issues where full garbage collections are not running as often as I would expect and am curious if the VmWare variable has anything to do with it.

Answer:
In general, the garbage collector will only run a full GC when it really needs to.  The reason is that it takes a lot of time.  It will try to do more smaller GCs that take a lot less time.  Fo the most part, this seems to be a good strategy.
There are some extra GC flags you can add to the VM if you want to try to tweek things.
See this
Addtionally you probably want to make sure you're running the server vm and not the client vm.
I guess the real question is what you're trying to acheive.  If you're running out of memory its probably not because of the GC.  Its probably because of
Memory leaks
, and yes you can create them in memory managed environments.  They are just a little different.


Question:
I'd like to show/hide a column at runtime based on a particular condition. I'm using "Print when expression" to conditionally show/hide this column (and it's header) in my report. When the column is hidden, the space it would have occupied is left blank, which is not particularly attractive.

I would prefer if the extra space was used in a more effective manner, possibilities include:

the width of the report is reduced by the width of the hidden column

the extra space is distributed among the remaining columns

In theory, I could achieve the first by setting the width of the column (and header) to 0, but also indicate that the column should resize to fit its contents. But JasperReports does not provide a "resize width to fit contents" option.

Another possibility is to generate reports using the Jasper API instead of defining the report template in XML. But that seems like a lot of effort for such a simple requirement.

Answer:
If it is just one column, is it possible to place this column to the far right, and then use the print when expression. That way there is not a hole in the middle. I know this is not ideal, as I had tried to do what you are currently trying to accomplish in the past, and could not find what I call a good solution.
A second idea would to be create a second report based on the first with out the column, and then when calling the report check the condition, to decide which one to call. Again not ideal, but would work.
I know this is not really the answer you were looking for, but one of these suggestions may work for you.


Question:
I'm not asking about converting a LaTeX document to html.

What I'd like to be able to do is have some way to use LaTeX math commands in an html document, and have it appear correctly in a browser. This could be done server or client side.

Answer:
MediaWiki can do what you are looking for. It uses Texvc (
http://en.wikipedia.org/wiki/Texvc
) which "validates (AMS) LaTeX mathematical expressions and converts them to HTML, MathML, or PNG graphics." Sounds like what you are looking for.
Check out Wikipedia's article on how they handle math equations here:
http://en.wikipedia.org/wiki/Help:Formula
. They also have an extensive reference on LaTeX and pros/cons of the different rendering types (PNG/MathML/HTML).
MediaWiki uses a subset of TeX markup,
  including some extensions from LaTeX
  and AMS-LaTeX, for mathematical
  formulae. It generates either PNG
  images or simple HTML markup,
  depending on user preferences and the
  complexity of the expression. In the
  future, as more browsers are smarter,
  it will be able to generate enhanced
  HTML or even MathML in many cases.
  (See blahtex for information about
  current work on adding MathML
  support.)
More precisely, MediaWiki filters the
  markup through Texvc, which in turn
  passes the commands to TeX for the
  actual rendering. Thus, only a limited
  part of the full TeX language is
  supported; see below for details.
  ...
Pros of HTML
In-line HTML formulae always align properly with the rest of the HTML
  text.
The formula's background, font size and face match the rest of HTML
  contents and the appearance respects
  CSS and browser settings.
Pages using HTML will load faster.
Pros of TeX
TeX is semantically superior to HTML. In TeX, "x" means
  "mathematical variable x", whereas in
  HTML "x" could mean anything.
  Information has been irrevocably lost.
  This has multiple benefits:
TeX can be transformed into HTML, but not vice-versa. This means that on
  the server side we can always
  transform a formula, based on its
  complexity and location within the
  text, user preferences, type of
  browser, etc. Therefore, where
  possible, all the benefits of HTML can
  be retained, together with the
  benefits of TeX. It's true that the
  current situation is not ideal, but
  that's not a good reason to drop
  information/contents. It's more a
  reason to help improve the situation.
TeX can be converted to MathML for browsers which support it, thus
  keeping its semantics and allowing it
  to be rendered as a vector.
TeX has been specifically designed for typesetting formulae, so input is
  easier and more natural, and output is
  more aesthetically pleasing.
When writing in TeX, editors need not worry about browser support, since
  it is rendered into an image by the
  server. HTML formulae, on the other
  hand, can end up being rendered
  inconsistent of editor's intentions
  (or not at all), by some browsers or
  older versions of a browser.


Question:
I just started using SVN, and I have a cache directory that I don't need under source control. How can I ignore the whole directory/folder with SVN?

I am using Versions and TextMate on OS X and commandline.

Answer:
Set the
```
svn:ignore
```
property of the parent directory:
```
```
svn propset svn:ignore dirname .
```
```
If you have multiple things to ignore, separate by newlines in the property value.  In that case it's easier to edit the property value using an external editor:
```
```
svn propedit svn:ignore .
```
```


Question:
Can someone explain when to use each of these?  They almost seem interchangeable in many cases.

The Custom Control gets added to the toolbar while the User Control (ascx) can not.  The Custom Control does not get rendered in the Designer while the User Control does.  Beyond that, how do you choose which is the right one to use?

Also, I am looking for the best way to access the controls from JavaScript (GetElementById).  So, a point in the right direction for adding client side support would be great.

Answer:
This is from Microsoft's site:
Web user controls
Easier to create
Limited support for consumers who use a visual design tool
A separate copy of the control is required in each application
Cannot be added to the Toolbox in Visual Studio
Good for static layout
Web custom controls
Harder to create
Full visual design tool support for
consumers
Only a single copy of the control is
required, in the global assembly
cache
Can be added to the Toolbox in
Visual Studio
Good for dynamic layout
http://msdn.microsoft.com/en-us/library/aa651710(VS.71).aspx


Question:
I would like to have something like this:

class Foo {
private:
  int bar;
public:
  void setBar(int bar);
  int getBar() const;
}

class MyDialog : public CDialogImpl<MyDialog> {
  BEGIN_MODEL_MAPPING()
    MAP_INT_EDITOR(m_editBar, m_model, getBar, setBar);
  END_MODEL_MAPPING()
  // other methods and message map
private:
  Foo * m_model;
  CEdit m_editBar;
}

Also it would be great if I could provide my custom validations:

MAP_VALIDATED_INT_EDITOR(m_editBar, m_model, getBar, setBar, validateBar)
...
bool validateBar (int value) {
  // custom validation
}

Have anybody seen something like this?

P.S. I don't like DDX because it's old and it's not flexible, and I cannot use getters and setters.

Answer:
The
Cocoa Bindings
provide exactly what you want, but they are only available in the Mac / Objective-C word.
GNUstep
is a free version of it, but it's still Objective-C, not C++.
However, it might be a good inspiration for an own framework, or a good starting point for further research.


Question:
I need to do the following for the purposes of paging a query in nHibernate:

Select count(*) from
(Select e.ID,e.Name from Object as e where...)

I have tried the following,

select count(*) from Object e where e = (Select distinct e.ID,e.Name from ...)

and I get an nHibernate Exception saying I cannot convert Object to int32.

Any ideas on the required syntax?

EDIT

The Subquery uses a distinct clause, I cannot replace the e.ID,e.Name with Count(*) because Count(*) distinct is not a valid syntax, and distinct count(*) is meaningless.

Answer:
If you just need
```
e.Id
```
,
```
e.Name
```
:
```
select count(*) from Object where
```
.....


Question:
This is not a new topic, but I am curious how everyone is handling either .js or .css that is browser specific.

Do you have .js functions that have if/else conditions in them or do you have separate files for each browser?

Is this really an issue these days with the current versions of each of the popular browsers?

Answer:
I use a framework to handle 99% of the xbrowser stuff.
For everything not covered in the framework, I'd use a if/else or a try/catch.


Question:
How to make database connection pool in PowerBuilder (v9+) with...

...ODBC?

...SQL Server?

...Oracle?

Answer:
Unfortunately, at least with PB 9, you can't
natively
.  PB has always been a two-tier dev tool.  However, if you are using the WebServices support that started in PB 9 you can get around this limitation by invoking WebServices on a connection pooled appServer.  I haven't played with PB 11.5 yet BTW.  Could be different there.
Jason


Question: I'm looking to add a numeric up / down control to a .Net StatusStrip.  Unfortunately, it isn't listed as an option in the UI designer.  Is there a way to do this?

Answer:
You can use a
ToolStripControlHost
class to host a custom ( NumericUpDown for now ) class.
You can also derive from this class "NumericUpDownToolStripItem" which initialize the "Control" property with the custom control and can populate next properties from the hosted control ( Min, Max, Value - for example ).


Question: I have VB6 application , I want to put some good error handling finction in it which  can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this

Answer:
First of all, go get
MZTools for Visual Basic 6
, its free and invaluable.  Second add a custom error handler on every function (yes, every function).  The error handler we use looks something like this:
```
```
On Error GoTo {PROCEDURE_NAME}_Error

{PROCEDURE_BODY}

    On Error GoTo 0
    Exit {PROCEDURE_TYPE}

{PROCEDURE_NAME}_Error:

   LogError "Error " & Err.Number & " (" & Err.Description & ") in line " & Erl & _
            ", in procedure {PROCEDURE_NAME} of {MODULE_TYPE} {MODULE_NAME}"
```
```
Then create a LogError function that logs the error to disc.  Next, before you release code add Line Numbers to every function (this is also built into MZTools).  From now on you will know from the Error Logs everything that happens.  If possible, also, upload the error logs and actually examine them live from the field.
This is about the best you can do for unexpected global error handling in VB6 (one of its many defects), and really this should only be used to find unexpected errors.   If you know that if there is the possibility of an error occurring in a certain situation, you should catch that particular error and handle for it.  If you know that an error occurring in a certain section is going to cause instability (File IO, Memory Issues, etc) warn the user and know that you are in an "unknown state" and that "bad things" are probably going happen.  Obviously use friendly terms to keep the user informed, but not frightened.


Question: How compatible is code written under Solaris with Open Solaris ? I would be interested specifically in some kernel modules .

Answer: I think it is hard to quantify software compatibility, but I'd say code written for Solaris is quite forward compatible with OpenSolaris kernel. OpenSolaris source code evolves into what will be Solaris 11, and Sun's commitment to backwards compatibility is quite a fact.


Question: I have a web application that needs to take a file upload from the user and upload it to a remote server.  I can take input from user to server fine via file_field, but can't seem to work out the next step of uploading from server to remote.  Net::HTTP doesn't do multipart forms out of the box, and I haven't been able to find another good solution.  I need something that will allow me to go from user -> server -> remote instead of going user -> remote.  Anyone succeeded in doing this before?

Answer:
Surprisingly multipart form posts really aren't in Net:HTTP. A
thread
from comp.lang.ruby seems to have snippet of code you might find useful to perform the encoding necessary:
```
```
BOUNDARY = "AaB03x"

def encode_multipartformdata(parameters = {})
  ret = String.new
  parameters.each do |key, value|
    unless value.empty?
      ret << "\r\n--" << BOUNDARY << "\r\n"
      ret << "Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n"
      ret << value
    end
  end
  ret << "\r\n--" << BOUNDARY << "--\r\n"
end
```
```


Question:
Let's say I have a string holding a mess of text and (x)HTML tags. I want to remove all instances of a given tag (and any attributes of that tag), leaving all other tags and text along.  What's the best Regex to get this done?

Edited to add:  Oh, I appreciate that using a Regex for this particular issue is not the best solution.  However, for the sake of discussion can we assume that that particular technical decision was made a few levels over my pay grade? ;)

Answer:
Attempting to parse HTML with regular expressions is generally an
extremely
bad idea. Use a parser instead, there should be one available for your chosen language.
You
might
be able to get away with something like this:
```
```
</?tag[^>]*?>
```
```
But it depends on exactly what you're doing. For example, that won't remove the tag's content, and it may leave your HTML in an invalid state, depending on which tag you're trying to remove. It also copes badly with invalid HTML (and there's a lot of that about).
Use a parser instead :)


Question:
I'm working for a customer with a huge legacy codebase consisting of various Java en JSP based applications.

Most querying is done using the home-build 'orm' system. Some applications use Plain Old JDBC. Some applications are based on Hibernate (yes HQL build with plus signs is a potential problem as well). Some of the older applications are entirely writen in JSP.

I've found a couple of SQL inject bugs manually. But I could really use some sort of tool to search for potential weak spots.

Any ideas?

Answer:
When I was working on localization of "this-will-never-need-localization" application, we use a home-made tool to analyzing compiled code ( IL in .NET, it is same as byte-code in Java ).
You can find calling the specified methods which works with DB ( typicaly CRUD operations ) wicht has a string parameter with SQL command, and track the string instance up and check for concating.
We used the .NET Reflector for decompiling and tracking strings. But I don't know, if is available similar tool for Java :(.


Question:
By default netbeans stores it's settings in a directory called .netbeans under the user's home directory. Is it possible to change the location of this directory (especially under Windows)?

Thanks to James Schek I now know the answer (change the path in netbeans.conf) but that leads me to another question:
Is there a way to include the current username in the path to the netbeans setting directory?

I want to do something like this:

netbeans_default_userdir="D:\etc\${USERNAME}\.netbeans\6.5beta"

but I can't figure out the name of the variable to use (if there's any).
Of course I can achieve the same thing with the --userdir option, I'm just curious.

Answer:
yes, edit the netbeans.conf file under %NETBEANS_HOME%\etc.
Edit the line with:
netbeans_default_userdir="${HOME}/.netbeans/6.0"
If you need different "profiles"--i.e. want to run different copies of Netbeans with different home directories, you can pass a new home directory to the launcher. Run "netbeans.exe --userdir /path/to/dir" or "nb.exe --userdir /path/to/dir"


Question:
I have 2 arrays of 16 elements (chars) that I need to "compare" and see how many elements are equal between the two.

This routine is going to be used millions of times (a usual run is about 60 or 70 million times), so I need it to be as fast as possible. I'm working on C++ (C++Builder 2007, for the record)

Right now, I have a simple:

matches += array1[0] == array2[0];

repeated 16 times (as profiling it appears to be 30% faster than doing it with a for loop)

Is there any other way that could work faster?

Some data about the environment and the data itself:

I'm using C++Builder, which doesn't have any speed optimizations to take into account. I will try eventually with another compiler, but right now I'm stuck with this one.

The data will be different most of the times. 100% equal data is usually very very    rare (maybe less than 1%)

Answer:
Is it faster as one statement?
```
```
matches += (array1[0] == array2[0]) + (array1[1] == array2[1]) + ...;
```
```


Question: By default, emacs 22.1.1 only shows the top of the compilation buffer when you first issue the compile command.  I would like it to scroll to the bottom automatically when I use the compile command in order to save keystrokes.  This way I can easily get a status of the current compilation by just looking at the compile buffer and seeing which files are currently being compiled instead of having to switch windows and scroll to the bottom of the buffer.  Any ideas?

Answer:
From Info > emacs > Compilation:
If you set the variable
```
compilation-scroll-output
```
to a non-
```
nil
```
value, then the compilation buffer always scrolls to follow output as
  it comes in.


Question: I have writtent some Oracle storedprocedures in these there are more then 20 input parameters and from them morethen 10 parameters are required , I want all with some value and do not want to accept null values for that , Is there anything that I can declare in the Procedure defination itself which can restrict null input parameter or Will I have to check for each value and Raise the exception if the required value is null ?

Answer:
In PL/SQL I don't know of a way around checking each one.
If you are calling the stored procedure from an external library, that library might have that functionality. This is probably not likely because frequently NULL input parameters are required.
You could make a helper PL/SQL procedure that, given a value, will raise an exception if it is null to save on redundant code. You could then write a chunk of perl/python/groovy that would slurp up your procedure declaration and crank out these calls to your null check procedure.


Question: Killing the processs while obtaining this information would be fine.

Answer:
A quick-and-dirty way would be
```
ObjectSpace.each_object{|e| p e}
```
. You could do some tests to determine what you wanted to keep, or Marshal the objects.


Question:
I'm wondering what is the best way to handle error messages in my application.

Currently I'm working on a web application and all error messages are stored in the database and we get them by ID, negative is an error , and positive are success messages.

the problem is that is hard to maintain and keep tracking of text messages.

What are your approaches ?

Answer:
Generally speaking, I keep the text of the error messages in resource files. If you're using .NET 2.0 or higher (Visual Studio 2005 or higher), resource files are automatically compiled into strongly-typed classes, making the code which accesses said messages much more clear and readable.
(EDIT: Having seen another comment which mentions localization, I feel honor-bound to mention it here as well: .NET resource files do an excellent job of localization. You can get the localized text of the resource via the exact same code, with just a few minor tweaks to provide CultureInfo.)
That said, it sounds like a part of this problem domain is a message number. Are these errors being thrown from the database (say, as part of stored procs or triggers)? In that case, then database storage most likely is the right place for them, if only because that documents them most closely to where the "magic numbers" are being used.


Question:
While googling, I see that using java.io.File#length() can be slow.
FileChannel has a size() method that is available as well.

Is there an efficient way in java to get the file size?

Answer:
Well, I tried to measure it up with the code below:
For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of:
```
```
LENGTH sum: 10626, per Iteration: 10626.0

CHANNEL sum: 5535, per Iteration: 5535.0

URL sum: 660, per Iteration: 660.0
```
```
For runs = 5 and iterations = 50 the picture draws different.
```
```
LENGTH sum: 39496, per Iteration: 157.984

CHANNEL sum: 74261, per Iteration: 297.044

URL sum: 95534, per Iteration: 382.136
```
```
File must be caching the calls to the filesystem, while channels and URL have some overhead.
Code:
```
```
import java.io.*;
import java.net.*;
import java.util.*;

public enum FileSizeBench {

    LENGTH {
        @Override
        public long getResult() throws Exception {
            File me = new File(FileSizeBench.class.getResource(
                    "FileSizeBench.class").getFile());
            return me.length();
        }
    },
    CHANNEL {
        @Override
        public long getResult() throws Exception {
            FileInputStream fis = null;
            try {
                File me = new File(FileSizeBench.class.getResource(
                        "FileSizeBench.class").getFile());
                fis = new FileInputStream(me);
                return fis.getChannel().size();
            } finally {
                fis.close();
            }
        }
    },
    URL {
        @Override
        public long getResult() throws Exception {
            InputStream stream = null;
            try {
                URL url = FileSizeBench.class
                        .getResource("FileSizeBench.class");
                stream = url.openStream();
                return stream.available();
            } finally {
                stream.close();
            }
        }
    };

    public abstract long getResult() throws Exception;

    public static void main(String[] args) throws Exception {
        int runs = 5;
        int iterations = 50;

        EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class);

        for (int i = 0; i < runs; i++) {
            for (FileSizeBench test : values()) {
                if (!durations.containsKey(test)) {
                    durations.put(test, 0l);
                }
                long duration = testNow(test, iterations);
                durations.put(test, durations.get(test) + duration);
                // System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations));
            }
        }

        for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) {
            System.out.println();
            System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations)));
        }

    }

    private static long testNow(FileSizeBench test, int iterations)
            throws Exception {
        long result = -1;
        long before = System.nanoTime();
        for (int i = 0; i < iterations; i++) {
            if (result == -1) {
                result = test.getResult();
                //System.out.println(result);
            } else if ((result = test.getResult()) != result) {
                 throw new Exception("variance detected!");
             }
        }
        return (System.nanoTime() - before) / 1000;
    }

}
```
```


Question:
I'm developing a Mac App in Java that logs into any one of our client's databases.  My users want to have several copies of this program running so they can log into a couple clients at the same time, rather than logging out and logging back in.

How can I allow a user to open several copies of my App at once?

I'm using Eclipse to develop, and Jarbundler to make the app.

Edit: More Importantly, is there a way to do so in the code base, rather than have my user do something funky on their system?  I'd rather just give them a 'Open New Window' menu item, then have them typing things into the Terminal.

Answer:
From the Terminal (or in a script wrapper):
```
```
/Applications/TextEdit.app/Contents/MacOS/TextEdit  &
```
```
Something like that should work for you.
To do this in Java:
```
```
String[] cmd = { "/bin/sh", "-c", "[shell commmand goes here]" };
 Process p = Runtime.getRuntime().exec (cmd);
```
```


Question:
I need to determine if a Class object representing an interface extends another interface, ie:

 package a.b.c.d;
    public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{
    }

according to the spec Class.getSuperClass() will return null for an Interface.

If this Class represents either the
  Object class, an interface, a
  primitive type, or void, then null is
  returned.

Therefore the following won't work.

Class interface = Class.ForName("a.b.c.d.IMyInterface")
Class extendedInterface = interface.getSuperClass();
if(extendedInterface.getName().equals("a.b.d.c.ISomeOtherInterface")){
    //do whatever here
}

any ideas?

Answer:
Use Class.getInterfaces such as:
```
```
Class<?> c; // Your class
for(Class<?> i : c.getInterfaces()) {
     // test if i is your interface
}
```
```
Also the following code might be of help, it will give you a set with all super-classes and interfaces of a certain class:
```
```
public static Set<Class<?>> getInheritance(Class<?> in)
{
    LinkedHashSet<Class<?>> result = new LinkedHashSet<Class<?>>();

    result.add(in);
    getInheritance(in, result);

    return result;
}

/**
 * Get inheritance of type.
 *
 * @param in
 * @param result
 */
private static void getInheritance(Class<?> in, Set<Class<?>> result)
{
    Class<?> superclass = getSuperclass(in);

    if(superclass != null)
    {
        result.add(superclass);
        getInheritance(superclass, result);
    }

    getInterfaceInheritance(in, result);
}

/**
 * Get interfaces that the type inherits from.
 *
 * @param in
 * @param result
 */
private static void getInterfaceInheritance(Class<?> in, Set<Class<?>> result)
{
    for(Class<?> c : in.getInterfaces())
    {
        result.add(c);

        getInterfaceInheritance(c, result);
    }
}

/**
 * Get superclass of class.
 *
 * @param in
 * @return
 */
private static Class<?> getSuperclass(Class<?> in)
{
    if(in == null)
    {
        return null;
    }

    if(in.isArray() && in != Object[].class)
    {
        Class<?> type = in.getComponentType();

        while(type.isArray())
        {
            type = type.getComponentType();
        }

        return type;
    }

    return in.getSuperclass();
}
```
```
Edit: Added some code to get all super-classes and interfaces of a certain class.


Question: What version of java, eclipse and WPT should I be using?

Answer:
Java 2 SDK 5.0 or higher
The Release notes tell you all at this site
http://wso2.org/project/wsas/java/2.3/docs/tools/ide.html


Question:
I would like to implement a data access object pattern in C++, but preferably without using multiple inheritance and/or boost (which my client does not like).

Do you have any suggestions?

Answer:
OTL (otl.sourceforge.net) is an excellent C++ database library.  It's a single include file so doesn't have all the complexity associated (rightly or wrongly!) with Boost.
In terms of the DAO itself, you have many options.  The simplest that hides the database implementation is just to use C++ style interfaces and implement the data access layer in a particular implementation.
```
class MyDAO {
  // Pure virtual functions to access the data itself
}

class MyDAOImpl : public MyDAO {
  // Implementations to get the data from the database
}
```


Question:
I have an int array as a property of a Web User Control. I'd like to set that property inline if possible using the following syntax:

<uc1:mycontrol runat="server" myintarray="1,2,3" />

This will fail at runtime because it will be expecting an actual int array, but a string is being passed instead. I can make myintarray a string and parse it in the setter, but I was wondering if there was a more elegant solution.

Answer:
Have you tried looking into Type Converters? This page looks worth a look:
http://www.codeguru.com/columns/VB/article.php/c6529/
Also, Spring.Net seems to have a StringArrayConverter (
http://www.springframework.net/doc-latest/reference/html/objects-misc.html
- section 6.4) which, if you can feed it to ASP.net by decorating the property with a TypeConverter attribute, might work..


Question: I'm auditing our existing web application, which makes heavy use of HTML frames. I would like to download all of the HTML in each frame, is there a method of doing this with wget or a little bit of scripting?

Answer:
```
```
wget --recursive --domains=www.mysite.com http://www.mysite.com
```
```
Which indicates a recursive crawl should also traverse into frames and iframes.  Be careful to limit the scope of recursion only to your web site since you probably don't want to crawl the whole web.


Question: I want an expression that will fail when it encounters words such as "boon.ini" and "http". The goal would be to take this expression and be able to construct for any set of keywords.

Answer:
Rather than negating the result within the expression, you should do it in your code. That way, the expression becomes pretty simple.
```
```
\b(boon\.ini|http)\b
```
```
Would return
```
true
```
if boon.ini or http was anywhere in your string. It won't match words like httpd or httpxyzzy because of the
```
\b
```
, or word boundaries. If you want, you could just remove them and it will match those too. To add more keywords, just add more pipes.
```
```
\b(boon\.ini|http|foo|bar)\b
```
```


Question:
Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing

$result = mysql_query("SELECT id FROM table");
$total = mysql_num_rows($result)

I was told this was not very efficient or fast, if you have a lot of records in the table.

Answer:
You should use
SQL's built in COUNT function
:
```
```
$result = mysql_query("SELECT COUNT(id) FROM table");
```
```


Question:
I'm starting work on a project using Rails, but I'm waiting for the 3rd edition of the pragmatic rails book to come out before I purchase a book.

Anyway, my question is a bit more pointed than how do I get started...

What are some of the must have gems that everyone uses?

I need basic authentication, so I have the restful authentication gem, but beyond that, I don't know what I don't know. Is there a run down of this information somewhere? Some basic setup that 99% of the people start with when starting a new rails application?

Thanks in advance.

Answer:
The gems and plugins that I tend to use on most of my projects are:
Restful Authentication
-- For authentication
Will Paginate
-- For pagination
Attachment Fu
-- For image and file attachments
RedCloth
-- For textile rendering
Capistrano
-- For deployment


Question: Does anybody know, if closures will be in Java 7?

Answer:
It is unknown until the Java SE 7 JSR is created (presumably by Danny Coward) and an expert group is formed and the contents selected.
My Java 7 page is a good collection of links about Java 7 in general and has links to all of the closures proposals and blog entries:
http://tech.puredanger.com/java7#closures
And I maintain a Java 7 link blog where you can find links on closures and other stuff at:
http://java7.tumblr.com
And you might find my Java 7 Predictions blog post to be interesting as well if you want my opinions:
http://tech.puredanger.com/2008/08/02/java7-prediction-update/
UPDATE: Mark Reinhold stated at Devoxx in Dec. 08 that closures will NOT be included in Java 7 due to a lack of consensus on how to implement.


Question:
I'm trying to build a Windows installer using Nullsoft Install System that requires installation by an Administrator. The installer makes a "logs" directory.  Since regular users can run this application, that directory needs to be writable by regular users.  How do I specify that all users should have permission to have write access to that directory in the NSIS script language?

I admit that this sounds a like a sort of bad idea, but the application is just an internal app used by only a few people on a private network.  I just need the log files saved so that I can see why the app is broken if something bad happens.  The users can't be made administrator.

Answer:
One way: call the shell, and use
```
cacls
```
or
```
xcacls
```
.


Question:
I would like to use my laptop as a web development (PHP, Python, etc.) machine, but I'm hesitant to do this unless I can ensure that it can not be accessed by the outside world.

I'm guessing that something more than a firewall is necessary, such as configurations to the Apache configuration files, but I'm not sure what else I would need to be 100% sure it's locked down tightly.

Answer:
You need to configure the server daemon to only bind to localhost using the Listen directive like this:
```
```
Listen 127.0.0.1
```
```
An alternative is to configure access control for the main server like this
```
```
<Directory "/var/www/localhost/htdocs">
AllowOverride None
Deny from all
Allow from 127.0.0.1/255.0.0.0
</Directory>
```
```
Remember to put the root directory of your server in the Directory Directive.


Question:
The situation: we have a large database with a number of denormalized tables. We frequently have to resummarize the data to keep the summary tables in synch. We've talked on and off about using computed columns to keep the data fresh. We've also talked about triggers, but that's a separate discussion.

In our summary tables, we denormalized the table such that the Standard ID as well as the Standard Description is stored in the table.  This inherently assumes that the table will be resummarized often enough so that if they change the standard description, it will also change it in the summary table.
A bad assumption.

Question:
What if we made the Standard Description in the summary table a derived/computed column which selects the standard description from the standard table?
Is there a tremendous performance hit by dropping a computed column on a table with 100,000-500,000 rows?

Answer:
Computed columns are fine when they are not calculation intensive and are not executed on a large number of rows. Your questions is "will there be a hit by dropping the computed column." Unless this column is an index that is used by the query (REAL bad idea to index a comp col - i don't know if you can depending on your DB), then dropping it cant hurt your performance (less data to query and crunch).
If the standard table has the description, then you should be joining it in from the id and not using any computation.
You alluded to what may be a real problem, and that is the schema of your database. I have had problems like this before, where a system was built to handle one thing, and something like reporting needs to be bolted on/in. Without refactoring your schema to balance all of the needs, Sunny's idea of using views is just about the only easy way.
If you want to post some cleansed DDL and data, and an example of what you are trying to get out of the db, we may be able to give you a less subjective answer.


Question:
When Mac OS X goes to sleep, due to closing a laptop or selecting "Sleep" from the Apple menu, how does it suspend an executing process?

I suppose non-windowed processes are simply suspended at an arbitrary point of execution.  Is that also true for Cocoa apps, or does the OS wait until control returns to the run loop dispatcher, and goes to sleep in a "known" location?  Does any modern OS do that, or is it usually safe enough to simply suspend an app no matter what it is doing?

I'm curious, because allowing sleep to occur at any moment means, from the app's perspective, the system clock could suddenly leap forward by a significant amount.  That's a possibility I don't usually consider while coding.

Answer:
I believe it will just suspend all apps wherever they happen to be.
Remember, this happens all the time anyway.  Applications are constantly suspended and resumed due to context switching.  So, really, the clock could jump between any 2 instructions in your app, though usually not in a noticable/significant way.
If the OS waited for the app to return to some main loop you could run into situations where applications cause the sleep to hang.  If they're doing a lot of work and not returning to the run loop dispatcher they would prevent the machine from going to sleep.  That wouldn't be very good. :)


Question: Just like it reads.

Answer:
From wikipedia:
The Semantic Web is an evolving
  extension of the World Wide Web in
  which the semantics of information and
  services on the web is defined, making
  it possible for the web to understand
  and satisfy the requests of people and
  machines to use the web content. It
  derives from World Wide Web Consortium
  director Sir Tim Berners-Lee's vision
  of the Web as a universal medium for
  data, information, and knowledge
  exchange.


Question:
I wanted to use fstream to read a txt file.

I am using inFile >> characterToConvert, but the problem is that this omits any spaces and newline.

I am writing an encryption program so I need to include the spaces and newlines.

What would be the proper way to go about accomplishing this?

Answer:
The following c++ code will read an entire file...
```
```
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
  string line;
  ifstream myfile ("foo.txt");

  if (myfile.is_open()){

    while (!myfile.eof()){
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }
  return 0;
}
```
```
post your code and I can give you more specific help to your problem...


Question:
I have some WCF methods that are used to transmit information from a server application to a website frontend for use in binding.  I'm sending the result as an XElement that is a root of an XML tree containing the data I want to bind against.

I'd like to create some tests that examine the data and ensure it comes across as expected.

My current thinking is this:  Every method that returns an XElement tree has a corresponding schema (.XSD) file.  This file is included within the assembly that contains my WCF classes as an embedded resource.

Tests call the method on these methods and compares the result against these embedded schemas.

Is this a good idea?  If not, what other ways can I use to provide a "guarantee" of what kind of XML a method will return?

If it is, how do you validate an XElement against a schema?  And how can I get that schema from the assembly it's embedded in?

Answer:
Id say validating xml with a xsd schema is a good idea.
How to validate a XElement with the loaded schema:
As you see in this example you need to validate the XDocument first to get populate the "post-schema-validation infoset" (There might be a solution to do this without using the Validate method on the XDOcument but Im yet to find one):
```
```
String xsd =
@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
   <xsd:element name='root'>
    <xsd:complexType>
     <xsd:sequence>
      <xsd:element name='child1' minOccurs='1' maxOccurs='1'>
       <xsd:complexType>
        <xsd:sequence>
         <xsd:element name='grandchild1' minOccurs='1' maxOccurs='1'/>
         <xsd:element name='grandchild2' minOccurs='1' maxOccurs='2'/>
        </xsd:sequence>
       </xsd:complexType>
      </xsd:element>
     </xsd:sequence>
    </xsd:complexType>
   </xsd:element>
  </xsd:schema>";
String xml = @"<?xml version='1.0'?>
<root>
    <child1>
        <grandchild1>alpha</grandchild1>
        <grandchild2>beta</grandchild2>
    </child1>
</root>";
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsd)));
XDocument doc = XDocument.Load(XmlReader.Create(new StringReader(xml)));
Boolean errors = false;
doc.Validate(schemas, (sender, e) =>
{
    Console.WriteLine(e.Message);
    errors = true;
}, true);
errors = false;
XElement child = doc.Element("root").Element("child1");
child.Validate(child.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>
{
    Console.WriteLine(e.Message);
    errors = true;
});
```
```
How to read the embedded schema from an assembly and add it to the XmlSchemaSet:
```
```
Assembly assembly = Assembly.GetExecutingAssembly();
// you can use reflector to get the full namespace of your embedded resource here
Stream stream = assembly.GetManifestResourceStream("AssemblyRootNamespace.Resources.XMLSchema.xsd");
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(null, XmlReader.Create(stream));
```
```


Question: How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.

Answer:
Try this:
```
```
import os;
print os.environ.get( "USERNAME" )
```
```
That should do the job.


Question:
We log values and we only log them once in a table. When we add values to the table we have to do a look up everytime to see if it needs to insert the value or just grab the id. We have an index on the table (not on the primary key) but there are about 350,000 rows (so it is taking 10 seconds to do 10 of these values).

So either

We figure out a way to optimize it

Strip it this feature out or

Do something completely different when logging these values.

Answer:
Just to be clear, the index is on the (presumably varchar or nvarchar) field in the table, correct? Not the PK?
ok, after your edit: You're doing an indexed lookup on a large (n)varchar text field. Even with the index that can be pretty slow -- you're still doing 2 big string comparisons. I can't really thing of a great way to do this, but some initial SWAGS:
compute a hash of the to-be-logged text, and store that in the database for subsequent lookups
as another poster suggested, store all of the rows, and filter out dupes in the query (or with a nightly batch, whatever
don't check for duplicates. Catching an exception may still be cheaper than the lookup*
hire someone with a really good memory who's fast with a mouse. When a message is going to be logged, flash it to their screen with an accept/deny prompt. If the entry is a dupe, ahve them click "deny"
* yeah, I know I'll be down-modded for that, but sometimes pragmatism just works.


Question: I can understand the use for one level of namespaces. But 3 levels of namespaces. Looks insane. Is there any practical use for that? Or is it just a misconception?

Answer:
Big codebases will need it.  Look at boost for an example.  I don't think anyone would call the boost code 'insane'.
If you consider the fact that at any one level of a hierarchy, people can only comprehend somewhere very roughly on the order of 10 items, then two levels only gives you 100 maximum.  A sufficiently big project is going to need more, so can easily end up 3 levels deep.


Question:
What resources have to be manually cleaned up in C# and what are the consequences of not doing so?

For example, say I have the following code:

myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
// Use Brush

If I don't clean up the brush using the dispose method, I'm assuming the garbage collector frees the memory used at program termination? Is this correct?

What other resources do I need to manually clean up?

Answer:
Handles to internal windows data structures.
Database connections.
File handles.
Network connections.
COM/OLE references.
The list goes on.
It's important to call
```
Dispose
```
or even better yet, use the
```
using
```
pattern.
```
```
using (SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black))
{
    // use myBrush
}
```
```
If you don't dispose something, it'll be cleaned up when the garbage collector notices that there are no more references to it, which may be after some time.
In the case of
```
System.Drawing.Brush
```
, Windows will keep internal windows structures for the brush loaded in memory until all programs release their handle.


Question:
I love vim and the speed it gives me. But sometimes, my fingers are too speedy and I find myself typing :WQ instead of :wq. (On a German keyboard, you have to press Shift to get the colon :.) Vim will then complain that WQ is Not an editor command.

Is there some way to make W and Q editor commands?

Answer:
Try
```
```
:command WQ wq
 :command Wq wq
 :command W w
 :command Q q
```
```
This way you can define your own commands. See
```
:help command
```
for more information.


Question:
When programming by contract a function or method first checks whether its preconditions are fulfilled, before starting to work on its responsibilities, right? The two most prominent ways to do these checks are by assert and by exception.

assert fails only in debug mode. To make sure it is crucial to (unit) test all separate contract preconditions to see whether they actually fail.

exception fails in debug and release mode. This has the benefit that tested debug behavior is identical to release behavior, but it incurs a runtime performance penalty.

Which one do you think is preferable?

See releated question here

Answer:
Disabling assert in release builds is like saying "I will never have any issues whatsoever in a release build", which is often not the case. So assert shouldn't be disabled in a release build. But you don't want the release build crashing whenever errors occur either, do you?
So use exceptions and use them well. Use a good, solid exception hierarchy and ensure that you catch and you can put a hook on exception throwing in your debugger to catch it, and in release mode you can compensate for the error rather than a straight-up crash. It's the safer way to go.


Question:
I do not currently have this issue, but you never know, and thought experiments are always fun.

Ignoring the obvious problems that you would have to have with your architecture to even be attempting this, let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunch of wide and varied operations in the same code block, e.g.:

WidgetMaker.SetAlignment(57);
contactForm["Title"] = txtTitle.Text;
Casserole.Season(true, false);
((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true;

Multiplied by a hundred.  Some of these might work, others might go badly wrong.  What you need is the C# equivalent of "on error resume next", otherwise you're going to end up copying and pasting try-catches around the many lines of code.

How would you attempt to tackle this problem?

Answer:
```
On Error Resume Next
```
is a really bad idea in the C# world. Nor would adding the equivalent to
```
On Error Resume Next
```
actually help you. All it would do is leave you in a bad state which could cause more subtle errors, data loss and possibly data corruption.
But to give the questioner his due, you could add a global handler and check the TargetSite to see which method borked. Then you could at least know what line it borked on. The next part would be to try and figure out how to set the "next statement" the same way the debugger does it. Hopefully your stack won't have unwound at this point or you can re-create it, but it's certainly worth a shot. However, given this approach the code would have to run in Debug mode every time so that you would have your debug symbols included.


Question: If there is a cookie set for a subdomain, metric.foo.com, is there a way for me to delete the metric.foo.com cookie on a request to www.foo.com? The browser (at least Firefox) seems to ignore a Set-Cookie with a domain of metric.foo.com.

Answer:
Cookies are only readable by the domain that created them, so if the cookie was created at metric.foo.com, it will have to be deleted under the same domain as it was created.  This includes sub-domains.
If you are required to delete a cookie from metric.foo.com, but are currently running a page at www.foo.com, you will not be able to.
In order to do this, you need to load the page from metric.foo.com, or create the cookie under foo.com so it can be accessable under any subdomain.  OR use this:
Response.cookies("mycookie").domain = ".foo.com"
...while creating it, AND before you delete it.
..untested - should work.