q:
Multimap essentially has groups of data sorted by the key. I want a method by which I could access these individual groups and get their aggregate values.
For example, in a std::multimap< string, int > I store

{"Group1", 1},
{"Group1", 2},
{"Group1", 3},

{"Group2", 10},
{"Group2", 11},
{"Group2", 12}

Having stored these values, I should be able to iterate this multimap and get the aggregate values of each "group". Problem is there aren't any functions defined in STL to access MultiMaps in such a way. I could use lower_bound, upper_bound to manually iterate the multimap and total the group's contents, but I am hoping there could be better ways already defined in STL ? Can anyone propose a solution as to how I could get the aggregate values for a group in the above example.

[A]
If you already know the keys, you can use
```
multimap::equal_range
```
to get the iterators to the beginning and end of the group; use any standard algorithm to get the desired results from the range.  If you don't know the keys, you can start at
```
begin()
```
and iterate through them yourself, comparing keys to find the start of each new group.


q:
I have an application built in Flex Builder 3.  It has a fair amount of mxml and as3 code which uses some other custom compenents.  I have looked at the documentation on building components which shows how to make a simple mxml or action script component that extends something like a combobox, but I'm lost as to how to take a whole existing and independently functioning Application and turn it into a reusable component.

Basically, I'd just like to create multiple instances of this app inside of another flex project.

Anyone able to provide a little guidance?

[A]
If you simply want some "parent" Flex application to embed several instances of this autonomous child application, then you should see Adobe's
"Embedding Asset Types"
documentation, which describes how to embed one SWF file in another.
From the documentation:
You typically embed a Flex application
  when you do not require the embedding
  application to interact with the
  embedded application. If the embedding
  application requires interactivity
  with the embedded application, you
  might consider implementing it as a
  custom component, rather than as a
  separate application.
If you
do
require interaction between the embedded application and the parent application, you can look into the
SWFLoader
control.

s: huggingface

c: devops

d: intermediate


q:
I have a Visual Basic .NET program which needs to open and close an Excel spreadsheet.  Opening and reading the spreadsheet work fine, but trying to close the Excel 2007 application causes it to hang.  It seems to close, but if you look in the task manager the application is still running.  The code that I'm using to close it is

wbkData.Close(saveChanges:=False)
appExcel.Quit()
wbkData = Nothing
appExcel = Nothing

How can I get Excel to close properly?

[A]
I found a
solution in the MSDN Excel Blog
which worked for me.  It's explained as
There are two problems with the above:
(1) Although the code appears to
  dispose of the 'wbkData' object first,
  etc., the code above does not actually
enforce
this as the .NET Garbage Collection procedure can dispose of
  its objects in any order. (GC is
  non-deterministic in order, not just
  non-deterministic in timing.)
(2) Commands such as 'wsh =
  wbkData.Workssheets.Item(1)' -- or
  lines like it -- are very common and
  will create an RCW object wrapping a
  'Worksheets' object. You won't have a
  variable holding a reference to it, so
  you don't generally think about it,
  but this RCW object will not be
  disposed until the next Garbage
  Collection. However, the code above
  calls GC.Collect()
last
, and so the
  RCW is still holding a reference to
  this 'Worksheets' object when
  appExcel.Quit() is called. Excel hangs
  as a result.
The final code looks like
```
```
GC.Collect()
GC.WaitForPendingFinalizers()

wbkData.Close(SaveChanges:=False)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(wbkData) : wbkData = Nothing
appExcel.Quit()
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appExcel) : appExcel = Nothing
```
```


q:
List<String> nameList = new List<String>();
DropDownList ddl = new DropDownList();

List is populated here, then sorted:

nameList.Sort();

Now I need to drop it into the dropdownlist, which is where I'm having issues (using foreach):

foreach (string name in nameList){
    ddl.Items.Add(new ListItem(nameList[name].ToString()));
}

No workie - any suggestions? It's giving me compile errors:

Error - The best overloaded method match for 'System.Collections.Generic.List<string>.this[int]' has some invalid arguments

Error - Argument '1': cannot convert from 'string' to 'int'

[A]
Why not just bind the DDL directly to the List like
```
```
DropDownList ddl = new DropDownList();
ddl.DataSource = nameList;
ddl.DataBind();
```
```


q:
In T-SQL, you can do this:

SELECT ProductId, COALESCE(Price, 0)
FROM Products

How do you do the same thing in Access SQL?  I see examples for doing it with Nz in VBA, but I'm looking for the SQL equivalent.

Thanks.

[A]
Access supports the
```
Nz
```
function and allows you to use it in a query.  Note though that
```
Nz
```
is the same as the T-SQL
```
ISNULL
```
function.  It can not take an arbitrary number of parameters like
```
COALESCE
```
can.


q:
When is memory allocated in the .NET compact framework? If there is a difference between value and reference types, please detail. Documentation or steps to confirm are appreciated.

In particular, consider this scenario...

private MyClass item;  // here?

public void MyMethod()
{
    item = new MyClass();  // or here?
}

[A]
There are 3 different ways memory is allocated.
Static:
These are bound and allocated at compile time. Global static variables for example.
Stack Dynamic:
These are bound during runtime and pushed onto the stack. Such as a local variable in a function call.
Heap Dynamic:
Now heap dynamic also has a few different 'sub categories' such as implicit and explicit, but I won't go into that detail.
When you declare
```
```
private MyClass item;  // here?
```
```
a reference to MyClass is pushed onto the stack. It is only a reference and nothing more. Its value is null at that point.
```
```
public void MyMethod()
{
    item = new MyClass();  // or here?
}
```
```
It is at that point where memory is explicitly allocated on the heap by calling 'new MyClass()' and item then references it.
So in actuality, you have 2 variables after you call MyMethod. A refernce type named item, and an unnamed variable on the heap which item references that is of type MyClass.


q:
We've got VisualSVN Server set up as our Subversion server on Windows, and we use Ankhsvn + TortoiseSVN as clients on our workstations.

How can you configure the server to require commit messages to be non-empty?

[A]
VisualSVN Server 3.9 provides the
```
VisualSVNServerHooks.exe check-logmessage
```
pre-commit hook that helps you reject commits with empty or short log messages. See the article
KB140: Validating commit log messages in VisualSVN Server
for instructions.
Besides the built-in
```
VisualSVNServerHooks.exe
```
, VisualSVN Server and SVN in general uses a
number of hooks
to accomplish tasks like this.
```
start-commit
```
— run before commit transaction begins, can be used to do special permission checking
```
pre-commit
```
— run at the end of the transaction, but before commit. Often used to validate things such as a non zero length log message.
```
post-commit
```
— runs after the transaction has been committed. Can be used for sending emails, or backing up repository.
```
pre-revprop-change
```
— runs before a revision property change. Can be used to check permissions.
```
post-revprop-change
```
— runs after a revision property change. Can be used to email or backup these changes.
You need to use the
```
pre-commit
```
hook. You can write it yourself in just about any language your platform supports, but there are a number of scripts on the web. Googling "svn precommit hook to require comment" I found a couple that looked like they would fit the bill:
Perl Script
Python Script


q:
I have a lot of constants that are somehow related, at some point I need to pair them, something like this:

const
  key1 = '1';
  key2 = '2';
  key3 = '3';

  value1 = 'a';
  value2 = 'b';
  value3 = 'c';

I want to avoid doing:

if MyValue = key1 then Result := value1;

I know how to do it with string lists using:

MyStringList.Add(key1 + '=' + value1);
Result := MyStringList.Values[key1];

But, is there any simpler way to do this?

[A]
Yes, assignment can be done this way instead, avoiding manual string concatenation:
```
```
MyStringList.Values[Key1] := Value1;
```
```


q:
I have the following code in my Django application:

if 'book' in authorForm.changed_data:
   #Do something here...

I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, but I'd like to know the new values of the fields that have changed.

Any thoughts?

[A]
Hmm... Try this:
```
```
if authorForm.is_valid() and 'book' in authorForm.changed_data:
    new_value = authorForm.cleaned_data['book']
```
```


q:
I have a PHP client that requests an XML file over HTTP (i.e. loads an XML file via URL).  As of now, the XML file is only several KB in size.  A problem I can foresee is that the XML becomes several MBs or Gbs in size.  I know that this is a huge question and that there are probably a myriad of solutions, but What ideas do you have to transport this data to the client?

Thanks!

[A]
Gallery2, which allows you to upload photos over http, makes you set up a couple of php parameters,
```
post_max_size
```
and
```
upload_max_filesize
```
, to allow larger uploads.  You might want to look into that.
It seems to me that posting large files has problems with browser time-outs and the like, but on the plus side it works with proxy servers and firewalls better than trying a different file upload protocol.


q:
Is there a better way than the following to check to see if a string is nil OR has a length of 0 in Ruby?

if !my_string || my_string.length == 0
  return true
else
  return false
end

In C# there's the handy

string.IsNullOrEmpty(myString)

Anything similar to that in Ruby?

[A]
Every class has a
```
nil?
```
method:
```
```
if a_variable.nil?
    # the variable has a nil value
end
```
```
And strings have the
```
empty?
```
method:
```
```
if a_string.empty?
    # the string is empty
}
```
```
Remember that a string does
not
equal
```
nil
```
when it is empty, so use the
```
empty?
```
method to check if a string is empty.


q: I have a Tab Control with multiple Tab Pages. I want to be able to fade the tabs back and forth. I don't see an opacity option on the Tab Controls. Is there a way to cause a fade effect when I switch from one Tab Page to another?

[A]
There is no magic Fade switch in the standard windows control.
You could dump the content of the tab to a bitmap (using
DrawToBitmap
or
CopyFromScreen
?), show that bitmap in front of the TabControl, switch tabs, and then fade the bitmap.


q:
Exception: Failed to compare two elements in the array.

private void assignNames(DropDownList ddl, Hashtable names)
{
    List<ListItem> nameList = new List<ListItem>();
    if (ddl != null)
    {
        ddl.ClearSelection();
        ddl.Items.Add(new ListItem("Select Author"));
        foreach (string key in names.Keys)
        {
            nameList.Add(new ListItem(names[key].ToString(), key));

        }

    nameList.Sort();
}

So how can I use Sort() to compare on the "names" and not get stuck on the key?

[A]
what type of object is "names"?
EDIT:
From what I can tell you will have to specify an IComparer for this to work, not sure if I fully understand what you are trying to do though.
EDIT:
This is way too complicated for what I "feel" your intent is, you basically want to populate a dropdown list with a sorted list of Author names.
you should be able to have a
```
```
List<string> auhtorNames;
authorNames.Sort();
ddl.DataSource = authorNames;
ddl.DataBind();
```
```


q:
I was recently put in charge of the wiki for the development team. The wiki is still in its infancy, so I have a lot of room to work with. It goal is to house internal to the development team. Currently, the main piece of information that the wiki holds is Coding Standards.

What are some best practices your dev team uses for its internal wiki?

What information is important to have on a dev wiki?

If you were to go to the wiki for your dev team what information would you expect to see?

Is there some information that shouldn't go on the wiki even though it seems like a good idea?

-- edit --

Also, is there a good way to organize the information? ( such as by layer ( data, ui), by porject, or other)

[A]
Introduction to the source base for new programmers
General documentation (not the API documentation per-se, but more tutorial like things)
Lists of staff / who's doing what and how to reach them
Notes / resources / articles that explain concepts used in the software
Documentation of the build process and the filesystem layout of the codebase
Other things I usually put up there are
Planning / todo lists
Information that is interesting for others to read
Everything else that I feel should be shared


q:
I have this in some WSDL:

<element name="startDate" type="xsd:dateTime"/>
<element name="endDate" type="xsd:dateTime"/>

Which results in the following text in the SOAP envelope:

<startDate>2008-10-29T12:01:05</startDate>
<endDate>2008-10-29T12:38:59.65625-04:00</endDate>

Only some times have the milliseconds and zone offset. This causes me a headache because I'm trying to get a range of 37 minutes and 54 seconds in this example, but because of the offset I end up with 4 hours, 37 minutes, 54.65625 seconds. Is this some kind of rounding error in DateTime? How do I prevent this from happening?

[A]
What are you using to generate the date?  If you are building this XML in your code rather than using some serializer (WCF or XmlSerializer) you could use System.Xml.XmlConvert to generate and interpret the date as follows:
To create the string to put in the XML:
```
```
DateTime startDate = DateTime.Now;
string startDateString = System.Xml.XmlConvert.ToString(startDate);
```
```
To get the date out of the XML:
```
```
DateTime startDateFromXml = System.Xml.XmlConvert.ToDateTime(startDateString);
```
```
If you start with two DateTime instances that differ by 37 minutes and 54 seconds before you push them into XML they will still differ by 37 minutes and 54 seconds after you pull them out of the XML.


q:
How does one setup DUnit Testing in a Midas/DataSnap project in Delphi 2006

Edit

How does one set up a Dunit Test into a TRemoteDataModule
The project wizard in Delphi 2006 does not work with TRemoteDataModule

[A] The question doesn't entirely make sense.  Unit tests are performed in a separate project, not within your DataSnap server. Generally, tests which connect to a database are integration tests rather than unit tests.  What is it, exactly that you want to test?  If it's utility methods within, say, a TRemoteDataModule, you should extract those out into a separate class as class methods, and test them there.  You should not have to instantiate an application server to perform unit tests.


q:
I would like to display a Drupal view without the page template that normally surrounds it - I want just the plain HTML content of the view's nodes.

This view would be included in another, non-Drupal site.

I expect to have to do this with a number of views, so a solution that lets me set these up rapidly and easily would be the best - I'd prefer not to have to create a .tpl.php file every time I need to include a view somewhere.

[A]
there are probably a number of ways around this, however, the "easiest" may be just setting your own custom theme, and having the page.tpl.php just be empty, or some random divs
```
```
// page.tpl.php

<?php print $content ?>

```
```
this method would basically just allow node.tpl.php to show (or any of drupal's form views, etc...) and would be an easy way to avoid modifying core, or having to alter the theme registry to avoid displaying page.tpl.php in the first place.
edit
: see comments
ok i played around with views a bit, it looks like it takes over and constructs it's own "node.tpl.php" (in a sense) for display within "page.tpl.php". on first glance, my gut feeling would be to hook into
```
theme_registry_alter()
```
.
when you're looking at a views page, you have access to piles of information here, as well as the page.tpl.php paths/files. as such i would do something like:
```
```
function modulejustforalteration_theme_registry_alter(&$variables) {
  if (isset($variables['views_ui_list_views']) ) {
  // not sure if that's the best index to test for "views" but i imagine it'll work
  // as well as others
    $variables['page']['template'] = 'override_page';
  }
}
```
```
this should allow you to use a "override_page.tpl.php" template in your current theme in which you can remove anything you want (as my first answer above).
a few things:
as i said, not sure if
```
views_ui_list_views
```
is always available to check against, but it sounds like it should be set if we're looking at a view
you can alter the
```
theme paths
```
of the
```
page
```
array if you prefer (to change the location of where drupal will look for page.tpl.php, instead of renaming it altogether)
there doesn't appear to be any identifiers for this specific view, so this method might be an "all views will be stripped" approach. if you need to strip the page.tpl.php for a specific view only, perhaps hooking into
```
template_preprocess_page()
```
might be a better idea.


q: pre tags are super-useful for code blocks in HTML and for debugging output while writing scripts, but how do I make the text word-wrap instead of printing out one long line?

[A]
The answer, from
this page
in CSS:
```
```
pre {
    white-space: pre-wrap;       /* Since CSS 2.1 */
    white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
    white-space: -pre-wrap;      /* Opera 4-6 */
    white-space: -o-pre-wrap;    /* Opera 7 */
    word-wrap: break-word;       /* Internet Explorer 5.5+ */
}
```
```


q:
I have a GIF image that has an alpha set, and when my site loads in Firefox 3.0, it acts transparently on the parts of the image that should.  However, when I try to load the GIF image in IE7, it comes back as a solid block.  Actually, it is like the color from the image bled into the transparent area.

Do anyone have any suggestions for resolving this kind of problem?  Pointers on what to look into, or a route you've used to solve this kind of problem.

I've been controlling this in CSS -- and while I'd like to avoid the conditional comments route and multiple CSSes, I'd be willing if the suggestion tangibly shows how I can resolve the IE compatibility problems.

Thanks,
Sean

[A]
Try these two -- mess with the numbers until you get it right. i 4get which is for IE and which is FF/chrome
```
```
opacity: 7;
filter: alpha(Opacity=7);
```
```


q:
I'm checking for existing of a row in in_fmd, and the ISBN I look up can be the ISBN parameter, or another ISBN in a cross-number table that may or may not have a row.

select count(*)
from in_fmd i
where (description='GN')
    and ( i.isbn in
    (
        select bwi_isbn from bw_isbn where orig_isbn = ?
        union all
        select cast(? as varchar) as isbn
    )
)

I don't actually care about the count of the rows, but rather mere existence of at least one row.

This used to be three separate queries, and I squashed it into one, but I think there's room for more improvement.  It's PostgreSQL 8.1, if it matters.

[A]
Why bother with the
```
UNION ALL
```
```
```
select count(*)
from in_fmd i
where (description='GN')
    and (
        i.isbn in (
            select bwi_isbn from bw_isbn where orig_isbn = ?
        )
        or i.isbn = cast(? as varchar)
    )
```
```
I would probably use a
```
LEFT JOIN
```
-style query instead of the
```
IN
```
, but that's more personal preference:
```
```
select count(*)
from in_fmd i
left join bw_isbn
    on bw_isbn.bwi_isbn = i.isbn
    and bw_isbn.orig_isbn = ?
where (i.description='GN')
    and (
        bw_isbn.bwi_isbn is not null
        or i.isbn = cast(? as varchar)
    )
```
```
The inversion discussed over IM:
```
```
SELECT SUM(ct)
FROM (
    select count(*) as ct
    from in_fmd i
    inner join bw_isbn
        on bw_isbn.bwi_isbn = i.isbn
        and bw_isbn.orig_isbn = ?
        and i.isbn <> cast(? as varchar)
        and i.description = 'GN'

    UNION

    select count(*) as ct
    from in_fmd i
    where i.isbn = cast(? as varchar)
        and i.description = 'GN'
) AS x
```
```


q: The only method provided by the DNN framework to get a module by ID also required a tab ID.  What can I do if I don't have a tab ID?

[A]
The GetModule method off of the DotNetNuke.Entities.Modules.ModuleController class will accept a "null" value for tab ID if you don't have a tab ID.  That is, try the following:
```
```
new ModuleController().GetModule(moduleId, DotNetNuke.Common.Utilities.Null.NullInteger)
```
```
See also
my blog post on the subject
.


q: By default, I think my vimrc setttings enable the auto-wrapping. However, sometimes, I would like to see text lines are not wrapped. Is there any command I toggle the text line wrapping enabled and disabled? This would avoid me to exit and to change settings.

[A]
```
```
:set nowrap
```
```
There is also the
```
linebreak
```
option that controls whether wrapped text is broken at word boundaries or not.


q:
I don't use Eclipse as an IDE, and have no interest in doing so.  However, I do like its source-level debugging.

Is there any way I can use it to debug a C++ Linux app without going through the ritual of creating a project?  (In effect, can I just use it like a frontend to gdb?)

If not, what are the steps I need to follow to create a project that I can use to just debug an existing C++ program that is built using Makefiles or other tools (SCons, CMake, etc.).  I don't want to be able to "develop" in Eclipse; all I need to do is debug.

[A]
Take a look at
this question
. Create a C/C++-project, use your project's source directory as project directory, select to use the external builder, and change "make" to whatever tool you want.
The tricky part is to get the indexer to work correctly and find all your header files.
EDIT: CMake 2.6.x has support for generating CDT project files, which might be a more straightforward solution.


q:
I am working on a legacy ASP application. I am attempting to insert a value (40.33) into a field in SQL Server 2000 that happens to be a float type.  Every place I can see (via some logging) in the application is sending 40.33 to the Stored Procedure.  When I run SQL Profiler against the database while the call is happening, the value that I see in the trace is 4.033000183105469e+001

Where is all the extra garbage coming from (the 183105469)?

Why is it that when I pass in 40, or 40.25 there is nothing extra?

Is this just one of the weird side effects of using float?  When I am writing something I normally use money or decimal or something else, so not that familiar with the float datatype.

[A] I think this is probably just a precision issue - the 0.33 part of the number can't be represented exactly in binary - this is probably the closest that you can get to.


q:
I have a block of product images we received from a customer.  Each product image is a picture of something and it was taken with a white background.  I would like to crop all the surrounding parts of the image but leave only the product in the middle.  Is this possible?

As an example: [http://www.5dnet.de/media/catalog/product/d/r/dress_shoes_5.jpg][1]

I don't want all white pixels removed, however I do want the image cropped so that the top-most row of pixels contains one non-white pixel, the left-most vertical row of pixels contains one non-white pixel, bottom-most horizontal row of pixels contains one non-white pixel, etc.

Code in C# or VB.net would be appreciated.

[A]
I've written code to do this myself - it's not too difficult to get the basics going.
Essentially, you need to scan pixel rows/columns to check for non-white pixels and isolate the bounds of the product image, then create a new bitmap with just that region.
Note that while the
```
Bitmap.GetPixel()
```
method works, it's relatively slow. If processing time is important, you'll need to use
```
Bitmap.LockBits()
```
to lock the bitmap in memory, and then some simple pointer use inside an
```
unsafe { }
```
block to access the pixels directly.
This article
on CodeProject gives some more details that you'll probably find useful.


q:
Connection.close() may throw SqlException, but I have always assumed that it is safe to ignore any such exceptions (and I have never seen code that does not ignore them).

Normally I would write:

 try{
    connection.close();
 }catch(Exception e) {}

Or

 try{
    connection.close();
 }catch(Exception e) {
     logger.log(e.getMessage(), e);
 }

The question is:

Is it bad practice (and has anyone had problems when ignoring such exceptions).

When Connection.close() does throw any exception.

If it is bad how should I handle the exception.

Comment:

I know that discarding exceptions is evil, but I'm reffering only to exceptions thrown when closing a connection (and as I've seen this is fairly common in this case).

Does anyone know when Connection.close() may throw anything?

[A]
In general, I've had days wasted by people throwing away exceptions like that.
I recommend following a few basic rules with exceptions:
If you are ABSOLUTELY SURE you will NEVER cause a problem with a checked exception, catch JUST that exception and comment exactly why you don't need to handle it. (Sleep throws an InterruptedException that can always be ignored unless you actually are interested in it, but honestly this is the only case I usually ignore--even at that, if you never get it, what's the cost of logging it?)
If you are not sure, but you may get it occasionally, catch and log a stack trace just so that if it is causing a problem, it can be found.  Again, catch only the exception you need to.
If you don't see any way the checked exception can be thrown, catch it and re-throw it as an unchecked exception.
If you know exactly what is causing the exception, catch it and log exactly why, you don't really need a stack trace in this case if you are very clear as to what's causing it (and you might mention the class that's logging it if you're not already using log4j or something.
It sounds like your problem would fall into the last category, and for this kind of a catch, never do what you wrote (Exception e), always do the specific exception just in case some unchecked exception is thrown (bad parameters, null pointer, ...)
Update:
The main problem here is that Checked Exceptions are ungood.  The only highly used language they exist in is Java. They are neat in theory, but in action they cause this behavior of catch and hide that you don't get with unchecked exceptions.
A lot of people have commented on the fact that I said that hiding them is okay sometimes.  To be specific, the one case I can think of is:
```
```
try {
    Thread.sleep(1000);
catch (InterruptedException e) {
    // I really don't care if this sleep is interrupted!
}
```
```
I suppose the main reason I feel this use is okay is because this use of InterruptedException is an abuse of the checked exception pattern in the first place, it's communicating the result of a sleep more than indicating an exception condition.
It would have made much more sense to have:
```
```
boolean interrupted=Thread.sleep(1000);
```
```
But they were very proud of their new checked exception pattern when they first created Java (understandably so, it's really neat in concept--only fails in practice)
I can't imagine another case where this is acceptable, so perhaps I should have listed this as
the
single case where it might be valid to ignore an exception.


q: I downloaded the free CodeRush Xpress version to try it.  Is there a way to change the colors it uses for it's highlighting and line drawing?  ie the matching braces.  I have a dark color scheme and my monitor I have VS on must suck because I can't see the lines.  Yet on the LCD I can.  Is there a way to change the colors?

[A]
I use
CodeRush Xpress 9.2
. It is possible to configure some colors used for highlighting in the Options menu of
CodeRush Xpress
. You can find the menu in
Visual Studio
under
DevExpress
->
Options
. Go to the
Painting
sub-item of the
Editor
item to control some of the colors used (among them
Navigation Fields
,
Navigation Links
and
Text fields
).
If the
DevExpress
menu doesn't appear in your
Visual Studio
installation, just press
```
Alt+Ctrl+Shift+O
```
to directly go to DevExpress Options. Or, if you permanently want the
DevExpress
menu entry in
Visual Studio
, set the following registry key and restart it:
```
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Developer Express\CodeRush for VS\9.2]
    "HideMenu"=dword:00000000
```
```
This works at least with
Visual Studio 2005
and
2008
.


q: I work at a small company and our production system uses a hand-rolled RESTful API, implemented in Java with JAXB.  We now find that we're taking on customers who use Ruby on Rails, and I have to come up with a reference implementation to show customers how to use our API in Ruby. I'd love to be able to just tell them to use ActiveResource, but the XML required by our API uses (and absolutely requires) namespaces.  Unfortunately, we've already got a number of other customers who've already integrated this API, so removing the usage of namespaces is out of the question.  What's the best way to generate XML with namespaces in Ruby ?

[A]
"Best" obviously depends on your needs.
The
fastest
way to generate any XML in ruby is to use
libxml-ruby
-
link to rdoc
.
If your server gets any kind of load at all, this will be the way to go.
The
easiest
way to generate any XML in ruby is to use
REXML
as it's part of the standard library and therefore it "just works". If your XML generation is something that hardly ever gets used, it's probably easier to just go with rexml.
Both support XML namespaces - check the rdocs to find out how to set and get namespaces


q:
A library using off_t as a parameter for one function (seek). Library and application are compiled differently, one with large file support switched off, the other with large file support. This situation results in strange runtime errors, because both interpret off_t differently. How can the library check at runtime the size of off_t for the app? Or is there another solution, so that at least the user gets a meaningful error?

EDIT: The library (programmed in c and with autoconf) already exists and some third-party application use it. The library can be compiled with large file support (by default via AC_SYS_LARGEFILE). It is multiplatform, not only linux. How can be detected/prevented that installed applications will be broken by the change in LFS?

[A]
You could add an API to the library to return the sizeof(off_t) and then check it from the client.  Alternatively the library could require every app to provide the API in order to successfully link:
library.c:
```
```
size_t lib_get_off_t_size (void)
{
    return (sizeof(off_t));
}
```
```
client.c (init_function):
```
```
if (lib_get_off_t_size() != sizeof(off_t) {
    printf("Oh no!\n");
    exit();
}
```
```
If the library has an init function then you could put the check there, but then the client would have to supply the API to get the size of its off_t, which generally isn't how libraries work.


q:
I have a helper class that is just a bunch of static methods and would like to subclass the helper class.  Some behavior is unique depending on the subclass so I would like to call a virtual method from the base class, but since all the methods are static I can't create a plain virtual method (need object reference in order to access virtual method).

Is there any way around this?  I guess I could use a singleton.. HelperClass.Instance.HelperMethod() isn't so much worse than HelperClass.HelperMethod().  Brownie points for anyone that can point out some languages that support virtual static methods.

Edit: OK yeah I'm crazy. Google search results had me thinking I wasn't for a bit there.

[A]
Virtual static methods don't make sense.  If I call
```
HelperClass.HelperMethod();
```
, why would I expect some random subclass' method to be called?  The solution really breaks down when you have 2 subclasses of
```
HelperClass
```
- which one would you use?
If you want to have overrideable static-type methods you should probably go with:
A singleton, if you want the same subclass to be used globally.
A tradition class hierarchy, with a factory or dependency injection, if you want different behavior in different parts of your application.
Choose whichever solution makes more sense in your situation.


q:
Given a date range, I need to know how many Mondays (or Tuesdays, Wednesdays, etc) are in that range.

I am currently working in C#.

[A]
Any particular language and therefore date format?
If dates are represented as a count of days, then the difference between two values plus one (day), and divide by 7, is most of the answer.  If both end dates are the day in question, add one.
Edited:
corrected 'modulo 7' to 'divide by 7' - thanks.  And that is integer division.


q:
Suppose xmlNode is a XML DOM node, how do you get its XML system independently?

For IE, it is xmlNode.xml;

For Netscape, it is new XMLSerializer().serializeToString(xmlNode).

In jQuery, is there any built-in method I can leverage?


q:
Two table:

StoreInfo:
UserId uniqueidentifier
StoreNo nvarchar
UserName nvarchar
Password nvarchar

UserInfo:
UserId uniqueidentifier
UserName nvarchar
Password nvarchar

the UserId on StoreInfo is currently null. How do i update StoreInfo's UserId with UserInfo's UserId based on StoreInfo's UserName and Password is match to the UserName and Password from UserInfo.

the following is the query that i wrote which update the entire UserId in StoreInfo with the first UserId from UserInfo so i know it's wrong.

declare @UserName nvarchar(255)
declare @Password nvarchar(25)
declare @UserId uniqueidentifier

select @UserName = UserName, @Password = Password, @UserId = UserId
from UserInfo

select UserId, Password
   from FranchiseInfo
   where UserID = @UserName and Password = @Password

update FranchiseInfo
set UserI = @UserId

[A]
```
```
UPDATE StoreInfo
 set UserId = ui.UserId
 from StoreInfo si
  inner join UserInfo ui
   on ui.UserName = si.UserName
    and ui.Password = si.Password
 where si.UserId is null
```
```
This will update all rows in the table where UserId is not set.  Build out the where clause if you only want to update selected rows.  (I haven't tested this, so watch for typos!)


q:
I have some HTML that looks like this:

<ul class="faq">
    <li class="open">
        <a class="question" href="">This is my question?</a>
        <p>Of course you can, it will be awesome. </p>
    </li>
</ul>

Using CSS I'm setting the p tag to display:none;. I want to use jQuery to display or hide the p tag when the anchor is clicked, but I'm having some troubles with the sibling selector.

Just trying to get the selector working, I tried:

$("a.question").click(function () {
    $(this + " ~ p").css("background-color", "red");
});

to test it out. Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen.

[A]
```
```
$(this).next("p").css("...")
```
```
the "p" above is optional, if you just want the next non-whitespace node in the DOM.


q:
I have this large C++ project that I need to build on a platform that does not have a parallel make (like make -j on Linux). The server has 6 CPU's and I want to do a parallel build manually.

I can generate a task list like this for about 300 object files. I use the Makefile for the dependency checks and incremental build:

make -f Makefile obj1.o

make -f Makefile obj2.o

make -f Makefile obj3.o
...

How would I execute these tasks in parallel with no more then 6 tasks running at a time using Ksh and Perl? (Java or Python are not available :-( )

[A]
If the OS is properly handling inter-processor communication and scheduling, you should just be able to throw all the makes into backgrounded processes, as long as there are no interdependencies.
If they're all independent, I would issues a series of commands like this:
```
```
make -f Makefile obj1.o &
make -f Makefile obj2.o &
...
make -f Makefile objn.o &
```
```
With dependencies, string them with the double ampersand (
```
&&
```
) so that the dependent item doesn't start until its 'parent' has finished.
I realize that's not quite the solution you requested, but it's how I would attack the problem :)


q: I have some configuration values for an asp.net web app.  They will be maintained by a system admin once the system goes live.  Should I store these values in the database or in a config file?  Is there a best practice for this sort of thing?

[A]
Depending on the context of the config information, you could choose to leave it in the web.config or you could create maintenance tables for it in the database. I would typcially keep things more backend specific, like connection strings, ftp locations, usernames/passwords(for the application, not user permissions) in the web.config though.
I normally keep more relative information that relates to the information in the database rather than the application itself, in the database.
This is all loosely based though and not always the case.


q:
The windows installed on my machine has the locale en_AU and that's what JasperReports uses. I already tried changing the locale of all users, including the Administrator but it still uses en_AU.

How can I change that locale? Is it possible to change the REPORT_LOCALE parameter on my report?

[A]
The locale is set during execution, not in the JRXML.
Using Java, set the
```
REPORT_LOCALE
```
parameter for the report's parameter map. For example:
```
```
InputStream reportTemplate = getReportTemplate();
JRDataSource dataSource = getDataSource();

java.util.Map parameters = getParameters();
java.util.Locale locale = new Locale( "en", "US" );
parameters.put( JRParameter.REPORT_LOCALE, locale );

JasperFillManager.fillReport( reportTemplate, parameters, dataSource );
```
```
Using Jaspersoft Studio, open the project properties dialog to the
Report Execution
area:
Using iReport, set the report locale in the Options window under the "Report execution options" section in the General tab. This will set the report locale when run.


q: I want to create a javascript badge that displays a list of links. We host the javascript on our domain.  Other sites can put an empty div tag on their page and at the bottom a reference to our javascript that would render the content in the div tag.  How do you implement something like this?

[A]
just as you say, have them put a div at the bottom of their page:
```
```

```
```
then have them link to your javascript:
```
```

```
```
then have them alter their body tag, or onload to call your script
```
```

```
```


q:
There is a pretty strong need for us to design some workflows around various processes.  The problem is none of us actually know any workflow technology yet, and finding good data to compare the available options has been tedious and not entirely fruitful.

So I figured I'd ask you guys.

The main technologies we are looking at are Windows Workflow Foundation and eDocs Workflow.  What other options are there?  Sharepoint 2007 has workflow functionality too, right?  Is that just based on WF?

What are the pros and cons of the various technologies?  How do they compare?

EDIT: Also, one feature the administrative types like with eDocs Workflow is that it provides a method for them to edit it themselves.  I believe Sharepoint '07 does as well.  Is there some other way to allow that with a straight WWF implementation?

[A]
It is possible to 'rehost' the WF designer (the one from Visual Studio) in your own application, so that users can author workflows. There are a number of code examples on the web, the most important one from MS itself:
http://msdn.microsoft.com/en-us/library/aa480213.aspx
).
At some point, when evaluating WF, I implemented a demo application that did this and added some features and found that although it works, not everybody can understand and use the more difficult activities (like the policy activity) that require understanding of how the rules engine works.


q: I am writing a batch file script using Windows command and want to change each occurrence of some blank space with ","  What is the simplest way to do that?

[A] Well it will depend a lot on how you are getting the data, but you may be able to finagle something with a For-Do construct. Make the field seperator be a space then build the string back in the do with a , between each token. Might I suggest a more robust scripting language? You should have VBScript on just about any relatively modern windows bow.


q: English is not my mother tongue. However, I have to write comments in English. I want to improve my "comment English" by studying a piece of code which is commented in a good English. Please recommend an open source project which contains a lot of meaningful comments written by people with an excellent command of the language.

[A]
I don't think comments are a good place to learn, even if you have to emulate this style. Comments are often not even correct English and good projects will not have too many comments anyway, hence, not much to learn from.
If, on the other hand, you take a project that is commented extensively you can be almost sure that it's not a great role model since the programmers were incapable of conveying terse meaning. This is a generalization, of course. However, I believe it's (almost?) always true. YMMV.
Instead, learn English by studying the experts. There has been
a question
about this. I recommended
“On Writing Well” by William Zinsser
and I will do so again.
(By the way, English isn't my mother tongue either.)


q: I am using MS SQL Server 2005, I have dates stored in epoch time (starting 1970) I need to create a statement that will affect any record that has not been updated in the last 24 hours.

[A]
You can convert from SQL Server DateTime to Epoch time by calculating the number of seconds that have elapsed since Jan 1, 1970, like this.
```
Select DateDiff(Second, '19700101', GetDate())
```
To get rows from the last 24 hours....
```
```
Select Columns
From   Table
Where  EpochColumn Between DateDiff(Second, '19700101', GetDate()) And DateDiff(Second, '19700101, GetDate()-1)
```
```


q:
I am working on a windows service that polls for a connection to a network enabled devices every 15 seconds.  If the service is not able to connect to a device, it throws an exception and tries again in 15 seconds.  All of this works great.

But, lets say one of the devices is down for a day or more.  I am filling up my exception log with the same exception every 15 seconds.  Is there a standard way to prevent an exception from being written to the event log if the exception being thrown hasn't changed in the last x number of hours?

[A]
Maybe have a workflow that if the polls fails for a certain number of times, the polling interval is increased. e.g. polls every 15 seconds for like 3 times, if it fails then increase the polling interval to one minute, if it fails for n times then increase the time to one hour.
To be honest the workflow above doesnt really solve your problem. If I were you, I would reverse the workflow. Instead of the server polling for devices, why not do it the other way round? When a device connected to a networked machine, your client side service sends a message to the server, so that the server knows that the device is connected and alive.
Hope this helps...
RWendi


q:
How can you find out the number of active users when you're using a StateServer?   Also is it possible to query the StateServer and retrieve the contents in the Session State?

I know that this is all possible if you use SqlServer for a backing store, but I want them to be in memory.

[A]
Tracking the number of users would need to be done at the application level, not the session level.
You should be able to see what is currently in the session with the following:
```
```
StringBuilder builder = new StringBuilder();
foreach ( String key in Session.Contents ) {
    builder.AppendFormat("{0}: {1}<br />", key, Session[key]);
}
Response.Write(builder.ToString());
```
```


q: Is this possible?  I want to have the To:, Body, and an Attachment all pre-populated so all the user has to do is click send.  Thanks!

[A]
Open a new mail message (
```
ipm.note
```
is the
message class
for emails)
```
```
outlook.exe /c ipm.note
```
```
Open a new mail message and populate sender:
```
```
outlook.exe /c ipm.note /m someone@microsoft.com
```
```
Open a new mail message with attachment:
```
```
outlook.exe /c ipm.note /a filename
```
```
Combination: (First one below didn't work in Office 2016, second did)
```
```
outlook.exe /c ipm.note /m someone@microsoft.com&subject=test%20subject&body=test%20body
 outlook.exe /c ipm.note /m "someone@microsoft.com&subject=test%20subject&body=test%20body"
```
```
The %20 has to be used to produce a blank space.
More details at
Command Line for Creating a Pre-Addressed E-mail Message
Command-line switches can be found
here
This works for instance with a classic Outlook 2016 (build 16.0.4849.1000).
But, as
Snozzlebert
notes
in the comments
, for a  Outlook 365 Version 2001 (Build 12430.20184) the syntax would be:
```
```
outlook.exe /c ipm.note /m "someone@microsoft.com?subject=test"
```
```
the culprit was the
```
&
```
after the email-address - replacing it with
```
?
```
solved the problem.
It seems that Microsoft changed the syntax to the HTML mailto syntax.


q: Are there any plugins/tools available to go through the classpath of an eclipse project (or workspace) and highlight any unused jars?

[A]
ClassPathHelper
is a good start.
It automatically identifies orphan jars and much more.
The only limitation is with dependencies that are not defined in classes, e.g. in dependency injection framework configuration files.
You also have other options/complements, such as:
workingfrog "Relief"
, which relies on the ability to deal with real objects by examining their shape, size or relative place in space it gives a "physical" view on java packages, types and fields and their relationships, making them easier to handle.
Unnecessary Code Detector
: a eclipse PlugIn tool to find unnecessary (dead) public java code.


q: Anyone have a good resource or provide a sample of a natural order sort in C# for an FileInfo array?  I am implementing the IComparer interface in my sorts.

[A]
The easiest thing to do is just P/Invoke the built-in function in Windows, and use it as the comparison function in your
```
IComparer
```
:
```
```
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
```
```
Michael Kaplan has some
examples of how this function works here
, and the changes that were made for Vista to make it work more intuitively. The plus side of this function is that it will have the same behaviour as the version of Windows it runs on, however this does mean that it differs between versions of Windows so you need to consider whether this is a problem for you.
So a complete implementation would be something like:
```
```
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

public sealed class NaturalStringComparer : IComparer<string>
{
    public int Compare(string a, string b)
    {
        return SafeNativeMethods.StrCmpLogicalW(a, b);
    }
}

public sealed class NaturalFileInfoNameComparer : IComparer<FileInfo>
{
    public int Compare(FileInfo a, FileInfo b)
    {
        return SafeNativeMethods.StrCmpLogicalW(a.Name, b.Name);
    }
}
```
```


q:
Is it legal to more or less "copy" (or euphemistically, be very "inspired by") the idea and UI of a copyrighted program? This question popped in my mind when looking at "Things" which is a Mac-only program.

How legal would it be for someone to make a Windows version of this program with a basically identical UI design and feature set? Where are the legal boundaries of what counts as copyright infringement?

Unless you specify otherwise, I am assuming an "IANAL" for any answer, so you don't have to write that. ;)

[A]
Specific elements of a design can be copyrighted. Apple won the "trashcan" icon, but effectively nothing else during the Microsoft/Apple lawsuit over a look and feel. As long as the code is entirely your own, the graphics are your own (and yes, copying too closely a
specific
graphic element like the trashcan can be a problem) and you aren't doing cloning elements that are trademark/tradedress related, you should be within the law (in the US).
Of course, that doesn't mean that someone can't
sue
you. Meritless lawsuits are started all the time for intimidation. Also note that patents can cover the interaction of the user with a UI, so copyright might not be your primary problem in some cases.


q: I have a private const int defined in a C# class. I want compilation to fail with an error if the value of this int mod 3 != 0. How can I accomplish this?

[A]
Although there is an
#error
pre-processor directive for generating compile-time errors, there is no way for it to be based on the existence of a const value. It only works with compiler symbols, like "DEBUG", for which a value can't be assigned.


q:
I'm experiencing an issue with ActiveMQ and would like to trace/view all ActiveMQ activity.  The only log file I can find is one associated with persistent data (if this is turned on).  Are there any other log files I view or generate to tell me what's happening under the hood of ActiveMQ and why my consumers aren't consuming messages?  Any other suggestions?

Thanks in advance!

[A]
activemq has a jmx interface that you can connect to.
this gives us access to consumer counts messages queued dequeue and all sorts of data on memory usage etc.
http://activemq.apache.org/jmx.html
Has all the details to get you started.
I find it excellent in finding out whats going on with activemq.
A quick firing up of jconsole and you will be well on your way to finding out what is going on.
Paul


q:
I want to do a select in MySql that combines several columns... something like this pseudocode:

SELECT payment1_paid AND payment2_paid AS paid_in_full
FROM denormalized_payments
WHERE payment1_type = 'check';

Edit: payment1_paid and payment2_paid are booleans.

I can't use any other language for this particular problem than MySql.

Thanks for any help!

Edit: Sorry to everybody who gave me suggestions for summing and concatenating, but I've voted those early answers up because they're useful anyway. And thanks to everybody for your incredibly quick answers!

[A]
Just do
```
```
Select CONCAT(payment1_paid, payment2_paid) as paid_in_full
from denormalized_payments
where payment1_type = 'check';
```
```
You can concat any number of field you want.


q:
I need to have a single instance application (as per this answer), but it needs to be deployed via click once.

The problem is that I require that click once doesn't automatically detect an update an attempt to load a newer version while the application is running.  If it is running, then I need the other instance to be made active. Usually, when selecting a Click Once link, the very first thing it does is attempt to find an update. I want to intercept this and check for an already running instance prior to launching the normal update process.

Does anyone know how this is possible within a Click Once deployment scenario?

[A]
I don't think you'll be able to do it quite like this as the check before run is outside of your code.
However you can change the clickonce deployment options to check for updates during code execution.
If you need more control then you can use the
ApplicationDeployment Update
or
CheckForUpdate
methods to have absolute over the update process.


q:
This is the sequel to this question.

I would like to combine three columns into one on a MySql select. The first two columns are boolean and the third is a string, which is sometimes null. This causes strange results:

Select *, (payment1_paid && ((payment2_paid || payment2_type ="none"))) as paid_in_full from payments

Note: payment1_paid is boolean, payment2_paid is boolean, payment2_type is varchar.

Note: Please ignore how ridiculous the structure of this table is. Behind every piece of bad code there is a long explanation :)

Edit: Null is not interesting to me for the varchar value. I only want to know if it's really "none."

Thanks in advance for your help!

[A]
I guess you want NULL to be false? Try
```
(payment_paid IS NULL || payment2_type = "none")
```


q:
Back in the earlier days of the internet I remember that in certain browsers, every time you downloaded an image or a file, the URL of where that file was downloaded from would be written into that file's properties (I guess the summary tab?). I think Netscape v2 did this if I remember correctly.

I really miss that kind of functionality as every once in a while I'll run into a neat little program stored somewhere in the depths of my hard drive and wonder where I got it from originally.

I googled around but I'm not quite sure what terms to use to describe what I'm looking for. So I'm wondering if anyone knows of a Firefox plug-in or something similar that would do this?

[A]
For the IE Browser I use the hell out of Fidler to look at all traffic going across the wire.
For FireFox, you can use the FireBug plugin. There is a "Net" tab that will show you request information that is going across the wire.
Most of the time you can use one of these tools to see what URL was requested in order to start a download. You can also view all the get and post information that might need to be sent in order to have your request succeed.
Fidler is here:
http://www.fiddlertool.com/fiddler/
FireBug is here:
https://addons.mozilla.org/en-US/firefox/addon/1843
Best of Luck!


q:
So I'm reading The Art & Science of Javascript, which is a good book, and it has a good section on JSONP. I've been reading all I can about it today, and even looking through every question here on StackOverflow. JSONP is a great idea, but it only seems to resolve the "Same Origin Problem" for getting data, but doesn't address it for changing data.

Did I just miss all the blogs that talked about this, or is JSONP not the solution I was hoping for?

[A]
JSONP results in a SCRIPT tag being generated to another server with any parameters that might be required as a GET request. e.g.
```
```
<script src="http://myserver.com/getjson?customer=232&callback=jsonp543354" type="text/javascript">
</script>
```
```
There is technically nothing to stop this sort of request altering data on the server, e.g. specifying newName=Tony.  Your response could then be whether the update succeeded or not.  You will be limited by whatever you can fit on a querystring.  If you are going with this approach add some random element as a parameter so that proxy's won't cache it.
Some people may consider this goes against the way GET's are supposed to work i.e. they shouldn't cause data to change.


q:
Has anyone ever tried, or had any success at getting Wascana (Eclipse CDT + MinGW for Windows) to compile FFMPEG under Windows. Apparently it is possible, there is even a tutorial at Craig Shaw's website but I have not been able to make it work.

I run ./configure on the FFMPEG source code then create a new project in Eclipse and point it at the source but it doesn't recognise it as a Makefile project. I think I need to create a builder which works with MinGW but my feeble attempts so far have been unsuccessful.

[A]
Hey, I can answer my own question! After a lot of fiddling around, I have come up with the procedure:
NOTE: This is for Wascana 0.9.3 and a Sep 2008 SVN version of FFMPEG.
Prepare Environment
After installing Wascana, you'll need to update various MinGW and MSYS packages. Download and unpack the following (you can download them from the MinGW website):
MSYS packages:
bash-3.1
coreutils-5.97
m4-1.4.7
make-3.81
MinGW packages:
w32api-3.12
MinGW Runtime 3.15
Build
Unpack the FFMPEG source code and configure like so (do not compile it yet):
./configure --enable-memalign-hack --disable-shared --enable-static --disable-mmx --disable-mmx2 --disable-optimizations --disable-stripping
Launch Wascana/Eclipse and create a new C project.
Do not select "Hello World" project, just select a Makefile project and select the MinGW toolchain.
Set the project path to wherever your FFMPEG source code is.
Click finish and the source should build itself!
Install
Right click the project and select Make Targets > Create.
In the dialog, set both the Make Target and Target name to "install".
Run the target you just created. This will install the FFMPEG libraries.
Execute and Debug
Open the Debug Dialog
Right-click on "C/C++ Local Application" and choose "New"
Fill in the project name and select the EXE you want to run (in my case, ffplay_g.exe)
Go to the debugger tab and change the debugger to "MinGW gdb Debugger"
I also had to make sure a copy of SDL.dll was in the ffmpeg directory.
Phew, what an ordeal. That all worked for me, hopefully it will work for you too!


q: I need to write an extension method on a byte[].  Is that possible?

[A]
Sure, just make the first parameter of type
```
byte[]
```
.


q: When I press the standard Ctrl + E, C (an other variants) in VS2008 whilst editing a CSS file, it says that command is not available. How do I setup a shortcut to apply a plain old /* */ comment to selected text in VS? Thanks

[A]
Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module...
Paste the following in the source editor:
```
```
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module CommentCSS
    Sub CommentCSS()
        Dim selection As TextSelection
        selection = DTE.ActiveDocument.Selection

        Dim selectedText As String
        selectedText = selection.Text

        If selectedText.Length > 0 Then
            selection.Text = "/*" + selectedText + "*/"
        End If
    End Sub
End Module
```
```
You can create a keyboard shortcut by going to Tools|Options... and selecting
Keyboard
under the
Environment
section in the navigation on the left.  Select your macro and assign any shortcut you like.
You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the
Macros
section in the navigation on the left.  Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.


q:
My realtime app generates a data log: 100 words of data @10Khz.  I need to analyze it and produce some plots of the results.   There are intermediate calculations involved - I need to take some differences, averages, etc.   Excel would work fine, except for:

the 32000 item limit on graph data series is too small - that's only 3 seconds of data.

the glacial speed at which it processes changes to graphs containing large data series is unbearable.

What are good alternatives to Excel for manipulating and plotting large quantities of data?  I'm looking for something interactive, not a library.

[A]
For this sort of stuff we typically roll our own, but I know that isn't the solution you want. Can you use a good quality database (eg Oracle) to do the manipulation, then maybe put the summarized data back into Excel for the plotting? I believe Excel will link to databases these days, so you could make it quite automated.
Otherwise there are statistical tools like [SAS][1], but get your cheque book out first.
[1]:
http://www.sas.com/technologies/analytics/statistics/stat/index.html
SAS


q:
I have an app which could benefit from the user being able to choose to set an image as the wallpaper (the background image on the "slide to unlock" screen).

Is there a way for non-jailbreak third-party apps to do this? A search for "wallpaper" in the iPhone documentation returns nothing.

[A]
```
```
<configuration>
   <system.web>
      <compilation>
         <assemblies>
            <add assembly="<AssemblyName>, Version=<Version>, Culture=<Culture>, PublicKeyToken=<PublicKeyToken>"/>
         </assemblies>
      </compilation>
   </system.web>
</configuration>
```
```


q:
I have a table like as follows:

SoftwareName    Count    Country
Project         15       Canada
Visio           12       Canada
Project         10       USA
Visio           5        USA

How do I query it to give me a summary like...

SoftwareName    Canada    USA    Total
Project         15        10     25
Visio           12        5      17

How to do in T-SQL?

[A]
```
```
SELECT SoftwareName,
  SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada,
  SUM( CASE Country WHEN 'USA'    THEN [Count] ELSE 0 END ) AS USA,
  SUM( [Count] ) AS Total
FROM [Table]
GROUP BY SoftwareName;
```
```


q:
I have heard that LINQ2SQL has been written to support multiple database vendor providers however for internal political reasons at MS, only SQL Server has been supported.

Is this a fair summary of the situation, and if so has a timetable been released as to when other databases will be supported?

I am aware of Matt Warren's BUILDING AN IQUERYABLE PROVIDER series on the wayward weblog, but I would prefer not to build something now that will be released (probably better than I will do it) later

[A]
Check the
ADO.NET Entity Framework
(and
Linq to Entities
), you can look here also a
Sample Entity Framework Provider for Oracle
, and
here
are more examples about creating Data Providers for EF.


q:
I know that it is possible (in theory) to create a new type at run-time, but is it possible to modify a method body of an existing type at run-time? My plan (if I can get this to work) is to tag up methods with a custom attribute, and then at run-time search for methods with the attribute, and insert some of my own code into the method body.

Any suggestions?

I suppose if I can't get that approach to work, I could always go with a virtual method in a base class (with the attributes), combined with a static factory to spit out a derived dynamic type with my run-time generated method in the child class. This would not be quite as clean to use though.

[A]
Are you planning to do this for arbitrary types?  I would suppose not given that you are going to decorate the methods with an attribute.
Given that, I would think the better approach would be to define abstract methods in a super class for your types.  A method on the super class can house the boiler-plate method code, and delegate to the concrete implementations via the abstract methods for the individual type's behavior of that method.
Generally speaking though, unless you get into create code files and compiling dynamic assemblies at runtime, what you are looking to do can't be done.  There are likely far more practical OO principles and patterns you can use to achieve close to the same result.


q:
I would like to implement a command line interface for a Java application. This wouldn't be too difficult to do, except I would like the command line program to affect the state of another Java GUI program. So for example, I could type:

java CliMain arg1 arg2

And another running GUI instance would perform an appropriate action.

What is the easiest way of implementing something like this?

[A]
You could have the GUI application listen on a TCP port (on the
```
localhost
```
interface) and the CLI application would connect to it.
One way to do this would be to use REST over HTTP.


q:
Does anyone know a good SMTP/IMAP server library for C#?

I only found some long abandoned projects.

Only SERVER SIDE libraries, please no more posts about client libs.

Thanks,
Fionn

[A]
For SMTP, there's
```
System.Net.Mail
```
. For IMAP, I don't know.  But once you fetch the email from the server, you'll want to parse it. The MIME parsing is the hard part.  For that, I use, and recommend,
```
SharpMimeTools
```
.


q: What's an easy to use SNMP client library for c++?

[A]
Probably the best choice is
net-snmp
.  Note that the library has "C" linkage but will work just fine with C++.


q:
I'm trying to convert some strings that are in French Canadian and basically, I'd like to be able to take out the French accent marks in the letters while keeping the letter. (E.g. convert é to e, so crème brûlée would become creme brulee)

What is the best method for achieving this?

[A]
I've not used this method, but Michael Kaplan describes a method for doing so in his blog post (with a confusing title) that talks about stripping diacritics:
Stripping is an interesting job (aka
On the meaning of meaningless, aka All
Mn characters are non-spacing, but
some are more non-spacing than
others)
```
```
static string RemoveDiacritics(string text)
{
    var normalizedString = text.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder(capacity: normalizedString.Length);

    for (int i = 0; i < normalizedString.Length; i++)
    {
        char c = normalizedString[i];
        var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder
        .ToString()
        .Normalize(NormalizationForm.FormC);
}
```
```
Note that this is a followup to his earlier post:
Stripping diacritics....
The approach uses
String.Normalize
to split the input string into constituent glyphs (basically separating the "base" characters from the diacritics) and then scans the result and retains only the base characters. It's just a little complicated, but really you're looking at a complicated problem.
Of course, if you're limiting yourself to French, you could probably get away with the simple table-based approach in
How to remove accents and tilde in a C++ std::string
, as recommended by @David Dibben.


q:
So I just love it when my application is working great in Firefox, but then I open it in IE and... Nope, please try again.

The issue I'm having is that I'm setting a CSS display property to either none or table-cell with JavaScript.

I was initially using display: block, but Firefox was rendering it weird without the table-cell property.

I would love to do this without adding a hack in the JavaScript to test for IE.  Any suggestions?

Thanks.

[A]
Well,
IE7 does not have
```
display: table(-cell/-row)
```
so you will have to figure something else out or do browser targeting (which I agree, is bad hack). As a quick fix (I don't know what you're trying to achieve, appearance-wise) you could try
```
display: inline-block
```
and see what it looks like.
Maybe figure out a way to do
```
display: block
```
and solve the problem of "Firefox rendering it weird" instead? Can you describe what you mean by the weird rendering exactly?


q:
What's the most elegant way of implementing a DropDownList in ASP.NET that is editable without using 3rd party components.

As a last resort I will probably try using a TextBox with an AutoCompleteExtender with an image to 'drop down' the list; or a TextBox overlapping a HTML Select with some JavaScript to fill values from the Select to the TextBox. But I'm really hoping there is a more terse and maintainable solution.

Thanks in advance.

[A]
One Control on a Page
You can follow
this simple example for an Editable DropDownlist on Code Project
that uses standard ASP.NET TextBox and DropDownList controls combined with some JavaScript.
However, the code did not work for me until I added a reference to get the ClientID values for the TextBox and DropDownList:
```
```
<script language="javascript" type="text/javascript">

function DisplayText()
{
    var textboxId = '<% = txtDisplay.ClientID %>';
    var comboBoxId = '<% = ddSelect.ClientID %>';
    document.getElementById(textboxId).value = document.getElementById(comboBoxId).value;
    document.getElementById(textboxId).focus();
}
</script>

<asp:TextBox style="width:120px;position:absolute" ID="txtDisplay" runat="server"></asp:TextBox>

<asp:DropDownList ID="ddSelect" style="width:140px" runat="server">
    <asp:ListItem Value="test1" >test1</asp:ListItem>
    <asp:ListItem Value="test2">test2</asp:ListItem>
</asp:DropDownList>
```
```
Finally, in the code behind just like in the original example, I added the following to page load:
```
```
protected void Page_Load(object sender, EventArgs e)
{
    ddSelect.Attributes.Add("onChange", "DisplayText();");
}
```
```
Multiple Controls on a Page
I placed all of the above code in its own ASCX User Control to make it reusable across my project. However, the code as presented above only works if you require just one editable DropDownList on a given page.
If you need to support multiple custom DropDownList controls on a single page, it is necessary to set the JavaScript function name to be unique to avoid conflicts. Do this by once again using the ClientID:
in the ASCX file:
```
```
function DisplayText_<% = ClientID %>(){...}
```
```
in the code behind:
```
```
/// ...
ddSelect.Attributes.Add("onChange", "DisplayText_" + ClientID + "();");
///..
```
```
This is one way to avoid using 3rd party controls.


q:
I'm looking for a relativity cheap .NET Micro Framework development board for use on a personal robotics project. I'd don't need much for I/O, but I want at least one serial port and one Ethernet port.

I would prefer not to have to spend more than US$300 on the board, but if there is an obvious reason to get a better one I'm flexible.

Currently I'm looking at this device from SJJ Embedded Micro Solutions. Has anyone had experience with this device?

[A]
I have not had experience with the SJJ Embedded board, but I might just have to give it a shot.
I'm working on a robotics project as a hobby, and I'm currently prototyping with
Lego Mindstorms
and the Robotics SDK from Microsoft. I had planned on swapping to an
Arduino
which uses a C-like programming language and weighs in at around US$30 assembled.


q:
I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as Console.

For example, if I want to add an extension to Console, called 'WriteBlueLine', so that I can go:

Console.WriteBlueLine("This text is blue");

I tried this by adding a local, public static method, with Console as a 'this' parameter... but no dice!

public static class Helpers {
    public static void WriteBlueLine(this Console c, string text)
    {
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.WriteLine(text);
        Console.ResetColor();
    }
}

This didn't add a 'WriteBlueLine' method to Console... am I doing it wrong? Or asking for the impossible?

[A]
You can't add
static
methods to a type.  You can only add (pseudo-)instance methods to an instance of a type.
The point of the
```
this
```
modifier is to tell the C# compiler to pass the instance on the left-side of the
```
.
```
as the first parameter of the static/extension method.
In the case of adding static methods to a type, there is no instance to pass for the first parameter.


q: I was browsing the Hidden Features of C# question and thought I would try out one of the features I was unfamiliar with.  Unfortunately I use Visual Studio 2005 and the feature in question was introduced later.   Is there a good list for new features in C# 3.0 (Visual Studio 2008) vs. C# 2.0 (Visual Studio 2005)?

[A]
Here's a link to the MS page on .NET 3.0:
http://msdn.microsoft.com/en-us/library/bb822048.aspx
...and on VS 2008 for C#:
http://msdn.microsoft.com/en-us/library/bb383815.aspx
I haven't tried VS2008 and .NET 3.0 out, but I figure the links might help ;)


q:
'''use Jython'''

import shutil

print dir(shutil)

There is no, shutil.move, how does one move a file with Jython?
and while we at it, how does one delete a file with Jython?

[A]
```
os.rename()
```
to move, and
```
os.unlink()
```
to delete -- just like Python pre-
```
shutil
```
.


q:
I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky.
The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.

What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?

[A]
One way is to add the paths to your code using sys.path.
```
```
import sys

sys.path.append(somepath)
```
```
Another way is to use site, which processes .pth files in addition to adding to sys.path.
```
```
import site

site.addsitedir(sitedir, known_paths=None)
```
```
https://docs.python.org/library/site.html
But you probably don't want to add this to all your related code.
I've seen mention of sitecustomize.py being used to perform something like this, but after some testing I couldn't get it to work as might be expected.
Here it mentions that auto-import of sitecustomize.py ended in 2.5, if your not on 2.5 try it out.  (just add one of the path add methods above to the file and drop it in the directory your program is run)
A work around method is mentioned in the post for users of 2.5 and up.
http://code.activestate.com/recipes/552729/


q:
Why don't we see C-like languages that allow for callables with polymorphism in the return type? I could see how the additional type inference would be a hurdle, but we have plenty of languages with full-fledged type inference systems (that work for varying levels of "work").

Edit: By return type polymorphism I mean overloading the function signature only in the return type. For example, C++ and Java only allow overloading in the type of the formal parameters, not in the return type.

[A]
If by "return type polymorphism" you mean overloading based on the return value type, I'm not sure about other languages, but for C++ here's the answer (pretty much from the horse's mouth):
Function return types don't come into play in overload resolution simply because Stroustrup (I assume with input from other C++ architects) wanted overload resolution to be 'context independent'. See 7.4.1 - "Overloading and Return Type" from the "C++ Programming Language, Third Edition".
The reason is to keep resolution for
  an individual operator or function
  call context-independent.
They wanted it to be based only on how the overload was called - not how the result was used (if it was used at all).  Indeed, many functions are called without using the result or the result would be used as part of a larger expression.  One factor that I'm sure came into play when they decided this was that if the return type was part of the resolution there would be many calls to overloaded functions that would need to be resolved with complex rules or would have to have the compiler throw an error that the call was ambiguous.
And, Lord knows, C++ overload resolution is complex enough as it stands...


q:
What does the following code do? A link to something in the PHP manual would also be nice.

if ($_SERVER['SERVER_PORT'] <> 443) {
    doSomething();
}

[A]
Same as !=, "Not equal"
```
```
false <> true // operator will evaluate expression as true
false != true // operator will evaluate expression as true
```
```
Here is some reference:
PHP Comparison Operators


q:
I am building a utility page for a web app that I am working on.   I have an element that I want to use as a "console" of sorts.

I get entries for the console via Ajax calls (using prototype's Ajax.PeriodicalUpdater).

The problem I'm having is that when I insert new lines to the bottom of the "console", the scrollbar stays in the initial position (so I always see the top lines unless I manually scroll down).

How can I make the scrollbar automatically stay at the bottom?

I am using prototype for a few libraries that require it in this project, so I would prefer to stick with that or regular javascript if possible.

Just as a note, I already tried this:

onComplete: function() {
    $('console').scrollTop = $('console').scrollHeight;
}

It almost works, except that it is always "one step behind", and I can't see the most recent item.

[A]
```
```
new Ajax.PeriodicalUpdater(container, url, {
    onComplete: function() {
        (function() {
            container.scrollTop = container.scrollHeight;
        }).defer();
    }
});
```
```


q:
I wrote this scheme code to compute one solution of the quadratic equation ax2 + bx + c = 0

(define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a)))

However, someone told me that this procedure is hard to understand. Why?

What would a cleaned up version of this procedure look like?
Please let me know why the new procedure would be easier to understand.

Thanks

[A]
Well, one reason is that it's all on one line. You can make it more readable using something called
pretty-printing
, where you break it up into multiple lines and use whitespace:
```
```
(define (solve-quadratic-equation a b c)
  (define disc (sqrt (- (* b b)
                        (* 4.0 a c))))
  (/ (+ (- b) disc)
     (* 2.0 a)))
```
```
This way you can more clearly see the structure of the expressions.
And here's a quote from
SICP
:
There is no limit (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as
```
```
(+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))
```
```
which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form
```
```
(+ (* 3
      (+ (* 2 4)
         (+ 3 5)))
   (+ (- 10 7)
      6))
```
```
following a formatting convention known as
pretty-printing
, in which each long combination is written so that the operands are aligned vertically. The resulting indentations display clearly the structure of the expression.


q:
Programs that index filesystems seem to know which parts have changed since their last index and only rescan that part. How can I determine where the filesystem/files have changed since my last index. Don't care what language you answer in but I'm thinking c and windows.

An example of such a program is Sequoia View which generates a treemap of your hard disk.

[A]
A fairly simplistic method would be to take the file system's reported files sizes, dates (as integer values), and file names in a given directory and calculate a
checksum
you could then associate with that directory.  You would still need to perform this calculation on all of the directories using file system data  but you wouldn't have to go in depth (opening files to check for differences) unless a checksum reported a difference.
For tracking specific changes at the file level you would store checksums based on individual file attributes, and of the course the presence of or absence of files and subdirectories since the last scan.
This wouldn't necessarily guarantee that changes have not occurred as there are file system utilities for altering all manner of attributes though it would be a good first step for a basic scan.
You may find the
source code
for
fswatch
helpful.


q:
Is anyone familiar with this?

Write a procedure that takes as inputs
  a procedure that computes f and a
  positive integer n and returns the
  procedure that computes the nth
  repeated application of f. The
  procedure should be able to be used as
  follows:

((repeated square 2) 5)
625

I know that the following code I've created for the composition of functions will help make the solution simpler, but I'm not sure where to go from here:

(define (compose f g) (lambda (x) (f (g x))))

[A]
Well, you probably want something like this, right?
```
```
((repeated square 3) 5)
-> (square ((repeated square 2) 5))
-> (square (square ((repeated square 1) 5)))
-> (square (square (square ((repeated square 0) 5))))
-> (square (square (square (identity 5))))
```
```
(I don't know whether
```
identity
```
is predefined in Scheme.  If not, it's easy to write.)
Now, this is not directly reproducible because you can't magically enclose code outside of the call to
```
repeated
```
with arbitrary stuff.  However, what do these reduction steps look like when rewritten using
```
compose
```
?  Can you make out a pattern in the resulting list of steps and reproduce it?


q:
How do you programmatically set a DataContext that specifies the selected item of a list?

More simply, how do you reproduce this type of binding in code?

<StackPanel>
    <ListBox Name="listBox1" />
    <TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" />
</StackPanel>

[A]
You need to set a Name for the textbox so you can refer to it in code.  Then you should just be able to assign an object to the DataContext property.  You can create a data binding programatically like so:
```
```
Binding binding = new Binding();
binding.ElementName = "listBox1";
binding.Path = new PropertyPath("SelectedItem");
binding.Mode = BindingMode.OneWay;
txtMyTextBox.SetBinding(TextBox.TextProperty, binding);
```
```


q:
I'm having trouble getting pictures supported with PIL - it throws me this:

IOError: decoder jpeg not available

I installed PIL from binary, not realizing I needed libjpeg.

I installed libjpeg and freetype2 through fink.

I tried to reinstall PIL using instructions from http://timhatch.com/ (bottom of the page)

Download PIL 1.1.6 source package and have the Developer Tools already installed

Patch setup.py with this patch so it can find the Freetype you already have.

patch -p0 < leopard_freetype2.diff

sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)

But I'm still getting the same error.

I'm on Leopard PPC.

[A]
Is the python path still looking at the old binary version of libjpeg?
You will need to modify it to point to the new place if it is.
When you compiled the new version of the PIL did it say that it found libjpeg? It will compile happily without it (iirc) and the first sign of trouble you will see is at include time.
You will need to adjust the path at ./configure time.
The diff might just not work for you. You should test some more and then perhaps file a bug.


q: How would I implement a binary search using just an array?

[A]
Ensure that your array is sorted since this is the crux of a binary search.
Any indexed/random-access data structure can be binary searched.  So when you say using "just an array", I would say arrays are the most basic/common data structure that a binary search is employed on.
You can do it recursively (easiest) or iteratively.  Time complexity of a binary search is O(log N) which is considerably faster than a linear search of checking each element at O(N). Here are some examples from
Wikipedia: Binary Search Algorithm
:
Recursive:
```
```
BinarySearch(A[0..N-1], value, low, high) {
    if (high < low)
        return -1 // not found
    mid = low + ((high - low) / 2)
    if (A[mid] > value)
        return BinarySearch(A, value, low, mid-1)
    else if (A[mid] < value)
        return BinarySearch(A, value, mid+1, high)
    else
       return mid // found
    }
```
```
Iterative:
```
```
BinarySearch(A[0..N-1], value) {
   low = 0
   high = N - 1
   while (low <= high) {
       mid = low + ((high - low) / 2)
       if (A[mid] > value)
           high = mid - 1
       else if (A[mid] < value)
           low = mid + 1
       else
           return mid // found
   }
   return -1 // not found
}
```
```


q: What are the usual methods to compare two polygons for similarity? Vertices are in 2D.

[A]
You will find
some methods exposed here
.
Turning function
Graph matching
Shape signature by deformation
It is used in domains such as
image retrieval
(p. 52), where turning function is illustrated.


q:
Can someone explain to me how XOR swapping of two variables with no temp variable works?

void xorSwap (int *x, int *y)
{
    if (x != y) {
        *x ^= *y;
        *y ^= *x;
        *x ^= *y;
    }
}

I understand WHAT it does, but can someone walk me through the logic of how it works?

[A]
Most people would swap two variables x and y using a temporary variable, like this:
```
```
tmp = x
x = y
y = tmp
```
```
Here’s a neat programming trick to swap two values without needing a temp:
```
```
x = x xor y
y = x xor y
x = x xor y
```
```
More details in
Swap two variables using XOR
On line 1 we combine x and y (using XOR) to get this “hybrid” and we store it back in x. XOR is a great way to save information, because you can remove it by doing an XOR again.
On line 2. We XOR the hybrid with y, which cancels out all the y information, leaving us only with x. We save this result back into y, so now they have swapped.
On the last line, x still has the hybrid value. We XOR it yet again with y (now with x’s original value) to remove all traces of x out of the hybrid. This leaves us with y, and the swap is complete!
The computer actually has an implicit “temp” variable that stores intermediate results before writing them back to a register. For example, if you add 3 to a register (in machine-language pseudocode):
```
```
ADD 3 A // add 3 to register A
```
```
The ALU (Arithmetic Logic Unit) is actually what executes the instruction 3+A. It takes the inputs (3,A) and creates a result (3 + A), which the CPU then stores back into A’s original register. So, we used the ALU as temporary scratch space before we had the final answer.
We take the ALU’s implicit temporary data for granted, but it’s always there. In a similar way, the ALU can return the intermediate result of the XOR in the case of x = x xor y, at which point the CPU stores it into x’s original register.
Because we aren’t used to thinking about the poor, neglected ALU, the XOR swap seems magical because it doesn’t have an explicit temporary variable. Some machines have a 1-step exchange XCHG instruction to swap two registers.


q:
How to add new item in existing string array in C#.net?

I need to preserve the existing data.

[A]
I would use a List if you need a dynamically sized array:
```
```
List<string> ls = new List<string>();
ls.Add("Hello");
```
```


q:
I want to compute for month difference of 2 dates which will return a float value.

example:

date1='4/23/2008'
date2='12/31/2008'

that will be 7.y months. I want to find the y value. can someone give me the formula to make this in sql codes? tnx..

[A]
There's no standard sql to handle this universally. It depends on what database you're using. Basically, you need to convert the two date strings to the date format your database engine uses internally and subtract the two dates, what the result of the subtraction means will, again, depend. In Oracle, you'd use
```
to_date()
```
for the conversion and the result of the subtraction will be a float representing the time in number of days.
In short, search your db's manual for a section about date handling or data types.


q:
I've heard of "error" when using floating point variables.  Now I'm trying to solve this puzzle and I think I'm getting some rounding/floating point error.  So I'm finally going to figure out the basics of floating point error.

What is a simple example of floating point/rounding error (preferably in C++) ?

Edit:  For example say I have an event that has probability p of succeeding.  I do this event 10 times (p does not change and all trials are independent).  What is the probability of exactly 2 successful trials?  I have this coded as:

double p_2x_success = pow(1-p, (double)8) * pow(p, (double)2) * (double)choose(8, 2);

Is this an opportunity for floating point error?

[A]
Generally, floating point error refers to when a number that cannot be stored in the IEEE floating point representation.
Integers are stored with the right-most bit being 1, and each bit to the left being double that (2,4,8,...).  It's easy to see that this can store any integer up to 2^n, where n is the number of bits.
The mantissa (decimal part) of a floating point number is stored in a similar way, but moving left to right, and each successive bit being half of the value of the previous one.  (It's actually a little more complicated than this, but it will do for now).
Thus, numbers like 0.5 (1/2) are easy to store, but not every number <1 can be created by adding a fixed number of fractions of the form 1/2, 1/4, 1/8, ...
A really simple example is 0.1, or 1/10.  This can be done with an infinite series (which I can't really be bothered working out), but whenever a computer stores 0.1, it's not exactly this number that is stored.
If you have access to a Unix machine, it's easy to see this:
```
```
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.1
0.10000000000000001
>>>
```
```
You'll want to be really careful with equality tests with floats and doubles, in whatever language you are in.
(As for your example, 0.2 is another one of those pesky numbers that cannot be stored in IEEE binary, but as long as you are testing inequalities, rather than equalities, like p <= 0.2, then you'll be okay.)


q:
I hope someone will be able to answer my question.

I have Subversion set up, served by Apache2+SSL, doing web development.

I want a post-commit hook that runs svn update on my testing server, so when someone commits, it will automatically update the testing site. The hook doesn't work because the certificate is a self generated one and it's not trusted.

I've tried to accept (p)ermanently, but it doesn't.

Any ideas?

[A]
You didn't say what platform your testing server is running, but if it's a Windows box, then you need to add the certificate to your testing server's certificate store. The following technet articles might be of some use:
Certificate stores: Public Key
A Step-by-Step Guide to Advanced Certificate Management


q:
FindBugs has found a potential bug in my code. But it is not a bug.

Is it possible to mark this occurrence as 'not a bug' AND have it removed from the bug list?

I have documented quite clearly why for each case it is not a bug.

For example. A class implements the comparable interface. it has the compareTo method. I have however not overridden the equals method.

FindBugs does not like this as the JavaDocs state that it is recommended that

(x.compareTo(y)==0) == (x.equals(y))

Although in my case the above condition is and always will be true.

[A]
Probably by adding a
filter
as parameter of findbugs
Match clauses can only match information that is actually contained in the bug instances
```
```
<Match>
   <Class name="com.foobar.MyClass" />
   <Method name="myMethod" />
   <Bug pattern="EQ_COMPARETO_USE_OBJECT_EQUALS" />
</Match>
```
```


q:
If f is a numerical function and n is a positive integer, then we can form the nth repeated application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, if f is the function x + 1, then the nth repeated application of f is the function x + n. If f is the operation of squaring a number, then the nth repeated application of f is the function that raises its argument to the 2^nth power. Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. Your procedure should be able to be used as follows:

((repeated square 2) 5)
625

You can use this to simplify the answer:

 (define (compose f g) (lambda (x) (f (g x))))

[A]
Did you just delete and reask this question?  I'm copying my former answer here (thankfully, my browser had cached it):
Well, you probably want something like this, right?
```
```
((repeated square 3) 5)
-> (square ((repeated square 2) 5))
-> (square (square ((repeated square 1) 5)))
-> (square (square (square ((repeated square 0) 5))))
-> (square (square (square (identity 5))))
```
```
(I don't know whether identity is predefined in Scheme. If not, it's easy to write.)
Now, this is not directly reproducible because you can't magically enclose code outside of the call to repeated with arbitrary stuff. However, what do these reduction steps look like when rewritten using compose? Can you make out a pattern in the resulting list of steps and reproduce it?


q:
What would be the best way to avoid SQL injection on the C#.net platform.

Please post an C# implementation if you have any.

[A]
There's no algorithm needed - just don't use string concatenation to build SQL statements. Use the SqlCommand.Parameters collection instead. This does all the necessary escaping of values (such as replacing
```
'
```
with
```
''
```
) and ensures the command will be safe because somebody else (i.e. Microsoft) has done all the testing.
e.g. calling a stored procedure:
```
```
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand("MySprocName", connection))
{
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.AddWithValue("@Param1", param1Value);
    return command.ExecuteReader();
}
```
```
This technique also works for inline SQL statements, e.g.
```
```
var sql = "SELECT * FROM MyTable WHERE MyColumn = @Param1";
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand(sql, connection))
{
    command.Parameters.AddWithValue("@Param1", param1Value);
    return command.ExecuteReader();
}
```
```


q:
What is the recommended practice? Should I add the my sub-folder under the fitnesse folder to version control?

Context: working on a single developer rails pet project. I've my rails project under version-control (Subversion) however my fitnesse wiki pages lie under the fitnesse program folder.

Fitnesse seems to have its own version-control... (I see numbered zips along with each of my wiki pages) Is it reliable? Where does it store the revisions?

[A]
FitNesse stores old revisions of every page in a zip file in the same directory as the page's files. The zip filename marks the timestamp of the revision. It works similar to wikipedia - history, but not full-fledged version control.
In our company we wanted a setup where whenever we checkout a (possibly old) revision of the source, we also check out FitNesse tests that pass for that specific version.
Therefore, we installed FitNesse (the fitnesse directory, including the FitNesse executable and the FitNesseRoot directory) inside our source tree in version control, setting a rule to not import *.zip within the FitNesseRoot directory (as we have version control to keep history for us and don't need them).
This works excellent with sane SCMs (I used svn w/ svn-tortoise).
When we moved to Microsoft Foundation Server source control we had many issues with the checkout-edit-checkin workflow. Then again, this workflow is simply a bad idea in general, and should only be used by insane control-freaks.
(edit: answered commenter's question)


q: I have checked with the wikipedia article, and it seems like it is missing the c++ version of a code example.  I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?

[A]
I've done a search and replace on the C# example. This might not help you, because if you understand C++ then you should be able to understand the C# as it uses the same constructs and keywords (classes, functions, namespaces, public, etc)
```
```
// "Subsystem ClassA"
#include <iostream>
class SubSystemOne
{
public:
    void MethodOne()
    {
        std::cout << " SubSystemOne Method" << std::endl;
    }
}

// Subsystem ClassB"

class SubSystemTwo
{
public:
    void MethodTwo()
    {
        std::cout << " SubSystemTwo Method" << std::endl;
    }
}

// Subsystem ClassC"

class SubSystemThree
{
public:
    void MethodThree()
    {
            std::cout << " SubSystemThree Method" << std::endl;
    }
}

// Subsystem ClassD"

class SubSystemFour
{
public:
    void MethodFour()
    {
        std::cout << " SubSystemFour Method" << std::endl;
    }
}

// "Facade"

class Facade
{
    SubSystemOne one;
    SubSystemTwo two;
    SubSystemThree three;
    SubSystemFour four;

public:
    Facade()
    {
    }

    void MethodA()
    {
        std::cout << "\nMethodA() ---- " << std::endl;
        one.MethodOne();
        two.MethodTwo();
        four.MethodFour();
    }
    void MethodB()
    {
        std::cout << "\nMethodB() ---- " << std::endl;
        two.MethodTwo();
        three.MethodThree();
    }
}

int Main()
{
    Facade facade = new Facade();

    facade.MethodA();
    facade.MethodB();

    return 0;
}
```
```


q: I want to scale an image in C# with quality level as good as Photoshop does. Is there any C# image processing library available to do this thing?

[A]
When you draw the image using GDI+ it scales quite well in my opinion. You can use this to create a scaled image.
If you want to scale your image with GDI+ you can do something like this:
```
```
Bitmap original = ...
Bitmap scaled = new Bitmap(new Size(original.Width * 4, original.Height * 4));
using (Graphics graphics = Graphics.FromImage(scaled)) {
  graphics.DrawImage(original, new Rectangle(0, 0, scaled.Width, scaled.Height));
}
```
```


q: Can anyone explain to me how to get the visual state manager to work with a WPF application? It's just been added to the new wpftoolkit. I installed it as told, but even the sample doesn't show the VSM. In silverlight it work, but not in WPF. If installed the latest Blend 2 and updated with the SP1.

[A]
Read these 2 articles on VSM in WPF:
http://dotnet.org.za/rudi/archive/2008/10/29/silverlight-love-for-wpf.aspx
http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-visual-state-manager-overview.aspx
Their is a registry setting that needs to be "turned on" for VSM in WPF support for blend... Read more
here


q: Please give me some insight on how to get the best start on applying Aspect Oriented Programming to my C#.net applications?

[A]
I recommend trying
Spring.NET
. It lets you create "Interceptor" classes that can be wrapped around calls into business objects simply by adding entries into the application's config file.
We've used it to do connection/transaction handling, error logging and authentication. Which keeps all of those "aspects" out of the business logic code.