q: How does one invoke a groovy method that prints to stdout, appending the output to a string?

[A]
This demonstrates how you can do this.  Paste this into a Groovy script file and run it.  You will see the first call functions as normal.  The second call produces no results.  Finally, the last step in the main prints the results of the second call that were redirected to a ByteArrayOutputStream.
Have fun!
```
```
void doSomething() {
  println "i did something"
}

println "normal call\n---------------"
doSomething()
println ""

def buf = new ByteArrayOutputStream()
def newOut = new PrintStream(buf)
def saveOut = System.out

println "redirected call\n---------------"
System.out = newOut
doSomething()
System.out = saveOut
println ""

println "results of call\n---------------"
println buf.toString()
```
```


q:
I am 90% sure I saw this answer on stackoverflow before, in fact I had never seen the "int?" syntax before seeing it here, but no matter how I search I can't find the previous post, and it's driving me crazy.

It's possible that I've been eating the funny mushrooms by accident, but if I'm not, can someone please point out the previous post if they can find it or re-explain it?  My stackoverflow search-fu is apparently too low....

[A]
int? is shorthand for
```
Nullable<int>
```
.
This
may be the post you were looking for.

s: huggingface

c: devops

d: intermediate


q:
In an attempt to add some parameter validation and correct usage semantics to our application, we are trying to add correct exception handling to our .NET applications.

My question is this: When throwing exceptions in ADO.NET if a particular query returns no data or the data could not be found, what type of exception should I use?

Psuedocode:
(read, don't scrutinize the semantics of the code, I know it won't compile)

public DataSet GetData(int identifier)
{
    dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString();
    DataSet ds = dataAdapter.Fill(ds);
    if (ds.table1.Rows.Count == 0)
        throw new Exception("Data not found");

    return ds;
}

[A]
As far as ADO.net is concerned, a query that returns zero rows is not an error. If your application wishes to treat such a query as an error, you should create your own exception class by inheriting from Exception.
```
```
public class myException : Exception
{
   public myException(string s) : base()
   {
      this.MyReasonMessage = s;
   }
}

public void GetData(int identifier)
{
    dataAdapter.Command.Text = "Select * from table1 Where ident = " + identifier.toString();
    DataSet ds = dataAdapter.Fill(ds);
    if (ds.table1.Rows.Count == 0)
        throw new myException("Data not found");
}
```
```


q:
string percentage = e.Row.Cells[7].Text;

I am trying to do some dynamic stuff with my GridView, so I have wired up some code to the RowDataBound event. I am trying to get the value from a particular cell, which is a TemplateField. But the code above always seems to be returning an empty string.

Any ideas?

To clarify, here is a bit the offending cell:

<asp:TemplateField HeaderText="# Percentage click throughs">
<ItemTemplate>
    <%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %>
</ItemTemplate>
</asp:TemplateField>

On a related note, does anyone know if there is a better way of selecting the cell in the row. It sucks putting in cell[1]. Couldn't I do cell["mycellname"], so if I decide to change the order of my cells, bugs wont appear?

[A]
First you need to wrap your code in a
```
Label
```
or
```
Literal
```
control so that you can reference it properly. What's happening is that there's no way for the system to keep track of it, because there's no control associated with the text. It's the control's responsibility to add its contents to viewstate.
You need to use gridView.FindControl("controlName"); to get the control in the row. From there you can get at its properties including
```
Text
```
.
You can also get at the DataItem property of the Row in question and cast it to the appropriate type and extract the information directly.


q:
I doubt it can be done portably, but are there any solutions out there?  I think it could be done by creating an alternate stack and reseting SP,BP, and IP on function entry, and having yield save IP and restore SP+BP.  Destructors and exception safety seem tricky but solvable.

Has it been done?  Is it impossible?

[A]
Does
COROUTINE a portable C++ library for coroutine sequencing
point you in the right direction? It seems like an elegant solution that has lasted the test of time.....it's 9 years old!
In the DOC folder is a pdf of the paper A Portable C++ Library for Coroutine Sequencing by Keld Helsgaun which describes the library and provides short examples using it.
[update] I'm actually making successful use of it myself. Curiosity got the better of me, so I looked into this solution, and found it was a good fit for a problem I've been working on for some time!


q:
I have two threads in an Android application, one is the view thread, and the other is the worker thread. What I want to do is, sleep the worker thread until the view thread terminates the handling of the onDraw method.

How i can do this? is there any wait for the signal or something?

[A]
Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can continue its work.  Whenever the worker thread reaches a point where it should sleep, it does this:
```
```
stick.wait();
```
```
When the view thread finishes its onDraw work, it calls this:
```
```
stick.notify();
```
```
Note the requirement that the view thread owns the monitor on the object.  In your case, this should be fairly simple to enforce with a small sync block:
```
```
void onDraw() {
  ...
  synchronized (stick) {
    stick.notify();
  }
} // end onDraw()
```
```
Consult the javadoc for java.lang.Object on these methods (and notifyAll, just in case); they're very well written.


q:
My question is, which version-naming scheme should be used for what type of project.

Very common is major.minor.fix, but even this can lead to 4 number (i.e. Firefox 2.0.0.16). Some have a model that odd numbers indicate developer-versions and even numbers stable releases. And all sorts of additions can enter the mix, like -dev3, -rc1, SP2 etc.

Exists reasons to prefer one scheme over another and should different type of projects (i.e. Open Source vs. Closed Source) have different version naming schemes?

[A]
I personally prefer MAJOR.MINOR.BUGFIX-SUFFIX where SUFFIX is
```
dev
```
for development versions (version control checkouts),
```
rc1
```
/
```
rc2
```
for release candidates and no suffix for release versions.
If you have suffixes for development checkouts, maybe even with the revision number, there is no need to make them even/odd to keep them apart.


q:
I recently heard of BDD and found it very similar to TDD.

Which of these two do you use (if any)?

and which are the pros and cons of each?

[A]
BDD is similar to TDD but with a different mindset. In BDD you're trying to create executable specifications instead of tests. This is mostly accomplished by using a different vocabulary but similar mechanics as TDD.
BDD seems to be a reaction to a lot of cases where people claimed to be doing TDD but were writing integration tests instead of unit tests. BDD people thought talking about tests was misleading and so tests became specifications. This seems a bit metaphysical but there are some good ideas behind it.


q:
I can use properties of an Excel Worksheet to tell if the worksheet is protected (Worksheet.Protection, Worksheet.ProtectContents etc).

How can I tell using VBA if the entire workbook has been protected?

[A]
Worksheet.ProtectedContents is what you would need to use, on each Worksheet.
So I would set up a loop like this:
```
```
Public Function wbAllSheetsProtected(wbTarget As Workbook) As Boolean

Dim ws As Worksheet

wbAllSheetsProtected = True

For Each ws In wbTarget.Worksheets
    If ws.ProtectContents = False Then
        wbAllProtected = False
        Exit Function
    End If
Next ws

End Function
```
```
The function will return True if every worksheet is protected, and False if there are any worksheets not protected.  I hope this is what you were looking for.


q:
I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.

<div id="panel">
  <div id="field_name">TEXT GOES HERE</div>
</div>

Here's what the function will look like:

function showPanel(fieldName) {
  var fieldNameElement = document.getElementById('field_name');
  //Make replacement here
}

[A]
```
```
$('field_name').innerHTML = 'Your text.';
```
```
One of the nifty features of Prototype is that
```
$('field_name')
```
does the same thing as
```
document.getElementById('field_name')
```
. Use it! :-)
John Topley's answer using Prototype's
```
update
```
function is another good solution.


q:
I'm preparing to deploy my Django app and I noticed that when I change the "DEBUG" setting to False, all references to static files (i.e., JavaScript, CSS, etc..) result in HTTP 500 errors.

Any idea what's causing that issue (and how to fix it)?

[A]
I would highly recommend letting your web server handle the static requests, without getting to Django. In my
```
urls.py
```
, I only add the static request handler when debug is set to True.
Technically, Django serving the static works fine though. Definitely read the short docs page,
http://docs.djangoproject.com/en/dev/howto/static-files/
. You'll want to use an entry like this in
```
urls.py
```
```
```
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': '/path/to/media'})
```
```


q:
I'm looking for some programming guides to C# GUI design.  I come from the Java camp (where I can happily hand-code Swing/AWT GUIs) and thus don't have a clue where to start :(

Also, what difference (if any) is there between the Windows Presentation Foundation and WinForms?

[A]
Windows Presentation Foundation
is a vector-based system that is part of .NET 3.0.  It allows you to define your UI in XAML, and can do all sorts of animation, 3D, etc. very easily.  It's much newer and still being evalulated by a lot of folks.
Windows Forms
is a wrapper over older windows UI classes (Win32/MFC or whatever).  It came with .NET 1.0 and uses C# to define all the UI and its layout.  It's the tried and true UI method.


q:
I have a site using a custom favicon.ico. The favicon displays as expected in all browsers except IE. When trying to display the favicon in IE, I get the big red x; when displaying the favicon in another browser, it displays just fine. The page source includes
 and it does work in other browsers. Thanks for your thoughts.

EDIT: SOLVED: The source of the issue was the file was a jpg renamed to ico. I created the file as an ico and it is working as expected. Thanks for your input.

[A]
Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to check:
Is the code like this:
```
```
<link rel="icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
```
```
Is it in the
```
<head>
```
?
Is the image a
real
ico file? (renaming a bitmap is not a real .ico! Mildly different format)
Does it work when you add the page as a bookmark?


q:
I have a table in a MSSQL database that looks like this:

Timestamp (datetime)
Message (varchar(20))

Once a day, a particular process inserts the current time and the message 'Started' when it starts. When it is finished it inserts the current time and the message 'Finished'.

What is a good query or set of statements that, given a particular date, returns:

0 if the process never started

1 if the process started but did not finish

2 if the process started and finished

There are other messages in the table, but 'Started' and 'Finished' are unique to this one process.

EDIT: For bonus karma, raise an error if the data is invalid, for example there are two 'Started' messages, or there is a 'Finished' without a 'Started'.

[A]
```
```
Select Count(Message) As Status
From   Process_monitor
Where  TimeStamp >= '20080923'
       And TimeStamp < '20080924'
       And (Message = 'Started' or Message = 'Finished')
```
```
You could modify this slightly to detect invalid conditions, like multiple starts, finishes, starts without a finish, etc...
```
```
Select  Case When SumStarted = 0 And SumFinished = 0 Then 'Not Started'
             When SumStarted = 1 And SumFinished = 0 Then 'Started'
             When SumStarted = 1 And SumFinished = 1 Then 'Finished'
             When SumStarted > 1 Then 'Multiple Starts'
             When SumFinished > 1 Then 'Multiple Finish'
             When SumFinished > 0 And SumStarted = 0 Then 'Finish Without Start'
             End As StatusMessage
From    (
          Select Sum(Case When Message = 'Started' Then 1 Else 0 End) As SumStarted,
                 Sum(Case When Message = 'Finished' Then 1 Else 0 End) As SumFinished
          From   Process_monitor
          Where  TimeStamp >= '20080923'
                 And TimeStamp < '20080924'
                 And (Message = 'Started' or Message = 'Finished')
        ) As AliasName
```
```


q:
Management wants us to switch to Infragistics. But my boss says that any 3rd party is destined to fail, and at that point there won't be anything we can do about it.

Is he right, is he wrong? I don't know.

What are your opinions, is it better to use something developed inside the company, or do you prefer something like DevExpress, Infragistics, Krypton to name a few or is there something else even better that you would recommend instead?

[A]
I don't think it's entirely bad to rely on third parties. Some are very reputable and will do a great job of supporting you. But on the other hand, some are terrible to work with even if they stay in business. I don't know anything about the frameworks you've mentioned, though.
Have you considered an open source framework? That way you can still work on it yourself if all else fails. Of course, you have to take into account licensing requirements when doing this, but I think it's definitely something you should look into if it's appropriate for the project.


q:
What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's non-standard and only supported by Firefox.

 I've done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency.

 I've also seen recursive copying functions with various flaws.

I'm surprised no canonical solution exists.

[A]
If there wasn't any builtin one, you could try:
```
```
function clone(obj) {
    if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj)
        return obj;

    if (obj instanceof Date)
        var temp = new obj.constructor(); //or new Date(obj);
    else
        var temp = obj.constructor();

    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = clone(obj[key]);
            delete obj['isActiveClone'];
        }
    }
    return temp;
}
```
```


q: I want to filter a java.util.Collection based on a predicate.

[A]
Use
CollectionUtils.filter(Collection,Predicate)
, from Apache Commons.


q:
"It is not possible to check out a single file. The finest level of checkouts you can do is at the directory level."

How do I get around this issue when using Subversion?

We have this folder in Subversion where we keep all our images. I just want to check out one file (image) from that. This folder is really big and has ton of other stuff which I don't need now.

[A]
Use
```
svn cat
```
or
```
svn export
```
.
For that, you don't need to fetch the working directory, but you will not be able to commit any changes you make. If you need to make changes and commit them, you need a working directory, but you don't have to fetch it completely. Checkout the revision where the directory was still/almost empty, and then use 'svn cat' to extract the file from HEAD.


q:
I have implemented the WMD control that Stack Overflow uses into a project of mine, it almost works like a charm, but when I save the changes to the database it is saving the HTML version and not the Markdown version.

So where I have this in my text box:

**boldtext**

It is really saving this:

<b>boldtext</b>

How do I make it save the Markdown version?

[A]
Before you include
```
wmd.js
```
, or whatever you've named the WMD editor JavaScript code locally, add one line of JavaScript code:
```
```
wmd_options = {"output": "Markdown"};
```
```
This will force the output of the editor to Markdown.


q: My client has a multi-page PDF file.  They need it split by page.  Does anyone know of a way to do this - preferably in C#.

[A]
PDFSharp
is an open source library which may be what you're after:
Key Features
Creates PDF documents on the fly from any .Net language
Easy to understand object model to compose documents
One source code for drawing on a PDF page as well as in a window or on the printer
Modify, merge, and split existing PDF files
This sample
shows how to convert a PDF document with n pages into n documents with one page each.


q: I'm a big fan of the Jadclipse plugin and I'd really like to upgrade to Eclipse 3.4 but the plugin currently does not work. Are there any other programs out there that let you use jad to view source of code you navigate to from Eclipse? (Very useful when delving into ambiguous code in stack traces).

[A]
I'm successfully using JadClipse with Eclipse 3.4
Eclipse 3.4.0.I20080617-2000
JadClipse 3.3.0
It just works!
EDIT:
Actually, see
OlegSOM's answer
below for the additional steps that you might need to remember to take, if like me you forget to read documentation sometimes!


q: Ruby's standard popen3 module does not work on Windows. Is there a maintained replacement that allows for separating stdin, stdout, and stderr?

[A]
POpen4
gem has a common interface between unix and Windows. The following example (from their website) works like a charm.
```
```
require 'rubygems'
require 'popen4'

status =
  POpen4::popen4("cmd") do |stdout, stderr, stdin, pid|
    stdin.puts "echo hello world!"
    stdin.puts "echo ERROR! 1>&2"
    stdin.puts "exit"
    stdin.close

    puts "pid        : #{ pid }"
    puts "stdout     : #{ stdout.read.strip }"
    puts "stderr     : #{ stderr.read.strip }"
  end

puts "status     : #{ status.inspect }"
puts "exitstatus : #{ status.exitstatus }"
```
```


q: I'm using Team Foundation Build but we aren't yet using TFS for problem tracking, so I would like to disable the work item creation on a failed build. Is there any way to do this? I tried commenting out the work item info in the TFSBuild.proj file for the build type but that didn't do the trick.

[A]
Try adding this inside the PropertyGroup in your TFSBuild.proj:
```
```
<SkipWorkItemCreation>true</SkipWorkItemCreation>
```
```
If you are curious as to how this works, Microsoft.TeamFoundation.Build.targets contians the following:
```
```
<Target Name="CoreCreateWorkItem"
          Condition=" '$(SkipWorkItemCreation)'!='true' and '$(IsDesktopBuild)'!='true' "
          DependsOnTargets="$(CoreCreateWorkItemDependsOn)">

    <PropertyGroup>
      <WorkItemTitle>$(WorkItemTitle) $(BuildNumber)</WorkItemTitle>
      <BuildLogText>$(BuildlogText) $(DropLocation)\$(BuildNumber)\BuildLog.txt.</BuildLogText>
      <ErrorWarningLogText Condition="!Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')"></ErrorWarningLogText>
      <ErrorWarningLogText Condition="Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')">$(ErrorWarningLogText) $(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt.</ErrorWarningLogText>
      <WorkItemDescription>$(DescriptionText) %3CBR%2F%3E $(BuildlogText) %3CBR%2F%3E $(ErrorWarningLogText)</WorkItemDescription>
    </PropertyGroup>

    <CreateNewWorkItem
          TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
          BuildUri="$(BuildUri)"
          BuildNumber="$(BuildNumber)"
          Description="$(WorkItemDescription)"
          TeamProject="$(TeamProject)"
          Title="$(WorkItemTitle)"
          WorkItemFieldValues="$(WorkItemFieldValues)"
          WorkItemType="$(WorkItemType)"
          ContinueOnError="true" />

  </Target>
```
```
You can override any of this functionality in your own build script, but Microsoft provide the handy SkipWorkItemCreation condition at the top, which you can use to cancel execution of the whole target.


q:
I'm a big fan of the way Visual Studio will give you the comment documentation / parameter names when completing code that you have written and ALSO code that you are referencing (various libraries/assemblies).

Is there an easy way to get inline javadoc/parameter names in Eclipse when doing code complete or hovering over methods? Via plugin? Via some setting? It's extremely annoying to use a lot of libraries (as happens often in Java) and then have to go to the website or local javadoc location to lookup information when you have it in the source jars right there!

[A]
Short answer would be yes.
You can attach source using the properties for a project.
Go to Properties (for the Project) -> Java Build Path -> Libraries
Select the Library you want to attach source/javadoc for and then expand it, you'll see a list like so:
```
```
Source Attachment: (none)
Javadoc location: (none)
Native library location: (none)
Access rules: (No restrictions)
```
```
Select Javadoc location and then click Edit on the right hahnd side. It should be quite straight forward from there.
Good luck :)


q:
I am used to TYPO3 where I just can upload an image within the content element an then just determine the size an so on.

Is there a way to handle images in drupal somehow like this?

[A]
I'm just starting to learn about drupal, but here are some of my finds in the Drupal-image-gallery department - perhaps one of these will do what you want:
Flickrup
PROG Gallery
Gallery2


q:
I'm trying to setup some friendly URLs on a SharePoint website. I know that I can do the ASP.Net 2.0 friendly URLs using RewritePath, but I was wondering if it was possible to make use of the System.Web.Routing that comes with ASP.NET 3.5 SP1.

I think I've figured out how to get my route table loaded, but I'm not clear on what method to use to get the correct IHttpHandler to pass out.

Thanks!

[A]
It should be as easy as the below.
```
```
var route = new Route("blah/{*path}", new MyRouteHandler());
RouteTable.Routes.Add(route);

public class MyRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        // return some HTTP handler here
    }
}
```
```
Then register System.Web.Routing.UrlRoutingModule under HTTP modules in web.config and you should be good to go.
```
```
<add name="Routing" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
```
```


q:
I have a list control in GTK+ (a gtk.TreeView with one column), with "find-as-you type" enabled (so typing any text will open a small search field for searching through the list entries). Now, if the user enters some search text like "abc", should I search only for entries starting with "abc", or should I search for entries that contain "abc" somewhere in their text?

(links to relevant Human Interface Guidelines appreciated)

[A]
As a user, I appreciate a "contains" search rather than a "starts with".  Sometimes you can't remember exactly what you're looking for and it's more helpful to suggest things that are similar to your search query rather than using it as a straight filter.
There are times when there are multiple way to list something as well, ie:
```
```
Shining, The - King, Stephen
The Shining - Stephen King
King, Stephen - The Shining
```
```
etc.. In my opinion, typing in "Shining" should return any of those results.


q:
I was wondering if there is a good way to hook into the Application_Start of a SharePoint 2007 site when developing a feature? I know I can directly edit the Global.asax file in the site root, but is there a way to do this so that it gets deployed with the feature?

Thanks!

[A]
My gut feeling on this is that it won't be possible. Application_Start is called by the runtime as the asp.net engine is starting up, so there most likely can't be any way to hook the handler outside of modifying the Global.asax - e.g. the hook must be declarative and persistent as it has to survive the application stopping/unloading. So, if you have to write to the global.asax, I guess you could write a Feature EventReceiver to perform the modification.
That aside, can you give more details on the why? Perhaps there are other angles of attack. The idea of modifying the global.asax on the fly makes me feel ill. That can't be good.
Oisin


q:
In C++, what's the easiest way to get the local computer's IP address and subnet mask?

I want to be able to detect the local machine's IP address in my local network. In my particular case, I have a network with a subnet mask of 255.255.255.0 and my computer's IP address is 192.168.0.5. I need to get these had two values programmatically in order to send a broadcast message to my network (in the form 192.168.0.255, for my particular case)

Edit: Many answers were not giving the results I expected because I had two different network IP's. Torial's code did the trick (it gave me both IP addresses).

Edit 2: Thanks to Brian R. Bondy for the info about the subnet mask.

[A]
You can use gethostname followed by gethostbyname to get your local interface internal IP.
This returned IP may be different from your external IP though.  To get your external IP you would have to communicate with an external server that will tell you what your external IP is.  Because the external IP is not yours but it is your routers.
```
```
//Example: b1 == 192, b2 == 168, b3 == 0, b4 == 100
struct IPv4
{
    unsigned char b1, b2, b3, b4;
};

bool getMyIP(IPv4 & myIP)
{
    char szBuffer[1024];

    #ifdef WIN32
    WSADATA wsaData;
    WORD wVersionRequested = MAKEWORD(2, 0);
    if(::WSAStartup(wVersionRequested, &wsaData) != 0)
        return false;
    #endif

    if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
    {
      #ifdef WIN32
      WSACleanup();
      #endif
      return false;
    }

    struct hostent *host = gethostbyname(szBuffer);
    if(host == NULL)
    {
      #ifdef WIN32
      WSACleanup();
      #endif
      return false;
    }

    //Obtain the computer's IP
    myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
    myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
    myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
    myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;

    #ifdef WIN32
    WSACleanup();
    #endif
    return true;
}
```
```
You can also always just use 127.0.0.1 which represents the local machine always.
Subnet mask in Windows:
You can get the subnet mask (and gateway and other info) by querying subkeys of this registry entry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
Look for the registry value SubnetMask.
Other methods to get interface information in Windows:
You could also retrieve the information you're looking for by using:
WSAIoctl
with this option: SIO_GET_INTERFACE_LIST


q: Our development team work with Borland C++ Builder 6 and CodeGear C++ Builder 2007 (as well as Visual Studio). I hear a lot of comments that the Builder 2007 IDE crashes a lot more than BCB6 does. Does anyone out there have any experience of the C++ Builder 2009 IDE yet, particularly with a decent size application, and if so how does this compare with 6 or 2007 in terms of overall robustness?

[A]
I haven't used C++ Builder 2009 but maybe this will help you.
According to Chris Pattinson (QA manager at CodeGear), they made over 4000 fixes in both Delphi and C++ Builder 2009 (See this blog:
http://blogs.codegear.com/chrispattinson/2008/09/19/38897
)
He links to an article on cn.codegear.com which details all of the fixes for C++ Builder, see
http://dn.codegear.com/article/38715


q:
JSF is setting the ID of an input field to search_form:expression. I need to specify some styling on that element, but that colon looks like the beginning of a pseudo-element to the browser so it gets marked invalid and ignored. Is there anyway to escape the colon or something?

input#search_form:expression {
  ///...
}

[A]
Backslash:
```
```
input#search_form\:expression {  ///...}
```
```
See also
Using Namespaces with CSS
(MSDN)


q:
After installing a third-party SDK, it very discourteously makes one if its templates the default item in "Add New Item..." dialog in Visual Studio 2005. This is also the case for all other similar dialogs - "Add Class...", "Add User Control..." etc.

Is there a way to change this behavior?

[A]
Try looking at the registry under
```
```
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\
```
```
I see some relevant entries on my machine under
```
```
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0
```
```
for VS2008.


q: (using the IMAP commands, not with the assistance of any other mail package)

[A]
I guess you COPY the message to the new folder and then delete (EXPUNGE) it in the old one.
RFC3501
HINT
There's no DELETE command that does what you mean, you have to flag the message as deleted and then EXPUNGE the mailbox. Have a look at the RFC. Be careful with DELETE, as it deletes whole mailboxes, not single mails.


q:
Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container?

I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.

[A]
You can use poor-man's dependency injection:
```
```
public ProductController() : this( new Foo() )
{
  //the framework calls this
}

public ProductController(IFoo foo)
{
  _foo = foo;
}
```
```


q:
I switched from Perl to Python about a year ago and haven't looked back.  There is only one idiom that I've ever found I can do more easily in Perl than in Python:

if ($var =~ /foo(.+)/) {
  # do something with $1
} elsif ($var =~ /bar(.+)/) {
  # do something with $1
} elsif ($var =~ /baz(.+)/) {
  # do something with $1
}

The corresponding Python code is not so elegant since the if statements keep getting nested:

m = re.search(r'foo(.+)', var)
if m:
  # do something with m.group(1)
else:
  m = re.search(r'bar(.+)', var)
  if m:
    # do something with m.group(1)
  else:
    m = re.search(r'baz(.+)', var)
    if m:
      # do something with m.group(2)

Does anyone have an elegant way to reproduce this pattern in Python?  I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...

[A]
Using named groups and a dispatch table:
```
```
r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<data>.+)')

def do_foo(data):
    ...

def do_bar(data):
    ...

def do_baz(data):
    ...

dispatch = {
    'foo': do_foo,
    'bar': do_bar,
    'baz': do_baz,
}

m = r.match(var)
if m:
    dispatch[m.group('cmd')](m.group('data'))
```
```
With a little bit of introspection you can auto-generate the regexp and the dispatch table.


q:
I have a Java application that monitors a folder for incoming XML files.  When a new file is detected I need to test the file that it is not currently being updated and is closed.  My thought is to use File.canWrite() to test this.  Is there any issue with doing this?  Is this a good way to test that a file has been completely written?

Other ideas I am throwing around are:

Parse the incoming XML file and test
that the closing tag is there.

Check for the EoF character.

I just am not sure that any of these methods will handle all scenarios.

[A]
No, canWrite is not suitable for this purpose. In general the file will be writable even if another process is writing.
You need a higher level protocol to coordinate the locking. If you plan to use this code on a single platform, you may be able to use
NIO's FileLock facility
. But read the documentation carefully, and note that on many platforms, the lock is only advisory.
Another approach is to have one process write the file with a name that your process won't recognize, then rename the file to a recognizable name when the write is complete. On most platforms, the rename operation is atomic if the source and destination are the same file system volume. The name change might use a different file extension, or even moving the file from one directory to another (on the same volume).
Since in this case you are working exclusively with XML, looking for a close tag would work, but it isn't foolproof—what if there are comments after the final markup, or the writer or simply doesn't write valid XML?
Looking for the EOF will
not
work. There will always be an EOF, even when the writer has just opened the file and hasn't written anything yet. If this weren't so, the easiest thing would be to allow the reader to start parsing as soon as the file showed up; it would simply block until the writer closed the file. But the file system doesn't work this way. Every file has an end, even if some process is currently moving it.


q: As far as I understand, CouchDB indexes are updated when a view is queried.  Assuming there are more reads than writes, isn't this bad for scaling?  How would I configure CouchDB to update indexes on writes, or better yet, on a schedule?

[A]
CouchDB does regenerate views on update, but only on what has changed since the last read access to the view. Assuming your read volume greatly outweighs your write volume, this shouldn't be a problem.
When you're changing large numbers of documents at once this could lead to the possibility of the first read requests taking a noticeable amount of time. To alleviate this a few different possibilities have been suggested. Most rely on registering with CouchDB's update notifications and triggering reads automatically.
An example script for doing exactly that is available on the CouchDB wiki at [1].
[1]
http://wiki.apache.org/couchdb/RegeneratingViewsOnUpdate


q:
According to  select name from system_privilege_map System has been granted:

SELECT ANY TABLE

...and lots of other * ANY TABLES.

Plainly running

select * from the_table;
select * from the_table;

...nets the given response:

ERROR at line 1:
  ORA-00942: table or view does not exist

I can log in as that user and run the same command just fine.

I'm running under the assumption I should be able to run queries (select in this case) agaisnt a general user's DB table. Is my assumption correct, and if so, how do I do it?

[A]
If the_table is owned by user "some_user" then:
```
```
select * from some_user.the_table;
```
```


q:
I'm getting confused with the include/exclude jargon, and my actual SVN client doesn't seem to have (or I've been unable to find it easily) a simple option to add or remove a certain type of files for version control.

Let's say for example I've added the entire Visual Studio folder, with its solutions, projects, debug files, etc., but I only want to version the actual source files. What would be the simplest way to do that?

[A]
At the lowest level, SVN allows you to ignore certain files or patterns with
svn:ignore
attribute. VS add-ins for SVN such as
VisualSVN
will automatically ignore those files on your behalf. If you're using
TortoiseSVN
, you can right-click files and folders in Explorer and choose
Add to Ignore List
.


q: How do I find the location of my site-packages directory?

[A]
A solution that:
outside of virtualenv - provides the path of
global
site-packages,
insidue a virtualenv - provides the
virtualenv's
site-packages
...is this one-liner:
```
```
python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
```
```
Formatted for readability (rather than use as a one-liner), that looks like the following:
```
```
from distutils.sysconfig import get_python_lib
print(get_python_lib())
```
```
Source:
an very old version of
"How to Install Django" documentation
(though this is useful to more than just Django installation)


q:
Can I simulate in C#/C++ code Control+Alt+Delete sequence in Vista?
When UAC enabled/disabled?
How it is done in XP?

Can you provide a code sample that works in Vista?

[A]
PostMessage(HWND_BROADCAST, WM_HOTKEY, 0, MAKELONG(MOD_ALT | MOD_CONTROL, VK_DELETE));
You get PostMessage from the user32 dll
edit:
CodeProject article that has code for it
edit: There is some
discussion from VNC
on why that won't work in Vista and how to set up UAC to allow it.


q:
I don't develop too many desktop / Windows Forms applications, but it had occurred to me that there may be some benefit to using the MVC (Model View Controller) pattern for Windows Forms .NET development.

Has anyone implemented MVC in Windows Forms? If so, do you have any tips on the design?

[A]
Well, actually Windows Forms implements a "free-style" version of MVC, much like some movies implement some crappy "free-style" interpretation of some classic books (Romeo & Juliet come to mind).
I'm not saying Windows Forms' implementation is bad, it's just... different.
If you use Windows Forms and proper OOP techniques, and maybe an ORM like EntitySpaces for your database access, then you could say that:
The ORM/OOP infrastructure is the Model
The Forms are the Views
The event handlers are the Controller
Although having both View and Controller represented by the same object make separating code from representation way more difficult (there's no easy way to plug-in a "GTK+ view" in a class derived from Microsoft.Windows.Forms.Form).
What you can do, if you are careful enough. Is keep your form code
completely
separate from your controller/model code by only writing GUI related stuff in the event handlers, and all other business logic in a separate class. In that case, if you ever wanted to use GTK+ to write another View layer, you would only need to rewrite the GUI code.


q: I have a method that's about ten lines of code.  I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code.  This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers.  What's my best alternative?

[A]
Anonymous inner class
Say you want to have a function passed in with a
```
String
```
param that returns an
```
int
```
.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.
```
```
interface StringFunction {
    int func(String param);
}
```
```
A method that takes the pointer would just accept
```
StringFunction
```
instance like so:
```
```
public void takingMethod(StringFunction sf) {
   int i = sf.func("my string");
   // do whatever ...
}
```
```
And would be called like so:
```
```
ref.takingMethod(new StringFunction() {
    public int func(String param) {
        // body
    }
});
```
```
EDIT:
In Java 8, you could call it with a lambda expression:
```
```
ref.takingMethod(param -> bodyExpression);
```
```


q:
I'm implementing charts using The Ziya Charts Gem. Unfortunately, the documentation isn't really helpful or I haven't had enough coffee to figure out theming. I know I can set a theme using

chart.add(:theme, 'whatever')

Problem: I haven't found any predefined themes, nor have I found a reference to the required format.

[A]
To partly answer my own question, there are some themes in the website sources which can be checked out at
```
```
svn co svn://rubyforge.org/var/svn/liquidrail/samples/charting
```
```
(then go to /public/charts/themes/)


q:
I have an XML file that starts like this:

<Elements name="Entities" xmlns="XS-GenerationToolElements">

I'll have to open a lot of these files. Each of these have a different namespace but will only have one namespace at a time (I'll never find two namespaces defined in one xml file).

Using XPath I'd like to have an automatic way to add the given namespace to the namespace manager.
So far, i could only get the namespace by parsing the xml file but I have a XPathNavigator instance and it should have a nice and clean way to get the namespaces, right?

-- OR --

Given that I only have one namespace, somehow make XPath use the only one that is present in the xml, thus avoiding cluttering the code by always appending the namespace.

[A]
Unfortunately, XPath doesn't have any concept of "default namespace".  You need to register namespaces with prefixes with the XPath context, and then use those prefixes in your XPath expressions.  It means for very verbose xpath, but it's a basic shortcoming of XPath 1.  Apparently XPath 2 will address this, but that's no use to you right now.
I suggest that you programmatically examine your XML document for the namespace, associate that namespace with a prefix in the XPath context, then use the prefix in the xpath expressions.


q:
In crontab, I can use an asterisk to mean every value, or "*/2" to mean every even value.

Is there a way to specify every odd value? (Would something like "1+*/2" work?)

[A]
Try
```
```
1-23/2
```
```
From your question, I'm assuming Vixie Cron.  I doubt this will work with any other cron.


q:
I want to build an executable to distribute to people without python installed on their machines.

Is there an add-on to Eclipse that allows this? I couldn't find one.

If not, do you have a builder that you recommend that would make it easy to go to my python project directory created in Eclipse, and bundle it all up?

Thanks,
Mark

[A]
It's not eclipse, but ActiveState's
ActivePython FAQ
mentions the freeze utility, which sounds like it might be close to what you're asking for.


q:
I'm using a lat/long SRID in my PostGIS database (-4326).  I would like to find the nearest points to a given point in an efficient manner.  I tried doing an

ORDER BY    ST_Distance(point, ST_GeomFromText(?,-4326))

which gives me ok results in the lower 48 states, but up in Alaska it gives me garbage.  Is there a way to do real distance calculations in PostGIS, or am I going to have to give a reasonable sized buffer and then calculate the great circle distances and sort the results in the code afterwards?

[A]
This is from SQL Server, and I use Haversine for a ridiculously fast distance that may suffer from your Alaska issue (can be off by a mile):
```
```
ALTER function [dbo].[getCoordinateDistance]
    (
    @Latitude1  decimal(16,12),
    @Longitude1 decimal(16,12),
    @Latitude2  decimal(16,12),
    @Longitude2 decimal(16,12)
    )
returns decimal(16,12)
as
/*
fUNCTION: getCoordinateDistance

    Computes the Great Circle distance in kilometers
    between two points on the Earth using the
    Haversine formula distance calculation.

Input Parameters:
    @Longitude1 - Longitude in degrees of point 1
    @Latitude1  - Latitude  in degrees of point 1
    @Longitude2 - Longitude in degrees of point 2
    @Latitude2  - Latitude  in degrees of point 2

*/
begin
declare @radius decimal(16,12)

declare @lon1  decimal(16,12)
declare @lon2  decimal(16,12)
declare @lat1  decimal(16,12)
declare @lat2  decimal(16,12)

declare @a decimal(16,12)
declare @distance decimal(16,12)

-- Sets average radius of Earth in Kilometers
set @radius = 6366.70701949371

-- Convert degrees to radians
set @lon1 = radians( @Longitude1 )
set @lon2 = radians( @Longitude2 )
set @lat1 = radians( @Latitude1 )
set @lat2 = radians( @Latitude2 )

set @a = sqrt(square(sin((@lat2-@lat1)/2.0E)) +
    (cos(@lat1) * cos(@lat2) * square(sin((@lon2-@lon1)/2.0E))) )

set @distance =
    @radius * ( 2.0E *asin(case when 1.0E < @a then 1.0E else @a end ) )

return @distance

end
```
```
Vicenty is slow, but accurate to within 1 mm (and I only found a javascript imp of it):
```
```
/*
 * Calculate geodesic distance (in m) between two points specified by latitude/longitude (in numeric degrees)
 * using Vincenty inverse formula for ellipsoids
 */
function distVincenty(lat1, lon1, lat2, lon2) {
  var a = 6378137, b = 6356752.3142,  f = 1/298.257223563;  // WGS-84 ellipsiod
  var L = (lon2-lon1).toRad();
  var U1 = Math.atan((1-f) * Math.tan(lat1.toRad()));
  var U2 = Math.atan((1-f) * Math.tan(lat2.toRad()));
  var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
  var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);

  var lambda = L, lambdaP = 2*Math.PI;
  var iterLimit = 20;
  while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0) {
    var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
    var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) +
      (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
    if (sinSigma==0) return 0;  // co-incident points
    var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
    var sigma = Math.atan2(sinSigma, cosSigma);
    var sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
    var cosSqAlpha = 1 - sinAlpha*sinAlpha;
    var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
    if (isNaN(cos2SigmaM)) cos2SigmaM = 0;  // equatorial line: cosSqAlpha=0 (§6)
    var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
    lambdaP = lambda;
    lambda = L + (1-C) * f * sinAlpha *
      (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
  }
  if (iterLimit==0) return NaN  // formula failed to converge

  var uSq = cosSqAlpha * (a*a - b*b) / (b*b);
  var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
  var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
  var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
    B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
  var s = b*A*(sigma-deltaSigma);

  s = s.toFixed(3); // round to 1mm precision
  return s;
}
```
```


q:
I have a ASP.NET application running on a remote web server and I just started getting this error.  I can't seem to reproduce it in my development environment:

Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.

Could this be due to some misconfiguration of .NET Framework or IIS 6?

Update:
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code.  (Note that Set is a class that implements a set of unique objects.  It inherits from IEnumerable.)  This line:

Set<int> set = new Set<int>();

Is compiled into this line:

Set<int> set = (Set<int>) new ICollection<CalendarModule>();

The Calendar class is a totally unrelated class!!  Has anyone ever noticed .NET incorrectly compiling code like this before?

[A] Is your IIS setup to use .NET 2.0?  If not, change it to 2.0.  If you can't see 2.0 in the list then you'll need to run aspnet_regiis from the 2.0 framework directory.


q: Is it possible to throw an exception in a JSP without using scriptlet code?

[A]
You can throw an exception if you do this:
```
```
<c:out value="${1/0}" />
```
```
or something that is similarly "illegal"
Ideally though, since JSPs are associated with the view...you don't want to throw an exception. You want to catch them with
```
<c:catch>
```


q:
I need your help in determining the best approach for analyzing industry-specific sentences (i.e. movie reviews) for "positive" vs "negative". I've seen libraries such as OpenNLP before, but it's too low-level - it just gives me the basic sentence composition; what I need is a higher-level structure:
- hopefully with wordlists
- hopefully trainable on my set of data

Thanks!

[A]
What you are looking for is commonly dubbed
Sentiment Analysis
. Typically, sentiment analysis is not able to handle delicate subtleties, like sarcasm or irony, but it fares pretty well if you throw a large set of data at it.
Sentiment analysis usually needs quite a bit of pre-processing. At least tokenization, sentence boundary detection and part-of-speech tagging. Sometimes, syntactic parsing can be important. Doing it properly is an entire branch of research in computational linguistics, and I wouldn't advise you with coming up with your own solution unless you take your time to study the field first.
OpenNLP has some tools to aid sentiment analysis, but if you want something more serious, you should look into the
LingPipe
toolkit. It has some built-in SA-functionality and a nice
tutorial
. And you can train it on your own set of data, but don't think that it is entirely trivial :-).
Googling for the term will probably also give you some resources to work with. If you have any more specific question, just ask, I'm watching the nlp-tag closely ;-)


q: Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution.

[A]
If you can modify the string:
```
```
// Note: This function returns a pointer to a substring of the original string.
// If the given string was allocated dynamically, the caller must not overwrite
// that pointer with the returned value, since the original pointer must be
// deallocated using the same allocator with which it was allocated.  The return
// value must NOT be deallocated using free() etc.
char *trimwhitespace(char *str)
{
  char *end;

  // Trim leading space
  while(isspace((unsigned char)*str)) str++;

  if(*str == 0)  // All spaces?
    return str;

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace((unsigned char)*end)) end--;

  // Write new null terminator character
  end[1] = '\0';

  return str;
}
```
```
If you can't modify the string, then you can use basically the same method:
```
```
// Stores the trimmed input string into the given output buffer, which must be
// large enough to store the result.  If it is too small, the output is
// truncated.
size_t trimwhitespace(char *out, size_t len, const char *str)
{
  if(len == 0)
    return 0;

  const char *end;
  size_t out_size;

  // Trim leading space
  while(isspace((unsigned char)*str)) str++;

  if(*str == 0)  // All spaces?
  {
    *out = 0;
    return 1;
  }

  // Trim trailing space
  end = str + strlen(str) - 1;
  while(end > str && isspace((unsigned char)*end)) end--;
  end++;

  // Set output size to minimum of trimmed string length and buffer size minus 1
  out_size = (end - str) < len-1 ? (end - str) : len-1;

  // Copy trimmed string and add null terminator
  memcpy(out, str, out_size);
  out[out_size] = 0;

  return out_size;
}
```
```


q: I have email addresses encoded with HTML character entities. Is there anything in .NET that can convert them to plain strings?

[A]
Use
```
Server.HtmlDecode
```
to decode the HTML entities. If you want to
escape
the HTML, i.e. display the
```
<
```
and
```
>
```
character to the user, use
```
Server.HtmlEncode
```
.


q: I'm looking for a simple, easy to understand algorithm to alphabetically sort an array of characters in C.

[A]
Easy?  Do a bubble sort.
This is java and int rather than char, but you can easily adapt it...
```
```
int[] bubble(int a[])
    {
    for (int i = a.length; --i>=0; )
        {
        for (int j = 0; j<i; j++)
            {
            if (a[j] > a[j+1])
                {
                int T = a[j];
                a[j] = a[j+1];
                a[j+1] = T;
                }
            }
        }
    return(a);
    }
```
```


q:
I've been too lax with performing DB backups on our internal servers.

Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript?

[A]
Schedule the following to backup all Databases:
```
```
Use Master

Declare @ToExecute VarChar(8000)

Select @ToExecute = Coalesce(@ToExecute + 'Backup Database ' + [Name] + ' To Disk =     ''D:\Backups\Databases\' + [Name]   + '.bak'' With Format;' + char(13),'')
From
Master..Sysdatabases
Where
[Name] Not In ('tempdb')
and databasepropertyex ([Name],'Status') = 'online'

Execute(@ToExecute)
```
```
There are also more details on my blog: how to
Automate SQL Server Express Backups
.


q:
For example, I have an ASP.NET form that is called by another aspx:

string url = "http://somewhere.com?P1=" + Request["param"];
Response.Write(url);

I want to do something like this:

string url = "http://somewhere.com?P1=" + Request["param"];
string str = GetResponse(url);
if (str...) {}

I need to get whatever Response.Write is getting as a result or going to url, manipulate that response, and send something else back.

Any help or a point in the right direction would be greatly appreciated.

[A]
```
```
WebClient client = new WebClient();
string response = client.DownloadString(url);
```
```


q:
Is there a Java package providing funcionality like the .Net System.Data namespace ?
Specificaly the DataSet and Adaptor classes ?

[A]
ADO.NET is a framework with multiple uses, and DataSet is one of the main abstractions. Tell us more about what you want to achieve, and I'm sure somebody will find a Java framework for that purpose.
If you want a simple way to map Java objects to a data backend (like XML files), take a look at some of the POJO (Plain Old Java Object) frameworks.


q:
I have a dilemma, I'm using Java and Oracle and trying to keep queries on PL/SQL side. Everything is OK, until I have these complex queries which may and may not have conditions.

It's not hard in Java to put together WHERE clause with conditions, but it's not nice.
And on PL/SQL side I also found out that the only possibility for dynamic queries is string manipulations like

IF inputname IS NOT NULL THEN
    query := query ||' and NAME=' || inputname;
END IF;

Now I'm thinking, I'm leaving query in PL/SQL and sending WHERE clause with function parameter.
Any good recommendations or examples please?

[A]
SQLBuilder
might be useful to you from the Java side.  It allows you to write compile-time checked Java code that dynamically builds sql:
```
```
String selectQuery =
  (new SelectQuery())
  .addColumns(t1Col1, t1Col2, t2Col1)
  .addJoin(SelectQuery.JoinType.INNER_JOIN, joinOfT1AndT2)
  .addOrderings(t1Col1)
  .validate().toString();
```
```


q:
I have a dict, that looks like this:

{
    'foo': {
        'opt1': 1,
        'opt2': 2,
        },
    'foo/bar': {
        'opt3': 3,
        'opt4': 4,
        },
    'foo/bar/baz': {
        'opt5': 5,
        'opt6': 6,
        }
    }

And I need to get it to look like:

{
    'foo': {
        'opt1': 1,
        'opt2': 2,
        'bar': {
            'opt3': 3,
            'opt4': 4,
            'baz': {
                'opt5': 5,
                'opt6': 6,
                }
            }
        }
    }

I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.

[A]
Like this:
```
```
def nest(d):
    rv = {}
    for key, value in d.iteritems():
        node = rv
        for part in key.split('/'):
            node = node.setdefault(part, {})
        node.update(value)
    return rv
```
```


q: When I try to display the contents of a LOB (large object) column in SQL*Plus, it is truncated.  How do I display the whole thing?

[A]
```
```
SQL> set long 30000
SQL> show long
long 30000
```
```


q: There is no summary available of the big O notation for operations on the most common data structures including arrays, linked lists, hash tables etc.

[A]
I guess I will start you off with the time complexity of a linked list:
Indexing---->O(n)
Inserting / Deleting at end---->O(1) or O(n)
Inserting / Deleting in middle--->O(1) with iterator O(n) with out
The time complexity for the Inserting at the end depends if you have the location of the last node, if you do, it would be O(1) other wise you will have to search through the linked list and the time complexity would jump to O(n).


q:
I am a developer for a .net application that uses ClickOnce for deployment. I have deployed it over 60 times and computers have not had any issues downloading the latest release. However, when I deployed this morning, the following error occurs when computers with Office 2007 installed tries to start the application:

Unable to install or run the application. The application requires that assembly stdole Version 7.0.3300.0 be installed in the Global Assembly Cache (GAC) first. Please contact your system administrator.

However, computers with Office 2003 can start the application with no problem.

Does anyone have any recommendations on resolving this issue?

[A]
I am not sure about your particular problem, but the Office 12 version of the stdole library is different (and -in my experience- not always backwards compatible) than then one you have when you use Office 2003.
We use a wrapper around the Office DLLs to use the Mailmerge features Office has to offer and, believe it or not, Microsoft changed the interfaces
again
, therefore we have to compile
two
different wrappers, linked against
two
different office versions. In short, a PITA.
I am not coding against MS office again until they don't provide a Managed library.
Despite the rant, I think that you should install Office 12 in your computer and test from there. You'll notice that all the Office stuff is different. If you can make it work under Office 12 it
may
be compatible with machines with Office 11 (also known as 2003), but don't count on it and test it before deploying anything.
I don't think that this has anything to do with ClickOnce; it's more a GAC/OfficeVersion issue. Also, check for possible Vista problems, as the UAC and the DEP stuff tend to interfere with the way "old" applications used to work.


q: I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?

[A]
Can this be done with HTTP headers?
Yes, this is the way to go.
If
the information is provided, it's in the header as the
```
Content-Length
```
. Note, however, that this is not necessarily the case.
Downloading only the header can be done using a
```
HEAD
```
request instead of
```
GET
```
. Maybe the following code helps:
```
```
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://example.com/");
req.Method = "HEAD";
long len;
using(HttpWebResponse resp = (HttpWebResponse)(req.GetResponse()))
{
    len = resp.ContentLength;
}
```
```
Notice the property for the content length on the
```
HttpWebResponse
```
object – no need to parse the
```
Content-Length
```
header manually.


q:
Anyone know if it is possible to write an app that uses the Java Sound API on a system that doesn't actually have a hardware sound device?

I have some code I've written based on the API that manipulates some audio and plays the result but I am now trying to run this in a server environment, where the audio will be recorded to a file instead of played to line out.

The server I'm running on has no sound card, and I seem to be running into roadblocks with Java Sound not being able to allocate any lines if there is not a Mixer that supports it. (And with no hardware devices I'm getting no Mixers.)

Any info would be much appreciated -

thanks.


q:
So I've got some C code:

#include <stdio.h>
#include <string.h>

/* putting one of the "char*"s here causes a segfault */
void main() {
  char* path = "/temp";
  char* temp;
  strcpy(temp, path);
}

This compiles, runs, and behaves as it looks. However, if one or both of the character pointers is declared as global variable, strcpy results in a segmentation fault. Why does this happen? Evidently there's an error in my understanding of scope.

[A]
You forgot to allocate and initialize temp:
```
```
temp = (char *)malloc(TEMP_SIZE);
```
```
Just make sure TEMP_SIZE is big enough. You can also calculate this at run-time, then make sure the size is enough (should be at least strlen(path))


q:
I am working on an application that detects the most prominent rectangle in an image, then seeks to rotate it so that the bottom left of the rectangle rests at the origin, similar to how IUPR's OSCAR system works.  However, once the most prominent rectangle is detected, I am unsure how to take into account the depth component or z-axis, as the rectangle won't always be "head-on".  Any examples to further my understanding would be greatly appreciated.  Seen below is an example from IUPR's OSCAR system.

alt text http://quito.informatik.uni-kl.de/oscar/oscar.php?serverimage=img_0324.jpg&montage=use

[A]
You don't actually need to deal with the 3D information in this case, it's just a mappping function, from one set of coordinates to another.
Look at affine transformations, they're capable of correcting simple skew and perspective effects. You should be able to find code somewhere that will calculate a transform from the 4 points at the corners of your rectangle.
Almost forgot - if "fast" is really important, you could simplify the system to only use simple shear transformations in combination, though that'll have a bad impact on image quality for highly-tilted subjects.


q:
As someone who is only barely proficient in javascript, is jQuery right for me?  Is there a better library to use?  I've seen lots of posts related to jQuery and it seems to be the most effective way to incorporate javascript into ASP.NET applications.

I've been out to jQuery's site and have found the tutorials and other helpful information.  Any other reference material (i.e books, blogs, etc.) would be helpful.

Thanks!

[A]
Pros: you don't have to deal with the tangled mess that is cross-platform Javascript compatibility. You don't have to worry about which browsers support standard event handlers and which have their own event systems. You don't have to write two hundred lines of DOM manipulation withHugeLongFunctionNamesFromHell to get nice dynamic pages.
Cons: It's an extra 15KB of code your users have to download the first time they load your page.


q: I have a file. I want to get its contents into a blob column in my oracle database or into a blob variable in my PL/SQL program. What is the best way to do that?

[A]
Depends a bit on your environment.  In Java you could do it something like this...
```
```
// Need as OracleConnection in mConnection

// Set an EMPTY_BLOB()
String update = "UPDATE tablename"+
                " SET   blob_column = EMPTY_BLOB()"+
                " WHERE  ID = "+id;
CallableStatement stmt = mConnection.prepareCall(update);
stmt.executeUpdate();

// Lock the row FOR UPDATE
String select    = "BEGIN " +
                        "  SELECT " + blob_column
                        "  INTO ? " +
                        "  FROM " + tablename +
                        "  WHERE  ID = '" + id + "'" +
                        "  FOR UPDATE; " +
                        "END;";

stmt = mConnection.prepareCall(select);
stmt.registerOutParameter(1, java.sql.Types.BLOB);
stmt.executeUpdate();

BLOB blob = (BLOB) stmt.getBlob(1);
OutputStream bos = blob.setBinaryStream(0L);
FileInputStream fis = new FileInputStream(file);
//  Code needed here to copy one stream to the other
fis.close();
bos.close();
stmt.close();

mConnection.commit();
```
```
But it really depends what environment / tools you're using.  More info needed.


q:
Does anyone know any implementation of a templated cache of objects?

You use a key to find object (the same as in std::map<>)

You specify a maximum number of objects that can be in the cache at the same time

There are facilities to create an object not found in the cache

There are facilities to know when an object is discarded from the cache

For example :

typedef cache<int, MyObj*> MyCache;
MyCache oCache;
oCache.SetSize(1);
oCache.Insert(make_pair(1, new MyObj());
oCache.Touch(1);
MyObj* oldObj = oCache.Delete(1);

...

It can be as simple as a LRU or MRU cache.

Any suggestions are welcomed!

Nic

[A]
In an application I can hardly imagine it would speed/boost up performance to store objects that apparently can be re-created (hip: since they can be automatically discarded, when the cache tops).
A sw cache would require memory-fetching through associativism code, surely slower then memory allocation and constructor running (mostly memory initializations).
With the exception of manual user configuration to avoid the paging mechanism (precisely to boost performance, btw), most OS "caches" memory for you on disk... it's "paging", a form of "high-cost caching", because nothing gets thrown away, and it's done by specific HW, a sub-processing unit called Memory Management Unit...
A caching-code, in the big picture, would be slowing processes while being redundant.


q:
I have a table UserAliases (UserId, Alias) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.

Example:

UserId/Alias
1/MrX
1/MrY
1/MrA
2/Abc
2/Xyz

I want the query result in the following format:

UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz

Thank you.

I'm using SQL Server 2005.

p.s. actual T-SQL query would be appreciated :)

[A]
group_concat() sounds like what you're looking for.
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality.  here's one of the hits i found:
http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html


q:
I need a way to modify a value in a table after a certain amount of time has passed.  My current method is as follow:

insert end time for wait period in table

when a user loads a page requesting the value to be changed, check to see if current >= end time

if it is, change the value and remove the end time field, if it isn't, do nothing

This is going to be a major feature on the site, and so efficiency is the key; with that in mind, you can probably see the problem with how I'm doing it.  That same chunk of code is going to be called every time someone access a page that needs the information.

Any suggestions for improvements or better methods would be greatly appreciated, preferably in php or perl.

In response to cron job answers:
Thanks, and I'd like to do something like that if possible, but hosts limits are the problem.  Since this is a major part of the app, it can't be limited.

[A]
Can you use a cron job to check each field in the database periodically and update that way?
A big part of this is how frequently the updates are required.  A lot of shared hosts limit the frequency of cron checks, for example no more than every 15 minutes, which could affect the application.


q:
So I've got maybe 10 objects each of which has 1-3 dependencies (which I think is ok as far as loose coupling is concerned) but also some settings that can be used to define behavior (timeout, window size, etc).

Now before I started using an Inversion of Control container I would have created a factory and maybe even a simple ObjectSettings object for each of the objects that requires more than 1 setting to keep the size of the constructor to the recommended "less than 4" parameter size.  I am now using an inversion of control container and I just don't see all that much of a point to it.  Sure I might get a constructor with 7 parameters, but who cares?  It's all being filled out by the IoC anyways.

Am I missing something here or is this basically correct?

[A]
G'day George,
First off, what are the dependencies between the objects?
Lots of "isa" relationships? Lots of "hasa" relationships?
Lots of fan-in? Or fan-out?
George's response: "has-a mostly, been trying to follow the composition over inheritance advice...why would it matter though?"
As it's mostly "hasa" you should be all right.
Better make sure that your construction (and destruction) of the components is done correctly though to prevent memory leaks.
And, if this is in C++, make sure you use virtual destructors?


q:
I can't quite figure this out. Microsoft Access 2000, on the report total section I have totals for three columns that are just numbers. These =Sum[(ThisColumn1)], 2, 3, etc and those grand totls all work fine.

I want to have another column that says =Sum([ThisColumn1])+Sum([ThisColumn2]) + Sum([ThisColumn3]) but can't figure those one out. Just get a blank so I am sure there is an error.

[A]
Give the 3 Grand Totals meaningful Control Names and then for the Grand Grand Total use:
```
```
=[GrandTotal1] + [GrandTotal2] + [GrandTotal3]
```
```
Your Grand Total formulas should be something like:
```
```
=Sum(Nz([ThisColumn1], 0))
```
```


q: Pros. and cons? how long do you use it? What about jambi?

[A]
I've used Qt on a couple of projects I did in c++ on several platforms over a period of seven years.  I think it works pretty well and definitely was quicker for me to develop a decent GUI app on the Mac than plodding through a language I didn't know (Objective-C) at the time.
I think the signal/slot mechanism is a bit funky but isn't horrible.  Once you're use it for a bit, it's not a show stopper.  The connection stuff is easy to bungle up (or at least it was) and it's always good to check the return on those because your app will go merrily on its way and not tell you that it didn't work.
I've never used jambi.


q:
I've never used the Global Temporary Tables however I have some questions how they will work in a php environment.

How is data shared: Assuming persistent connections to oracle through php using oci8.  Is the data tied to a database id? is it done based on the Apache httpd demons?  Or is each individual request unique?

When is the data for the session cleared from the global temporary table? I'm assuming (or rather hoping) that its done when the php script exits.  Alternatively if not I'm assuming I'll need to remove it before script exit.

[A]
If I remember correct, the data in global temporary tables is available only from one active session and only for this active session (I mean session = connection). So you can see only data which was inserted before in active session. Therefore I belive, this data is cleared after closing session. No matter which language are you using.
At least I think so. :D
As is it written here:
http://www.oracle-base.com/articles/8i/TemporaryTables.php
The data in a global temporary table is private, such that data inserted by a session can only be accessed by that session.
Data in temporary tables is automatically delete at the end of the database session, even if it ends abnormally.
Sorry for my bad english.


q:
How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like:

//MySQL
SELECT foo FROM table LIMIT 10, 10

But I can't find a way to define offset.

[A]
I face this problem in MS Sql too... no Limit or rownumber functions. What I do is insert the keys for my final query result (or sometimes the entire list of fields) into a temp table with an identity column... then I delete from the temp table everything outside the range I want... then use a join against the keys and the original table, to bring back the items I want. This works if you have a nice unique key - if you don't, well... that's a design problem in itself.
Alternative with slightly better performance is to skip the deleting step and just use the row numbers in your final join. Another performance improvement is to use the TOP operator so that at the very least, you don't have to grab the stuff past the end of what you want.
So... in pseudo-code... to grab items 80-89...
```
```
create table #keys (rownum int identity(1,1), key varchar(10))

insert #keys (key)
select TOP 89 key from myTable ORDER BY whatever

delete #keys where rownumber < 80

select <columns> from #keys join myTable on #keys.key = myTable.key
```
```


q: On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?

[A]
You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.
For example:
```
```
class Booking < ActiveRecord::Base
  has_many   :booking_payments
  ....
  def destroy
    raise "Cannot delete booking with payments" unless booking_payments.count == 0
    # ... ok, go ahead and destroy
    super
  end
end
```
```
Alternatively you can use the before_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead.
```
```
def before_destroy
  return true if booking_payments.count == 0
  errors.add :base, "Cannot delete booking with payments"
  # or errors.add_to_base in Rails 2
  false
  # Rails 5
  throw(:abort)
end
```
```
```
myBooking.destroy
```
will now return false, and
```
myBooking.errors
```
will be populated on return.


q: For some reason, when I try to install SQL Server 2008 Express, I get an error saying that I need to have .Net Framework 3.5 installed first, but the thing is: I already have! So could anybody tell me if I can bypass this verification by updating a registry key or something? I have np with visual studio or any other thing... just when I try to install sql express.

[A] I ran into this once before. Make sure that it is installed. Reinstall if necessary. I believe what I did was install SP1. SQL Server 2008 has a tendency of trying to install the Compact Framework 3.5 and based on the build or refresh of SQL, Compact Framework 3.5 SP1. HTH!


q:
I recently moved my website to a shared hosting solution at asmallorange.com, but I had to set my domain to use their provided nameservers in order for the site to properly resolve.  I was determined to keep control of the domain's DNS but I could find no way to make my top level domain resolve to the shared location which was in the format of

server.asmallorange.com/~username

So I know I'm missing something here, my question is this:

What in their nameservers/DNS entry makes it possible for server.sharedhost.com/~username to serve as a top level domain? (ie. http://topleveldomain.com)

[A]
Nothing.  DNS simply maps topleveldomain.com to server.sharedhost.com.  It's the webserver which looks at the
```
Host: topleveldomain.com
```
header and knows that's equivalent to server.sharedhost.com/~username.


q:
Has anyone done this?  Basically, I want to use the html by keeping basic tags such as h1, h2, em, etc; clean all non http addresses in the img and a tags; and HTMLEncode every other tag.

I'm stuck at the HTML Encoding part.  I know to remove a node you do a "node.ParentNode.RemoveChild(node);" where node is the object of the class HtmlNode. Instead of removing the node though, I want to HTMLEncode it.

[A]
You would need to remove the node representing the element you don't want. The encoded HTML would then need to be re-added as a text node.
If you don't want to process the children of the elements that you want to throw away, you should be able to just use OuterHtml ... something like this might work:
```
```
node.AppendChild(new HtmlTextNode { Text = HttpUtility.HtmlEncode(nodeToDelete.OuterHtml) });
```
```


q:
Is there a way to test if an object is a dictionary?

In a method I'm trying to get a value from a selected item in a list box.  In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time.

I would like to do something similar to this:

if (listBox.ItemsSource is Dictionary<??>)
{
    KeyValuePair<??> pair = (KeyValuePair<??>)listBox.SelectedItem;
    object value = pair.Value;
}

Is there a way to do this dynamically at runtime using reflection?  I know it's possible to use reflection with generic types and determine the key/value parameters, but I'm not sure if there's a way to do the rest after those values are retrieved.

[A]
Check to see if it implements IDictionary.
See the definition of System.Collections.IDictionary to see what that gives you.
```
```
if (listBox.ItemsSource is IDictionary)
{
    DictionaryEntry pair = (DictionaryEntry)listBox.SelectedItem;
    object value = pair.Value;
}
```
```
EDIT:
Alternative when I realized KeyValuePair's aren't castable to DictionaryEntry
```
```
if (listBox.DataSource is IDictionary)
{
     listBox.ValueMember = "Value";
     object value = listBox.SelectedValue;
     listBox.ValueMember = ""; //If you need it to generally be empty.
}
```
```
This solution uses reflection, but in this case you don't have to do the grunt work, ListBox does it for you. Also if you generally have dictionaries as data sources you may be able to avoid reseting ValueMember all of the time.


q: How do I copy a file in Python?

[A]
```
shutil
```
has many methods you can use. One of which is:
```
```
import shutil

shutil.copyfile(src, dst)

# 2nd option
shutil.copy(src, dst)  # dst can be a folder; use shutil.copy2() to preserve timestamp
```
```
Copy the contents of the file named
```
src
```
to a file named
```
dst
```
. Both
```
src
```
and
```
dst
```
need to be the entire filename of the files, including path.
The destination location must be writable; otherwise, an
```
IOError
```
exception will be raised.
If
```
dst
```
already exists, it will be replaced.
Special files such as character or block devices and pipes cannot be copied with this function.
With
```
copy
```
,
```
src
```
and
```
dst
```
are path names given as
```
str
```
s.
Another
```
shutil
```
method to look at is
```
shutil.copy2()
```
. It's similar but preserves more metadata (e.g. time stamps).
If you use
```
os.path
```
operations, use
```
copy
```
rather than
```
copyfile
```
.
```
copyfile
```
will only accept strings.


q: Ideally something that will work with Oracle, MS SQL Server, MySQL and Posgress.

[A]
At the moment there's no open-source library that supports all the SQL backends you mention.
CLSQL
comes quite close (lacking only support for MS SQL). The alternatives are:
CL-RDBMS
(which supports Oracle, Postgres through Postmodern and SQLite3)
Postmodern
(only Postgres).
If you can use a commercial Lisp, you can give a try to
CommonSQL
included with Lispworks, which supports all the databases you mentioned.
CLSQL looks like the most popular open source library at the moment. Unfortunately, it seems to suffer from bit rot, and the developers had to make some compromises to support all those platforms.
If the RDB backend is not a constraint, then I recommend Postmodern. It is very well documented and has a clean API (and a nice small language compiled to SQL). Also, it is well maintained and small enough to keep being understandable and extensible. It focuses only on Postgres, not trying to be all things for all people.


q:
I was trying to remove all the lines of a file except the last line but the following command did not work, although file.txt is not empty.

$cat file.txt |tail -1 > file.txt

$cat file.txt

Why is it so?

[A]
It seems to not like the fact you're writing it back to the same filename.  If you do the following it works:
```
```
$cat file.txt | tail -1 > anotherfile.txt
```
```


q:
We have a customer requesting data in XML format. Normally this is not required as we usually just hand off an Access database or csv files and that is sufficient. However in this case I need to automate the exporting of proper XML from a dozen tables.

If I can do it out of SQL Server 2005, that would be preferred. However I can't for the life of me find a way to do this. I can dump out raw xml data but this is just a tag per row with attribute values. We need something that represents the structure of the tables. Access has an export in xml format that meets our needs. However I'm not sure how this can be automated. It doesn't appear to be available in any way through SQL so I'm trying to track down the necessary code to export the XML through a macro or vbscript.

Any suggestions?

[A]
There's an outline
here
of a macro used to export data from an access db to an xml file, which may be of some use to you.
```
```
Const acExportTable = 0

Set objAccess = CreateObject("Access.Application")
objAccess.OpenCurrentDatabase "C:\Scripts\Test.mdb"

'Export the table "Inventory" to test.xml
objAccess.ExportXML acExportTable,"Inventory","c:\scripts\test.xml"
```
```


q:
This is a sample (edited slightly, but you get the idea) of my XML file:

<HostCollection>
  <ApplicationInfo />
  <Hosts>
    <Host>
      <Name>Test</Name>
      <IP>192.168.1.1</IP>
    </Host>
    <Host>
      <Name>Test</Name>
      <IP>192.168.1.2</IP>
    </Host>
  </Hosts>
</HostCollection>

When my application (VB.NET app) loads, I want to loop through the list of hosts and their attributes and add them to a collection. I was hoping I could use the XPathNodeIterator for this. The examples I found online seemed a little muddied, and I'm hoping someone here can clear things up a bit.

[A]
You could load them into an XmlDocument and use an XPath statement to fill a NodeList...
```
```
Dim doc As XmlDocument = New XmlDocument()
doc.Load("hosts.xml")
Dim nodeList as XmlNodeList
nodeList = doc.SelectNodes("/HostCollectionInfo/Hosts/Host")
```
```
Then loop through the nodes


q:
How many messages does the queue for a standard window hold? What happens when the queue overflows?

The documentation for GetMessage and relatives doesn't say anything about this, and PeekMessage only gives you a yes/no for certain classes of messages, not a message count.

This page says that the queues are implemented using memory-mapped files, and that there is no message count limit, but that page is about WinCE. Does this apply to desktop Win32 as well?

[A]
10000 by default, but it can be adjusted via the registry.
If queue overflows, PostMessage fails.
Documentation here:
```
PostMessage
```
function on MSDN


q:
NOTE: I am not set on using VI, it is just the first thing that came to mind that might be able to do what I need. Feel free to suggest any other program.

I have a form with nearly 100 fields that I would like to auto-fill with PHP. I know how to do the autofill, but I would like to avoid manually adding the needed text to 100 fields.

Is there an automated way I can take the text:

<input name="riskRating" id="riskRating" type="text" />

and change it to:

<input name="riskRating" id="riskRating" type="text" value="<?php echo $data['riskRating']; ?>" />

Remember that I am wanting to do this to almost 100 fields. I am trying to avoid going to each field, pasting in the PHP code and changing the variable name manually.

I'm hoping some VI guru out there knows off the top of his/her head.


q: what configuration needs to be tweaked, and where does it live, in order to increase the maximum allowed post size?

[A]
Apache Tomcat by default sets a limit on the maximum size of HTTP POST requests it accepts. In Tomcat 5, this limit is set to 2 MB. When you try to upload files larger than 2 MB, this error can occur.
The solution is to reconfigure Tomcat to accept larger POST requests, either by increasing the limit, or by disabling it. This can be done by editing [TOMCAT_DIR]/conf/server.xml. Set the Tomcat configuration parameter maxPostSize for the HTTPConnector to a larger value (in bytes) to increase the limit. Setting it to 0 in will disable the size check. See the
Tomcat Configuration Reference
for more information.


q: How can you strip non-ASCII characters from a string? (in C#)

[A]
```
```
string s = "søme string";
s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty);
```
```


q:
I know I can do this:

IDateTimeFactory dtf = MockRepository.GenerateStub<IDateTimeFactory>();
dtf.Now = new DateTime();
DoStuff(dtf); // dtf.Now can be called arbitrary number of times, will always return the same value
dtf.Now = new DateTime()+new TimeSpan(0,1,0);  // 1 minute later
DoStuff(dtf); //ditto from above

What if instead of IDateTimeFactory.Now being a property it is a method IDateTimeFactory.GetNow(), how do I do the same thing?

As per Judah's suggestion below I have rewritten my SetDateTime helper method as follows:

    private void SetDateTime(DateTime dt) {
        Expect.Call(_now_factory.GetNow()).Repeat.Any();
        LastCall.Do((Func<DateTime>)delegate() { return dt; });
    }

but it still throws "The result for ICurrentDateTimeFactory.GetNow(); has already been setup." errors.

Plus its still not going to work with a stub....

[A]
You can use Expect.Call to accomplish this. Here's an example using the record/playback model:
```
```
using (mocks.Record())
{
   Expect.Call(s.GetSomething()).Return("ABC"); // 1st call will return ABC
   Expect.Call(s.GetSomething()).Return("XYZ"); // 2nd call will return XYZ
}
using (mocks.Playback())
{
   DoStuff(s);
   DoStuff(s);
}
```
```


q:
Using jQuery, how do you bind a click event to a table cell (below, class="expand") that will change the image src (which is in the clicked cell - original will be plus.gif, alternating with minus.gif) and hide/show the row immediately below it based on whether that row has a class of hide. (show it if it has a class of "hide" and hide if it does not have a class of "hide"). I am flexible with changing ids and classes in the markup.

Thanks

Table rows

<tr>
  <td class="expand"><img src="plus.gif"/></td>
  <td>Data1</td><td>Data2</td><td>Data3</td>
</tr>
<tr class="show hide">
  <td> </td>
  <td>Data4</td><td>Data5</td><td>Data6</td>
</tr>

[A]
You don't need the show and hide tags:
```
```
$(document).ready(function(){
    $('.expand').click(function() {
        if( $(this).hasClass('hidden') )
            $('img', this).attr("src", "plus.jpg");
        else
            $('img', this).attr("src", "minus.jpg");

        $(this).toggleClass('hidden');
        $(this).parent().next().toggle();
    });
});
```
```
edit: Okay, I added the code for changing the image.  That's just one way to do it.  I added a class to the expand attribute as a tag when the row that follows is hidden and removed it when the row was shown.


q:
I've got the directive

<VirtualHost *>
    <Location />
        AuthType Digest
        AuthName "global"
        AuthDigestDomain /
        AuthUserFile /root/apache_users
        <Limit GET>
            Require valid-user
        </Limit>
    </Location>
    WSGIScriptAlias / /some/script.wsgi
    WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25
    WSGIProcessGroup mywsgi
    ServerName some.example.org
</VirtualHost>

I'd like to know in the /some/script.wsgi

def application(environ, start_response):
    start_response('200 OK', [
        ('Content-Type', 'text/plain'),
    ])
    return ['Hello']

What user is logged in.

How do I do that?

[A]
add
```
WSGIPassAuthorization On
```
:
```
```
<VirtualHost *>
    <Location />
        AuthType Digest
        AuthName "global"
        AuthDigestDomain /
        AuthUserFile /root/apache_users
        <Limit GET>
            Require valid-user
        </Limit>
    </Location>
    WSGIPassAuthorization On
    WSGIScriptAlias / /some/script.wsgi
    WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25
    WSGIProcessGroup mywsgi
    ServerName some.example.org
</VirtualHost>
```
```
Then just read
```
environ['REMOTE_USER']
```
:
```
```
def application(environ, start_response):
    start_response('200 OK', [
        ('Content-Type', 'text/plain'),
    ])
    return ['Hello %s' % environ['REMOTE_USER']]
```
```
More information at
mod_wsgi documentation
.


q:
I'm writing an iPhone app with Cocoa in xcode.  I can't find any tutorials or sample code that shows how to take photos with the built in camera.  How do I do this?  Where can I find good info?

Thanks!

[A]
The
```
UIImagePickerController
```
class lets you take pictures or choose them from the photo library.  Specify the source type as
```
UIImagePickerControllerSourceTypeCamera
```
.
See also this question previously asked:
Access the camera with iPhone SDK


q: In wxWidgets, how can you find the pixels per inch on a wxDC? I'd like to be able to scale things by a real world number like inches. That often makes it easier to use the same code for printing to the screen and the printer.


q:
My Google-fu is failing me on this question.

I have a coworker who has Visual Studio 2005 on his machine. I have Visual Studio 2008. He wants to open a project I wrote in C# 3.0, and we've gotten that far, but VS2005 barfs on the 3.0 code, like var.

He has the 3.0 and 3.5 frameworks installed, as well as the Visual Studio 2005 Extensions for Windows Workflow. What else does he need? Or are we pursuing a lost cause, a wild goose chase spurred by my thinking that I heard this was possible somewhere one time?

Please don't suggest he install VS2008 or the Express edition. That simply isn't possible at this time. :(

[A] The IDE itself may not support the 3.0 functionality. If you can live without the 3.0 features you can compile to 2.0 which he should be able to run ok.


q:
This is an interesting conundrum.

We have a WPF app that has a Vista-like theme using soft pastels, Aero control templates, etc. What we've noticed is that this UI appears incredibly washed out on low quality LCDs. Is there a way to boost color saturation application-wide or are we at the mercy of bad monitors? Can we even tell, programmatically if we're being displayed on a low quality monitor?

EDIT:

Basically, these answers are what I wanted someone to confirm, without me leading people to say them! It was a management decision higher than me to go with this appearance and I needed some corroboration.

Thanks everyone!

[A]
I am not sure if WPF allows you to do anything, but my guess is that you can't directly control a user's monitor.
You can get things about the user's computer, namely bitdepth, but to adjust on-the-fly graphical information would be hugely expensive (processor wise).
You could write a routine that does it - changes the color of the graphics or such thing, but why?  It's the client machine - you really should program with the idea that you have no control over it.  If it is washed out on their screens, then they need better hardware, or they need to adjust the brightness/contract on their monitors correctly.  It's basically out of your realm of control.


q:
Is it possible to disable a trigger for a batch of commands and then enable it when the batch is done?

I'm sure I could drop the trigger and re-add it but I was wondering if there was another way.

[A]
```
```
DISABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }
ON { object_name | DATABASE | ALL SERVER } [ ; ]
```
```
http://msdn.microsoft.com/en-us/library/ms189748(SQL.90).aspx
followed by the inverse:
```
```
ENABLE TRIGGER { [ schema_name . ] trigger_name [ ,...n ] | ALL }
ON { object_name | DATABASE | ALL SERVER } [ ; ]
```
```
http://msdn.microsoft.com/en-us/library/ms182706(SQL.90).aspx


q:
I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following:

1-234-567-8901

1-234-567-8901 x1234

1-234-567-8901 ext1234

1 (234) 567-8901

1.234.567.8901

1/234/567/8901

12345678901

I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.


q:
I have an Enum called Status defined as such:

public enum Status {

    VALID("valid"), OLD("old");

    private final String val;

    Status(String val) {
        this.val = val;
    }

    public String getStatus() {
        return val;
    }

}

I would like to access the value of VALID from a JSTL tag. Specifically the test attribute of the <c:when> tag. E.g.

<c:when test="${dp.status eq Status.VALID">

I'm not sure if this is possible.

[A]
So to get my problem fully resolved I needed to do the following:
```
```
<% pageContext.setAttribute("old", Status.OLD); %>
```
```
Then I was able to do:
```
```
<c:when test="${someModel.status == old}"/>...</c:when>
```
```
which worked as expected.


q:
devenv mysolution.sln /build "Release|Win32" /project myproject

When building from the command line, it seems I have the option of doing a /build or /rebuild, but no way of saying I want to do "project only" (i.e. not build or rebuild the specified project's dependencies as well). Does anyone know of a way?

[A]
Don't call
```
devenv
```
, use the genericized build tool instead:
```
```
vcbuild subproject.vcproj "release|win32"
```
```


q:
Suppose I use the [RemoteClass] tag to endow a custom Flex class with serialization intelligence.

What happens when I need to change my object (add a new field, remove a field, rename a field, etc)?

Is there a design pattern for handling this in an elegant way?

[A]
Adding or removing generally works.
You'll get runtime warnings in your trace about properties either being missing or not found, but any data that is transferred and has a place to go will still get there. You need to keep this in mind while developing as not all your fields might have valid data.
Changing types, doesn't work so well and will often result in run time exceptions.
I like to use explicit data transfer objects and not to persist my actual data model that's used throughout the app.  Then your translation from DTO->Model can take version differences into account.


q:
I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.

I don't know if it depends on the technologies used, but I'll use Tomcat 5.5

I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)

[A]
Couldn't you just put the object in the HttpSession and then refer to it by its attribute name in each of the servlets?
e.g:
```
```
getSession().setAttribute("thing", object);
```
```
...then in another servlet:
```
```
Object obj = getSession.getAttribute("thing");
```
```


q:
In this MSDN article, MS explains how to specify other delimiters besides commas for csv-type exports from SSRS 2005, however, literal tab characters are stripped by the config file parser, and it doesn't appear that MS has provided a workaround.

This entry on Microsoft Connect seems to confirm this.

Has anyone developed a way to export tab-delimited files from SSRS 2005?

Or perhaps developed an open-source custom renderer to get the job done?

Note:  I've heard of manually appending &rc:FieldDelimiter=%09 via URL access, but that's not an acceptable workaround for my users and doesn't appear to work anyways.

[A]
I used a select query to format the data and BCP to extract the data out into a file. In my case I encapsulated it all in a stored procedure and scheduled it using the SQL Agent to drop files at certain times. The basic coding is similar to:
```
```
use tempdb
go
create view vw_bcpMasterSysobjects
as
   select
      name = '"' + name + '"' ,
      crdate = '"' + convert(varchar(8), crdate, 112) + '"' ,
      crtime = '"' + convert(varchar(8), crdate, 108) + '"'
   from master..sysobjects
go
declare @sql varchar(8000)
select @sql = 'bcp "select * from tempdb..vw_bcpMasterSysobjects
                     order by crdate desc, crtime desc"
               queryout c:\bcp\sysobjects.txt -c -t, -T -S'
                                             + @@servername
exec master..xp_cmdshell @sql
```
```
Please have a look at the excellent post
creating-csv-files-using-bcp-and-stored-procedures
.


q:
How can i check to see if a static class has been declared?
ex
Given the class

class bob {
    function yippie() {
        echo "skippie";
    }
}

later in code how do i check:

if(is_a_valid_static_object(bob)) {
    bob::yippie();
}

so i don't get:
Fatal error: Class 'bob' not found in file.php on line 3

[A]
```
bool class_exists( string $class_name [, bool $autoload  ]
```
)
This function checks whether or not the given class has been defined.


q:
How to disable standard ASP.NET handling of 401 response code (redirecting to login page) for AJAX/JSON requests?

For web-pages it's okay, but for AJAX I need to get right 401 error code instead of good looking 302/200 for login page.

Update:
There are several solutions from Phil Haack, PM of ASP.NET MVC - http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx

[A]
You could choose to create a custom
```
FilterAttribute
```
implementing the
```
IAuthorizationFilter
```
interface.
In this attribute you add logic to determine if the request are supposed to return JSON. If so, you can return an empty JSON result (or do whatever you like) given the user isn't signed in. For other responses you would just redirect the user as always.
Even better, you could just override the
```
OnAuthorization
```
of the
```
AuthorizeAttribute
```
class so you don't have to reinvent the wheel. Add the logic I mentioned above and intercept if the
```
filterContext.Cancel
```
is true (the
```
filterContext.Result
```
will be set to an instance of the
```
HttpUnauthorizedResult
```
class.
Read more about
"Filters in ASP.NET MVC CodePlex Preview 4"
on Phil Haacks blog. It also applies to the latest preview.


q:
Many websites have the concept of sending messages from user to user.  When you send a message to another user, the message would show up in their inbox.  You could respond to the message, and it would show up as a new entry in that message thread.

You should be able to see if you've read a given message already, and messages that have got a new response should be able to be at the top.

How would you design the classes (or tables or whatever) to support such a system?

[A]
```
```
user
 id
 name

messages
 id
 to_user_id
 from_user_id
 title
 date

message_post
 id
 message_id
 user_id
 message
 date
```
```
classes would reflect this sort of schema


q:
I have a local mercurial repository with some site-specific changes in it.  What I would like to do is set a couple files to be un-commitable so that they aren't automatically committed when I do an hg commit with no arguments.

Right now, I'm doing complicated things with mq and guards to achieve this, pushing and popping and selecting guards to prevent my changes (which are checked into an mq patch) from getting committed.

Is there an easier way to do this?  I'm sick of reading the help for all the mq commands every time I want to commit a change that doesn't include my site-specific changes.

[A]
I would put those files in
```
.hgignore
```
and commit a "sample" form of those files so that they could be easily recreated for a new site when someone checks out your code.