Question:
At a new job I started, we have both a Java application that handles most of the heavy lifting in the core business logic, and we also have a Rails application that of course handles the web interface to this server.  Both of these access the same database.

Up until now, most of the focus has been on the Java application, and as such, there are no migrations in the Rails project.  The sql to update the shared database is managed in a file like changes.sql.

As you can imagine, this makes it somewhat difficult to develop.

My initial thought was to combine the codebases for the Java project and the Rails application, because there is a dependency there, and to manage that SQL file in the source.  However, I thought I'd ask here to see if anyone else had tackled this issue with some degree of success.

Answer:
One approach is to use the rails migration tools, generate the DDL files for the database and use Hibernate to update the Java objects that relate to specific database entities.  You don't really say how you manage database changes on the Java side or whether you use an ORM, but you can certainly synchronize the two with a little work.
Or you can go the other way around and let the Java definitions control changes on the Rails side.
I think the key to doing this successfully is to select one of the two platforms as your "primary database modeller" and develop the process to migrate that model to the other platform.  Attempting to allow changes from both will only cause headaches.


Question:
Is it possible to configure Windows Servers that reside on the same domain such that when a web service call is made from a web app using an IP address, the request does not go via a proxy server?

The web service is running on one of the servers on the domain.

I want to configure IP based security on the server that hosts the web service such that it only allows connections from specific servers.  Currently all requests go via the proxy server rendering IPSec problematic.

Within the browser I can specify that requests following a specific pattern should bypass the proxy server.  It's essentially this behaviour I want to replicate with the servers.

Thanks

Answer:
With ASMX the proxy can be set on the Proxy property:
http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!435.entry
With WCF, this is part of the binding configuration:
http://blogs.infosupport.com/porint/archive/2007/08/14/Configuring-a-proxy_2D00_server-for-WCF.aspx


Question: I would like to use the ispell-buffer command in Emacs. It uses the English language by default. Is there an easy way to switch to another dictionary (for example, another language)?

Answer:
From the file ispell.el you may specify some options for the
```
ispell
```
commands. This happens by adding a section to the end of your file like this:
```
```
;; Local Variables:
;; ispell-check-comments: exclusive
;; ispell-local-dictionary: "american"
;; End:
```
```
Note the double semicolon marks the start of comments in the current mode. It should probably be changed to reflect the way your file (programming language) introduces comments, like
```
//
```
for Java.


Question:
Given the Python function:

def a_method(arg1, arg2):
    pass

How can I extract the number and names of the arguments. I.e., given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2").

The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed "a,b" when I call a_method("a", "b")?

Answer:
In CPython, the number of arguments is
```
```
a_method.func_code.co_argcount
```
```
and their names are in the beginning of
```
```
a_method.func_code.co_varnames
```
```
These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.
One portable way to admit "pass-through" arguments is to define your function with the signature
```
func(*args, **kwargs)
```
. This is used a lot in e.g.
matplotlib
, where the outer API layer passes lots of keyword arguments to the lower-level API.


Question:
I've seen a couple of font topics on SO and it seems a majority of people use monospace fonts for programming tasks. I have been using Verdana for programming for a couple of years and I really like the enhanced readability, without missing anything monospace related.

Why do you use a monospace font?

Answer:
In a monospace font:
Equal-length string literals look equal.
It's easier to see thin punctuation marks like : () {}
Similar characters look more different: Il 0O vs
```
Il 0O
```
You know whether or not a line will wrap on a window X characters wide. This means that your team can standardize on say 100 character lines and a line will always look like a line


Question: How to create instance of AxHost abstract class

Answer:
You cannot create an instance of an abstract class.
You typically do not use the AxHost class directly. You can use the Windows Forms ActiveX Control Importer (Aximp.exe) to generate the wrappers that extend AxHost.
See
http://msdn.microsoft.com/en-us/library/system.windows.forms.axhost.aspx
for an example.


Question: I work for a custom cabinetry manufacturer and we write our own pricing program for our product.  I have a form that has a pop-up box so the user can select which side the hinge will be on for ambiguous doors on that cabinet.  I've got that to work so far, but when they copy an item and paste it at the bottom I don't want the pop-up box to come up.  Is there any way in Access VBA to know whether the new record is being pasted or entered manually?

Answer:
Perhaps something on the lines of this would suit.
```
```
Option Compare Database
Public gvarPasted As Boolean

Private Sub txtText_AfterUpdate()
If Not gvarPasted Then
    'Open pop-up here
Else
    gvarPasted = False
End If
End Sub

Private Sub txtText_KeyDown(KeyCode As Integer, Shift As Integer)
'Detect ctrl-V combination
If Shift = acCtrlMask And KeyCode = vbKeyV Then
    gvarPasted = True
End If
End Sub
```
```


Question:
I have been asked to audit any/all changes in a MySQL table. Does anyone know of any tools out there to help me do this or do I need to write my own solution?

If I write my own audting, my initial thought it to make a separate table and build a string of changes in the PHP code. Something like "fieldname1 -> oldvalue | fieldname2 -> oldvalue, ...". If you see a major problem with this method, please let me know.

Answer:
Use a
trigger
to detect changes and to write before/after values to a log table.


Question:
In .NET, Windows Forms have an event that fires before the Form is loaded (Form.Load), but there is no corresponding event that is fired AFTER the form has loaded.  I would like to execute some logic after the form has loaded.

Can anyone advise on a solution?

Answer:
I sometimes use (in Load)
```
```
this.BeginInvoke((MethodInvoker) delegate {
  // some code
});
```
```
or
```
```
this.BeginInvoke((MethodInvoker) this.SomeMethod);
```
```
(change "this" to your form variable if you are handling the event on an instance other than "this").
This pushes the invoke onto the windows-forms loop, so it gets processed when the form is processing the message queue.
[updated on request]
The Control.Invoke/Control.BeginInvoke methods are intended for use with threading, and are a mechanism to push work onto the UI thread. Normally this is used by worker threads etc. Control.Invoke does a synchronous call, where-as Control.BeginInvoke does an asynchronous call.
Normally, these would be used as:
```
```
SomeCodeOrEventHandlerOnAWorkerThread()
{
  // this code running on a worker thread...
  string newText = ExpensiveMethod(); // perhaps a DB/web call

  // now ask the UI thread to update itself
  this.Invoke((MethodInvoker) delegate {
      // this code runs on the UI thread!
      this.Text = newText;
  });
}
```
```
It does this by pushing a message onto the windows message queue; the UI thread (at some point) de-queues the message, processes the delegate, and signals the worker that it completed... so far so good ;-p
OK; so what happens if we use Control.Invoke / Control.BeginInvoke on the UI thread? It copes... if you call Control.Invoke, it is sensible enough to know that blocking on the message queue would cause an immediate deadlock - so if you are already on the UI thread it simply runs the code immediately... so that doesn't help us...
But Control.BeginInvoke works differently: it
always
pushes work onto the queue, even it we are already on the UI thread. This makes a really simply way of saying "in a moment", but without the inconvenience of timers etc (which would still have to do the same thing anyway!).


Question:
I have a GridView control in an Asp.net application, that has a <asp:buttonField> of type="image" and CommandName="Delete".

Is there any way to execute a piece of javascript before reaching the OnRowDelete event?

I want just a simple confirm before deleting the row.

Thanks!

EDIT: Please Note that <asp:ButtonField> tag does not have an OnClientClick attribute.

Answer:
I would use a TemplateField instead, and populate the ItemTemplate with a regular asp:Button or asp:ImageButton, depending one what is needed. You can then execute the same logic that the RowCommand event was going to do when it intercepted the Delete command.
On either of those buttons I would then use the OnClientClick property to execute the JavaScript confirm dialog prior to this.
```
```
<script type="text/javascript">
   function confirmDelete()
   {
       return confirm("Are you sure you want to delete this?");
   }
</script>

...

<asp:TemplateField>
  <ItemTemplate>
     <asp:ImageButton ID="DeleteButton" runat="server"
        ImageUrl="..." AlternateText="Delete" ToolTip="Delete"
        CommandName="Delete" CommandArgument='<%# Eval("ID") %>'
        OnClientClick="return confirmDelete();" />
  </ItemTemplate>
</asp:TemplateField>
```
```


Question:
I have a problem with Visual C++ 2008. I have installed opencv and I've created a new program and I build it with no errors. However, it complains about not finding MSVCR90D.dll when debugging. In release mode there is no problem at all.

I do have MSVCR90D.dll in one of Winsxs folders. Does anyone know a get-around to this problem? Is this a known bug?

Gerard

Answer:
There are several potential solutions described in this
forum post
. See if any of those help.
One hint from there:
Go to %System Drive%\Windows\WinSxS
  and look for the directory
  x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_597c3456
If this doesn't exist, go to the VS
  setup and make sure you have all
  libraries installed under VC++.
And another one:
I had the same problem, but fixed it
  by turning off incremental linking
  (Project properties... Linker...
  General... Enable Incremental Linking:
  No).
Confirming the last one:
Projects built on a software-mounted
  drive complain about a missing
  MSVCR90D.dll.  The problem goes away
  if you turn off incremental linking
  (and rebuild all, of course).


Question: Is there a special project type for creating a WCF to be hosted in IIS?

Answer:
I assume you're talking about VS 2008.
I can't see a way to have the WCF Service Library template use IIS for hosting. My advice is to create an ASP.NET Web Application, configure it to be IIS hosted, delete the Default.aspx file, and then add the WCF Service to the project.


Question:
I have a form that uses jQuery to submit an ajax post and it serializes the form that is sent up. The code looks like this:

var form = $("form");
var action = form.attr("action");
var serializedForm = form.serialize();
$.post(action, serializedForm, function(data)
{
  ...
});

The problem here is that if a field has trailing white space, the serialize function will turn those spaces to plus (+) signs, when they should be stripped.

Is there a way to get the fields trimmed without doing the following:

$("#name").val( jQuery.trim( $("#name") ) );

Answer:
Trim all
<input>
and
<textarea></textarea>
element values in the DOM:
```
```
$('input, textarea').each(function(){
    $(this).val(jQuery.trim($(this).val()));
});
```
```


Question: The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?

Answer:
Is object:
```
```
function isObject ( obj ) {
   return obj && (typeof obj  === "object");
}
```
```
Is array:
```
```
function isArray ( obj ) {
  return isObject(obj) && (obj instanceof Array);
}
```
```
Because arrays are objects you'll want to test if a variable is an array first, and then if it is an object:
```
```
if (isArray(myObject)) {
   // do stuff for arrays
}
else if (isObject(myObject)) {
   // do stuff for objects
}
```
```


Question:
I'm in the process of developing a social network site.

And been thinking of scalability from day one of the project, I've fine tuned the site and queries to the best of my ability.

However; Certain pages are very data heavy and I'm not quite sure if they are loading as fast as they could so I was thinking of implementing a distributed caching solution.

But not quite sure what I should cache and not cache. Or if current page load times of 1 second is good or bad.

The heaviest query is grabbing member information this query gets all the member's info and anything related to them such as in this site's case their goals, blog type entries, encouragements, photos, status updates (like twitter), blog info (for crossposting their entries) etc etc.

Anyhow, should I cache this info? And do you think 1 second page load times are reasonably fast? Some pages are less than a second between 4-6 10ths of a second.

Answer:
The page loading question was already asked:
What is considered a good response time for a dynamic, personalized web application?
In terms of caching, you have to measure the amount of time that would be spent loading the data each time versus loading from the cache. The bigger the cache, the less effective it becomes. So you don't want to load too much data into the cache. What we use here is a rolling cache, with the least recently used data being dropped once we hit the cache size limit. You then tune the limit according to actual performance results.


Question:
I am wondering how the JBoss ExceptionSorter classes are able to check for database errors.

The application (the EJB or persistence framework) is holding the reference to the database Connection, so SQLExceptions are caught by the application. How is JBoss able to see the contents of the exception?

Does JBoss wrap the connection and intercept these messages or something like that?

Answer:
JBoss uses a connection pool for its datasources (org.jboss.resource.adapter.jdbc.local.LocalTxDataSource). The ExceptionSorter takes an SQLException as a parameter which it then just checks for certain strings which map to certain errors. If the errors represent a physical connection problem then they will look somewhat like "Socket error" or "broken pipe".
This Exception Sorter will then return a boolean value representing the state of the connection back to the connection pool which will then invalidate and remove any connections that returned false.
For an Oracle database:
```
```
<property name="exceptionSorterClassName"><value>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</value></property>
```
```
This will work for an Oracle database. Here is the code for that ExceptionSorter implementation:
http://kickjava.com/src/org/jboss/resource/adapter/jdbc/vendor/OracleExceptionSorter.java.htm
How the internal programming of where or how the connection pool checks the connection is unknown to me. Check the JBoss source code.


Question:
I have three Java JCheckboxes in a column, arranged by setting the layout of the container JPanel to GridLayout(3, 1, 1, 1).  When I run the program, there is too much vertical space between the JCheckBoxes; it looks like more than 1 pixel.  Since I've already set the vertical space between the JCheckboxes in the layout to be 1 pixel, how else can I reduce the vertical space between these JCheckboxes?

Thanks.

Answer:
I explored using
```
GridLayout
```
,
```
BorderLayout
```
, and
```
GridBagLayout
```
and I believe that any extra vertical space that is present in your application is due to the sizing of the JCheckBox component, not related to the layout manager. All of the examples below have no space between components in the layout manager.
GridLayout
```
```
//Changing to 3,1,1,0 makes slightly smaller (1 pixel) gap vertically
GridLayout layout = new GridLayout( 3, 1, 1, 0 );
JPanel main = new JPanel( layout );
main.add( new JCheckBox( "box 1" ) );
main.add( new JCheckBox( "box 2" ) );
main.add( new JCheckBox( "box 3" ) );
```
```
GridBagLayout
```
```
GridBagConstraints gbc = new GridBagConstraints();
JPanel main = new JPanel( new GridBagLayout() );
gbc.gridx=0;
gbc.gridy=0;
gbc.ipady=0;
main.add( new JCheckBox( "box 1" ), gbc );
gbc.gridy=1;
main.add( new JCheckBox( "box 2" ), gbc );
gbc.gridy=2;
main.add( new JCheckBox( "box 3" ), gbc );
```
```
BorderLayout
```
```
JPanel main = new JPanel( new BorderLayout() );
main.add( new JCheckBox( "box 1" ), BorderLayout.NORTH );
main.add( new JCheckBox( "box 2" ), BorderLayout.CENTER );
main.add( new JCheckBox( "box 3" ), BorderLayout.SOUTH );
```
```


Question:
I need to give users the ability to optionally add metadata to documents. Another way to state this is the fact that users need to add at least 5 categories to a document.

Basically what I want to do is dynamically add metadata (or categories) to a document on an ad hoc basis. Here are the options that I have thought of:

Option 1:
Should I do this by dynamically creating new table columns in the database?

Option 2:
Should I define 5 columns called attirbute1,attirbute2,attirbute3,attirbute4,attirbute5 and then only use and show them if the user requires the attributes.

Option 3:
Should I create a metadata table that keeps track of the columns and the data associated with them?

What do you think is the best way to achieve this? Can you think of any other ways to easily add this functionality. The problem is that the functionality needs to be very generic.

Answer:
Each document has a unique DocumentID.
Just add another table that has three columns:
```
DocumentID
MetaName
MetaData
```
Then they can add as many pieces of metadata to a given document.  If all their documents use the same metanames then it's trivial to search the metadata.
-Adam


Question:
I have data from MySQL showing all organisations a customer got, with all details of employess in each organisation. I want to list each organisation name only once i.e. in a single cell ( row span) and all employees in that organisation against this name like:

Org1     Emp1 Name, Emp1 Phone, Emp1 Address
         Emp2 Name, Emp2 Phone, Emp2 Address

Org2     Emp1 Name, Emp1 Phone, Emp1 Address
         Emp2 Name, Emp2 Phone, Emp2 Address

How do I display this data because the number of employess for each organisation is not known in advanced, so I do'nt about setting value of rowspan. Similarly how do I start a row for other organisation? Do I have to write two queries?

Many Thanks.

Answer:
Classic.
Workaround: only display the name if different than the previous one. You can even not bother about the rowspan (you keep an empty cell).
```
```
$currentOrg = '';
while ($row = mysql_fetch_object($query)) {
   if ($row->org != $currentOrg) {
      echo "$row->org".
   }
   $currentorg = $row->org;
}
```
```
Not the most beautiful but so simple.


Question:
We all know the good old "disable the submit button" trick but what are the best ways to handle multiple submissions server side? I have an application where it is absolutely critical that a form only be sent once - it processes a credit card. I didn't write how it is right now but as a quick fix I threw on the disable-on-submit technique, however some impatient users that have javascript disabled are still getting charged twice.

So, what are ways to avoid this? I can think of a few - I have used a few in the past - but I'd like to see if there's any "best practices" on how to tackle this one. I am using PHP but I'm more interested in concepts.

edit: I am aware of the token technique and it is what I have used in the past, this question is more or less to see if my approach is in line with what the rest of you fine programmers use.

Answer:
One really effective way is to submit a token along with the request, and keep a list of used tokens. If the token is not valid, or the token has already been processed, then abort.
The token can be as simple as an incrementing integer, stored in a hidden text field, or you can encrypt it to increase security. This feature can be made more robust by generating the token when the page is created, encrypting it, then confirming the token has been generated AND has not been processed.


Question:
Is there a best way to turn an integer into its month name in .net?

Obviously I can spin up a datetime  to string it and parse the month name out of there. That just seems like a gigantic waste of time.

Answer:
Why not just use
```
somedatetime.ToString("MMMM")
```
?


Question: I'm trying to connect from my Java application to a development server that has port 8088 closed which is used for RMI. I appreciate any help on how to open that port.

Answer:
Slicehost have some good documentation on setting up iptables on Ubuntu:
http://articles.slicehost.com/2008/4/25/ubuntu-hardy-setup-page-1
http://articles.slicehost.com/2008/9/2/mail-server-opening-ports-in-the-firewall


Question: I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome.

Answer:
This is pretty much Python-independent!  It's a classic example of Unix interprocess communication.  One good option is to use
```
popen()
```
to open a pipe between the parent and child processes, and pass data/messages back and forth along the pipe.
Take a look at the
```
subprocess
```
module
, which can set up the necessary pipes automatically while spawning child processes.


Question: Is there a simple Model Checker tool. I am planning to implement a model checker tool which will analyze the code for some of the predefined properties.

Answer:
CBMC
is one simple-ish tool I'm aware of that actually operates on code.  Model checking in general is a heavily-researched field, but as folks have already commented, this breadth makes it difficult to suggest something with the info provided.  There are thousands of SAT solvers, formal tools for HDL/state machine verification, and plenty of commercial static source analyzers.
In any case, CBMC is a good tool, but don't take my word for it; Ed Clarke, the main faculty member behind this work, won the Turing Award this year ;-)


Question:
I want to use Sharepoint with python (C-Python)

Has anyone tried this before ?

Answer:
SharePoint exposes several web services which you can use to query and update data.
I'm not sure what web service toolkits there are for Python but they should be able to build proxies for these services without any issues.
This article should give you enough information to get started.
http://www.developer.com/tech/article.php/3104621


Question:
We have inherited an ant build file but now need to deploy to both 32bit and 64bit systems.

The non-Java bits are done with GNUMakefiles where we just call "uname" to get the info.  Is there a similar or even easier way to mimic this with ant?

Answer:
You can just pass a parameter into the build file with the value you want. For example, if your target is
```
dist
```
:
```
```
ant -Dbuild.target=32 dist
```
```
or
```
```
ant -Dbuild.target=64 dist
```
```
and then in your Ant build script, take different actions depending on the value of the
```
${build.target}
```
property (you can also use
conditions
to set a default value for the property if it is not set).
Or, you can check the value of the
built-in
system properties
, such as
```
${os.arch}
```
.


Question:
I am still new to sharepoint and would like to know if it is possible to make a query that works across several lists. My list looks like this

Customers (id, name and so forth)
Orders ( id, order number, customer and some additional info)
OrderItems (id, name, price, description and so on)

I would like to create a view that will display the OrderItems grouped by Order which again will be grouped by Customer.

In pure .net code that is pretty easy but is it possible to implement it only using sharepoint lists?

Answer:
Without custom code or third party components you would have only a few options. Using SharePoint Designer to create a Data View or creating a custom Query with some complex CAML which I'm not even sure is entirely possible.
Personally I would look more towards using Master Detail functionality using a combination of web part connections and filtering. By activating Enterprise features you have available a number of Filter Web Parts that should be able to be combined to filter lists to selected values.
Personally I have gone with custom code to bring back list data based on queries and then used the GetDataTable() method of the SPListItemCollection object. Once you have the list items in DataTables you have numerouse ways to sort filter and aggregate the information.
I should add to this that there is a great article on displaying information from a dataset using the SPGridView and SPMenuField. Once you have your DataTables you could establish relationships in a dataset to display the information using these controls:
http://blogs.msdn.com/powlo/archive/2007/02/25/displaying-custom-data-through-sharepoint-lists-using-spgridview-and-spmenufield.aspx


Question:
If I view the HTML generated by one of my Jasper reports in IE7 I see the following:

<BR /><BR />
<A name="JR_PAGE_ANCHOR_0_1">
<TABLE style="WIDTH: 1000px" cellSpacing="0" cellPadding="0" bgColor="#ffffff" border="0">
<-- table body omitted -->
</TABLE>

The two BR tags are added via the JRHtmlExporterParameter.HTML_HEADER parameter. After these tags and before the beginning of the report table that there's an unclosed anchor tag that is generated by Jasper reports. The fact that this tag is not correctly closed is messing up the formatting of my report because IE is hyperlinking the entire report TABLE. I'm not using this anchor tag, so if I could prevent Jasper from generating it, that would solve my problem.

Incidentally, this problem only occurs in IE, in Firefox everything works fine because the anchor tag is properly closed.

Thanks in advance,
Don

Answer:
That's odd code, the
```
<br />
```
tags are XHTML-style, while the unclosed
```
a
```
tags are good old HTML, like the upper case tag names. If you serve such page with plain HTML header/content-type, perhaps IE will be happy.
When you write that Firefox closes the tag, I suppose you mean it correctly doesn't extend the hyperlink span over block tags. Note that FF's view source can display closing tags that are not there when you save the page to disk!
Frankly, I don't know if you can get rid of these anchors with some config. If nobody comes with a real solution, maybe you can download Jasper's source code and search JR_PAGE_ANCHOR in it, looking if the code generating it is conditionally driven.
Or, if you can, you can apply post-processing of the generated code.


Question:
Our clients use a vb6 version of our software.

We are upgrading them to a .NET application written in C#...

Is there less bulk using .net 2.0 than .net 3.5?

My definition of less bulk would be: Smaller size, smaller installation time, etc.

Most of them probably already have 2.0 anyway.

I only ask because I would like to take advantage of LINQ in 3.5.

Answer: If you would like to take advantage of LINQ, then go for 3.5! I find there's not more 'bulk' when using it myself, but unless you want to use LINQ, then either is fine.


Question:
In ActivePerl, "ppm" installs a package from the Internet, "ppm install x.ppd" installs from a ppd file, but most CPAN packages are distributed as .tar.gz

How do you supply modules to a machine running ActivePerl that doesn't have an Internet connection?  ("make" will probably not be available.)

Update: an Internet connection can be used to download files and transfer them to the machine with a USB key, etc.

Answer:
See:
http://docs.activestate.com/activeperl/5.10/faq/ActivePerl-faq2.html#zip_files


Question:
When my application opens too many windows the taskbar groups them into one button. Each window has its own icon, but the grouping icon is the default "unknown"-kind icon.

How can I set the grouping icon?

Answer:
The taskbar group icon can be set in the registry on a per application basis.
For explorer, this would be here:
```
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Applications\explorer.exe]
"TaskbarGroupIcon"="C:\Windows\Explorer.exe,13"
```
```


Question:
Obviously I could create a Calendar object with the date and use get(DAY) on it, but knowing Groovy, I would guess there is an easier, quicker way I just don't know about?

Answer

(date1..date2).size() == 1 // true if two dates are on same calendar day

Answer:
Quickly opened the Groovy In Action book and found the following sample that should help:
```
```
def today = new Date()
def yesterday = today-1
assert (yesterday..today).size() == 2
```
```


Question:
I have been reading carefully through the mediawiki documentation but I have not been able to find out how to create new groups.

When I look at Special:Userrights, I see only 3 groups :
Bots, Sysops, Bureaycrats

I would like to create my own custom groups, so I can use some extensions like the http://www.mediawiki.org/wiki/Extension:Group_Based_Access_Control.

Can someone tell me how it's done, or point me to some documentation?

Answer:
I beleive I have found the answer, I just need to add the UserGroup and the permission to the wgGroupPermissions array in the LocalSettings.php file.
```
```
$wgGroupPermissions['TomatoUsers']['read']  = true;
$wgGroupPermissions['TomatoUsers']['edit']  = false;
```
```


Question:
I need to run a Linux CLI command and get its stdout output from C.

I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.

Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.

There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status.

Answer:
Use
```
popen()
```
and
```
pclose()
```
.
```
popen()
```
does not actually wait, of course, but reads on the pipe will block until there is data available.
```
pclose()
```
waits, but calling it prematurely could cut off some output from the forked process. You'll want to determine from the stream when the child is done...
Possibly already discussed at
How can I run an external program from C and parse its output?


Question:
We've got a fairly large amount of code that just made the jump to Java 5. We've been using generics in those components targeted at being released in the Java 5 version, but the remaining code is, of course, full of raw types. I've set the compiler to generate an error for raw types and started manually clearing them, but at the present rate it'll take a very long time to go through with it (there are about 2500 errors). And that's with Eclipse's helpful Infer Generic Type quick fix, which always gets rid of the errors, but often generates code that needs further work.

Is there any better way to dealing with this? Are there any automated tools better than Eclipse? Any way to apply the refactoring to all occurences instead of doing them one-by-one? Or do you just ignore the warnings?

Answer:
I would suggest ignoring the warnings.  Otherwise, you'll be putting a lot of time into updating the legacy code without making any improvements to its functionality.
Update:
Great comment from
Luke
that I thought should get more visibility:
"Generics are a way to catch run time bugs at compile time. Unless this legacy code has bugs in it that you think are related to casting I would leave it alone (if it ain't broke, don't fix it)"


Question: I installed Python 2.6 for one user on Windows Vista.  Python works okay, but when I try: import Tkinter, it says the side-by-side configuration has errors.  I've tried tinkering with the Visual Studio runtime, with no good results.  Any ideas on how to resolve this?

Answer: Maybe you should downgrade to 2.5 version?


Question: Is it possible to to change a <span> tag (or <div>) to preformat its contents like a <pre> tag would using only CSS?

Answer:
Look at the
W3C CSS2.1 Default Style Sheet
or the
CSS2.2 Working Draft
. Copy all the settings for PRE and put them into your own class.
```
```
pre {
    display: block;
    unicode-bidi: embed;
    font-family: monospace;
    white-space: pre;
}
```
```


Question:
function Submit_click()
{
  if (!bValidateFields())
    return;
}

function bValidateFields() {
/// <summary>Validation rules</summary>
/// <returns>Boolean</returns>
...
}

So, when I type the call to my bValidateFields() function intellisence in Visual Studio doesn't show my comments. But according to this it should. Should it?

Answer:
Did you try adding the
```
/// <reference>
```
comment at the top of the external library?  I've run into this in the past and it resolved my issue.


Question:
I'm looking for a way to transform a genuine string into it's hexadecimal value in SQL. I'm looking something that is Informix-friendly but I would obviously prefer something database-neutral

Here is the select I am using now:

SELECT SomeStringColumn from SomeTable

Here is the select I would like to use:
    SELECT hex( SomeStringColumn ) from SomeTable

Unfortunately nothing is that simple... Informix gives me that message:
Character to numeric conversion error

Any idea?

Answer:
Can you use Cast and the fn_varbintohexstr?
```
```
SELECT master.dbo.fn_varbintohexstr(CAST(SomeStringColumn AS varbinary))
FROM SomeTable
```
```
I'm not sure if you have that function in your database system, it is in MS-SQL.
I just tried it in my SQL server MMC on one of my tables:
```
```
SELECT     master.dbo.fn_varbintohexstr(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM         Customer
```
```
This worked as expected. possibly what I know as master.dbo.fn_varbintohexstr on MS-SQL, might be similar to informix hex() function, so possibly try:
```
```
SELECT     hex(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM         Customer
```
```


Question: Nowadays, we have tons of Javascript libraries per page in addition to the Javascript files  we write ourselves.  How do you manage them all?  How do you minify them in an organized way?

Answer:
First of all,
YUI Compressor
.
Keeping them organized is up to you, but most groups that I've seen have just
come up with a convention
that makes sense for their application.
It's generally optimal to
package up your files
in such a way that you have a small handful of packages which can be included on any given page for optimal caching.
You also might consider dividing your javascript up into segments that are
easy to share
across the team.


Question: We have a small 3 developer team that is currently using Subversion for our source control. We expect the team to group to 8 members within the next 6 to 12 months. We are considering changing our source control to either TFS or Mercurial for improved branching. I know TFS is overkill for just branching, but that is the immediate need, and the other features of TFS could aid our team. One of our main concerns with TFS is we've heard that there is a lot of overhead deploying it, especially on a small team. I'm hoping to get some community insight into just how much overhead there may be involved, suggestions to make the process easier, and anything else the community may feel is useful in making the decision to implement.

Answer:
It's been awhile, but I'm thinking that it takes about a half-day to get setup, plus some time reading the manuals beforehand to make sure you know what you're doing.  Configuration doesn't take too long -- you need to add all of your developers in as licensed users.  Setting up projects is not too hard.  I usually set up AD groups to map on the project roles and add those groups to the appropriate roles.  I set up a new project in about 1/2 hour.
Note: I don't use any of the features of TFS except source control.  If you plan to item tracking, use the project sharepoint site, etc., your mileage will vary quite a bit.  I've found that on our projects (2-3 developers) a wiki works just as well for project management.


Question:
I want to display some WPF elements near to the selected item of a ListView. How can I obtain the coordinates (screen or relative) of the selected ListViewItem?

<ListView
    x:Name="TechSchoolListView"
    ClipToBounds="False"
    Width="Auto" Height="Auto"
    HorizontalContentAlignment="Stretch"
    VerticalContentAlignment="Top"
    ItemTemplate="{DynamicResource TechSchoolDataTemplate}"
    ItemsSource="{Binding Path=TechSchoolResearchList, Mode=Default}"
    SelectedIndex="1"
    SelectedValue="{Binding Path=SelectedTechSchool, Mode=Default}"
    SelectionChanged="TechSchoolList_SelectionChanged"
    ItemContainerStyle="{DynamicResource TechSchoolItemContainerStyle}"
    ScrollViewer.CanContentScroll="False"
    ScrollViewer.VerticalScrollBarVisibility="Disabled" >
    <ListView.Background>
        <SolidColorBrush Color="{DynamicResource PanelBackgroundColor}"/>
    </ListView.Background>
</ListView>

Answer:
You should use
ContainerFromElement
to get the item's container, which is a visual and from there you can get the coordinates. You can't express this in XAML, however. You need to do it in code, on one of the ListView events, raised when the selected item is changed. Btw, keep in mind that the item can be its own container.
You can't do this in XAML, as there's no attached property on the item that shows the item is selected. (though I haven't played with WPF in a while, so that might have changed)


Question:
I'm writing a mobile content adaptation plugin for a bespoke CMS in PHP. The CMS contains <img/> links to images with absolute URLs which are all 400 pixels wide and vary in height.

I'd like to parse the HTML (which is stored in MySQL) and re-scale each image to a new width - this will vary according to the device. I'd also like to cache the images to prevent needlessly resizing them on-the-fly every time the page is loaded

What's the best way for me to achieve this in PHP using either ImageMagick or GD?

Answer:
what about doing something a bit different. basically off load the caching/resizing to an on demand model. so say your application is being run on device A, which requires 200x200 images. you'd change the image links to:
```
```
<img src="/images/image.php?height=200&width=200&source=filename.jpg" />
```
```
image.php could be a script which does the following:
make sure the existing file exists, and grab it from cache if it exists at this size
if not, resize the image and cache it
the next time your app looks for that image, it would be sent back at the 200px size. alternatively, if the app is now looking for a 300x300 image, that would be built/cached on the new request.


Question:
I'm currently maintaining a CVS repository for source control.  There is a push afoot to move to StarTeam.  It has already been purchased and is a corporate standard for most projects.  I was told by the corporate owners of the StarTeam servers that there is no known way to do a complete migration of our current CVS repository to StarTeam.  We have been advised to do a checkout of the latest version and import that into StarTeam.

I would really prefer to keep all of my version history and not have to choose between simply losing all of the data or maintaining my CVS repository indefinitely.

Has anybody had any luck doing this?  Any recommended tools or processes?  Or am I just wasting my time and I should just migrate and cut my losses?

UPDATE: The official response from Borland is that this is definitely doable, but not with the boxed software.  I can purchase services from Borland to help me accomplish this.

Answer:
I wonder why a "professional" tool does not provide any means to import from well known legacy systems...
Although it may sound queer at first, i would recommend converting the cvs repos to subversion ( using e.g.
cvs2svn
, offered by tigris.org ), and then creating your own script to update from the subversion repos and commit into the starteam repository, provided it does offer an api or an command line client.
The advantage is that subversion supports nicely things like omitting branches or directories, and offer access via an api, which cvs does not.
Also, the documentation on subversion is quite extensive. (
example
on using the subversion api from python
Good luck!


Question:
I've developed an application (C#) that currently sits on a a number of workstations.  Each workstation accesses the same database (MS-SQL).  I've been asked to port this to Citrix.  Can anyone offer insight into documentation or suggestion of where someone would start with this?  Is the application installed on the Citrix server and then simply made available to users or do I need to do further development to make it ready for this type of deployment?

Can anyone offer insight into Citrix application development?

Answer:
For fairly straight forward app things just run.
Does you app need use localization configuration?  i.e. time / date or currency formatting?  There are Citrix settings that can do many things in this area.  The users computer settings can be "projected" into Citrix or they could be overridden in Citrix.
Also do you use the machine name for anything?  That will be the server name and not the users local machine name.
You can get a bit of a simulation in a Windows Server environment by getting a couple of remote desktop sessions running your app.


Question:
Working through some programming interview challenges I found online, I had to write an algorithm to reverse a const char * and return a pointer to a new char *. I think I have it, but to make it work properly I had to do some wonky stuff - basically having to account for the null-terminating character myself. Somehow I feel this is wrong, but I'm stumped, and I was wondering if someone could help me out:

char * reverse(const char * str)
{
  int length = strlen(str);
  char * reversed_string = new char[length+1];

  for(int i = 0; i < length; ++i)
  {
    reversed_string[i] = str[(length-1) - i];
  }
  //need to null terminate the string
  reversed_string[length] = '\0';

  return reversed_string;

}

int main(int argc, char * argv[])
{

  char * rev_str = reverse("Testing");

  cout << "Your string reversed is this: " << rev_str << endl;

  delete rev_str;
  rev_str = 0;

  return 0;
}

Answer:
I had this question once. That's the first answer that comes to mind, but the follow-up is, "now do it without allocating any memory."
```
```
int length = strlen(string);
for(int i = 0; i < length/2; i++) {
  char c = string[i];
  string[i] = string[length - i];
  string[length - i] = c;
}
```
```
EDIT: Some folks have expressed disdain for not using pointers. This is a tiny bit more readable, though not completely optimal. Others have entered the pointer solution, so I won't repeat it here.
One commenter challenged that it should be doable without a (stack based) holding cell for the swap. The mechanism for doing that is bitwise XOR. Replace the inside of the loop with
```
```
string[i] = string[i] ^ string[length - i];
string[length - i] = string[i] ^ string[length - i];
string[i] = string[i] ^ string[length - i];
```
```
But in general, modern compilers can optimize out the local variable of a naive swap. For details,
See Wikipedia


Question:
What query can return the names of all the stored procedures in a SQL Server database

If the query could exclude system stored procedures, that would be even more helpful.

Answer:
```
```
select *
  from dbo.sysobjects
 where xtype = 'P'
   and status > 0
```
```


Question:
I have two methods that I need to call in my WCF application from the client.

Authenticate(username, password)
GetUser(username)

Is it possible to combine these calls to avoid so many calls being sent back/forth?

Answer:
There are a few ways to handle this type of thing. First, you can use WCF sessions to initiate a group of commands that need to maintain some context between calls:
http://msdn.microsoft.com/en-us/library/ms733136.aspx
Secondly, you can take advantage of WCF's support for WS-Security standards to avoid the need to pass credentials as a second call:
http://msdn.microsoft.com/en-us/library/aa702565.aspx


Question:
I'm working with a client that needs to generate millions of the alphanumeric codes used in magazine scratch-off cards, bottlecap prizes, and so on. They have to be short enough to print on a cap, they want to make sure that ambiguous characters like 1 and I, 0 and O, etc. are not included, and they have to be explicitly stored for future use -- we can't just have an algorithm that determines 'validity' when someone tries to redeem one. Finally, they want to make sure that the codes are randomly distributed inside of a large "code space" so that people can't just guess additional codes by walking through the alphabet.

Are there any pointers towards reasonably efficient algorithms for generating these kinds of code sets? I've scratched a few out on the back of an envelope, but this problem smells like a trap for the unwary.

Answer:
Let's suppose you can use a character set of, say, 40 symbols of unambiguous upper,lower and numeric characters.
For a sequence of n chars, you've got 40
n
combinations
40
4
= 2,560,000
40
5
= 102,400,000
40
6
= 4,096,000,000
40
7
= 163,840,000,000
40
8
= 6,553,600,000,000
Thus 8 chars gives a pretty good space to work in - if you generated 10 million codes, you'd have to try hundreds of thousands of combinations to brute force a code.
Or you come at from the other direction - give the number of
possible
codes, how many codes
should
you generate to avoid the trap they call the
Birthday Paradox
?
Taking the 8 char code, 6,553,600,000,000 is approx 2
42
, thus you might reasonably generate 2
21
codes from it, or 2,097,152


Question:
What I'm looking for is a basic equivalent of JavaScript's Array::join() whereby you pass in a separator character and uses that in its return string of all the subscripts.  I could certainly write my own function using a StringBuilder or whatnot, but there must be something built into the .NET BCL.

EDIT: Array of anything, not necessarily string or char.  I'd prefer the method to simply call ToString() on each subscript object.  String.Join() is great except that you pass it an array of strings.

Answer:
If the array contains strings, you can just use
```
String.Join()
```
.  If the array does not contain strings, you'll need something a little more complicated so you can handle the cast or conversion process for each item it contains.
Update:
Using @JaredPar's code as the basis for a more generic example:
```
```
char sep = GetSeparatorChar();
object[] toJoin = GetToJoin();
string joined = toJoin.Aggregate((x,y) => x.ToString()+sep.ToString()+y.ToString());
```
```
Obviously you could do anything you wanted to x and y in that example to get the string to look how you wanted.


Question:
I remember working on a project with a group of developers and they always wanted static
 html text to be inside of an out tag (<c:out value="words" />). I don't remember why
 this was the case.

Is this really a best practice when building jsp pages?  What are the
advantages/disadvantages of such an approach?

Answer:
If you're just printing out plain text it's better to do it in HTML.  The advantage of the
```
c:out
```
tag is that you can evaluate expressions inside the tag.
```
```
<c:out value="Hello ${user.firstName} ${user.lastName}"/>
```
```


Question:
I have a site I'm working on that has an event page.  The owner wants to be able to edit the event page weekly.  Would it be easier to teach the site owner how to edit this one page and upload it or use a CMS just for this one page??

Apart from a contact form that posts to an email addy, the rest of the site is static.  Therefore I'd need to add in a db to store the username and password for CMS login.

If CMS then which one would be most suitable for this case?

Answer:
It depends on the complexity of the page. If it's a fixed structure where the client won't want to add links of photos you may want to give them the ability to edit a simple data file (not the page itself). Then read in the data file. I like to use a simple JSON format for this type of thing.
At least with a data file you can revert to an older version or handle the error gracefully, rather than having the client break the whole page.
If you want to go the CMS route,
Drupal
has a very well-established comunity with plenty of add-ons.
If you're more into roll-your-own programming, you can also look at the
Google Calendar API
,


Question: I need to store a url in a MySQL table. What's the best practice for defining a field that will hold a URL with an undetermined length?

Answer:
```
VARCHAR(512)
```
(or similar) should be sufficient.  However, since you don't really know the maximum length of the URLs in question, I might just go direct to
```
TEXT
```
.  The danger with this is of course loss of efficiency due to
```
CLOB
```
s being far slower than a simple string datatype like
```
VARCHAR
```
.


Question:
I was asked for a comprehensive breakdown on space used within a specific database.
I know I can use sys.dm_db_partition_stats in SQL Server 2005 to figure out how much space each table in a database is using, but is there any way to determine the individual and total size of the stored procedures in a database? (Short of opening each one and counting the characters, of course.)

Total space used by stored procs is not likely to be significant (compared to actual data), but with hundreds of them, it could add up.

Answer:
A slightly better way than counting the characters, is to use information schema.routines.  You could sum the length of each Routine Definition as (Note each routine definition will max out at 4,000 characters, see below for a method that doesn't have this restriction):
```
select Sum(Len(Routine_Definition)) from information_schema.routines
where routine_type = 'PROCEDURE'
```
Or you could return the length of each sp
```
select Len(Routine_Definition), * from information_schema.routines
where routine_type = 'PROCEDURE'
```
It's unlikely that the length of your stored procedures is the problem.  Usually running out of space with a database is due to things like not backing up the log file (and then shrinking it using dbcc shrinkfile or dbcc shrinkdatabase).
In Sql 2000, here is a routine that would provide the length without the 4000 character limit of above:
```
DECLARE @Name VarChar(250)
DECLARE RoutineCursor CURSOR FOR
   select Routine_Name from information_schema.routines where routine_type = 'PROCEDURE'

DECLARE @Results TABLE
   (   SpName   VarChar(250),
       SpLength   Int
   )

CREATE TABLE ##SpText
   (   SpText   VarChar(8000)   )

OPEN RoutineCursor
FETCH NEXT FROM RoutineCursor INTO @Name

WHILE @@FETCH_STATUS = 0
   BEGIN
      INSERT INTO ##SpText   (SpText)   EXEC sp_helptext @Name

      INSERT INTO @Results (SpName, SpLength) (SELECT @Name, Sum(Len(SpText)) FROM ##SpText)
      TRUNCATE TABLE ##SpText

      FETCH NEXT FROM RoutineCursor INTO @Name
   END

CLOSE RoutineCursor
DEALLOCATE RoutineCursor
DROP TABLE ##SpText

SELECT SpName, SpLength FROM @Results ORDER BY SpLength DESC
SELECT Sum(SpLength) FROM @Results
```


Question: I'm looking to add a tooltip to each row in a bound datagrid in vb.net winforms.  How can this be done?

Answer:
I haven't tried this myself but I would give it a shot:
```
```
System.Windows.Forms.ToolTip formToolTip = new System.Windows.Forms.ToolTip();
formToolTip .SetToolTip(item, "Row Tooltip");
```
```
Where
```
item
```
corresponds to the cell you're setting the tool tip for.


Question:
What is the best way to localize a collection (IEnumerable)?
From the BL I retrieve a collection of entities which still need to localized, I figured I write a method which extends the IEnumerable and returns the localized list.

How can i get the code underneath working? Any ideas? Maybe better options?

public static IEnumerable Localize(this IEnumerable items, CultureInfo cultureInfo)
{
    foreach(string item in items)
    {
        /*Error underneath, cannot assign to item*/
        item = ResourceHelper.GetString(item, cultureInfo);
    }
    return (items);
}

Answer:
have you tried something where you
yield
the item?
```
```
public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo culture)
{
    foreach (string item in items)
    {
        yield return ResourceHelper.GetString(item,culture);
    }
}
```
```
this won't change any other the items in the collection you are enumerating over, but it will return what you want it to.


Question:
I'm wondering what the best way is to have a "if all else fails catch it".

I mean, you're handling as much exceptions as possible in your application,
but still there are bound to be bugs, so I need to have something that
catches all unhandled exceptions so I can collect information and store
them in a database or submit them to a web service.

Does the AppDomain.CurrentDomain.UnhandledException event capture everything?
Even if the application is multithreaded?

Side note: Windows Vista exposes native API functions that allow any application
to recover itself after a crash... can't think of the name now... but I'd rather not
use it, as many of our users are still using Windows XP.

Answer:
In ASP.NET, you use the
```
Application_Error
```
function in the
```
Global.asax
```
file.
In WinForms, you use the
```
MyApplication_UnhandledException
```
in the
```
ApplicationEvents
```
file
Both of these functions are called if an unhandled exception occurs in your code. You can log the exception and present a nice message to the user from these functions.


Question:
How would you convert a parapraph to hex notation, and then back again into its original string form?

(C#)

A side note:  would putting the string into hex format shrink it the most w/o getting into hardcore shrinking algo's?

Answer:
```
```
public string ConvertToHex(string asciiString)
{
    string hex = "";
    foreach (char c in asciiString)
    {
        int tmp = c;
        hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}
```
```


Question: My application uses an event tap to capture keyboard events, and I'd like to know which device (i.e. which keyboard) each event comes from. Is there an sort of device-identifying information along with the CGEvent that a tap gets? I've looked at NSEvent's methods, and the various CGEventField keys, but none of them seem to be device-unique. Any help?

Answer:
You might want to take a look at DDHidLib, Dave Dribin's excellent framework to work with USB HID devices independently.
http://www.dribin.org/dave/blog/archives/2007/03/19/ddhidlib_10
(not just about joysticks, so read more than the first paragraph of that blog post)
Some of the functionality of DDHidLib no longer works under Leopard, due to some security concerns at Apple regarding capturing an HID device, but if you're lucky it might provide you with what you need.


Question:
The code is,

set VAR=before

if "%VAR%" == "before" (

  set VAR=after;

  echo %VAR%

)

What will the preceding Windows .bat file code segment display?  Why? (i.e. why doesn't it behave as you might first think)?

Answer:
Obviously, you'd think the output would be "after", given that we reset the env variable inside the loop.
But the output will actually be "before".  The reason is that variable substitution is done in .bat files by the interpreter when a command is read, rather than when it's executed.  So, for the compound statement, the variables in the body are evaluated when the if statement is first encountered.
You can make this work by using delayed environment variable expansion (need to enable it).  If it's enabled, you can then do:
```
```
set VAR=before

if "%VAR%" == "before" (

  set VAR=after;

  echo !VAR!

)
```
```
You can enable delayed environment variable expansion using the /v option when starting cmd.exe.
[Backstory--many of us still use legacy .bat files to drive things like make procedures, etc.  Obviously there are better scripting tools, but not always an option to use them.  I ran into this issue a while back and recently found two other people who had pulled their hair out over the same thing.  So it's useful to understand how the interpreter does variable substitution].


Question:
Could someone please explain the best way to connect to an Interbase 7.1 database using .NET/C#?

The application will be installed on many end user computers so the less "add-ons" that I will have to package with my application the better.

Answer:
Check this providers:
Interbase and Firebird Developer's for Visual Studio .Net
Firebird .NET Data Provider
FireBird - InterBase .NET (Mono) Providers


Question:
A cross join performs a cartesian product on the tuples of the two sets.

SELECT *
FROM Table1
CROSS JOIN Table2

Which circumstances render such an SQL operation particularly useful?

Answer:
You're typically not going to want a full Cartesian product for most database queries.  The whole power of relational databases is that you can apply whatever restrictions you might be interested in to allow you to avoid pulling unnecessary rows from the db.
I suppose one contrived example where you might want that is if you have a table of employees and a table of jobs that need doing and want to see all possible assignments of one employee to one job.


Question:
I am completely new to LINQ in C#/.NET.  I understand that I could use it to convert a DataSet into an Array/List, am I able to go in the opposite direction?

I'm using NPlot to generate a graph of captured prices, which are stored in a List, where PriceInformation is a class containing two public doubles and a DateTime.

Any suggestions very welcome.

Answer:
There's a method called
CopyToDataTable
.  That method will only help if you already have a IEnumerable(DataRow)
Here's how I'd do this:
```
```
//extension method to convert my type to an object array.
public static object[] ToObjectArray(this MyClass theSource)
{
  object[] result = new object[3];
  result[0] = theSource.FirstDouble;
  result[1] = theSource.SecondDouble;
  result[2] = theSource.TheDateTime;

  return result;
}

//some time later, new up a dataTable, set it's columns, and then...

DataTable myTable = new DataTable()

DataColumn column1 = new DataColumn();
column1.DataType = GetType("System.Double");
column1.ColumnName = "FirstDouble";
myTable.Add(column1);

DataColumn column2 = new DataColumn();
column2.DataType = GetType("System.Double");
column2.ColumnName = "SecondDouble";
myTable.Add(column2);

DataColumn column3 = new DataColumn();
column3.DataType = GetType("System.DateTime");
column3.ColumnName = "TheDateTime";
myTable.Add(column3);

// ... Each Element becomes an array, and then a row
MyClassList.ForEach(x => myTable.Rows.Add(x.ToObjectArray());
```
```


Question:
I am trying to fill a form in a php application from a C# client (Outlook addin). I used Fiddler to see the original request from within the php application and the form is transmitted as a multipart/form. Unfortunately .Net does not come with native support for this type of forms (WebClient has only a method for uploading a file).
Does anybody know a library or has some code to achieve this? I want to post different values and additionally (but only sometimes) a file.

Thanks for your help,
Sebastian

Answer:
This is cut and pasted from some sample code I wrote, hopefully it should give the basics. It only supports File data and form-data at the moment.
```
```
public class PostData
{

    private List<PostDataParam> m_Params;

    public List<PostDataParam> Params
    {
        get { return m_Params; }
        set { m_Params = value; }
    }

    public PostData()
    {
        m_Params = new List<PostDataParam>();

        // Add sample param
        m_Params.Add(new PostDataParam("email", "MyEmail", PostDataParamType.Field));
    }

    /// <summary>
    /// Returns the parameters array formatted for multi-part/form data
    /// </summary>
    /// <returns></returns>
    public string GetPostData()
    {
        // Get boundary, default is --AaB03x
        string boundary = ConfigurationManager.AppSettings["ContentBoundary"].ToString();

        StringBuilder sb = new StringBuilder();
        foreach (PostDataParam p in m_Params)
        {
            sb.AppendLine(boundary);

            if (p.Type == PostDataParamType.File)
            {
                sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
                sb.AppendLine("Content-Type: text/plain");
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
            else
            {
                sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
        }

        sb.AppendLine(boundary);

        return sb.ToString();
    }
}

public enum PostDataParamType
{
    Field,
    File
}

public class PostDataParam
{

    public PostDataParam(string name, string value, PostDataParamType type)
    {
        Name = name;
        Value = value;
        Type = type;
    }

    public string Name;
    public string FileName;
    public string Value;
    public PostDataParamType Type;
}
```
```
To send the data you then need to:
```
```
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);
oRequest.ContentType = "multipart/form-data";
oRequest.Method = "POST";
PostData pData = new PostData();

byte[] buffer = encoding.GetBytes(pData.GetPostData());

// Set content length of our data
oRequest.ContentLength = buffer.Length;

// Dump our buffered postdata to the stream, booyah
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();

// get the response
oResponse = (HttpWebResponse)oRequest.GetResponse();
```
```
Hope thats clear, i've cut and pasted from a few sources to get that tidier.


Question:
I'm collecting metadata using the sys.* views, and according to the documentation, the sys.identity_columns view will return the seed and increment values like so.

CREATE TABLE ident_test (
  test_id int IDENTITY(1000,10),
  other int
)

SELECT name, seed_value, increment_value
  FROM sys.identity_columns
 WHERE object_id = OBJECT_ID( 'ident_test' )

However, the above query just returns one column.  Is it just me?

(Note: I've had to change this question somewhat from its earlier version.)

Answer:
Are you sure you are running this in a database with tables with
```
IDENTITY
```
columns?
```
```
SELECT c.name, i.seed_value, i.increment_value
FROM sys.columns c
INNER JOIN sys.identity_columns i
    ON i.object_id = c.object_id
    AND i.column_id = c.column_id
```
```
Returns rows for me in a regular production database with a few identities.
Using a
```
LEFT JOIN
```
returns these rows as well as many which are not
```
IDENTITY
```
I ran this on another database, and I noticed some
```
NULL
```
s are returned (even in the
```
INNER JOIN
```
case).  This is because some of the columns are in
```
VIEW
```
s.
Try adding:
```
```
INNER JOIN sys.tables t
ON t.object_id = c.object_id
```
```
To filter only to actual
```
IDENTITY
```
columns in tables.


Question:
If I have a property that I want to let inheritors write to, but keep readonly externally, what is the preferred way to implement this? I usually go with something like this:

private object m_myProp;
public object MyProp
{
    get { return m_myProp; }
}
protected void SetMyProp(object value)
{
    m_myProp = value;
}

Is there a better way?

Answer:
```
```
private object m_myProp;
public object MyProp
{
    get { return m_myProp; }
    protected set { m_myProp = value; }
}
```
```
Or in C# 3.0
```
```
public object MyProp {get; protected set;}
```
```


Question:
I have a POCO object that goes 4 levels deep contained objects (like Invoice has line items that have taxes that have gl entries), and I want to turn the entire thing into a DataSet. So there would be 4 tables, each with constraints being applied to the parent table.

Does anyone know of something that would automated this?

Answer:
How do you populate this object? If it's from the database, there are two methods to structure your query such that the dataset is populated with separate, automatically related DataTable-s. Old and probably not supported anymore is the
SHAPE command
.
A better and more recent approach is to use
FOR XML
.
The later approach will also allow you to load a dataset from XML-serialized representation of your `POCO' (not FOR XML, but loading XML into DataSet)


Question:
I've often used pointers to const objects, like so...

const int *p;

That simply means that you can't change the integer that p is pointing at through p. But I've also seen reference to const pointers, declared like this...

int* const p;

As I understand it, that means that the pointer variable itself is constant -- you can change the integer it points at all day long, but you can't make it point at something else.

What possible use would that have?

Answer:
Same as a "const int" ... if the compiler knows it's not going to change, it can be optimization assumptions based on that.
```
```
struct MyClass
{
    char* const ptr;
    MyClass(char* str) :ptr(str) {}

    void SomeFunc(MyOtherClass moc)
    {
         for(int i=0; i < 100; ++i)
         {
                 printf("%c", ptr[i]);
                 moc.SomeOtherFunc(this);
         }
    }
}
```
```
Now, the compiler could do quite a bit to optimize that loop --- provided it knows that SomeOtherFunc() does not change the value of ptr.  With the const, the compiler knows that, and can make the assumptions.  Without it, the compiler has to assume that SomeOtherFunc will change ptr.


Question: How secure are php Sessions?  I am planning to use the native PHP sessions to authenticate users.  Can users modify session data like they can $_POST and $_GET data?

Answer:
PHP sessions are as secure as the session cookie given to the user.  All the data in the session is stored server-side, so users can't arbitrarily modify them except through whatever functionality your site provides.  However, PHP session cookies are a common target for cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.  Just the same, sessions are a good way to do user authentication as long as you're aware of the potential risks.
Some Wikipedia links:
CSRF
XSS


Question:
e.g,

foo1
foo2
foo10
foo100

rather than

foo1
foo10
foo100
foo2

Update: not interested in coding the sort myself (although that's interesting in its own right), but having the database to do the sort for me.

Answer:
You can use functions in your order-by clause.  In this case,
you can split the non-numeric and numeric portions of the
field and use them as two of the ordering criteria.
```
```
select * from t
 order by to_number(regexp_substr(a,'^[0-9]+')),
          to_number(regexp_substr(a,'[0-9]+$')),
          a;
```
```
You can also create a function-based index to support this:
```
```
create index t_ix1
    on t (to_number(regexp_substr(a, '^[0-9]+')),
          to_number(regexp_substr(a, '[0-9]+$')),
          a);
```
```


Question:
Came across this:

http://www.eggheadcafe.com/articles/adonet_source_code_generator.asp

And wondering if this is the right solution as I am not that big of a fan of creating a class for every stored procedure or do I use Enterprise Library for ASP.net 2.0 project.

Answer:
Is there any possibility of upgrading to framework 3.5? if so take a look at LINQ to SQL and Entity Framework as this will accomplish alot of this for you.
If not then as long as it generates standard code that doesnt tie you into 3rd party libraries then you could certainly use it. At my workplace we have our own generator similar to this and it works well although we will shortly be moving to LINQ to SQL.


Question:
We have a dedicated godaddy server and it seemed to grind to a halt when we had users downloading only 3MB every 2 seconds (this was over about 20 http requests).

I want to look into database locking etc. to see if that is a problem - but first I'm curious as to what a dedicated server ought to be able to serve.

Answer: A lot depends on what the 3MB is.  Serving up 1.5MBps of static data is way, way, way, within the bounds of even the weakest server.


Question:
I do TDD on a daily basis for my C++ development on Solaris10. It has greatly reduced the time I have to spend using my debugger but sometime this is the only option.

DBX is pretty powerful but not that user friendly. Note that I'm talking about console DBX not the SunStudio GUI for DBX).

What are the best productivity tips you can give for dbx C++ debugging?

PS. Changing debugger is not an option.

Answer:
I have bookmarked a few sites related to dbx. Here they are, in no particular order in case they might be useful to you:
Why Can't dbx Find My Function?
Online Help for the Dbx Debugger
Sun Studio: debugging a multi-threaded application w/ dbx
gdb vs. dbx: commands mapping and feature comparison
Importing debug information into dbx
command line dbx : See more source
Sun Studio C++ - Your .dbxrc
(NB: adapt the integer type used to cast pointers according to your pointer size)
Sun Studio: Investigating memory leaks with dbx
Sun Studio: Gathering memory allocations/leaks data, from a running process
EDIT on 2012 july 19th: I've tried to fix several link since Chris Quenelle's blog has moved. Some articles can still be accessed thanks to the wayback machine.


Question: Which sorting algorithm works best on mostly sorted data?

Answer:
Based on the highly scientific method of watching
animated gifs
I would say Insertion and Bubble sorts are good candidates.


Question: I'm not the best at PHP and would be extremely grateful if somebody could help. Basically I need to parse each line of a datafeed and just get each bit of information between each "|" - then I can add it to a database. I think I can handle getting the information from between the "|"'s by using explode but I need a bit of help with parsing each line from a text file as a singular. Infact to make it even more simple, I just need it to use each line of a variable, I will submit content to the variable using a textarea and a form. Any help would be greatly appreciated!

Answer:
You can read a file into an array of lines and do all the splitting with:
```
```
$lines = file("filename");
foreach($lines as $line) {
    $parts = explode("|", $line);
    // do the database inserts here
}
```
```
If you already have all the text in a variable as you said (e.g., with something like file_get_contents() ), you can explode on \n first and then do the same foreach statement as above.


Question: Has anyone got much experience deploying applications to Amazons EC2? I am considering doing this in future and wonder about peoples experiences compared to shared hosting and dedicated server hosting are.

Answer:
So far, so good. Being able to turn on 5/10/50/100+ machines at a time is awesome. It's even better being able to turn them off and forget about them. You need to change your mindset about how you store your persistent data, but once you have the sky is the limit.
Performance wise, small instances are slow. They're fine for load balancers and serving static content, etc, but if you are doing anything processor intensive, you need at least a m1.medium instance.
It's all pretty new, so there aren't many tools to help out yet. I'm using
Puppet
to configure my hosts and I have a set of PHP scripts for starting up clusters. I use LDAP as a host inventory database.
If you don't have the need/urge to build your own, see
Rightscale
for some really awesome tools for deploying/growing apps.


Question:
Inspired by this question

The choice of which algorithm to use to sort a collection can be made better if we know ahead of time how well sorted a collection is. Is there a way we can measure (or maintain a measurement) of how well sorted the collection is? Can we do this in such a way that the cost of maintaining or measuring how well sorted something doesn't outweigh the benefit of choosing the best sort algorithm?

Answer:
You could use sampling: Check N elements spaced evenly in the list and see how many are in order.  (Of course that only works in a random-access list, but usually that's the type you sort.)
Also have a threshold for small N.  If N is small (e.g.
```
10
```
) insertion sort is good even if the list isn't sorted.  Java makes this optimization for small N in what is otherwise a merge-sort.


Question:
I'm trying to find out how to read/write to the extended file properties in C#
e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer.
Any ideas how to do this?
EDIT: I'll mainly be reading/writing to video files (AVI/DIVX/...)

Answer:
There's
a CodeProject article
for an ID3 reader.  And a
thread at kixtart.org
that has more information for other properties. Basically, you need to call the
```
GetDetailsOf()
```
method
on the
folder
shell object for
```
shell32.dll
```
.


Question:
I'm looking for a Java library that is geared towards network math and already tested.  Nothing particularly fancy, just something to hold ips and subnets, and do things like print a subnet mask or calculate whether an IP is within a given subnet.

Should I roll my own, or is there already a robust library for this?

Answer:
org.apache.lenya.ac.IPRange
appears to have these features.
The Apache Lenya project is an open-source content management system.  It uses the Apache License, so you may be able to reuse just the code you need. (But as always, read the
license
yourself; don't trust legal advice from some guy on the internet! :-)


Question: I am trying to write a little backup program for friends and family and want it to be as simple to use a possible. I don't want to have to ask the user where to backup their data to, I just want to search for and use the first USB hard drive connected to the computer. Obtaining the unique ID of the hard drive would probably be a good idea too, just as a double check for next time the backup runs.

Answer:
A few pieces of information can be gathered without too much trouble:
Use GetDriveType to find the first removeable drive, test if writeable media exists (which will largely rule out CD drives).  May also want to look at further strings that are available when you query the drive information via win32.
Use libusb to see where the first storage class USB device is (will likely be a flash or hard drive)
This
C# article
points towards win32 disk drive classes you might be able to tap into.
Post your answer here when you find it!
-Adam


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

@sites = Site.find(session[:sites]) # will be an array of Site ids
@languages = Language.for_sites(@sites)

for_sites is a named_scope in the Language model that returns the languages associated with those sites, and languages are associated with sites using has_many through. The goal is for @languages to have a distinct array of the languages associated with the sites.

Instead of calling the Language object on the second line, I'd ideally like to say

@sites.languages

and have the same list returned to me. Is there any way to do that cleanly in Rails 2.1 (or edge)? I know associations and named scopes can extend the array object to have attributes, but unless I'm missing something that doesn't apply here. Any plugins that do this would be welcome, it doesn't have to be in core.

Answer:
Your instance variable @sites is an Array object and not Site so I don't think named_scope can be used. You can open up Array class to achieve this effect though (yikes)
```
```
class Array

  def languages
    ...
  end

end
```
```


Question:
I need to output the contents of a text field using MS Query Analyzer. I have tried this:

select top 1 text from myTable

(where text is a text field)

and

DECLARE @data VarChar(8000)
select top 1 @data = text from myTable
PRINT @data

The first one prints only the first 2000 or so characters and the second only prints the first 8000 characters. Is there any way to get all of the text?

Notes:

must work with SQL Server 7

Answer:
I don't think you can use varchar(MAX) in MSSQL7, so here's something that will give you all the data (note, what I'm understanding is you just want to visually see the data, and you aren't going put it in a variable or return it).
So, this will print off the entire string so you can visually see what's in the field:
```
```
DECLARE @limit as int,
        @charLen as int,
        @current as int,
        @chars as varchar(8000)

SET @limit = 8000

SELECT  TOP 1 @charLen = LEN(text)
FROM    myTable

SET @current = 1

WHILE @current < @charLen
BEGIN
    SELECT  TOP 1 @chars = SUBSTRING(text,@current,@limit)
    FROM    myTable
    PRINT @chars

    SET @current = @current + @limit
END
```
```


Question:
I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript.  How may I access them?

Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.

Related:

  Accessing the web page's HTTP Headers in JavaScript

Answer:
If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.
To retrieve the referrer, use
```
document.referrer
```
.
To access the user-agent, use
```
navigator.userAgent
```
.
As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.


Question: I'd like to log the call trace during certain points, like failed assertions, or uncaught exceptions.

Answer:
This
pretty much tells you what to do.
Essentially you need to set up the applications exception handling to log, something like:
```
```
#import <ExceptionHandling/NSExceptionHandler.h>

[[NSExceptionHandler defaultExceptionHandler]
                  setExceptionHandlingMask: NSLogUncaughtExceptionMask |
                                            NSLogUncaughtSystemExceptionMask |
                                            NSLogUncaughtRuntimeErrorMask]
```
```


Question:
I'm trying to learn GNUMake for a small project I'm working on. So far, even the "basic" tutorials seem pretty rough and I've yet to make sense of the makefile syntax.

Does anyone have some good resources for an absolute beginner to get familiar with GNUMake?

Answer:
The definitive guide is
http://www.gnu.org/software/make/manual/make.html
There is an o'reilly book "Managing Projects with GNU Make" which has more explanation.
You can also uses the earlier editions, they don't cover GnuMake specifically but are a lot thinner.
Make is a dirty secret among developers - none of us understand it, we just borrow a make script from somebody else and change it. I imagine only one script was ever written from scratch (probably by the creator of the tool).
When you need to do more than the simple example most people either switch to a more modern build system like Ant or roll their own in Perl/Python/etc.


Question: If I download a .gem file to a folder in my computer, can I install it later using gem install?

Answer:
Yup, when you do
```
gem install
```
, it will search the current directory first, so if your .gem file is there, it will pick it up. I found it on the
gem reference
, which you may find handy as well:
gem install will install the named
  gem. It will attempt a local
  installation (i.e. a .gem file in the
  current directory), and if that fails,
  it will attempt to download and
  install the most recent version of the
  gem you want.


Question:
Or if any body knows of an alternative control that does?

It would be handy to serve up content to the WebBrowser control that has embedded images & other resources from a database without having a dependency on these resources being hosted on a webserver or to create temporary files on the local file system.

Mhtml supports this but doesn't seem to work in a WebBrowser control when using the DocumentText property?

Answer:
Seems to be working for me.
example:
```
```
this.webBrowser1.Url = new System.Uri(@"C:\TempFiles\MyTest.mht");
```
```
what in particular is not working correctly?


Question:
I'm looking for Ruby's Active record for PHP. Something that is so simple that I just define my fields, extend the base ORM class, and I get ACID operations for free. I should get default getters and setters without writing any code, but overriding a default getter or setter is as easy as declaring get$fieldName or set$fieldName functions with the behavior I want.  Symphony makes you create about 5 files per object, and all defined objects always load as far as I can tell. What is a better alternative? Why is it better? Can you put simple examples in your answers please?

Doctrine is another ORM I've looked at besides symphony . There also you need to create yaml files that describe your data structures. The database already defines this stuff. What will just read my table defs without having to generate and store config files everywhere?

Answer:
Zend_Db_Table
and
Zend_Db_Table_Row
are fairly good at what you're describing.  You don't need any configuration file, most metadata is "discovered" from the database itself.
Technically these classes don't implement the ActiveRecord pattern.  Instead, they implement the
Table Data Gateway
and
Row Data Gateway
patterns.  Together, these offer similar value as ActiveRecord, and in some ways are more flexible than ActiveRecord.
But as with any ORM, there are inevitably some SQL queries and operations that you can't do through the OO interface.  No ORM can serve as one-stop shopping.
Footnote:  I worked on the Zend Framework project for a little over a year, especially on the Zend_Db component.  But I don't work for them anymore.


Question:
How do I access a page's HTTP response headers via JavaScript?

Related to this question, which was modified to ask about accessing two specific HTTP headers.

Related:

  How do I access the HTTP request header fields via JavaScript?

Answer:
Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been
repeatedly asked
, too, because some people would like to get the actual response headers of the original page request without issuing another one.
For AJAX Requests:
If an HTTP request is made over AJAX, it is possible to get the response headers with the
```
getAllResponseHeaders()
```
method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the
```
fetchSimilarHeaders()
```
function below. Note that this is a work-around to the problem that won't be reliable for some applications.
```
```
myXMLHttpRequest.getAllResponseHeaders();
```
```
The API was specified in the following candidate recommendation for XMLHttpRequest:
XMLHttpRequest - W3C Candidate Recommendation 3 August 2010
Specifically, the
```
getAllResponseHeaders()
```
method was specified in the following section:
w3.org:
```
XMLHttpRequest
```
: the
```
getallresponseheaders()
```
method
The MDN documentation is good, too:
developer.mozilla.org:
```
XMLHttpRequest
```
.
This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.
Getting header values from the Initial Page Request:
This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the
current page
(i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.
The following are a few suggestions for getting around that problem.
1. Requests on Resources which are largely static
If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.
```
```
function fetchSimilarHeaders (callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            //
            // The following headers may often be similar
            // to those of the original page request...
            //
            if (callback && typeof callback === 'function') {
                callback(request.getAllResponseHeaders());
            }
        }
    };

    //
    // Re-request the same page (document.location)
    // We hope to get the same or similar response headers to those which
    // came with the current page, but we have no guarantee.
    // Since we are only after the headers, a HEAD request may be sufficient.
    //
    request.open('HEAD', document.location, true);
    request.send(null);
}
```
```
This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.
2. Make Inferences
There are
some BOM properties
(Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g.
```
navigator.userAgent
```
is set to the value of the HTTP
```
User-Agent
```
header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.
3. Stash them
If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.


Question:
In the IDisposable.Dispose method is there a way to figure out if an exception is being thrown?

using (MyWrapper wrapper = new MyWrapper())
{
    throw new Exception("Bad error.");
}

If an exception is thrown in the using statement I want to know about it when the IDisposable object is disposed.

Answer:
Instead of the syntactic sugar of the using statement, why not just implement your own logic for this.  Something like:
```
```
try
{
  MyWrapper wrapper = new MyWrapper();

}
catch (Exception e)
{
  wrapper.CaughtException = true;
}
finally
{
   if (wrapper != null)
   {
      wrapper.Dispose();
   }
}
```
```


Question:
I'm trying to figure out a decent solution (especially from the SEO side) for embedding fonts in web pages. So far I have seen the W3C solution, which doesn't even work on Firefox, and this pretty cool solution. The second solution is for titles only. Is there a solution available for full text? I'm tired of the standard fonts for web pages.

Thanks!

Answer:
And it's unlikely too -- EOT is a fairly restrictive format that is supported only by IE.  Both Safari 3.1 and Firefox 3.1 (well the current alpha) and possibly Opera 9.6 support true type font (ttf) embedding, and at least Safari supports SVG fonts through the same mechanism.  A list apart had a good discussion about this a while
back
.


Question:
How can I comment a JSP expression like: <%= map.size() %>

Is there something like <%= // map.size() %>?

Answer:
One of:
In html
```
```
<!-- map.size here because -->
<%= map.size() %>
```
```
theoretically the following should work, but i never used it this way.
```
```
<%= map.size() // map.size here because %>
```
```


Question:
I am curious as to why an implicit cast fails in...

int? someValue = SomeCondition ? ResultOfSomeCalc() : null;

and why I have to perform an explicit cast instead

int? someValue = SomeCondition ? ResultofSomeCalc() : (int?)null;

It seems to me that the compiler has all the information it need to make an implicit casting decision, no?

Answer:
The relevant section of the C# 3.0 spec is 7.13, the conditional operator:
The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
If X and Y are the same type, then this is the type of the conditional
Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.


Question:
So after installing NUnit, the assemblies (nunit.framework, etc.) now appear in the References > Add Reference dialog, but they're not in the %WINDIR%\Microsoft.NET\Framework\v2.0.50727 dir and there is no NUnit registry entry for the Assembly Path (i.e. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramewokr\AssemblyFolder).

There's also no automatic entries created in the project properties Reference Paths for the NUnit install directory.  How the heck are they appearing in the "Add Dialog"?!?!  I thought the mentioned way were the only ways assemblies could appear in "Add Reference".

Answer:
Strange, [HKEY_CURRENT_USER\SOFTWARE\Microsoft.NETFramework\AssemblyFolders] should be the only thing driving this.
Perhaps this snippet from
this page
is relevant?
If you install the .NET Framework 3.0 Service Pack 1 (SP1), the following registry subkey is added:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\v3.0
```
```
If you install the .NET Framework 3.5, the following registry subkey is added:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\v3.5
```
```


Question: I would like to have my warnings set to the highest level using Microsoft Visual C++ compiler. Similar to using -pedantic on gcc. What compiler switches do you use to have the most warnings enabled?

Answer:
```
/W4 /Wall
```
should do the trick.


Question:
I need to apply some xml templates to various streams of xml data (and files, on occasion) and there seem to be a large number of xml libraries for java out there -- enough that it's difficult to quickly determine which libraries are still active, how they differ from the other options that are also active, and what criteria should be considered when choosing one.

What libraries do you use for manipulating xml in java, and why is it better than the alternatives?

Answer:
You should decide if you want/are able to load the whole document into memory.  If it is a large document, you may want to look at the sax
parser
.  This works well for large documents.  Otherwise you may want to look into a dom parser.


Question: Are the .net classes relating to DbProviderFactory thread safe?

Answer:
When you say "These instances are generated once at run time, and used for the rest of the service's life", do you mean the connection object? Also, do you mean you're keeping the connection object open through out the life of your service?  If your service is multi-threaded and you only have one instance of the connection (say for example a singleton or static class), you have to make sure the connection is only used by one thread at a time.
Without seeing much code, it sounds like a problem with how you treat the IDbConnection you get from the factory, instead of the factory itself.
We use the DbProviderFactory very heavily for our multithreaded applications, which connect to Oracle, FoxPro and SqlServer and I haven't seen this issue.
Good luck!
Ricardo.


Question:
I have just started migrating my homegrown persistence framework to JPA.

Given that the persistence frameworks hide a lot of the plumbing, I'm interested in knowing if NOT closing EntityManagers will create a resource leak, or if the frameworks will collect and close them for me.

I intend in all places to close them, but do I HAVE to?

At the moment using TopLink, just because it works with NetBeans easily, but am happy to investigate other JPA providers.

Answer:
You should.
Frameworks have no idea how you intend to use the EM, so they cannot close it (except, may be, on finalization, which is not guaranteed). Yes, not closing them would create a resource leak.
The idea is the same as "always close java.sql.Connection" (despite some data sources have settings to close them automatically by inactivity) or "always close Hibernate session".
Besides, if you plan to write portable code, you shouldn't rely on specific JPA provider "being smart" -- other may fail to close the EM in time.


Question: I need to write robust code in .NET to enable a windows service (server 2003) to restart itself. What is the best way to so this? Is there some .NET API to do it?

Answer:
I don't think you can in a self-contained service (when you call Restart, it will stop the service, which will interrupt the Restart command, and it won't ever get started again). If you can add a second .exe (a Console app that uses the ServiceManager class), then you can kick off the standalone .exe and have it restart the service and then exit.
On second thought, you could probably have the service register a Scheduled Task (using the command-line 'at' command, for example) to start the service and then have it stop itself; that would probably work.


Question:
This article here suggests to use -XX:+UseParNewGC "To enable a parallel young generation GC with the concurrent GC".

My confusion is that in order to enable both parallel and concurrent GC, should I

use -XX:+UseParNewGC or

use both -XX:+UseParNewGC and -XX:+UseConcMarkSweepGC ?

PS

I am using JVM 6.

Answer:
Since the document you linked was for a 1.4.2 VM that's what I'll assume you're using (JVMs 5 and 6 behave differently).
From
http://java.sun.com/docs/hotspot/gc1.4.2/
if -XX:+UseConcMarkSweepGC is used on
  the command line then the flag
  UseParNewGC is also set to true if it
  is not otherwise explicitly set on the
  command line
So the answer is you only need to use -XX:+UseConcMarkSweepGC and it will enable the concurrent collector with the parallel young generation collector.
Edit: for Java 6, the same flag (-XX:+UseConcMarkSweepGC) enables the concurrent collector. The choice of collector you want depends on a few things, and you should test different configurations. But there are some very general guidelines. If you have a single processor, single thread machine then you should use the serial collector (default for some configurations, can be enabled explicitly for with -XX:+UseSerialGC). For multiprocessor machines where your workload is basically CPU bound, use the parallel collector. This is enabled by default if you use the -server flag, or you can enable it explicitly with -XX:+UseParallelGC. If you'd rather keep the GC pauses shorter at the expense of using more total CPU time for GC, and you have more than one CPU, you can use the concurrent collector (-XX:+UseConcMarkSweepGC). Note that the concurrent collector tends to require more RAM allocated to the JVM than the serial or parallel collectors for a given workload because some memory fragmentation can occur.


Question:
This is the exception that I'm getting when I'm trying to bind to a System.Type.Name.

Here is what I'm doing:

this.propertyTypeBindingSource.DataSource = typeof(System.Type);

/* snip */

this.nameTextBox1.DataBindings.Add(
    new System.Windows.Forms.Binding(
        "Text",
        this.propertyTypeBindingSource,
        "Name", true));

Is there some trick with binding to System.Type, is it not allowed or is there any workaround? Have no problems with binding to other types.

Answer:
Found a workaround. Made a class
```
```
public class StubPropertyType
{
    public StubPropertyType(Type type)
    {
        this.StubPropertyTypeName = type.Name;
    }

    public string StubPropertyTypeName = string.Empty;
}
```
```
created a binding source
```
```
this.propertyStubBindingSource.DataSource = typeof(StubPropertyType);
```
```
created an instance of the class and bound the textbox to it.
```
```
this.nameTextBox.DataBindings.Add(
    new System.Windows.Forms.Binding(
        "Text",
        this.propertyStubBindingSource,
        "StubPropertyTypeName",
        true));
```
```
works exactly as required.


Question: In one of the stackoverflow podcasts (#18 I think) Jeff and Joel were talking about multi vs single tenant databases. Joel mentioned that "FogBugz on Demand" used a database per customer architecture and I was wondering if there is a point beyond which you'll need to have multiple database servers to distribute the load?

Answer:
Technically the limit of databases per instance in SQL Server is 32,767, but I doubt that you could use a SQL Server instance that has more than 2,000 databases, at that point the server would probably be not responsive.
You may be able to have close to 30,000 databases if they were all auto-closed and not being used. you can find more information about capacity limits here:
Maximum Capacity Specifications for SQL Server