Question:
I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image.

I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately).

I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap.

Answer:
Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many solutions, but they are all not too good. I think the problem is that Apple does not really document the meta data format for the necessary data.
Here's how I'm doing it for a long time, very successfully:
Create a new DMG, writeable(!), big enough to hold the expected binary and extra files like readme (sparse might work).
Mount the DMG and give it a layout manually in Finder or with whatever tools suits you for doing that. The background image is usually an image we put into a hidden folder (".something") on the DMG. Put a copy of your app there (any version, even outdated one will do). Copy other files (aliases, readme, etc.) you want there, again, outdated versions will do just fine. Make sure icons have the right sizes and positions (IOW, layout the DMG the way you want it to be).
Unmount the DMG again, all settings should be stored by now.
Write a create DMG script, that works as follows:
It copies the DMG, so the original one is never touched again.
It mounts the copy.
It replaces all files with the most up to date ones (e.g. latest app after build). You can simply use
mv
or
ditto
for that on command line. Note, when you replace a file like that, the icon will stay the same, the position will stay the same, everything but the file (or directory) content stays the same (at least with ditto, which we usually use for that task). You can of course also replace the background image with another one (just make sure it has the same dimensions).
After replacing the files, make the script unmount the DMG copy again.
Finally call hdiutil to convert the writable, to a compressed (and such not writable) DMG.
This method may not sound optimal, but trust me, it works really well in practice. You can put the original DMG (DMG template) even under version control (e.g. SVN), so if you ever accidentally change/destroy it, you can just go back to a revision where it was still okay. You can add the DMG template to your Xcode project, together with all other files that belong onto the DMG (readme, URL file, background image), all under version control and then create a target (e.g. external target named "Create DMG") and there run the DMG script of above and add your old main target as dependent target. You can access files in the Xcode tree using ${SRCROOT} in the script (is always the source root of your product) and you can access build products by using ${BUILT_PRODUCTS_DIR} (is always the directory where Xcode creates the build results).
Result: Actually Xcode can produce the DMG at the end of the build. A DMG that is ready to release. Not only you can create a release DMG pretty easy that way, you can actually do so in an automated process (on a headless server if you like), using xcodebuild from command line (automated nightly builds for example).


Question:
What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field?

Field with value "00345ABC" would need to return "345ABC".

Answer:
You are looking for the
trim() function
.
Alright, here is your example
```
```
SELECT TRIM(LEADING '0' FROM myfield) FROM table
```
```


Question: Business Objects Web Services returns error codes and I have yet to find a good resource where these are listed and what they mean.  I am currently getting an "The resultset was empty. (Error: WBP 42019)".  Any ideas on where these might be listed?  I've called Business Objects support and the tech couldn't even tell me.  Anyone?

Answer:
Perhaps
This
? (PDF Link - beware)
Found here: (Google cache, as the page appears dead):
http://209.85.173.104/search?q=cache:fyB21Ywrj-MJ:support.businessobjects.com/communityCS/TechnicalPapers/pecodes.pdf.asp+%22Business+Objects%22+%22Error+Codes%22&hl=en&ct=clnk&cd=1&gl=us


Question:
I have the following string:

cn=abcd,cn=groups,dc=domain,dc=com

Can a regular expression be used here to extract the string after the first cn= and before the first ,? In the example above the answer should be abcd.

Answer:
Yeah, using perl/java syntax
```
cn=([^,]*),
```
. You'd then get the 1st group.


Question: I am trying to do 'rake db:migrate' and getting the error message 'no such file to load -- openssl'. Both 'openssl' and 'openssl-devel' packages are installed. Others on Debian or Ubuntu seem to be able to get rid of this by installing 'libopenssl-ruby', which is not available for RedHat. Has anybody run into this and have a solution for it?

Answer:
There is probably a gem you are missing.  Can you provide the stack trace and the line of code where it originates?
Re-run rake with
```
--trace
```
to get the stack trace printed.
EDIT: Also what version of Ruby are you running?  openssl.rb is in my 1.8.6 install


Question:
I'm using freemarker, SiteMesh and Spring framework.
For the pages I use ${requestContext.getMessage()} to get the message from message.properties. But for the decorators this doesn't work. How should I do to get the internationalization working for sitemesh?

Answer:
You have to use the
fmt
taglib.
First, add the taglib for sitemesh and fmt on the fisrt line of the decorator.
```
```
<%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator"%>
<%@ taglib prefix="page" uri="http://www.opensymphony.com/sitemesh/page"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%>
<fmt:setBundle basename="messages" />
```
```
In my example, the i18n file is messages.properties. Then you need to use the fmt tag to use the mesages.
```
```
<fmt:message key="key_of_message" />
```
```


Question:
The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world.

Does anybody have a more detailed explanation of the problem?

Answer:
Suppose you have COMPANY and EMPLOYEE. COMPANY has many EMPLOYEES (i.e. EMPLOYEE has a field COMPANY_ID).
In some O/R configurations, when you have a mapped Company object and go to access its Employee objects, the O/R tool will do one select for every employee, wheras if you were just doing things in straight SQL, you could
```
select * from employees where company_id = XX
```
.  Thus N (# of employees) plus 1 (company)
This is how the initial versions of EJB Entity Beans worked.  I believe things like Hibernate have done away with this, but I'm not too sure.  Most tools usually include info as to their strategy for mapping.


Question: I want (barely computer literate) people to easily submit a large number of files (pictures) through my web application. Is there a simple, robust, free/cheap, widely used, standard tool/component (Flash or .NET - sorry no java runtime on the browser) that allows a web user to select a folder or a bunch of files on their computer and upload them?

Answer:
swfupload
, the best tool I know that lets you do that. Simple, easy to use and even has a fallback mechanism for the  1% web users that don't have flash 8+.


Question:
I am using the AjaxControlToolkit in VS2005, and it works fine. I do have some issues though, when I go to some pages I have, then click back, I get this JavaScript error:

'AjaxControlToolkit' is undefined

I have searched MSDN forums, and google, and tried many of the solutions, but none have worked. I have tried, EnablePartialRendering="true", and others. Short of rewriting everything and changing the workflow of my application, is there any way to find the root cause of this, or fix it?

Answer:
Is that a javascript error?
I suppose it has to do with back-button support in the toolkit.
And undefined errors mostly occurs because somehow the script that contains "AjaxControlToolkit" doesn't gets properly loaded.
Thing that come to mind:
The order scripts get loaded, does the Toolkit gets priority?
When there are errors in any of the loaded scripts all the other scripts that hasn't loaded yet will simply be canceled and not gets loaded.
See the outputted HTML of the problem page, find links to all the AXD files and make sure you can download them and see valid javascripts inside.
And if you don't already, get
Firefox
and
Firebug
and you should be able to trace to the actual script line that emits the error.
Hope this helps.


Question: For example if the user is currently running VS2008 then I want the value VS2008.

Answer:
I am assuming you want to get the name of the process owning the currently focused window. With some P/Invoke:
```
```
// The GetForegroundWindow function returns a handle to the foreground window
// (the window  with which the user is currently working).
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

// The GetWindowThreadProcessId function retrieves the identifier of the thread
// that created the specified window and, optionally, the identifier of the
// process that created the window.
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

// Returns the name of the process owning the foreground window.
private string GetForegroundProcessName()
{
    IntPtr hwnd = GetForegroundWindow();

    // The foreground window can be NULL in certain circumstances,
    // such as when a window is losing activation.
    if (hwnd == null)
        return "Unknown";

    uint pid;
    GetWindowThreadProcessId(hwnd, out pid);

    foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
    {
        if (p.Id == pid)
            return p.ProcessName;
    }

    return "Unknown";
}
```
```


Question: How do I find out what directory my console app is running in with C#?

Answer:
On windows (not sure about Unix etc.) it is the first argument in commandline.
In C/C++ firts item in argv*
WinAPI - GetModuleFileName(NULL, char*, MAX_PATH)


Question:
I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me?

gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) >>$(DEP)

Answer:
If there is an argument to GCC to do this, I don't know what it is. We end up piping the dependency output through
sed
to rewrite all occurrences of
```
<blah>.o
```
as
```
${OBJDIR}/<blah>.o
```
.


Question:
C# has the keyword called yield. VB.NET lacks this keyword. How have the Visual Basic programmers gotten around the lack of this keyword? Do they implement they own iterator class?  Or do they try and code to avoid the need of an iterator?

The yield keyword does force the compiler to do some coding behind the scenes. The implementation of iterators in C# and its consequences (part 1) has a good example of that.

Answer:
I personally just write my own iterator class that inherits from
```
IEnumerator(Of T)
```
. It does take some time to get it right, but I think in the end it's better to write it right then try to avoid it. Another method that I have done is to write a recursive method that returns
```
IEnumerable(Of T)
```
and just returns
```
List(Of T)
```
and uses
```
.AddRange
```
.


Question:
I know there is a way to add a IE control, how do you add a chrome control...? Is it even possible right now?

I'm need this because of the fast javascript VM found in chrome.

Answer:
IE control is actually ActiveX component - so it can be wrapped in .Net component. It is not real IE, it's mainly only its rendering engine (HTML+CSS+JS) plus web client (HTTP and some more protocols) Control itself has no menu, bookmarks etc. Chrome is full featured browser. So you should be asking for WebKit (rendering engine chrome use, developed by Safari's guys) control.
There is an outdated Mozilla ActiveX (actually Gecko rendering engine). It's much more complicated to use and only available as ActiveX, no native .Net/C#.


Question: How do I get the physical addresses of my machine in Java?

Answer:
```
```
try {
    InetAddress addr = InetAddress.getLocalHost();

    // Get IP Address
    byte[] ipAddr = addr.getAddress();

    // Get hostname
    String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
```
```


Question: Will IE6 negotiate a 256 bit AES SSL connection if the server is capable?

Answer:
Possibly, I can't work out for sure yet, but what I can tell you is AES256 appears to be restricted by US Export restrictions on high-security cryptography, and for this reason, some platforms may lack this capacity.
Also, upon further searching, msdn pages ( such as
this one
) seem to point to AES support ( period! ) being only available since Vista / IE7.
No news yet whether or not MS decided to backport it, but it looks dubious.


Question: Has anyone figured out how to use Crystal Reports with Linq to SQL?

Answer:
Altough I haven't tried it myself it seems to be possible by using a combination of DataContext.LoadOptions to make it eager to accept relations and GetCommand(IQueryable) to return a SQLCommand object that preserves relations.
See more info on
MSDN Forums
.


Question:
I need to get the value of the 'test' attribute in the xsl:when tag, and the 'name' attribute in the xsl:call-template tag.   This xpath gets me pretty close:

..../xsl:template/xsl:choose/xsl:when

But that just returns the 'when' elements, not the exact attribute values I need.

Here is a snippet of my XML:

<xsl:template match="field">
    <xsl:choose>
    <xsl:when test="@name='First Name'">
        <xsl:call-template name="handleColumn_1" />
    </xsl:when>
</xsl:choose>

Answer:
do you want
```
.../xsl:template/xsl:choose/xsl:when/@test
```
If you want to actually get the value 'First Name' out of the test attribute, you're out of luck -- the content inside the attribute is just a string, and not a piece of xml, so you can't xpath it. If you need to get that, you must use string manipulation (Eg, substring) to get the right content


Question:
I mean, this is Sakai, the open source project of a learning management system. But, really I'm clueless trying to estimate the hidden costs in one implementation project (on the technology side, not the pedagogy-stuff) in a small-medium scale institution.

Deployment (1 engineer two or three months, with experience in Java EE)

Customisation (1 engineer, 1 designer two or three months also)

Support (1 guy)

One server reasonably good with 4, 8 or 16 GB in RAM. It will host the application server, the database server, and da da! ?

???

can somebody experienced, give me advice in how to estimate the TCO in open source implementations like this? In fact, it could be Moodle, and in that case I would be lost too!

Yep, is not really a question of programming, but I think that this is one proper place to ask.

Thanks!

Answer:
I work on support staff for a large uni that uses Blackboard. All the support people are students working part time, so salary can be pretty low per hour. You'll want to have someone on permanent staff as an administrator, who could also be the developer/deployment guy. Perhaps only part time if your institution is small enough, but someone who knows the ins and outs of the system will be handy
when
(not if) things go wrong. (Maybe you could combine them with the support role?)  On that note, you'll probably want a seperate server for backups and recovery, at the least something that will backup data.
If your school is small enough, maybe one person could handle the admin/support/dev roles by themselves (my roles are both support and developent and I often wish I had admin priveleges). You could probably talk to your IT department on how much servers are going for these days, I'm not sure there or on competitive salary ranges (but students are cheap.) Hope that helps some.


Question:
Given a source color of any hue by the system or user, I'd like a simple algorithm I can use to work out a lighter or darker variants of the selected color. Similar to effects used on Windows Live Messenger for styling the user interface.

Language is C# with .net 3.5.

Responding to comment: Color format is (Alpha)RGB. With values as bytes or floats.

Marking answer: For the context of my use (a few simple UI effects), the answer I'm marking as accepted is actually the most simple for this context. However, I've given up votes to the more complex and accurate answers too. Anyone doing more advanced color operations and finding this thread in future should definitely check those out. Thanks SO. :)

Answer:
You can convert your color into the HSL color-space, manipulate it there and convert back to your color-space of choice (most likely that's RGB)
Lighter colors have a higher L-value, darker a lower.
Here's the relevant stuff and all the equations:
http://en.wikipedia.org/wiki/HSL_color_space
Another method is to simply interpolate your color with white or black. This will also desaturate the color a bit but it's cheaper to calculate.


Question:
Here is a snippet of CSS that I need explained:

#section {
    width: 860px;
    background: url(/blah.png);
    position: absolute;
    top: 0;
    left: 50%;
    margin-left: -445px;
}

Ok so it's absolute positioning of an image, obviously.

top is like padding from the top, right?

what does left 50% do?

why is the left margin at -445px?

Update:
width is 860px.
The actual image is 100x100 if that makes a difference??

Answer: When position is absolute, top is vertical distance from the parent (probably the body tag, so 0 is the top edge of the browser window). Left 50% is distance from the left edge. The negative margin moves it back left 445px. As to why, your guess is as good as mine.


Question:
I have a certain page (we'll call it MyPage) that can be accessed from three different pages. In the Web.sitemap file, I tried to stuff the XML for this page under the three separate nodes like this:

< Page 1 >

    < MyPage / >

    ...

< /Page 1 >

< Page 2 >

    < MyPage / >

    ...

< /Page 2 >

< Page 3 >

    < MyPage / >

    ...

< /Page 3 >

In doing so I received the following error:

Multiple nodes with the same URL 'Default.aspx' were found.
XmlSiteMapProvider requires that sitemap nodes have unique URLs.

I read online that the SiteMapNodes are stored as a dictionary internally which explains why I can't use the same URL.  In any case, I'm just looking for alternate ways to go about solving this problem.  Any suggestions would be greatly appreciated.

Answer:
That's not really the intended purpose of the Web.sitemap file.
From
MSDN Docs of the SiteMap class
,
Fundamentally, the SiteMap
  is a container for a hierarchical
  collection of SiteMapNode objects.
  However, the SiteMap does not maintain
  the relationships between the nodes;
  rather, it delegates this to the site
  map providers.
So, to paraphrase, the web.SiteMap only describes the
hierarchy
of the pages, and not the relationships
between
those pages.
However, if your intention is just to have the 'MyPage" linked from your other pages, then you don't need to have MyPage as child nodes of those other pages anyway.
Hope that helps clarify things a little.


Question:
For my school work, I do a lot of switching computers (from labs to my laptop to the library).  I'd kind of like to put this code under some kind of version control.  Of course the problem is that I can't always install additional software on the computers I use.  Is there any kind of version control system that I can keep on a thumb drive?  I have a 2GB drive to put this on, but I can get a bigger one if necessary.

The projects I'm doing aren't especially big FYI.

EDIT:  This needs to work under windows.

EDIT II:  Bazaar ended up being what I chose.  It's even better if you go with TortoiseBzr.

Answer:
The best answer for you is some sort of DVCS (popular ones being
Git
,
Mercurial
,
Darcs
,
Bazaar
...).  The reason is that you have a full copy of the whole repository on any machine you are using.  I haven't used these systems personally, so others will be best at recommending a DVCS with a small footprint and good cross platform compatibility.


Question:
What are your best usability testing tips?
I need quick & cheap.

Answer:
You have to watch people use your application. If you work in a reasonable sized company, do some 'hallway testing'. Pull someone who is walking past your door into the room and say something like, 'Could you please run the payroll on this system for the next month? It should only take two minutes'.
Hopefully they won't have any problems and it shouldn't be too much of an imposition on the people walking past. Fix up any hiccups or smooth over any processes that are unnecessarily complex and repeat. A lot.
Also, make sure you know what usability is and how to achieve it. If you haven't already, check out
The Design of Everyday Things
.


Question: What is std::pair for, why would I use it, and what benefits does boost::compressed_pair bring?

Answer:
You sometimes need to return 2 values from a function, and it's often overkill to go and create a class just for that.
std:pair comes in handy in those cases.
I think boost:compressed_pair is able to optimize away the members of size 0.
Which is mostly useful for heavy template machinery in libraries.
If you do control the types directly, it's irrelevant.


Question:
I have a datagridview that accepts a list(of myObject) as a datasource. I want to add a new row to the datagrid to add to the database. I get this done by getting the list... adding a blank myObject to the list and then reseting the datasource. I now want to set the focus to the second cell in the new row.

To CLARIFY i am trying to set the focus

Answer:
In WinForms, you should be able to set the
```
```
Me.dataEvidence.SelectedRows
```
```
property to the row you want selected.


Question: I have an HTTP server which is in our internal network and accessible only from inside it. I would like to put another server that would listen to an HTTPS port accessible from outside, and forward the requests to that HTTP server (and send back the responses via HTTPS). I know that there are several ways to do this with some programming involved (and I myself made a temporary solution with Tomcat and a very simple servlet I wrote), but is there a way to do the same just plugging parts already made (like Apache + modules)?

Answer:
With Apache look into mod_proxy.
Apache 2.2 mod_proxy docs
Apache 2.0 mod_proxy docs


Question:
Several Linq.Enumerable functions take an IEqualityComparer<T>. Is there a convenient wrapper class that adapts a delegate(T,T)=>bool to implement IEqualityComparer<T>? It's easy enough to write one (if your ignore problems with defining a correct hashcode), but I'd like to know if there is an out-of-the-box solution.

Specifically, I want to do set operations on Dictionarys, using only the Keys to define membership (while retaining the values according to different rules).

Answer:
I'm afraid there is no such wrapper out-of-box. However it's not hard to create one:
```
```
class Comparer<T>: IEqualityComparer<T>
{
    private readonly Func<T, T, bool> _comparer;

    public Comparer(Func<T, T, bool> comparer)
    {
        if (comparer == null)
            throw new ArgumentNullException("comparer");

        _comparer = comparer;
    }

    public bool Equals(T x, T y)
    {
        return _comparer(x, y);
    }

    public int GetHashCode(T obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}

...

Func<int, int, bool> f = (x, y) => x == y;
var comparer = new Comparer<int>(f);
Console.WriteLine(comparer.Equals(1, 1));
Console.WriteLine(comparer.Equals(1, 2));
```
```


Question: Would it be using a Websphere Adaptor for SAP or webmethods or something else?? Does something else need to be considered while opting for one of these??? The final system needs to be synchronous between SAP and the WCS front end.No ques..no delays....

Answer:
I recommend a combination of the SAP Business Connector (
http://service.sap.com/sbc-download
), which provides an easy interface for receiving/sending RFC calls from/to the SAP side, and the IBM WebSphere Java library, which allows easy interaction with WebSphere. ("webshphere.jar", can probably be found somewhere on
http://www.ibm.com/developerworks/websphere
.)
In the Business Connector you can then write a "Java Service", which acts as a bridge between the RFC data from SAP and the WebSphere data. Should be only a couple of days development effort.


Question: What is your single favorite mocking library for Python?

Answer:
I've only used one, but I've had good results with Michael Foord's Mock:
http://www.voidspace.org.uk/python/mock/
.
Michael's introduction says it better than I could:
There are already several Python mocking libraries available, so why another one?
Most mocking libraries follow the 'record -> replay' pattern of mocking. I prefer the 'action -> assertion' pattern, which is more readable and intuitive particularly when working with the Python unittest module.
...
It also provides utility functions / objects to assist with testing, particularly monkey patching.


Question:
I have a system that combines the best and worst of Java and PHP. I am trying to migrate a component that was once written in PHP into a Java One.

Does anyone have some tips for how I can parse a PHP serialized datastructure in Java? By serialized I mean output from php's serialize function.

Answer:
I'm sorry I gave the wrong answer before. I rechecked, and it didn't do quite want you want. I did find a solution for you though, again, in 3.4.
Highlight the class, do a copy CTRL-C or cut CTRL-X, click on the package you want the class do go into, and do a paste, CTRL-V. Eclipse will auto generate the class for you.
Convert Member Type to Top Level doesn't quite work. Doing that will create a field of the outer class and generate a constructor that takes the outer class as a parameter.


Question:
I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site.  How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?

If I run the following code:

>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')

I get:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

Answer:
Any particular reason you want to use Django's templates? Both
Jinja
and
Genshi
are, in my opinion, superior.
If you really want to, then see the
Django documentation on
```
settings.py
```
. Especially the section "Using settings without setting
```
DJANGO_SETTINGS_MODULE
```
". Use something like this:
```
```
from django.conf import settings
settings.configure (FOO='bar') # Your settings go here
```
```


Question: I've found the standard hashing function on VS2005 is painfully slow when trying to achieve high performance look ups. What are some good examples of fast and efficient hashing algorithms that should void most collisions?

Answer:
That always depends on your data-set.
I for one had surprisingly good results by using the CRC32 of the string. Works very good with a wide range of different input sets.
Lots of good CRC32 implementations are easy to find on the net.
Edit:
Almost forgot: This page has a nice hash-function shootout with performance numbers and test-data:
http://smallcode.weblogs.us/
<-- further down the page.


Question:
As a beginner to TDD I am trying to write a test that assumes a property has had its value changed on a PropertyGrid (C#, WinForms, .NET 3.5).

Changing a property on an object in a property grid does not fire the event (fair enough, as it's a UI raised event, so I can see why changing the owned object may be invisible to it).

I also had the same issue with getting an AfterSelect on a TreeView to fire when changing the SelectedNode property.

I could have a function that my unit test can call that simulates the code a UI event would fire, but that would be cluttering up my code, and unless I make it public, I would have to write all my tests in the same project, or even class, of the objects I am testing (again, I see this as clutter). This seems ugly to me, and would suffer from maintainability problems.

Is there a convention to do this sort of UI based unit-testing

Answer:
One option I would recommend for its simplicty is to have your UI just call a helper class or method on the firing of the event and unit test that. Make sure it (your event handler in the UI) has as little logic as possible and then from there I'm sure you'll know what to do.
It can be pretty difficult to reach 100% coverage in your unit tests. By difficult I mean of course inefficient. Even once you get good at something like that it will, in my opinion, probably add more complexity to your code base than your unit test would merit. If you're not sure how to get your logic segmented into a separate class or method, that's another question I would love to help with.
I'll be interested to see what other techniques people have to work with this kind of issue.


Question:
Possible Duplicate:

Pre & post increment operator behavior in C, C++, Java, & C#

Here is a test case:

void foo(int i, int j)
{
   printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);

I would expect to get a "0 1" output, but I get "0 0"
What gives??

Answer:
This is an example of unspecified behavior.  The standard does
not
say what order arguments should be evaluated in. This is a compiler implementation decision.  The compiler is free to evaluate the arguments to the function in any order.
In this case, it looks like actually processes the arguments right to left instead of the expected left to right.
In general, doing side-effects in arguments is bad programming practice.
Instead of
foo(test++, test);
you should write
foo(test, test+1); test++;
It would be semantically equivalent to what you are trying to accomplish.
Edit:
As Anthony correctly points out, it is undefined to both read and modify a single variable without an intervening sequence point. So in this case, the behavior is indeed
undefined
.  So the compiler is free to generate whatever code it wants.


Question: Is it possible to integrate SSRS reports to the webforms..an example will be enough to keep me moving.

Answer:
this is a knowledge base article which describes how to render report output to an aspx page in a particular file format.
http://support.microsoft.com/kb/875447/en-us


Question:
I need to store some simple properties in a file and access them from Ruby.

I absolutely love the .properties file format that is the standard for such things in Java (using the java.util.Properties class)... it is simple, easy to use and easy to read.

So, is there a Ruby class somewhere that will let me load up some key value pairs from a file like that without a lot of effort?

I don't want to use XML, so please don't suggest REXML (my purpose does not warrant the "angle bracket tax").

I have considered rolling my own solution... it would probably be about 5-10 lines of code tops, but I would still rather use an existing library (if it is essentially a hash built from a file)... as that would bring it down to 1 line....

UPDATE: It's actually a straight Ruby app, not rails, but I think YAML will do nicely (it was in the back of my mind, but I had forgotten about it... have seen but never used as of yet), thanks everyone!

Answer:
Is this for a Rails application or a Ruby one?
Really with either you may be able to stick your properties in a yaml file and then
```
YAML::Load(File.open("file"))
```
it.
NOTE from Mike Stone:
It would actually be better to do:
```
```
File.open("file") { |yf| YAML::load(yf) }
```
```
or
```
```
YAML.load_file("file")
```
```
as the ruby docs suggest, otherwise the file won't be closed till garbage collection, but good suggestion regardless :-)


Question: What is the maximum value of an int in ChucK?  Is there a symbolic constant for it?

Answer:
The ChucK API reference
uses the C
```
int
```
type, so the maximum value would depend on your local machine (2^31-1, around two billion on standard 32-bit x86). I don't see any references to retrieving limits, but if ChucK is extensible using C you could add a function that returns
```
MAXINT
```
.


Question:
Hi i need to generate 9 digit unique account numbers. Here is my pseudocode:

function generateAccNo()

    generate an account number between 100,000,000 and 999,999,999

    if the account number already exists in the DB
        call generateAccNo()    /* recursive call */
    else
        return new accout number
    end if

end function

The function seems to be working well, however I am a bit worried about the recursive call.

Will this cause any memory leaks (PHP 5 under apache)?

Is this an acceptable way to tackle this problem?

Thanks for your input.

Answer:
You realize this could very well cause a stack overflow, right? As the number of customesr increases, the probability of not finding a an acceptable account number increases.
Also, why can't you just do sequential account numbers and just increase by one every time? With this approach, you'd just have to read the max id currently in the database and just increment it.
Sorry to be so blunt, but your solution is a terrible way to tackle the problem. It'll use tons of memory (as the stack possibly grows infinitely) and it will makes tons of expensive calls to the database.
You should really consider some other approach:
I strongly recommend just incrementing the customer number every time you create a customer. In fact, if you set up your db properly (with auto increment on the id column), you won't even have to set the id. The id will be set for you whenever you insert a new customer.


Question:
uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
   //...

doesn't work. What am i doing wrong?

Answer:
Try
```
```
Convert.ToUInt32(hex, 16)  //Using ToUInt32 not ToUInt64, as per OP comment
```
```


Question:
I'm looking for an extremely fast atof() implementation on IA32 optimized for US-en locale, ASCII, and non-scientific notation.  The windows multithreaded CRT falls down miserably here as it checks for locale changes on every call to isdigit().  Our current best is derived from the best of perl + tcl's atof implementation, and outperforms msvcrt.dll's atof by an order of magnitude.  I want to do better, but am out of ideas.  The BCD related x86 instructions seemed promising, but I couldn't get it to outperform the perl/tcl C code.  Can any SO'ers dig up a link to the best out there?  Non x86 assembly based solutions are also welcome.

Clarifications based upon initial answers:

Inaccuracies of ~2 ulp are fine for this application.

The numbers to be converted will arrive in ascii messages over the network in small batches and our application needs to convert them in the lowest latency possible.

Answer:
I remember we had a Winforms application that performed so slowly while parsing some data interchange files, and we all thought it was the db server thrashing, but our smart boss actually found out that the bottleneck was in the call that was converting the parsed strings into decimals!
The simplest is to loop for each digit (character) in the string, keep a running total, multiply the total by 10 then add the value of the next digit. Keep on doing this until you reach the end of the string or you encounter a dot. If you encounter a dot, separate the whole number part from the fractional part, then have a multiplier that divides itself by 10 for each digit. Keep on adding them up as you go.
Example: 123.456
running total = 0, add 1 (now it's 1)
running total = 1 * 10 = 10, add 2 (now it's 12)
running total = 12 * 10 = 120, add 3 (now it's 123)
encountered a dot, prepare for fractional part
multiplier = 0.1, multiply by 4, get 0.4, add to running total, makes 123.4
multiplier = 0.1 / 10 = 0.01, multiply by 5, get 0.05, add to running total, makes 123.45
multipiler = 0.01 / 10 = 0.001, multiply by 6, get 0.006, add to running total, makes 123.456
Of course, testing for a number's correctness as well as negative numbers will make it more complicated. But if you can "assume" that the input is correct, you can make the code much simpler and faster.


Question: By default, Eclipse won't show my .htaccess file that I maintain in my project.  It just shows an empty folder in the Package Viewer tree.  How can I get it to show up?  No obvious preferences.

Answer:
In your package explorer, pull down the menu and select "Filters ...".  You can adjust what types of files are shown/hidden there.
Looking at my Red Hat Developer Studio (approximately Eclipse 3.2), I see that the top item in the list is ".* resources" and it is excluded by default.


Question: This is a really weird problem that I have been having. When I download Scriptaculous from the official web site, script.aculo.us, bundled in the ZIP is prototype.js version 1.6.0.1. This works perfectly fine, I can follow along the wiki examples and begin learning. However, when I upgrade to prototype 1.6.0.2 (the latest version) from prototypejs.org  everything breaks. I have read the documentation, named the new file prototype.js and nothing works. Any help is greatly appreciated!

Answer:
scriptaculous is a JS library built on top of prototype. As such, they will be behind prototype in their release schedule. To ensure that scriptaculous works only use it with the prototype file that came in the download.
Sure, given enough time and energy, you can find all the changed references from prototype 1.6.0.1 to 1.6.0.2 but is there really something in the newer version of prototype that you need today?  If not, then just wait for the scripaculous to update.


Question:
I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.

The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.

What is the best "drop in" solution to switch this over to using connection pooling in python?  I am imagining something like the commons DBCP solution for Java.

The process is long running and has many threads that need to make requests, but not all at the same time... specifically they do quite a lot of work before brief bursts of writing out a chunk of their results.

Edited to add:
After some more searching I found anitpool.py which looks decent, but as I'm relatively new to python I guess I just want to make sure I'm not missing a more obvious/more idiomatic/better solution.

Answer:
Wrap your connection class.
Set a limit on how many connections you make.
Return an unused connection.
Intercept close to free the connection.
Update:
I put something like this in dbpool.py:
```
```
import sqlalchemy.pool as pool
import MySQLdb as mysql
mysql = pool.manage(mysql)
```
```


Question:
First of all, I don't need a textual comparison so Beyond Compare doesn't do what I need.

I'm looking for a util that can report on the differences between two files, at the byte level.  Bare minimum is the need to see the percentage change in the file, or a report on affected bytes/sectors.

Is there anything available to save me the trouble of doing this myself?

Answer:
I guess it depends on what exactly is contained in the file, but here's a quick one:
```
```
hexdump file1 > file1.tmp
hexdump file2 > file2.tmp
diff file1.tmp file2.tmp
```
```
Since 16 bytes are typically reported on each line, this won't technically give you a count of the bytes changed, but will give you a rough idea where in the file changes have occurred.


Question: What principles do you generally follow when doing class design?

Answer:
Principles Of Object Oriented Class Design (the "SOLID" principles)
SRP:  The Single Responsibility
Principle
A class should have one,
and only one, reason to change.
OCP:  The Open Closed Principle
You
should be able to extend a classes
behavior, without modifying it.
LSP:  The Liskov Substitution
Principle
Derived classes must be
substitutable for their base
classes.
ISP:  The Interface Segregation
Principle
Make fine grained
interfaces that are client specific.
DIP:  The Dependency
Inversion Principle
Depend on
abstractions, not on concretions.
Source:
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
Video (Uncle Bob):
Clean Coding By Robert C. Martin ( Uncle Bob )


Question:
I'm working on a music writing application and would like to add the functionality to import Finale music files.  Right now, the only thing I know is that they are enigma binary files.

Does anyone have any suggestions on where I could start so that I could be able to parse through these types of files?

Answer:
Get a
good
hex editor and start looking inside some files. Look for common structure. Do some detective work. Look for fields that might be counts, sizes or offsets within the file. Make trivial changes in Finale and observe the changes in the file. Make changes with the hex editor, then load the changed file back into Finale and see if the change does what you thought it would.
So this is a completely unhelpful answer, but the best way to reverse the file-format is to jump in and just do it. You're probably in for a very long process BTW, but at least it's fun.
Oh, and pray the file-format isn't compressed...


Question:
Should entities have behavior? or not?

Why or why not?

If not, does that violate Encapsulation?

Answer: If you're strictly following MVC, your model (entities) won't have any inherent behavior.  I do however include whatever helper methods allow the easiest management of the entities persistence, including methods that help with maintaining its relationship to other entities.


Question:
I need to execute a batch file as part of the un-install process in a Windows installer project (standard OOTB VS 2008 installer project-vdproj).  One cannot execute a bat file directly from the Custom Actions in the installer project, so I wrote a quick vbs script to call the required bat file.

vbs code:

Set WshShell = WScript.CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing

When this script is run independent of the uninstall, it works perfectly.  However, when run as part of the uninstall, it does not execute the bat file (but the message box is shown, so I know the vbs file is called).  No errors reported (at least that I can tell).  Why doesn't this script work as part of the "Uninstall Custom Action"

Answer:
In your installer class, are you overriding the Uninstall method:
```
```
Public Overrides Sub Uninstall(ByVal savedState As System.Collections.IDictionary)
            MyBase.Uninstall(savedState)
           'Shell to batch file here
    End Sub
```
```
And secondly, have you qualified the full path to the batch file?


Question: When using an IoC container, is it considered good design to inject other classes into them? i.e. a persistence class

Answer:
This is the
Spreadsheet Conundrum
: do you write repository.store(entity) or entity.storeIn(repository)?
Each has its merits. I generally tend to favor repository.store(entity) for the main reason that I keep the methods of my entities domain-focused. It makes sense to write pen.dispenseInkOnto(Surface) because that is what pens do. It makes a little less sense to write pen.storeIn(penRepository).
The downside is you need to provide access to the internals of the entity class to the persistence class. Aside from getters, which introduce the same problem as entity.storeIn(), I'd go with a friend class, package protected access, internal access, or a
friend class pattern
of some kind to restrict access to internal to only those who need it.
As far general injection of classes, in the pen.dispenseInkOnto(Surface) example, you could very well make Surface an interface and use injection. I see no problem with this as long as you inject other entities, value objects, or services.


Question:
I'm looking for a method to assign variables with patterns in regular expressions with C++ .NET
something like

String^ speed;
String^ size;

"command SPEED=[speed] SIZE=[size]"

Right now I'm using IndexOf() and Substring() but it is quite ugly

Answer:
If you put all the variables in a class, you can use reflection to iterate over its fields, getting their names and values and plugging them into a string.
Given an instance of some class named InputArgs:
```
```
foreach (FieldInfo f in typeof(InputArgs).GetFields()) {
    string = Regex.replace("\\[" + f.Name + "\\]",
        f.GetValue(InputArgs).ToString());
}
```
```


Question: In c#, we have interfaces.  Where did these come from?  They didn't exist in c++.

Answer:
Java, perhaps?
http://java.sun.com/docs/books/tutorial/java/concepts/interface.html


Question:
How to add a click event listener to my custom control made with wxWidgets? The custom control uses wxWindow as the base. On the event list I see

wxEVT_LEFT_DOWN
wxEVT_LEFT_UP
wxEVT_LEFT_DCLICK
wxEVT_MIDDLE_DOWN
wxEVT_MIDDLE_UP
wxEVT_MIDDLE_DCLICK
wxEVT_RIGHT_DOWN
wxEVT_RIGHT_UP
wxEVT_RIGHT_DCLICK
wxEVT_MOTION
wxEVT_ENTER_WINDOW
wxEVT_LEAVE_WINDOW
wxEVT_MOUSEWHEEL

But there is no wxEVT_LEFT_CLICK or similar.

Answer:
Typically, there is no "click" event (and in the case of
wxWidgets
-
there isn't
). The action of clicking is broken into its two parts: Mouse Down and Mouse Up. Typically what you think of as a "left click" event is actually handled in a "left up" event.
Try it out:
Hover over a button (such as the "Add Comment" button this page)
Click the left-mouse button down and hold
Move the mouse off of the button while holding down
Release the left-mouse button
Nothing happens!
This time:
Hover over the same button
Click the
left-mouse button down and hold
Release the left-mouse button
The "click" action you expect is triggered by the up event!


Question: How do I write a cpp macro which expands to include newlines?

Answer:
Use
```
\
```
, like so:
```
```
#define my_multiline_macro(a, b, c) \
if (a) { \
    b += c; \
}
```
```


Question: What are the pros/cons of using black-box reuse over white-box reuse?

Answer:
White-box:
pros:
simple (very natural concept)
you have more control over things
cons:
requires intrinsic knowledge on
component internals
can be difficult to implement (OO inheritance constraints)
sometimes it leads to broken\incorrect inheritance chains
Black-box:
pros:
low coupling (gives late binding and other goodies)
cons:
not obvious (code is much harder to understand)
interfaces are more fragile than classes (i.e. interfaces vs inheritance)


Question:
We are running Selenium regression tests against our existing code base, and certain screens in our web app use pop-ups for intermediate steps.

Currently we use the commands in the test:

// force new window to open at this point - so we can select it later
selenium().getEval("this.browserbot.getCurrentWindow().open('', 'enquiryPopup')");
selenium().click("//input[@value='Submit']");
selenium().waitForPopUp("enquiryPopup", getWaitTime());
selenium().selectWindow("enquiryPopup");

...which works most of the time. Occasionally the test will fail on the waitForPopUp() line with

com.thoughtworks.selenium.SeleniumException: Permission denied

Can anyone suggest a better, more reliable method?

Also, we primarily run these tests on IE6 and 7.

Answer:
If you are running in *iehta mode then you are going to run into some glitches here and there. We run Selenium at my job and there seem to be lots of issues with IE and AJAX.
However, it sounds like the issue you are running into is one where Selenium is trying to access a component in another window before it completely loads up. I am not sure what your default timeout range is set to, but you may want to try increasing it to 60 (60000ms) seconds or so to get past the issue.
Other than that I would suggest running your tests in Firefox (using *chrome) as it produces much more reliable results, but sometimes it is simply not possible due to business requirements.


Question:
If given the choice, which path would you take?

ASP.NET Webforms + ASP.NET AJAX

or

ASP.NET MVC + JavaScript Framework of your Choice

Are there any limitations that ASP.NET Webforms / ASP.NET AJAX has vis-a-vis MVC?

Answer:
I love webforms, but ASP.NET AJAX is a pile of crap.
I prefer to use WebForms + custom HTTPHandlers handling the server side of any AJAX calls.
Heh, downvoted...
ASP.NET AJAX Is a pile of crap because a callback requires the entire page class to be reinstantiated, you aren't calling a single method, you are rebuilding the entire page on the server everytime.
Also, UpdatePanels return the entire page, only the section in the update panel is popped in, its a total waste of bandwidth.
I understand why its done this way, because WebForms controls can't really be easily other ways, but it still is really lousy.


Question:
Is it possible to check what version of BPL (ie Rtl70.BPL, Indy70.bpl etc) are installed on a clients computer when the program starts?

I have had some programs crash because the BPL on there computer is different to the ones on the build machine.

If i have to add each BPL used into the installer on each update, i think it will defeat one of the points on using them.

Delphi 7, if it makes a difference

Just a follow up on the issue i had.

The rtl70.bpl file was only slightly different between the build computer and the clients.

Clients Computer: 7.0.4.453 760 KB (778,240 bytes)  Tuesday, 20 August 2002, 4:40:26 PM

  Build computer: 7.0.4.453  760 KB (778,240 bytes)  Friday, 9 August 2002, 11:30:00 PM

The updater i was using ignored them as being the same (no change in build number), but when i manually deleted and copied the files every thing seemed to work.

Answer:
If your program crashes, it's probably because it can't load the library it's dynamically linked with. (As you where saying, this happens when the system can't find a copy of the needed libaries anywhere in the search path).
The problem is, that this happens at startup of an application, which the Windows OS does via an API called
MapAndLoad
(also read
this
). This API is called before your application is even started, so I see no way to intercept this.
One suggestion I could give, would be to use a launcher (which has to be statically linked, to prevent problems for when there are /no/ libraries at all).
This launcher could inspect your actual application, see what imports it needs, checks your environment and display a nice failure/troubleshooting suggestion dialog to the user.


Question:
What is the best way to generate a current datestamp in Java?

YYYY-MM-DD:hh-mm-ss

Answer:
```
```
Date d = new Date();
String formatted = new SimpleDateFormat ("yyyy-MM-dd:HH-mm-ss").format (d);
System.out.println (formatted);
```
```


Question:
I need to generate a directory in my makefile and I would like to not get the "directory already exists error" over and over even though I can easily ignore it.

I mainly use mingw/msys but would like something that works across other shells/systems  too.

I tried this but it didn't work, any ideas?

ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))
-mkdir $(OBJDIR)
endif

Answer:
If having the directory already exist is not a problem for you, you could just redirect stderr for that command, getting rid of the error message:
```
```
-mkdir $(OBJDIR) 2>/dev/null
```
```


Question:
I am trying to get Haml to work with my Ruby on Rails project. I am new to Ruby on Rails and I really like it. However, when I attempt to add an aplication.html.haml or index.html.haml for a view, I just receive errors.

I am using NetBeans as my IDE.

Answer:
First,
install haml
as a gem in bundler by adding this to your
```
Gemfile
```
:
```
```
gem "haml"
```
```
Run
```
bundle install
```
, then make sure your views are named with a
*.html.haml
extension.  For example:
```
```
`-- app
    `-- views
        |-- layouts
        |   `-- application.html.haml
        `-- users
            |-- edit.html.haml
            |-- index.html.haml
            |-- new.html.haml
            `-- show.html.haml
```
```


Question:
For RMI on server-side, do we need to start rmiregistry program, or just call LocateRegistry.createRegistry?
If both are possible, what are the advantages and disadvantages?

Answer:
They're the same thing...
```
rmiregistry
```
is a separate program, which you can run from a command line or a script, while
```
LocateRegistry.createRegistry
```
does the same thing programatically.
In my experience, for "real" servers you will want to use
```
rmiregistry
```
so that you know it's always running regardless of whether or not the client application is started.
```
createRegistry
```
is very useful for testing, as you can start and stop the registry from your test as necessary.


Question: For example, referencing something as System.Data.Datagrid as opposed to just Datagrid. Please provide examples and explanation. Thanks.

Answer:
You're being very explicit about the type you're referencing, and that is a benefit. Although, in the very same process you're giving up code clarity, which clearly is a downside in my case, as I want code to be readable and understandable. I go for the short version unless I have a conflict in different namespaces which can only be solved with the explicit referencing to classes.. Unless I make an alias for it with the keyword using:
```
```
using Datagrid = System.Data.Datagrid;
```
```


Question:
What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:

String str = "Hello";
var temp = str;
temp = 10;
temp = temp * 5;

Would that be possible?

Would that be beneficial?

Do any languages currently support both and how well does it work out?

Here is a better example (generics can't be used but the program does know the type):

var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String
if(username.length() == 0) {
    //Error
}

Answer:
Can you explain the difference between your example and
```
```
String str = "Hello";
Object temp = str;
temp = 10;
```
```


Question: When I print "\[\e[34m\]sometext" I get some text in blue, but can I specify the shade of blue somewhere?

Answer:
You're using an ANSI escape sequence, which has very limited color options.  I use an .Xdefaults file (explained in
this tutorial
).  These options won't make your shell prompt all colorful, but is used by editors such as vim.
Be aware that .Xdefaults can be picky about UNIX (CR) vs Windows (CRLF) line endings.  Use d2u or u2d to switch line endings as necessary.


Question: How to test if a line segment intersects an axis-aligned rectange in 2D? The segment is defined with its two ends: p1, p2. The rectangle is defined with top-left and bottom-right points.

Answer:
Use the
Cohen-Sutherland algorithm
.
It's used for clipping but can be slightly tweaked for this task.  It divides 2D space up into a tic-tac-toe board with your rectangle as the "center square".
then it checks to see which of the nine regions each of your line's two points are in.
If both points are left, right, top, or bottom, you trivially reject.
If either point is inside, you trivially accept.
In the rare remaining cases you can do the math to intersect with whichever sides of the rectangle are possible to intersect with, based on which regions they're in.


Question: How to check if a folder (directory) exists in Cocoa using Objective-C?

Answer:
Use
```
NSFileManager
```
's
```
fileExistsAtPath:isDirectory:
```
method.  See Apple's docs
here
.


Question: Do you think that writing about software (i.e. having a blog) and speaking on software (and concepts) make you a better programmer?

Answer:
Statistically speaking yes. You only retain about 20% of what you read and hear, but 80% of what you teach.
By writing about something or teaching about it, you force yourself to understand the concepts on a much deeper level.
UPDATE:
I wanted to update this with some links to more concrete data to support the statistics that I have been taught numerous times about learning retention rates. However, it would appear there is some
controversy surrounding these numbers
, even though the
NTL Institute for Applied Behavioral Science
maintains that research was done to back them up.


Question: My C(++) program, written and compiled using Visual C(++)/Visual Studio, runs fine on my own machine, but refuses to run on another machine. The error message I get is "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem."

Answer:
If you write a C++ program, it links dynamically to the C Runtime Library, or CRT for short. This library contains your printf, your malloc, your strtok, etcetera. The library is contained in the file called MSVCR80.DLL. This file is not by default installed on a Windows system, hence the application cannot run.
The solution? Either install the DLL on the target machine through VCREDIST.EXE (the Visual C++ Redistributable Package), or link to the CRT statically (plug the actual code for the used functions straight into your EXE).
Distributing and installing VCREDIST along with a simple application is a pain in the arse, so I went for the second option: static linking. It's really easy: go to your project's properties, unfold C/C++, click Code Generation, and set the Runtime Library to one of the non-DLL options. That's all there is to it.


Question:
If I'm writing an application that wants to communicate some information through the use of color, how can I change the background and foreground colors of a given widget?  I would like to know how to do this in glade if it's possible, as well as programmatically (to a computed color).

I want to know how to do this to a complex widget as well, for example, an HBox that contains a VBox that contains some Labels.

Ideally this would also include a solution solution that allows me to tint the widget's existing colors, and identify the average colors of any images in use by the theme, so that I can programmatically compensate for any color choices which might make text unreadable or otherwise clashing - but I would be happy if I could just turn a button red.

Answer:
Example program:
```
```
#include <gtk/gtk.h>

static void on_destroy(GtkWidget* widget, gpointer data)
{
        gtk_main_quit ();
}

int main (int argc, char* argv[])
{
        GtkWidget* window;
        GtkWidget* button;

        gtk_init(&argc, &argv);
        window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        g_signal_connect(G_OBJECT (window), "destroy",
                G_CALLBACK (on_destroy), NULL);
        button = gtk_button_new_with_label("Hello world!");
        GdkColor red = {0, 0xffff, 0x0000, 0x0000};
        GdkColor green = {0, 0x0000, 0xffff, 0x0000};
        GdkColor blue = {0, 0x0000, 0x0000, 0xffff};
        gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);
        gtk_widget_modify_bg(button, GTK_STATE_PRELIGHT, &green);
        gtk_widget_modify_bg(button, GTK_STATE_ACTIVE, &blue);
        gtk_container_add(GTK_CONTAINER(window), button);
        gtk_widget_show_all(window);
        gtk_main();
        return 0;
}
```
```


Question:
I'm not looking so much for language-specific answers, just general models for implementing a plugin system (if you want to know, I'm using Python). I have my own idea (register callbacks, and that's about it), but I know others exist. What's normally used, and what else is reasonable?

What do you mean by a plugin system? Does Dependency Injection and IOC containers sounds like a good solution?

I mean, uh, well, a way to insert functionality into the base program without altering it. I didn't intend to define it when I set out. Dependency Injection doesn't look particularly suitable for what I'm doing, but I don't know much about them.

Answer:
In Python you can use the entry-point system provided by
```
setuptools
```
and
```
pkg_resources
```
. Each entry point should be a function that returns information about the plugin -- name, author, setup and teardown functions, etc.


Question:
Does having several levels of base classes slow down a class?  A derives B derives C derives D derives F derives G, ...

Does multiple inheritance slow down a class?

Answer:
If there are no virtual functions, then it shouldn't. If there are then there is a performance impact in calling the virtual functions as these are called via function pointers or other indirect methods (depends on the situation). However, I do not think that the impact is related to the depth of the inheritance hierarchy.
Brian, to be clear and answer your comment. If there are no virtual functions anywhere in your inheritance tree, then there is no performance impact.


Question:
What tools do you use for Automated Builds / Automated Deployments? Why?

What tools do you recommend?

Answer:
Hudson
for automated builds. I chose it because it was the easiest to setup and demo. A system that's too complex and isn't slick-looking won't impress management enough to get them on-board for automated builds. Especially in a project that has a lot of inertia.


Question:
ZeroC's ICE (www.zeroc.com) looks interesting and I am interested in looking at it and comparing it to our existing software that uses WCF. In particular, our WCF app uses server callbacks (via HTTP).

Anybody who's compared them? How did it go? I'm particularly interested in the performance aspect, since interoperability isn't much of a concern for us right now. Thanks!

Answer:
I did a very terse review of ICE a few years ago, and although I haven't compared them directly before, having reasonable knowledge of WCF my thoughts might have some relevance.
Firstly, it's not entierely fair to compare WCF with ICE as WCF as ICE is a specific remote communication mechanism and WCF is a higher level remote communications framework.
While WCF is often thought of as implementing SOAP web services, and that is indeed its main use to date, it can also be used for implementing remote services using all manner of encodings and transport channels, which means it can theoretically be used for performant comms between applications.
In comparison, ICE is a cross-platform remote communicaton mechanism that uses binary encoding for performant communications between applications. It's something of a simplified evolution of CORBA and is more directly comparable to CORBA, DCOM, .NET Remoting, and JNI.
However, even though there's no direct correspondence between ICE and WCF, if you need your .NET app to communicate remotely then they're both contenders. Some of the decision points you might want to consider include:
Resourcing. It'll be easier to find developers with WCF experience than ICE experience.
Performance. If you want performance then ICE performs fast, but WCF can also be used in a performant configuration. Alternatively, .NET Remoting can provide very good performance, and whatever the MS-sponsored benchmarks say I've seen it outperform WCF by 10%.
Cross-platform. If you need to communicate with non-Windows applications then you're limited with the WCF options you can use. In addition, since every SOAP stack seems to implement the standards differently it can be a pain creating truly generic Web Services (though WS-I helps)
If you don't need every ounce of performance from day one, then I'd personally plump for WCF to start with, and then consider ICE if performance ever becomes critical. Even then it might be cheaper to scale out your service boxes than it is to move to ICE, and if you don't have any exotic cross-platform needs then you could always look at reconfiguring WCF for binary encoding etc


Question:
I sometimes notice programs that crash on my computer with the error: "pure virtual function call".

How do these programs even compile when an object cannot be created of an abstract class?

Answer:
I'd guess there is a vtbl created for the abstract class for some internal reason (it might be needed for some sort of run time type info) and something goes wrong and a real object gets it. It's a bug. That alone should say that something that can't happen is.
Pure speculation
edit:
looks like I'm wrong in the case in question. OTOH IIRC some languages do allow vtbl calls out of the constructor destructor.


Question: Does excess use of AJAX affects performance? In context of big size web-applications, how do you handle AJAX requests to control asynchronous requests?

Answer:
AJAX itself (being asynchronous requests).. No not generally.
However if you have an abundance of javascript and markup and have large amounts of data transferred via your xmlhttprequests then yes you can see a performance hit.  It really depends on how you want your website to function any degredation is generally avoidable if sculpted correctly.


Question:
After applying a CSS reset, I want to get back to 'normal' behavior for html elements like: p, h1..h6, strong, ul and li.

Now when I say normal I mean e.g. the p element adds spacing or a carriage return like result when used, or the size of the font and boldness for a h1 tag, along with the spacing.

I realize it is totally up to me how I want to set the style, but I want to get back to normal behavior for some of the more common elements (at least as a starting point that I can tweak later on).

Answer:
You mean like:
```
```
* {
    padding: 0;
    margin: 0;
}

h1, h2, h3, h4, h5, h6, p, blockquote, form, label, ul, ol, dl, fieldset, address {
    margin-bottom: 1em;
}
```
```
?
Actually, sorry I mis-read your question, you're after something more like Eric Meyer's total reset @
http://meyerweb.com/eric/tools/css/reset/


Question:
One of the biggest advantages of object-oriented programming is encapsulation, and one of the "truths" we've (or, at least, I've) been taught is that members should always be made private and made available via accessor and mutator methods, thus ensuring the ability to verify and validate the changes.

I'm curious, though, how important this really is in practice. In particular, if you've got a more complicated member (such as a collection), it can be very tempting to just make it public rather than make a bunch of methods to get the collection's keys, add/remove items from the collection, etc.

Do you follow the rule in general? Does your answer change depending on whether it's code written for yourself vs. to be used by others? Are there more subtle reasons I'm missing for this obfuscation?

Answer:
It's all about controlling what people can do with what you give them. The more controlling you are the more assumptions you can make.
Also, theorectically you can change the underlying implementation or something, but since for the most part it's:
```
```
private Foo foo;
public Foo getFoo() {}
public void setFoo(Foo foo) {}
```
```
It's a little hard to justify.


Question:
Progressive Enhancement is a web development methodology that not only allows greater portability and accessibility but in my opinion, makes the development process easier.

What I want is to know what the rest of the community think of this approach.

In particular: What do you believe is the minimum set of technologies that a web application should support?

Answer:
I personally block referrers, cookies and JavaScript by default and re-enable them temporarily or permanently on a site-by-site basis.
I'll forgive a web site for not working without cookies for signed-in users, however I get quite upset when they won't work without JavaScript if it's being used for trivial purposes.
Minimum requirements: HTML with basic structural elements + links, HTML forms + maybe cookies for applications.
Site could be run in a vt100, a "normal" browser, a phone, a screen reader...
-z


Question:
I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?

A couple things that we've seen/heard already include:

Google not being able to index content

CSS and styling in general seems to be a bit flaky

Looking for any additional feedback on these items as well. Thanks!

Answer:
No major pitfalls that I haven't been able to overcome easily. Use hosted mode heavily.
As you are using GWT-ext you will almost never need to touch CSS yourself unless you want to tweak the out of the box look.
My recommendation is to use a GWT "native" widget over a library one where they are close in features.
Re search engine indexing: yes the site will not have navigable URLs normally (unless you are only adding widgets to elements of a regular web site). You can do history back/forward functionality though.


Question:
I just wanted some opinions from people that have run Selenium (http://selenium.openqa.org) I have had a lot of experience with WaTiN and even wrote a recording suite for it. I had it producing some well-structured code but being only maintained by me it seems my company all but abandoned it.

If you have run selenium have you had a lot of success?

I will be using .NET 3.5, does Selenium work well with it?

Is the code produced clean or simply a list of all the interaction? (http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx)

How well does the distributed testing suite fair?

Any other gripes or compliments on the system would be greatly appreciated!

Answer:
If you are using
Selenium IDE
to generate code, then you just get a list of every action that selenium will execute. To me, Selenium IDE is a good way to start or do a fast "try and see" test. But, when you think about maintainability and more readable code, you must write your own code.
A good way to achieve good selenium code is to use the
Page Object Pattern
in a way that the code represents your navigation flow. Here is a good example that I see in
Coding Dojo Floripa
(from Brazil):
```
```
public class GoogleTest {

    private Selenium selenium;

    @Before
    public void setUp() throws Exception {
            selenium = new DefaultSelenium("localhost", 4444, "*firefox",
                            "http://www.google.com/webhp?hl=en");
            selenium.start();
    }

    @Test
    public void codingDojoShouldBeInFirstPageOfResults() {
            GoogleHomePage home = new GoogleHomePage(selenium);
            GoogleSearchResults searchResults = home.searchFor("coding dojo");
            String firstEntry = searchResults.getResult(0);
            assertEquals("Coding Dojo Wiki: FrontPage", firstEntry);
    }

    @After
    public void tearDown() throws Exception {
            selenium.stop();
    }

}

public class GoogleHomePage {

    private final Selenium selenium;

    public GoogleHomePage(Selenium selenium) {
            this.selenium = selenium;
            this.selenium.open("http://www.google.com/webhp?hl=en");
            if (!"Google".equals(selenium.getTitle())) {
                    throw new IllegalStateException("Not the Google Home Page");
            }
    }

    public GoogleSearchResults searchFor(String string) {
            selenium.type("q", string);
            selenium.click("btnG");
            selenium.waitForPageToLoad("5000");
            return new GoogleSearchResults(string, selenium);
    }
}

public class GoogleSearchResults {

    private final Selenium selenium;

    public GoogleSearchResults(String string, Selenium selenium) {
            this.selenium = selenium;
            if (!(string + " - Google Search").equals(selenium.getTitle())) {
                    throw new IllegalStateException(
                                    "This is not the Google Results Page");
            }
    }

    public String getResult(int i) {
            String nameXPath = "xpath=id('res')/div[1]/div[" + (i + 1) + "]/h2/a";
            return selenium.getText(nameXPath);
    }
}
```
```
Hope that Helps


Question:
I have been given a set of COBOL DAT, IDX and KEY files and I need to read the data in them and export it into Access, XLS, CSV, etc. I do not know the version, vendor of the COBOL code as I only have the windows executable that created the files.

I have tried Easysoft and Parkway ODBC drivers but I have not been successful in reading the data from the files.

I do not have access to the source code as the company that was distributing this product shut down.

Answer:
A few possibilities.
1/ See if you can find the names of the people that worked for the company.  They may be helpful.
2/ Open the DAT file in a text editor.  The data may be decodable from that.  If the basic format can be discerned, quick'n'dirty code can be written to extract it.
3/ Open up the executable in an editor, there may be strings in there that indicate which compiler was used, then you can search for info on its file formats.  If it's a DOS application, there's a good chance it was either Microsoft or Fujitsu COBOL.
4/ Consider placing job requests on work sites like elance or rentacoder; I don't think there's a cost if the work can't be done successfully.
5/ Hire someone to examine it and advise on the likelihood of recovery.
6/ Get a screen dump of the record contents for every active record and re-construct it from that.
Some of these are pretty hard so your mileage may vary.
Good luck.


Question: So I was reading these Asp.Net interview questions at Scott Hanselman's blog and I came across this question. Can anyone shed some light of what he's talking about.

Answer:
I think what he's asking here is how you wire up javascript functions to work hand in hand with your ASP.NET postback functionality.
i.e. How can I trigger a control's event using my own JavaScript?
The ASP.NET class library contains a
```
ClientScript
```
class - Found in the
```
System.Web.UI.Page
```
class - which enables you to programmatically add JavaScript to your ASP.NET page.
This contains a method called
```
GetPostBackEventReference
```
which will generate the
```
__doPostBack
```
script ASP.NET utilises to trigger events wired up to your web controls.
Hope that makes sense


Question: What are metaclasses? What are they used for?

Answer:
Note, this answer is for Python 2.x as it was written in 2008, metaclasses are slightly different in 3.x.
Metaclasses are the secret sauce that make 'class' work. The default metaclass for a new style object is called 'type'.
```
```
class type(object)
  |  type(object) -> the object's type
  |  type(name, bases, dict) -> a new type
```
```
Metaclasses take 3 args. '
name
', '
bases
' and '
dict
'
Here is where the secret starts. Look for where name, bases and the dict come from in this example class definition.
```
```
class ThisIsTheName(Bases, Are, Here):
    All_the_code_here
    def doesIs(create, a):
        dict
```
```
Lets define a metaclass that will demonstrate how '
class:
' calls it.
```
```
def test_metaclass(name, bases, dict):
    print 'The Class Name is', name
    print 'The Class Bases are', bases
    print 'The dict has', len(dict), 'elems, the keys are', dict.keys()

    return "yellow"

class TestName(object, None, int, 1):
    __metaclass__ = test_metaclass
    foo = 1
    def baz(self, arr):
        pass

print 'TestName = ', repr(TestName)

# output =>
The Class Name is TestName
The Class Bases are (<type 'object'>, None, <type 'int'>, 1)
The dict has 4 elems, the keys are ['baz', '__module__', 'foo', '__metaclass__']
TestName =  'yellow'
```
```
And now, an example that actually means something, this will automatically make the variables in the list "attributes" set on the class, and set to None.
```
```
def init_attributes(name, bases, dict):
    if 'attributes' in dict:
        for attr in dict['attributes']:
            dict[attr] = None

    return type(name, bases, dict)

class Initialised(object):
    __metaclass__ = init_attributes
    attributes = ['foo', 'bar', 'baz']

print 'foo =>', Initialised.foo
# output=>
foo => None
```
```
Note that the magic behaviour that
```
Initialised
```
gains by having the metaclass
```
init_attributes
```
is not passed onto a subclass of
```
Initialised
```
.
Here is an even more concrete example, showing how you can subclass 'type' to make a metaclass that performs an action when the class is created. This is quite tricky:
```
```
class MetaSingleton(type):
    instance = None
    def __call__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)
        return cls.instance

class Foo(object):
    __metaclass__ = MetaSingleton

a = Foo()
b = Foo()
assert a is b
```
```


Question:
When logging with Log4Net it's very easy to put class that called the log into the log file.  I've found in the past that this makes it very easy to trace through the code and see the flow through the classes.  In Log4Net I use the %logger property in the conversion pattern like so:

<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

And this gives me the output I want:

2008-09-19 15:40:26,906 [3132] ERROR <b>Log4NetTechDemo.Tester</b> [(null)] - Failed method

You can see from the output that the class that has called the log is Log4NetTechDemo.Tester, so I can trace the error back to that class quite easily.

In the Logging Applicaton Block I cannot figure out how to do this with a simple log call.  Does anyone know how it can be done?  If so, an example or steps to do so would be very helpful.

Answer:
We havn't found an easy way without hitting the StackTrace.  If it's an exception, we just grab from that:
```
```
StackTrace trace = new StackTrace(ex, true);
 StackFrame frame = trace.GetFrame(0);
```
```
For chatty items, we just write the string.  We have a snippet that's able to grab the class name on insertion.  We also declare the const string with the class name.
Not pretty, but it's the best we've found.  I hope someone else has a bettwe answer in this thread  :)


Question:
I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills.

Here's what I've got, but it seems like there should be an easier way.

public static TEntity InsertIfNotExists<TEntity>
(
    DataContext db,
    Table<TEntity> table,
    Func<TEntity,bool> where,
    TEntity record
)
    where TEntity : class
{
    TEntity existing = table.SingleOrDefault<TEntity>(where);

    if (existing != null)
    {
        return existing;
    }
    else
    {
        table.InsertOnSubmit(record);

        // Can't use table.Context.SubmitChanges()
        // 'cause it's read-only

        db.SubmitChanges();
    }

    return record;
}

Answer:
```
```
public static void InsertIfNotExists<TEntity>
                    (this Table<TEntity> table,
                     TEntity entity,
                     Expression<Func<TEntity,bool>> predicate)
    where TEntity : class
{
    if (!table.Any(predicate))
    {
        table.InsertOnSubmit(record);
        table.Context.SubmitChanges();
    }
 }

table.InsertIfNotExists(entity, e=>e.BooleanProperty);
```
```


Question:
Which CMS are you using in Java and what is your experience with it (in terms of extensibility, usage comfort, framework API, memory usage, performance etc.). I am looking for suggestions.

Specifically any one that supports a search engine(probably lucene or similar).

Answer:
We are using
opencms
.
I haven't tried to extend it beyond changing page templates (writing JSPs) but where usage is concerned it gets the job done, albeit the feeling you get is that you fight the system all the way through.
Memory consumption on the JVM running opencms is right now 161 Mb, the JVM running since January 2008. This is on a low traffic site serving around 6000 hits per month with an average traffic of 1800 Mb per month.


Question:
sub foo {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]%
@{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{
$_[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]}

update: I thought the word "puzzle" would imply this, but: I know what it does - I wrote it.  If the puzzle doesn't interest you, please don't waste any time on it.

Answer:
It takes two arrayrefs and returns a new arrayref with the contents of the second array rearranged such that the second part comes before the first part, split at a point based on the memory location of the first array. When the second array is empty or contains one item, just returns a copy of the second array. Equivalent to the following:
```
```
sub foo {
    my ($list1, $list2) = @_;
    my @output;
    if (@$list2 > 0) {
        my $split = $list1 % @$list2;
        @output = @$list2[$split .. $#$list2, 0 .. ($split - 1)];
    } else {
        @output = @$list2;
    }
    return \@output;
}
```
```
```
$list1 % @$list2
```
essentially picks a random place to split the array, based on
```
$list
```
which evaluates to the memory address of $list when evaluated in a numeric context.
The original mostly uses a lot of tautologies involving punctuation variables to obfuscate. e.g.
```
!$| | $|
```
is always 1
```
@- - @+
```
is always 0
Updated to note that
```
perltidy
```
was very helpful deciphering here, but it choked on
```
!!$^^^!$^^
```
, which it reformats to
```
!!$^ ^ ^ !$^ ^
```
, which is invalid Perl; it should be
```
!!$^^ ^ !$^^
```
. This might be the cause of RWendi's compile error.


Question:
I was happily using Eclipse 3.2 (or as happy as one can be using Eclipse) when for a forgotten reason I decided to upgrade to 3.4. I'm primarily using PyDev, Aptana, and Subclipse, very little Java development.

I've noticed 3.4 tends to really give my laptop a hernia compared to 3.2 (vista, core2duo, 2G). Is memory usage on 3.4 actually higher than on 3.2, and if so is there a way to reduce it?

EDIT: I tried disabling plugins (I didn't have much enabled anyway) and used the jvm monitor; the latter was interesting but I couldn't figure out how to use the info in any practical way. I'm still not able to reduce its memory footprint. I've also noticed every once in a while Eclipse just hangs for ~30 seconds, then magically comes back.

Answer:
Yes memory usage can get real high and you might run into problems with your JVM, as the default setting is a bit to low.
Consider using this startup parameters when running eclipse:
```
```
-vmargs -XX:MaxPermSize=1024M -Xms256M -Xmx1024M
```
```


Question:
I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast.

What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple.

Is there a way to check if there are any symlinks pointing to a particular folder?

Answer:
I'd use the find command.
```
```
find . -lname /particular/folder
```
```
That will recursively search the current directory for symlinks to
```
/particular/folder
```
. Note that it will only find absolute symlinks. A similar command can be used to search for all symlinks pointing at objects called "folder":
```
```
find . -lname '*folder'
```
```
From there you would need to weed out any false positives.


Question:
I just installed Glassfish V2 on my local machine just to play around with it.

I was wondering if there is a way to retrieve a param passed in by the GET HTTP method.

For instance,

http://localhost:8080/HelloWorld/resources/helloWorld?name=ABC

How do I retrieve the "name" param in my Java code?

Answer:
Like this:
```
```
@Path("/helloWorld")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
@Singleton
public class MyService {
    @GET
    public String getRequest(@QueryParam("name") String name) {
            return "Name was " + name;
    }
}
```
```


Question: Whilst refactoring some old code I realised that a particular header file was full of function declarations for functions long since removed from the .cpp file.  Does anyone know of a tool that could find (and strip) these automatically?

Answer:
If you index to code with Doxygen you can see from where is each function referenced. However, you would have to browse through each class (1 HTML page per class) and scan for those that don't have anything pointing to them.
Alternatively, you could use ctags to generate list of all functions in the code, and then use objdump or some similar tool to get list of all function in .o files - and then compare those lists. However, this can be problematic due to name mangling.


Question:
I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels.

What assembly and/or class should I use?

Answer:
Of course I googled already and found the PngBitmapDecoder class, but it doesn't seem to be available in .Net 2.0?
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.pngbitmapdecoder.aspx
The above link mentions it's in the PresentationCore assembly which I don't seem to have included with .Net 2.0


Question:
AFAIK one of the objectives of Stack Overflow is to make sure anyone can come here and find good answers to her Perl related questions. Certainly beginners would ask what is the best online source to learn Perl but others might just want to ask a question.

Probably the friendliest place is the Monastery of Perl Monks. It is a web site with a rating system similar to but more simple than Stack Overflow. You can find lots of good answers there and if you don't find an answer you can always ask.

The other big resource would be the mailing list of your local Perl Mongers group.

Where do you go when you are looking for an answer to a Perl related question?

Answer:
It's worth noting that
http://perlmonks.org
, in addition to the fora, has the Chatterbox, where simple questions can be answered immediately in conversation with other users.
It requires
setting up an account
and
logging in
before
using the Chatterbox
, though.


Question: Has any one done this before? It would seem to me that there should be a webservice but i can't find one.  I am writing an application for personal use that would just show basic info from IMDB.

Answer:
There is no webservice available.
But there are enough html scrapers written in every language to suit your needs!
I've used the
.NET 3.5 Imdb Services opensource project
in a few personal projects.
1 minute google results:
Perl:
IMDB-Film
Ruby:
libimdb-ruby
Python:
IMDbPY


Question:
I'm using the .NET TWAIN code from http://www.codeproject.com/KB/dotnet/twaindotnet.aspx?msg=1007385#xx1007385xx in my application.
When I try to scan an image when the scanner is not plugged in, the application freezes.

How can I check if the device is plugged in, using the TWAIN driver?

Answer:
I started of with the same source code that you downloaded from CodeProject, but moved most of the code in MainFrame.cs that initiates the scanning to a Scanner class.  In order to check for scan errors I call the following method in stead of calling Twain.Acquire directly:
```
```
enum AcquireResult
{
    OK = 0,
    InitFailed = 1,
    DeviceIDFailed = 2,
    CapabilityFailed = 3,
    UserInterfaceError = 4
}
private void StartScan()
{
    if (!_msgFilter)
    {
        _parent.Enabled = false;
        _msgFilter = true;
        Application.AddMessageFilter(this);
    }
    AcquireResult ar = _twain.Acquire();
    if (ar != AcquireResult.OK)
    {
        EndingScan();
        switch (ar)
        {
            case AcquireResult.CapabilityFailed:
                throw new Exception("Scanner capability setup failed");
            case AcquireResult.DeviceIDFailed:
                throw new Exception("Unable to determine device identity");
            case AcquireResult.InitFailed:
                throw new Exception("Scanner initialisation failed");
            case AcquireResult.UserInterfaceError:
                throw new Exception("Error with the Twain user interface");
            default:
                throw new Exception("Document scanning failed");
        }
    }
}
```
```
I usually initiate the scan event on a seperate thread in order for the app not to freeze while scanning is in progress.


Question:
Can somebody in SO please provide me with a list of resources about Enterprise Mashups and technologies related to SharePoint platform?

Update (as per suggestion of @Spoon16 in the comments):-
The mashup application may typically retrieve a list of contacts from a SharePoint site and display the address of a selected contact person on a map (again maybe Google maps).

Answer:
There are a number of different ways to pull external information into SharePoint.
For mashing up SharePoint data in external applications:
Web Services
; great web services coverage for the underlying API will allow you to build external mashups (like the one you mention in your question comment).  Specifically take a look at the
Lists Service
.
For mashing up external data sources inside of SharePoint:
Business Data Catalog
; when you have the enterprise version of Microsoft Office SharePoint Portal server you can use the Business Data Catalog to interact with a very wide variety of external datasources in a read/write fashion.  Works with relational databases and web services.
Enterprise Search
; the indexing capabilities provided by SharePoint's Enterprise search technology are extensive
RSS Web Part
; allows you to consume and apply XSLT transform to any RSS feed and output the result on any SharePoint page
Page Viewer Web Part
; allows an iframe to be embedded on any page, provides an easy mechanism of integrating external applications into the SharePoint environment
SharePoint has an
extensive development framework
that enables you to leverage the full capabilities of the .NET framework to make your wildest mashup dreams come true.  You can use even add additional services to SharePoint that expose the underlying data in custom ways (not covered by the Out of the Box web services) if you like.


Question:
Imagine I have an function which goes through one million/billion strings and checks smth in them.

f.ex:

foreach (String item in ListOfStrings)
{
    result.add(CalculateSmth(item));
}

it consumes lot's of time, because CalculateSmth is very time consuming function.

I want to ask: how to integrate multithreading in this kinda process?

f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items.

Maybe anyone can show some examples or articles..

Forgot to mention I need it in .NET 2.0

Answer:
You could try the
Parallel extensions
(part of .NET 4.0)
These allow you to write something like:
```
```
Parallel.Foreach (ListOfStrings, (item) =>
    result.add(CalculateSmth(item));
);
```
```
Of course result.add would need to be thread safe.


Question:
I have a large source repository split across multiple projects. I would like to produce a report about the health of the source code, identifying problem areas that need to be addressed.

Specifically, I'd like to call out routines with a high cyclomatic complexity, identify repetition, and perhaps run some lint-like static analysis to spot suspicious (and thus likely erroneous) constructs.

How might I go about constructing such a report?

Answer:
For static analysis there is
pylint
and
pychecker
. Personally I use pylint as it seems to be more comprehensive than pychecker.
For cyclomatic complexity you can try
this perl program
, or this
article
which introduces a python program to do the same


Question:
I'm facing a problem on the Win32 API. I have a program that, when it handles WM_PAINT messages, it calls BeginPaint to clip the region and validate the update region, but the BeginPaint function is always generating a WM_NCPAINT message with the same update region, even if the touched part that needs repainting is only inside the client region.

Do anyone has any clue why this is happening? It's on child windows with the WS_CHILD style.

Answer:
I guess the
```
WM_NCPAINT
```
message is always sent with the assumption that the border needs to be repainted as well!


Question:
I have two webapplication, one is a simple authenticationsite which can authenticate the logged in user and redirects him then to another site.

Therefore I have to pass ther userId (GUID) to the second application. Currently this is done via the URL but i would like to hide this id.

Has anybody an idea how to do this properly?

[EDIT]: I can't use the Session because of the ApplicationBoundaries (2 different Servers)

Answer:
Pass the GUID through a
session
, best way.
http://www.w3schools.com/ASP/asp_sessions.asp
OR, since it's 2 different servers, pass the information by POST method:
http://www.w3schools.com/aspnet/aspnet_forms.asp
The other possibility is to store the session state in a database on the local server, and remotely access that database from the other server to see if the user has successfully logged in and within session timelimit.
With that in mind, you can do the entire authentication remotely as well.  Remotely connect to the local database from the remote server and check the login credentials from there...that way you will be able to store the session and/or cookie on the remote server.
I would recommend AGAINST the hidden field proposition
, as it completely counteracts what you are trying to do!  You are trying to hide the GUID in the URL but posting the same information in your HTML code!  This is not the way to do it.
Best choice is the database option, or if not possible, then use HTTP POST.


Question:
In SQL Server 2000/2005,

Is it possible to force the default value to be written to already existing rows when adding a new column to a table without using NOT NULL on the new column?

Answer:
I doubt it.
http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx
The approach recommended by Microsoft is as follows (taken from the url above)
```
```
UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL
ALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL
```
```


Question:
I'm using a ASP.NET menu control. I'd like the menu to look like this, where link 1 through 10 are in one sitemap file and link 11 through 20 in another.

root
--link 1
(...)
--link 10
--link 11
(...)
--link 20

However, sitemap file MUST have a root  which I cannot seem to suppress.

Any thoughts?

-Edoode

Answer:
Is there any reason that you can't add a dummy root node and then subclass the ASP.NET menu control to ignore your dummy "root" node?
You should be able to tell your SiteMapProvider to use different site maps for the menu.
The other question I have is what's the purpose of having multiple sitemap files?  I'm sure you have a valid reason for this, but knowing what's going on would make it easier to understand and come up with a better solution.
That being said, I would come up with a homegrown menu system.  You could use jQuery and the superfish plugin on the front end and use C# to read your site map files on the back end to build the menuing structure.


Question: I would like to know what's the best technique to do single sign-on in web sites. It means that if you enter in more than one website, you will be authenticated in a "transparent" way. I'm using php + curl to set the cookies for the different sites, but i really would like to know if does exist a standard way to do it.

Answer:
The best way is to use Image tags which pull an image stream from your external sites.
So if you're at www.some-site.com and you want to also be signed into www.some-partner-site.com you have this displayed after logging in:
Because you're using an Image it forces the browser to "pull in" the contents of that URL.
I've recently built a solution which does it with ASP.NET but we also have a php-based partner site.
What image displayed is irrelivant, really you should not display any image at all (hence the 1x1 size)


Question: Say I have a table called myTable.  What is the SQL command to return all of the field names of this table?  If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well.

Answer:
MySQL 3 and 4 (and 5):
```
```
desc tablename
```
```
which is an alias for
```
```
show fields from tablename
```
```
SQL Server (from 2000) and MySQL 5:
```
```
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'tablename'
```
```
Completing the answer: like people below have said, in SQL Server you can also use the stored procedure
```
sp_help
```
```
```
exec sp_help 'tablename'
```
```


Question:
Is it possible to do like this:

interface IDBBase {
     DataTable getDataTableSql(DataTable curTable,IDbCommand cmd);
     ...
}

class DBBase : IDBBase {
     public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {
         ...
     }
}

I want to use the interface to implement to d/t providers (MS-SQL,Oracle...); in it there are some signatures to be implemented in the corresponding classes that implement it. I also tried like this:

genClass<typeOj>
{
    typeOj instOj;

    public  genClass(typeOj o)
    {      instOj=o;    }

    public typeOj getType()
    {        return instOj;    }

...

interface IDBBase
{
    DataTable getDataTableSql(DataTable curTable,genClass<idcommand> cmd);
    ...
}

class DBBase : IDBBase
{
    public DataTable getDataTableSql(DataTable curTable, genClass<SqlCommand> cmd)
    {
        ...
    }
}

Answer:
No it's not possible. Method should have same signature that one declared in the interface.
However you can use type parameter constraints:
```
```
interface IDBClass<T> where T:IDbCommand
{
    void Test(T cmd);
}

class DBClass:IDBClass<SqlCommand>
{
    public void Test(SqlCommand cmd)
    {
    }
}
```
```