q:
Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused.

And now that we're here, how do they differ from a regular function?

[A]
Not all closures are lambdas and not all lambdas are closures. Both are functions, but not necessarily in the manner we're used to knowing.
A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.
A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.
In an object-oriented language, closures are normally provided through objects. However, some OO languages (e.g. C#) implement special functionality that is closer to the definition of closures provided by purely
functional languages
(such as lisp) that do not have objects to enclose state.
What's interesting is that the introduction of Lambdas and Closures in C# brings functional programming closer to mainstream usage.


q:
I've been searching around for a Continuous Integration solution for Ruby on Rails, but haven't been too pleased with the results.  I came from a .NET shop that used CruiseControl.NET and was really spoiled with its ease of use and rich status/reporting.

Ideally I'm looking for:

The obvious Git/SVN and Test::Unit
integration

Integration with Rake and/or
Capistrano

A web interface showing the status
of the build

Email notification of failed builds.

Desktop notification (potentially
through Growl)

REST API for build statuses

Plugin framework for running other code analysis tools and reporting results in the UI

[A]
How about
CruiseControl.rb
?
Same crowd that did
```
CruiseControl
```
(thoughtworks) and written in
```
Ruby
```
. Very easy to use
```
Rake
```
to integrate your other tools, and can use the
ruby-growl
gem for your notifications.

s: huggingface

c: devops

d: intermediate


q:
What would be the most efficient data type to store a UUID/GUID in databases that do not have a native UUID/GUID data type? 2 BIGINTs?

And what would be the most efficient code (C# preferred) to convert to and from a GUID to that type?

Thanks.

[A]
Looking at the
.NET guid class
, there are a couple ways to initialize a guid:
Guid(Int32, Int16, Int16, Byte, Byte, Byte, Byte, Byte, Byte, Byte, Byte)
Guid(string)
While it may be more efficient, in theory, to store the integer in a database (you could use bit shifting to really store 4 32-bit integers.. but you'd have to calculate this out when loading and saving every time. Additionally, it would take 4 fields in the database.. I would imagine it would end up being less efficient.
Add in the impossibility of reading this directly in your database for debugging/testing purposes, and I'd say hands-down that it's best to store a string. It's only a 32-character field (36 if you include the dashes), and it's very easy to convert. guid.
ToString()
and
new Guid(stringValue);


q:
I am trying to use set.insert (key) as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like:

if (set.insert( key )) {
    // some kind of code
}

Is this allowed? Because the compiler is throwing this error:

conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal

[A]
set::insert returns a pair, try this:
```
```
if( set.insert( key ).second ) {
    // some kind of code
}
```
```


q:
I need a serviceable shell for MSYS.  This is my current dilemma:

The default rxvt.exe has a scroll bar and copy and paste, but doesn't send control characters or arrow keys to a running program in the shell (like interpreters/debuggers).  This is a real thorn when using the Haskell interpreter ghci.

The other shell sh.exe handles control characters (or at least some of them), but has no scroll bar or copy and paste.

rxvt also has (relatively) more issues with output buffering

What are my options?  Does the replacement shell need to be msys aware?  All I want is a sane environment to work with Haskell (ghc), C++ (gcc), and the basic tool chain (make and what not).  I'm willing to compile a shell if it doesn't involve crazy shenanigans.

[A]
You are confusing "shell" and "terminal emulator".
```
sh.exe
```
is the former; rxvt is the latter. (mind you, under Windows you can do without a terminal emulator because Windows creates one (a "console window") for any console program (such as sh.exe) if it's not already running inside one)


q:
I have a DataTable that has a boolean column called [Invalid]. I need to divide this data up by this Invalid column - valid rows can be edited, invalid rows cannot. My original plan was to use two BindingSources and set the Filter property ([Invalid] = 'false', for instance), which plays right into my hands because I have two DataGridViews and so I need two BindingSources anyway.

This doesn't work: the BindingSources set the Filter property associated with the DataTable, so both BindingSources hold the same data. Am I going to have to do two fetches from the database, or can I do what I want with the objects I have?

[A]
I think you need to do another join to get ab's max val for each a.id first.
Something like this:
```
```
select a.*
from a
left join (
    select aid, max(val) as val
    from ab
    group by aid
) abmax on abmax.aid=a.id
inner join ab on ab.aid=abmax.aid and ab.val=abmax.val
inner join b on b.id=ab.bid
where b.val='foo'
```
```


q:
What is the memory model for concurrency in C++03?

(And, does C++11 change the memory model to support concurrency better?)

[A]
Unfortunately in C++ there is no "Standard Memory Model" like that of Java. The actual implementation is left up to the compiler, runtime libraries and processors.
Thus the C++ memory model == chaotic mix-mash of models, which means you always have to try to write safe code that doesn't depend on a specific memory model, and that goes for threaded programming as well, because the compiler can do any optimization it wants to outside of a critical section, even out of order processing!


q:
What are some of the better AJAX Treeviews out there that support asynchronous JSON loading.

YUI TreeView seems nice, but bloated with tables, etc.

[A]
jQuery TreeView plugin
it's really good and it haves very nice
asynchronous
JSON
loading capabilities...
ExtJS TreeView Component
, also great, multi-level asynchronous loading, excelent for large trees.


q: I wrote a simple javascript image rotator which picks a random image on each page load.  The issue is that if i use a default image, that default image will show up for a second before the javascript loads and replaces it. Obviously if someone has javascript disabled i want them to see an image. How can i have a default image without a flickering of the default image.

[A]
If you hide the default image as the first thing you do when the page loads, there probably won't be a chance for the users to see the image. You can then install an onload handler on the image and change its source to your random image. When the image loads, you can unhide the image.
```
```
window.onload = function () {
    var img = document.getElementById("rotating_image");

    // Hide the default image that's shown to people with no JS
    img.style.visibility = "hidden";

    // We'll unhide it when our new image loads
    img.onload = function () {
        img.style.visibility = "visible";
    };

    // Load a random image
    img.src = "http://example.com/random" + Math.floor(Math.random() * 5) + ".jpg";

};
```
```


q:
I have several branches in TFS (dev, test, stage) and when I merge changes into the test branch I want the automated build and deploy script to find all the updated SQL files and deploy them to the test database.

I thought I could do this by finding all the changesets associated with the build since the last good build, finding all the sql files in the changesets and deploying them. However I don't seem to be having the changeset associated with the build for some reason so my question is twofold:

1) How do I ensure that a changeset is associated with a particular build?

2) How can I get a list of files that have changed in the branch since the last good build? I have the last successfully built build but I'm unsure how to get the files without checking the changesets (which as mentioned above are not associated with the build!)

[A]
So I can understand the intuitive appeal of this approach, but I don't think it's the right way to go.
For one thing it's going to be difficult. But the second problem is that TFS doesn't have a good way to record deployment data.
For the first question, I'm not sure what that means. For the second question you can use the build labels and tf history today list of the changed files.
As an alternative, you could reconsider how you want to manage SQL changes. I use a low-tech method of keeping the current pending changes in one directory, and then after deploying moving the files to a different directory. This method can be enhanced by keeping a deployment history table in the database. You may also want to look into vsts DB addition, the current
CTP
has a lot of new features around managing database changes. I also hear that
Red Gate
has nice database management tools as well.


q:
I have an application running on multiple IIS servers that need to parse a CSV file that is placed on a common network drive.  If I use the System.IO.FileSystemWatcher Created event to be notified of the event when the file is available, how can I ensure only one server parses the file?  If all servers are notified of this change, all will try to parse it.  Should the first server copy this locally and then parse it?  Would this cause errors on the other servers? Should I set the remote directory access to only allow one server read access?

The file contains records that needs to be inserted into a shared database, but there is no unique key for the records.  Therefore, if more than one server grabs the file at the same time and inserts the records, there will be duplicates in the database.

[A]
Key question is: Does something bad happen when all of them try and parse the file at roughly the same time? Multiple read access is basically allowed on the file system level, so this fact alone would not necessarily break anything.
I would probably try the method of creating a lock file on first file access and make servers look for the lock file before accessing the file. Delete the lock file when you're done.
You could also place an exclusive lock on the file, only one server will be able to do that at a time. The others will fail trying:
```
```
FileStream fs = new FileStream(
  FilePath,
  FileMode.Open,
  FileAccess.ReadWrite,
  FileShare.None
);
```
```


q:
If I have the string .....ZZ..ZZ..... or .Z.1.Z.23Z.4.Z55,

Is there an easy way of shifting all Zcharacters in the string one space right of the current position?

Some additional test strings are:

.Z

Z.

ZZ.

.ZZ

Z

ZZ

ZZZ

I think a few of the higher voted answers to this question (including the currently accepted one) do not work on these tests.

[A]
Just iterate through the text and swap characters:
```
```
int main ()
{
    char text[] = "...Z.Z.Z...", temp;
    int text_len = strlen (text), i;
    for (i = text_len - 1; i >= 0; i--)
    {
        if (text[i] == 'Z')
        {
                temp = text[i+1];
                text[i+1] = text[i];
                text[i] = temp;
        }
    }
    printf ("%s\n", text);
    return 0;
}
```
```
Produces:
```
```
[~]$ gcc zshift.c && ./a.out
....Z.Z.Z..
```
```
There's a lot of discussion in the comments about a possible off-by-1 error in the above code. However, simple testing / stepping through is enough to show that this is not the case.
```
```
zshift "Z." -> ".Z"
zshift ".Z" -> "."
zshift "Z" -> ""
```
```
I think the behavior of "dropping" trailing Zs when shifting off the end of the string is sensible. After all, if you shift the bits of an integer, bits that end up outside the bounds of the integer are dropped.
If another behavior is desired -- for example, shifting only within the string -- the change to the algorithm is minimal:
```
```
temp = text[i+1];
if (temp == 0) continue;
text[i+1] = text[i];
text[i] = temp;
```
```


q: Do you think ASP.NET MVC is able to develop RESTful web services and which approach you would use for it?

[A]
I would seriously look at ADO.NET Dataservices. (formaly code named Astoria) There's some really nice tooling for Restful services in there!
http://msdn.microsoft.com/en-us/data/bb931106.aspx


q:
Our groups legacy ASP 3.0 web apps were able to take advantage of a global error file by setting up a custom error file within IIS's Custom Error's tab.  I'm unable to find a similar solution for ASP.NET apps.

Does anyone know if there is a way to have a centralized "Error.aspx" page (for example) that will trap errors for an entire application pool?  The objective is to avoid adding custom code to each app's Global error handler ....

Any guidance is greatly appreciated!

[A]
You can add the
```
<customErrors defaultRedirect="[url]"></customErrors>
```
tag to your web.config or even up to your machine.config to redirect to a custom error page.  The custom errors tag also suppors multiple  subelements that can be used to define custom errors.
Just remember when editing the machine.config file, it will affect all the applications on that machine.


q:
What is the best way to deal with XML documents, XSD etc in C# 2.0?

Which classes to use etc. What are the best practices of parsing and making XML documents etc.

EDIT: .Net 3.5 suggestions are also welcome.

[A]
It depends on the size; for small to mid size xml, a DOM such as
XmlDocument
(any C#/.NET versions) or
XDocument
(.NET 3.5/C# 3.0) is the obvious winner. For using xsd, You can load xml using an
XmlReader
, and an XmlReader accepts (to
Create
) an
XmlReaderSettings
. The XmlReaderSettings objects has a
Schemas
property that can be used to perform xsd (or dtd) validation.
For writing xml, the same things apply, noting that it is a little easier to lay out content with LINQ-to-XML (XDocument) than the older XmlDocument.
However, for huge xml, a DOM may chomp too much memory, in which case you might need to use XmlReader/XmlWriter directly.
Finally, for manipulating xml you may wish to use
XslCompiledTransform
(an xslt layer).
The alternative to working with xml is to work with an object model; you can use
xsd.exe
to create classes that represent an xsd-compliant model, and simply load the xml
as objects
, manipulate it with OO, and then serialize those objects again; you do this with
XmlSerializer
.


q:
In Ruby I have often written a number of small classes, and had a main class organize the little guys to get work done. I do this by writing

require "converter.rb"
require "screenFixer.rb"
.
.
.

at the top of the main class. How do I do this in Java? Is it "import?"

Also, could someone please come up with a better title for this question?

[A]
```
```
public class Example {
   public Example(IConverter converter, IScreenFixer screenFixer) {

   }
}
```
```
http://en.wikipedia.org/wiki/Facade_pattern
?


q:
I have a COM SDK written in C++ and I'd like to create documentation for my product.  I understand that most people will probably not use C++ for integration with this COM component, but many will.

Which method is best to describe the API, without losing details that a C++ developer would need to know.


q: I am writing one web chat program using AJAX (a little bit). It is working when both users open a chat page, but I want to open a window when one user send data to others.

[A]
Sounds like you need to write some javascript to open a new window when a message is received.  How are you sending the message -
reverse Ajax
?
Presumably both users will need to have your chat applications web page open so that you have somewhere to put the reverse ajax hook code.


q: How does reverse proxy server work? Is it used to secure the main server? Is it used as a firewall? What are the reasons for using a proxy server? Could someone give a real world example?

[A]
Typically a normal proxy server looks at requests going from an internal network out to the internet and caches them so that if another client requests the same page, the proxy can give it to them much quicker than a brand new request to a remote server.
A reverse proxy works in the opposite way.
Generally a reverse proxy will be installed in front of a web server, so that the second time a client requests a page from that server, the proxy will give it back to the remote client without bothering the web server at all.
In many cases the reverse proxy and the web server are the same machine.  This is often done because the work the reverse proxy does is much, much simpler than going through a complete web server transaction.
Apache, lighthttpd and many other web servers can also function as reverse proxies.
Check
Wikipedia
for more info.


q:
Where can I find a free, lightweight YUI-like compressor for PHP?

I am sure it will decrease the file size but will compressing PHP code boost its performance?

Is this the same thing as an obfuscator?

[A]
There is a product called PHP Encoder by ionCube (
http://www.ioncube.com/sa_encoder.php
) which is enterprise grade compression and obfuscater.
PHP Encoder is a PHP extension to create and run compiled bytecodes for accelerated runtime performance and maximum security.
It will shrink the file size, and speed up runtime because the code is already partially compiled


q: If I'm using Visual Studio 2008 targeted to ASP.NET 2.0, then which version of the Ajax Control Toolkit should I be using?

[A]
You need the Toolkit version
1.0.20229.20821
,
AjaxControlToolkit.zip
the dll's are targeted to .NET 2.0 and you need also the
ASP.NET AJAX Extensions 1.0 for .NET 2.0
.


q:
Greenspunning. We've all had occasion to hack around a language's missing features to get what we need. Implementing pseudo-monadic patterns in Java,  Y Combinators in Javascript, variable immutability in C...

What do you consider your most impressive workaround in search of greater functionality? In hindsight, was it worth the hack? Even better: did it, like Ruby's string#to_proc, become an accepted feature of a later version of the language?


q: Can anyone point to live examples of SOAP or REST web services? How do you use or test an existing web service with a client?

[A]
A SOAP webservice which converts the temperature Celsius to Fahrenheit and other way around
http://www.w3schools.com/webservices/tempconvert.asmx
A description and source code is here
http://www.w3schools.com/webservices/ws_example.asp


q: How to put underline for first letter for access key for  ?

[A]
Tried the AccessKey attribute?
```
```
<asp:button id="Button1" runat="server" Text="Print" AccessKey="P" />
```
```
If it is really underlined is out of your control. The user agent (e.g. browser) is deciding that.


q:
So from what little I understand about packaging for Macs, I see that the actual program that launches is the one defined under the CFBundleExecutable key in Info.plist.

<key>CFBundleExecutable</key>
<string>JavaApplicationStub</string>

Now, my app doesnt work if /APP/Content/MacOS/JavaApplicationStub is not chmodded +x (It just fails silently without doing anything, which is a pain!).
Fair enough, its not executable I guess. But its a big problem if you are copying the app from somewhere that dosent support +x properties on files; such as windows, fat32 USB keys, CDROMs, websites, zip files, etc...

What can I do in these instances to make the app able to run?  Manually setting the execute bit is not an option.

There's got to be people who run Mac apps off CD, at the very least!

[A]
An alternative would be to create an audit log that might look like this:
```
```
AuditLog table
    EntityName varchar(2000),
    Action varchar(255),
    EntityId int,
    OccuranceDate datetime
```
```
where EntityName is the name of the table (eg: Contries, Provinces), the Action is the audit action (eg: Created, Removed etc) and the EntityId is the primary key of the modified row in the original table.
The table would need to be kept synchronized on each action performed to the tables. There are a couple of ways to do this:
1) Make triggers on each table that will add rows to AuditTable
2) From your application add rows in AuditTable each time a change is made to the repectivetables
Using this solution is very simple to get a list of logs in audit.
If you need to get columns from original table is also possible using joins like this:
```
```
select *
from
    Contries C
    join AuditLog L on C.Id = L.EntityId and EntityName = 'Contries'
```
```


q:
Currently when I build my site I have to manually open validate it at the 3wbc site (means when opera pops up, press ctr+alt+shft+u) for every page.
Is it possible to automatically validate every page whenever I build my pages?

P.s.: This page doesn't validate ;)

[A]
You can download and install your own copy of the validator -
http://validator.w3.org/source/
- and invoke it locally instead of trekking out to w3.org for each page. Still, this requires piggybacking over a web server through plain HTTP or the API. For a simpler solution you may prefer to download the SP library -
http://www.jclark.com/sp/index.htm
or
http://openjade.sourceforge.net/
- on which the W3 validator is based, then invoke the command 'nsgmls' from the command line.
There are of course also many desktop HTML validators that can process a batch of HTML pages at once, which may not be automated, but would certainly be much easier than manually checking each page. For example
http://arealvalidator.com/
(Windows),
http://www.webthing.com/software/validator-lite/install.html
(Unix).


q:
In this sentence:

myCommand.ExecuteReader(CommandBehavior.CloseConnection)

does it close connection in case of exception?

[A]
There are plenty of ways that the command can go wrong.
Ultimately it is the Close method of the data reader that will close the connection, provided nothing has gone wrong before.
If there is an exception that occurs inside ExecuteReader or any of its called methods, before the actual DataReader object is constructed, then no, the connection will not be closed.
In case of an exception, I wouldn't trust it to close the connection.


q: I have a Java service which now will execute in a batch mode. Multi threaded support is added to the service so for every batch request a thread pool will be dedicated to execute the batch. The question is how do I test this? I have functional tests that pass under the threaded version of the service but, somehow, I feel there must be an idiom for testing this.

[A]
There really isn't a "good" way to do this.  The best thing I can suggest would be TestNG, which allows you to annotate your test methods and cause them to be executed in
n
threads concurrently.  For example:
```
```
@Test(invocationCount=10, threadPool=10)
public void testSomethingConcurrently() {
    ...
}
```
```
My TestNG knowledge is rusty at best, but AFAIK that should invoke the
```
testSomethingConcurrently
```
method 10 times concurrently.  This is a nice and declarative way to run multi-threaded tests against your code.
You can of course do something similar in JUnit by spawning threads manually in a loop, but that's insanely ugly and difficult to work with.  I had to do this once for a project I was working on; those tests were a nightmare to deal with since their failures weren't always repeatable.
Concurrency testing is difficult and prone to frustration, due to its non-deterministic nature.  This is part of why there is such a big push these days to use better concurrency abstractions, ones which are easier to "reason about" and convince one's self of correctness.


q:
Could anyone provide any example of NAnt script for C++ project build automation?

Thanks!

[A]
If the project is in Visual Studio then you can use the
```
<Solution>
```
task, I think.  That's the simplest/ugliest way of doing it.
edit:
Just realised that SO filtered out my little XML tag there.


q:
How can i find out this information?

Ie,

I can install boost 1.35 with a command like

sudo port install boost

only to get boost 1.36 via port i would do something like this?

sudo port install boost-1.36

Hope that clears up my question


q:
How can I extract information from a website (http://tv.yahoo.com/listings)  and then create an XML file out of it? I want to save it so  to parse later and display information using JavaScript?

I am quite new to Perl and I have no idea about how to do it.

[A]
Of course. The easiest way would be the
Web::Scraper
module. What it does is it lets you define scraper objects that consist of
hash key names,
XPath expressions that locate elements of interest,
and code to extract bits of data from them.
Scraper objects take a URL and return a hash of the extracted data. The extractor code for each key can itself be another scraper object, if necessary, so that you can define how to scrape repeated compound page elements: provide the XPath to find the compound element in an outer scraper, then provide a bunch more XPaths to pull out its individual bits in an inner scraper. The result is then automatically a nested data structure.
In short, you can very elegantly suck data from all over a page into a Perl data structure. In doing so, the full power of XPath + Perl is available for use against any page. Since the page is parsed with HTML::TreeBuilder, it does not matter how nasty a tagsoup it is. The resulting scraper scripts are much easier to maintain and far more tolerant of minor markup variations than regex-based scrapers.
Bad news: as yet, its documentation is almost non-existent, so you have to get by with googling for something like [
miyagawa web::scraper
] to find example scripts posted by the module’s author.


q:
My company has developed (and still continues to develope) a large ASP.NET business application. Our platform is ASP.NET 2.0 using some ASP.NET Ajax. We're extensively using third-party components, like webgrids, comboboxes, treeviews, calendar and scheduling controls etc.

Now, I don't know a lot of ASP.NET MVC and I'd like to know if there is a way to use these third-party-controls in the ASP.NET MVC model. Or do vendors have to rewrite their products in order to make them suitable for ASP.NET MVC?

[A]
If they use the ASP.NET Control Model (That will be about 99,9% of controls written by ASP.NET Control vendors), they have to rewrite their controls. How much work there is in that, is very different depending of there arhitecture of their controls - the more ajax they already use, the more posible it is that they easily can change it to MVC.
ASP.NET AJAX Control toolkit for exsample can work with MVC. You can see how to do this in a video on WWW.ASP.NET:
http://www.asp.net/learn/mvc-videos/video-373.aspx


q:
I'm new to Flex, although not new to programming. I want to write a generic event handler that will be called by all my textinput boxes when they receive focus.  When they have focus, I want to change the colour of the textinput box.  When they lose focus, I want to restore the "inactive" color profile. I could write an ActionScript event handler for each textinput box, but we all know that's lame.  :o)  What I need, then, is a way to access the object which is calling the event handler.

In Delphi, I'd have written a function which passes in the Sender object, allowing me to access the calling object's properties.  I'm guessing ActionScript/Flex has a completely different architecture, which is why I'm having difficulty doing this.

Thanks in anticipation!

[A]
I hope I'm understanding what you're asking for... are you talking about event delegation?
This worked for me:
```
```
// 'focusOut' for blur
stage.addEventListener('focusIn', function(e:Event):void {
    // The focused control is e.target
});
```
```


q: How do I declare a private function in Fortran?

[A]
I've never written a line of FORTRAN, but
this thread about "Private module procedures"
seems to be topical, at least I hope so. Seems to contain answers, at least.
jaredor
summary:
The public/private attribute exists within modules in Fortran 90 and later. Fortran 77 and earlier--you're out of luck.


q:
In my Spring MVC based applications i use Freemarker and i like it very much, but it's lacking advantages provided by Composite View pattern.

I'm thinking of trying to use Tiles2 together with Freemarker - does anyone know where do i find a simple example of SpringMVC together with Tiles2+Freemarker?

[A]
nevermind, i've solved it. i just had to specify freemarker templates in tiles definitions file
```
```
<definition name="template" template="/WEB-INF/ftl/main.ftl">
```
```
and add freemarker servlet/maping to web.xml
```
```
<servlet>
    <servlet-name>freemarker</servlet-name>
    <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>

    <!-- FreemarkerServlet settings: -->
    <init-param>
        <param-name>TemplatePath</param-name>
        <param-value>/</param-value>
    </init-param>
    <init-param>
        <param-name>NoCache</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>ContentType</param-name>
        <param-value>text/html</param-value>
    </init-param>

    <!-- FreeMarker settings: -->
    <init-param>
        <param-name>template_update_delay</param-name>
        <param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->
    </init-param>
    <init-param>
        <param-name>default_encoding</param-name>
        <param-value>ISO-8859-1</param-value>
    </init-param>
    <init-param>
        <param-name>number_format</param-name>
        <param-value>0.##########</param-value>
    </init-param>

    <load-on-startup>5</load-on-startup>
</servlet>

 <servlet-mapping>
    <servlet-name>freemarker</servlet-name>
    <url-pattern>*.ftl</url-pattern>
 </servlet-mapping>
```
```
in spring configuration specify tiles as my primary view engine
```
```
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/defs/definitions.xml</value>
            </list>
        </property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
```
```


q:
How can I access Ethernet statistics from C/C++ code like netstat -e?

Interface Statistics

                       Received            Sent

Bytes                      21010071        15425579
Unicast packets               95512           94166
Non-unicast packets           12510               7
Discards                          0               0
Errors                            0               3
Unknown protocols                 0

[A]
Szia,
from
http://en.wikipedia.org/wiki/Netstat
On the Windows platform, netstat
  information can be retrieved by
  calling the GetTcpTable and
  GetUdpTable functions in the IP Helper
  API, or IPHLPAPI.DLL. Information
  returned includes local and remote IP
  addresses, local and remote ports, and
  (for GetTcpTable) TCP status codes. In
  addition to the command-line
  netstat.exe tool that ships with
  Windows, there are GUI-based netstat
  programs available.
  On the Windows platform, this command
  is available only if the Internet
  Protocol (TCP/IP) protocol is
  installed as a component in the
  properties of a network adapter in
  Network Connections.
MFC sample at CodeProject:
http://www.codeproject.com/KB/applications/wnetstat.aspx


q: How can I compile/run C or C++ code in a Unix console or a Mac terminal?

[A]
Assuming the current directory is not in the path, the syntax is
```
./[name of the program]
```
.
For example
```
./a.out
```


q:
I have a page, with some code in js and jQuery and it works very well. But unfortunately, all my site is very very old, and uses frames. So when I loaded my page inside a frame, $(document).ready() doesn't fire up.

My frameset looks like:

<frameset rows="79,*" frameBorder="1" frameSpacing="1" bordercolor="#5996BF" noresize>
    <frame name="header" src="Operations.aspx?main='Info.aspx'" marginwidth="0" marginheight="0" scrolling="no" noresize frameborder="0">
    <frame name="main" src="Info.aspx" marginwidth="0" marginheight="0" scrolling="auto" noresize frameborder="0">
</frameset>

My page is loaded into the main frame. What should I do?

[A]
There is no reason for
```
$(document).ready()
```
not to be called.
Be sure your page contains an include to
```
jquery.js
```
. Try to do a simple test with an empty HTML page and just an alert to see if there is another problem.
If you are trying to use this inside the HTML page that contains the frame's definition, keep in mind that there is no document there, you will have to use the


q:
I have table employee like,

employee
(
emp_id int primary key,
emp_name varchar(50),
mngr_id int)

and here mngr_id would either null or contain valid emp_id. This way it form the hierarchy of employees in the organization.

In order to traverse the entire hierarchy I had to write the recursive stored procedure. (in Oracle it's easy by using CONNECT BY .. START WITH)

So the question is that what is the performance impact of such stored procedure given that the level of hierarchy would not go beyond 10 levels !

Is there any other way to achieve the same ?

[A]
Regarding the last question: There are a few nice options at
"What is the most efficient/elegant way to parse a flat table into a tree?"
You should also consider caching the result of the recursion in an intermediate table. If you change that only on update to your hierarchy table, the recursion performance hit will be negligible.
EDIT:
Personally I would do the recursion in the presentation layer of my app, for example on the web server. This provides greater flexibility compared to what can be achieved in SQL, and you can also use session or application level caching. (Using a pre-constructed DB table that is kept up to date with a trigger never leaves you with an outdated cache, though.)


q:
In Visual Studio, when you compile foo.idl, MIDL generates the proxy information in foo_p.c.

Unfortunately, for Win32 and x64 files, it uses the same filename. For Win32, the file starts with:

#if !defined(_M_IA64) && !defined(_M_AMD64)

For x64, the file starts with:

#if defined(_M_AMD64)

When you build for Win32 and then immediately build for x64, it doesn't replace the foo_p.c file, meaning that the project fails to link.

I tried having a pre-build event that deletes the foo_p.c file if it's for the wrong architecture, but VS doesn't even bother to run that step.

How should I get it so that I can build one configuration and then the other?

[A]
You could modify the compiler settings for your IDL file to specify a different file name for the output proxy file according to the target platform. (Select Properties on the IDL file, then Configuration Properties / MIDL / Output).
For Win32 builds, use
```
foo_p_w32.c
```
For x64 builds, use
```
foo_p_x64.c
```
Then, in your Win32 project settings, exclude the file
```
foo_p_x64.c
```
and vice versa for the x64 project.
You need to do the same for the _i.c file, otherwise Visual Studio doesn't seem to rebuild the IDL at all.


q:
What is the simplest way of copying symbolic links on the Mac?

A python or perl solution would be preferred, but any solution would be a help.

I am copying frameworks for an installation package, and need the links to be maintained

[A]
In python you can use
os.readlink
and
os.symlink
to perform this action. You should check if what you operate on is actually a symbolic link with
os.lstat
and
stat.S_ISLNK
```
```
import os, stat
if stat.S_ISLNK(os.lstat('foo').st_mode):
    src = os.readlink('source')
    os.symlink(src, 'destination')
```
```
You could do it with the
-R option of cp
. This works because cp by default does not follow symbolic links but barks at copying non-files without specifying -R which means recursion.
```
```
cp -R source destination
```
```
In python that would be with the
subprocess.call
```
```
from subprocess import call
call(['cp', '-R', 'source', 'destination'])
```
```
Note that a
macosx alias
is not a symbolic link and therefore symbolic link specific treatment will fail on it.


q:
I'm trying to do XHTML DOM parsing with JTidy, and it seems to be rather counterintuitive task. In particular, there's a method to parse HTML:

Node Tidy.parse(Reader, Writer)

And to get the <body /> of that Node, I assume, I should use

Node Node.findBody(TagTable)

Where should I get an instance of that TagTable? (Constructor is protected, and I haven't found a factory to produce it.)

I use JTidy 8.0-SNAPSHOT.

[A]
You could use the
```
parseDOM
```
method instead, which would give you a
```
org.w3c.dom.Document
```
back:
```
```
Document document = Tidy.parseDOM(reader, writer);
Node body = document.getElementsByTagName("body").item(0);
```
```


q: How do I convert text between multi-byte text strings, for example Simplified Chinese GB 2312, into UTF8 using c++ ?

[A]
On unix systems you'd best use the iconv library.
See
iconv_open
,
iconv
,
iconv_close
You'd have to know the character encoding of course (EUC-CN, HZ).
If not on a unix system, search for some support in the OS, doing character conversions by hand is very hard to get right.


q: What'd also interest me is which have more or less dependencies.

[A]
Google is our friend
...
First hit:
http://syntax.rubyforge.org/chapter-1.html#s1


q:
For a file containing the given class, SomeCoolClass, what would be the proper or standard filename?

 1. somecoolclass.rb
 2. some_cool_class.rb
 3. some-cool-class.rb
 4. SomeCoolClass.rb

or some other variation?

I noticed in the Ruby stdlib, versions 1, 2 and 3 are used.

[A]
With just
Ruby
(i.e. not Rails), naming is only a convention.  In
Rails
the
convention
of using underscores is necessary (almost).
I think convention #2
```
lowercase_and_underscore.rb
```
is more common and looks pretty good, though an article
Here
says
```
lowercasenounderscore.rb
```
is the Ruby convention.
Pick either
which ever convention is more common or which ever one you like more.  The most important thing is to
be consistent within a project
.


q: What is the arrow operator (->) a synonym for?

[A]
The following two expressions are equivalent:
```
```
a->b

(*a).b
```
```
(subject to operator overloading, as Konrad mentions, but that's unusual).


q:
If I have a folder structure set up like this:

~/Projects
    emacs
        package1
            package1-helpers
        package2
            package2-helpers
            package2-more-helpers
        package3
            package3-helpers

How do I add these folders:

~/Projects/emacs

~/Projects/emacs/package1

~/Projects/emacs/package2

~/Projects/emacs/package3

...to the load-path from my .emacs file?

I basically need a short automated  version of this code:

(add-to-list 'load-path "~/Projects/emacs")
(add-to-list 'load-path "~/Projects/emacs/package1")
(add-to-list 'load-path "~/Projects/emacs/package2")
(add-to-list 'load-path "~/Projects/emacs/package3")

[A]
```
```
(let ((base "~/Projects/emacs"))
  (add-to-list 'load-path base)
  (dolist (f (directory-files base))
    (let ((name (concat base "/" f)))
      (when (and (file-directory-p name)
                 (not (equal f ".."))
                 (not (equal f ".")))
        (add-to-list 'load-path name)))))
```
```


q:
Is there an easy way with LINQ to flatten an XML file?

I can see a number of ways with XSLT but wondered what the best option with LINQ would be?

I cant put the xml structure up exactly as stackoverflow seems to filter chevron chars. But its something like this

nodeA

--nodeA1

--nodeA2

NodeB

I want to end up with

nodeA

nodeA1

nodeA2

NodeB

[A]
OK; it depends on the output you want - with XElement you'd need to do a bit of work to remove all the descendent nodes etc. However, it is actually quite simple with XmlDocument:
```
```
string xml = @"<xml><nodeA><nodeA1/><nodeA2/></nodeA><NodeB/></xml>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlDocument clone = new XmlDocument();
XmlElement root = (XmlElement) clone.AppendChild(clone.CreateElement("xml"));
foreach(XmlElement el in doc.SelectNodes("//*")) {
    root.AppendChild(clone.ImportNode(el, false));
}
Console.WriteLine(clone.OuterXml);
```
```
Outputs:
```
```
<xml><xml /><nodeA /><nodeA1 /><nodeA2 /><NodeB /></xml>
```
```
[was]
Care to define "flatten" in this context? i.e. "before" and "after"?
XDocument has Descendants() and DescendantNodes() which might do the job...


q:
Sometimes, when we're doing small changes to our web apps, e.g. bug fixes, we don't build a whole new WAR-file each time, but merely replace just the affected class files in the exploded web app directory under WEB-INF/classes and restart the app.

Is that okay?

[A]
I'd say that probably isn't a best practice, because of versioning: how do you know which version of the application you've got deployed? If you deploy a .war file your build process can take care of updating a build number (from source control, or separately, whatever - as long as each build has a different number it's OK).
If you're using continuous integration (and it's definitely a good idea to be) then your build process should be kicking out an 'artifact' (war file) each time you make changes in source code. also perhaps tagging the code in version control with the build number.
So, when you deploy your web app, you know exactly which version is running and which source code makes up that version.
Making small incremental changes by updating individual .class files I'd say is probably not a good idea for anything other than local developer testing.


q:
I need to include a copyright statement at the top of every Python source file I produce:

#   Copyright: © 2008 etc.

However, when I then run such a file I get this message:

SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details.

Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:

# -*- coding: iso-8859-1 -*-

to tell Python I'm using Latin encoding, or I can change the copyright statement to:

#   Copyright: \xa9 2008 etc.

which just possibly doesn't have the same legal standing.

Is there a more elegant solution?

[A]
The copyright symbol in ASCII is spelled
```
(c)
```
or "
```
Copyright
```
".
See circular 61,
Copyright Registration for Computer Programs
.
While it's true that the legal formalism (see Circular 1,
Copyright Basics
) is
The symbol © (the letter C in a
  circle), or the word “Copyright,” or
  the abbreviation “Copr.”; and...
And it's also true that
To guarantee protection for a
  copyrighted work in all UCC member
  countries, the notice must consist of
  the symbol © (the word “Copyright” or
  the abbreviation is not acceptable)
You can dig through circular
3
and
38a
.
This has, however, already been tested in court.  It isn't an interesting issue.  If you do a search for "(c) acceptable for c-in-a-circle", you'll find that lawyers all agree that (c) is an acceptable substitute.  See Perle and Williams.  See Scott on Information Technology Law.


q:
I appreciate that there are now many mechanisms in dotnet to deal with XML in a myriad of ways...

Suppose I have a string containing the XML....

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <Element1>
        <Element1_1>
            SomeData
        </Element1_1>
    </Element1>
    <Element2>
        Some More Data
    </Element2>
</root>

What is the simplest (most readable) way of removing Element1_1?

Update... I can use any .Net API available in .Net 3.5 :D

[A]
Which APIs are you able to use? Can you use .NET 3.5 and LINQ to XML, for instance? If so,
XNode.Remove
is your friend - just select Element1_1 (in any of the many ways which are easy with LINQ to XML) and call Remove() on it.
Examples of how to select the element:
```
```
XElement element = doc.XPathSelectElement("/root/Element1/Element1_1");
element.Remove();
```
```
Or:
```
```
XElement element = doc.Descendants("Element1_1").Single().Remove();
```
```


q: Is it okay to run Hibernate applications configured with hbm2ddl.auto=update to update the database schema in a production environment?

[A]
No, it's unsafe.
Despite the best efforts of the Hibernate team, you simply cannot rely on automatic updates
in production
. Write your own patches, review them with DBA, test them, then apply them manually.
Theoretically, if
hbm2ddl update
worked in development, it should work in production too. But in reality, it's not always the case.
Even if it worked OK, it may be sub-optimal. DBAs are paid that much for a reason.


q: I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?

[A]
If two copies fit in memory, then you can easily make a copy.  The second copy is the compressed version.  Sure, you can use numpy, but you can also use the
array
package.  Additionally, you can treat your big binary object as a string of bytes and manipulate it directly.
It sounds like your file may be
REALLY
large, and you can't fit two copies into memory.  (You didn't provide a lot of details, so this is just a guess.) You'll have to do your compression in chunks.  You'll read in a chunk, do some processing on that chunk and write it out.  Again, numpy, array or simple string of bytes will work fine.


q: I need a way to check for Wi-Fi routers/access points on my DS homebrew. I'm using PAlib.

[A]
i used the code from ds_wifi_test (which comes with the original dswifi library) when i tried to implement this. Basically, access points are scanned internally when you invoke
```
Wifi_ScanMode()
```
. You can then have the number of AP identified with
```
Wifi_GetNumAP()
```
and retrieve the information for the ith access point with
```
Wifi_GetAPData(i,&data);
```
```
```
nbitems=Wifi_GetNumAP();
Wifi_AccessPoint ap;

for (int i=0;i<nbitems; i++) {
   if(Wifi_GetAPData(i+scrolltop,&ap)==WIFI_RETURN_OK)
      do_whatever_with(&ap);
}
```
```
I'm not aware of any "helper" functions through the PALib in this regards. All the PALib seems to have is a few "wrappers" to ease common tasks once a WFC setting has been defined (
see day#20 tutorial
)


q:
I'm opening a new browser window from my site for some of the members. However, some may later close it, or it might have initially failed to open.

Is there a snippet of fairly plain Javascript that can be run on each page to confirm if another browser window is open, and if not, to provide a link to re-open it?

[clarification:] The code to check is a window is open would be run on other pages - not just in the same window and URL that opened it.  Imagine a user logging in, the window (tries to) open, and then they surf around in the same tab/window (or others) for some time before they close the 2nd window (or it never opened) - I want to be able to notice the window has been closed some time after the initial attempt at opening/after it's closed, so I'm not sure that checking the javascript's return from window.open() (with popup_window_handle.closed) is easily used, or indeed possible.

[A]
```
```
var myWin = window.open(...);

if (myWin.closed)
{
    myWin = window.open(...);
}
```
```


q:
How can I put up a "File Open" dialog from some VBA running in Excel?

I'm using Excel 2003.

[A]
Add a reference to ComDLG32.OCX and then something like...
```
```
Sub PromptForFile()
Dim d As New MSComDlg.CommonDialog

d.Filter = "xls"
d.Filename = "*.xls"
d.ShowOpen

Excel.Workbooks.Open d.Filename

Set d = Nothing
End Sub
```
```


q: I have a customer who needs to send some direct mailing to his contacts which is being collected from trade shows etc. I am thinking about providing a web based solution for them on sending direct mailing material- however this kind of solution always face a major difficulty on having the server blacklisted. I would like to know if there is any suggestions on how to maintain such SMTP server?

[A] Aside from the server (just set up exim or postfix and a web interface to send newsletters from, and do this on a server with an IP address that is different from your own personal mail server (maybe even a different network)), you will want to get your terms and conditions of use nice and tight so that you can remove access to the systems from any customer that has complaints made about emailing. Indeed you can mandate that all emails sent must be lawful (e.g., unsubscription option that works, etc).


q:
Control.TabIndex

Only allows me to overide the Tab order of controls in a given container.

Is there a way to specify this across all the controls in, for example a UserControl, regardless of the contains used to arrange the controls.

Cheers,

Jan

[A]
I'm not sure that there is a particularly good way of doing what you are asking, but check out
Changing WPF focus in code
.
That uses
```
KeyboardNavigation.TabNavigation
```
to set how the various containers take and give up the Focus on tabbing, and also sets the
```
TabIndex
```
properties for each control. Look at the example code with the
```
TabNavigation
```
set to "Continue".
If your tabbing problems are simple, you should be able to find a solution here, if they are complex of need to be generalised, then it might take some more work.


q:
My stomach churns when I see this kind of output.

http://www.freeimagehosting.net/uploads/e1097a5a10.jpg

and this was my command
as suggested by Best way to convert pdf files to tiff files

gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif a.pdf -c quit

What am I doing wrong?

(commercial products will not be considered)

[A]
tiffg4 is a black&white output device.
You should use tiff24nc or tiff12nc as the output device colour PDFs - see
ghostscript output devices
.
These will be uncompressed but you could put the resulting TIFFs through imagemagick or similar to resave as compressed TIFF.


q:
In LinqToSql, it is lovely easy to load a row, change a column, and submit the changes to the database:

using (MyDataContext wdc = new MyDataContext())
{
  Article article = wdc.Article.First(p => p.ID == id);
  article.ItemsInStock = itemsinstock;
  wdc.SubmitChanges();
}

The only drawback: Article is huge. To load the entire article, just to update one column is way overkill and slows down my app significantly.

Is there a way to update a single column using LINQ, without having to load the entire row?

Right now I revert to using ExecuteCommand where speed is of essence, but this is ugly and error prone:

wdc.ExecuteCommand("UPDATE Article SET ItemsInStock = @1 WHERE ID = @2", itemsinstock,id);

[A]
You need to set UpdateCheck on all properties of the Article class except the primary key (click on the class property in LINQ2SQL designer and switch to Properties Tool Window) to Never (not sure about WhenChanged, maybe that works too - go ahead and experiment with it!).
This will force LINQ2SQL to use
```
```
UPDATE ... SET ... WHERE ID = @2
```
```
instead of the long version with all columns in the WHERE-clause:
```
```
UPDATE ... SET ... WHERE ID = @2 AND ItemsInStock = @1 AND SomeOtherColumn = @3 AND...
```
```
Now you can use code like
```
```
context.Articles.Attach(article /* article with updated values */, new Article { ID = articleID, ItemsInStock = -1 } /* pretend that this is the original article */);
context.SubmitChanges();
```
```
Basically you indicate that only ItemsInStock property has changed - other props should have the same default value, articleID of course being the same.
NOTE: you don't need to fetch the article prior to that.


q:
After update, old Eclipse plugins remain in "plugins" folder (there are also leftovers in "features" folder).

Is there a way to remove those automatically?

[A]
Eclipse allows you to revert back to any previous configuration (go to the Help menu, then "Software Updates"). My guess is that Eclipse won't remove these old versions, or this functionality would no longer work.
If when you restart Eclipse you provide the "-clean" argument, it performs various cleanup operations, but for reasons stated above I don't think it will remove old plugins/features.


q:
I'm comparing the results produced when i use the 'Make .exe' compared to when i run the exact same process using the exact same variables though the IDE vb 6 debugger.

I've tried an array of different compiler options but to no avail.

So my question is why would i get a difference between the debugger and the 'Make .exe'?
have you ever come arross something similar and if so did you find a fix?

the program takes a large file of counts of cars in a timeperiod and averages them into 15 minute timeperiods for the day over a month for each route.
It elminates certain records depending on if there outside the standard deviation and other statistical algorithms To eliminate values.
its a bit to much code to post unfortunately...

[A]
```
Debug.Assert
```
and
```
Debug.Print
```
Statement are not compiled into the binary. I sometimes use this to detect whether I am in the IDE or a compiled binary:
```
On Error Resume Next
Debug.Print 1/0
If Err=0 then
  'Compiled Binary
else
  'in the IDE
End if
```
Be careful with statements like this:
```
```
Debug.Assert( DoSomeThingImportend() )
```
```
In the compiled version this statement will not be executed.


q:
Suppose, objects of type A are stored in DB. Here's the way I load specific one from DB using hibernate:

org.hibernate.Session session = ...;
long id = 1;
A obj = session.load(A.class, id);

If object with id=1 doesn't exist I will get ObjectNotFoundException. But is there a way to check if such object exists without having to catch the exception? What I would like to have is smth like:

org.hibernate.Session session = ...;
long id = 1;
boolean exists = session.exists(A.class, id);
if(exists){
 // do smth.....
}

Couldn't find it hibernate docs...

[A]
You can use
```
session.get
```
:
```
```
public Object get(Class clazz,
                  Serializable id)
           throws HibernateException
```
```
It will return null if the object does not exist in the database. You can find more information in
Hibernate API Documentation
.


q:
The following Code does not compile

Dim BasicGroups As String() = New String() {"Node1", "Node2"}
Dim NodesToRemove = From Element In SchemaDoc.Root.<Group> _
                    Where Element.@Name not in BasicGroups
For Each XNode In NodesToRemove
    XNode.Remove()
Next

It is supposed to Remove any Immediate child of the rootnode which has an attribute called name whose value is Not listed in the BasicGroups StringArray.

What is the correct syntax for this task?

[A]
You probably want to move the 'not' part. Eg (psuedo code)
```
```
where (not (list.Contains(foo))
```
```


q:
I've seen this in a few places

function fn() {
    return +new Date;
}

And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing.

Can anyone explain?

[A]
JavaScript is loosely typed, so it performs type coercion/conversion in certain circumstances:
http://blog.jeremymartin.name/2008/03/understanding-loose-typing-in.html
http://www.jibbering.com/faq/faq_notes/type_convert.html
Other examples:
```
```
>>> +new Date()
1224589625406
>>> +"3"
3
>>> +true
1
>>> 3 == "3"
true
```
```


q:
Is there a way in SWT to get a monospaced font simply, that works across various operating systems?

For example. this works on Linux, but not Windows:

Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);

or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.

I tried getting the system font from Display, but that wasn't monospaced.

[A]
According to the section on
Font Configuration Files
in the JDK documentation of
Internationalization Support
-related APIs, the concept of
Logical Font
s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files:
The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways.
So in your case, I'd try
```
Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);
```
to get a handle to the physical monospaced font of the current platform your code is running on.
Edit
: It seems that SWT doesn't know anything about logical fonts (
Bug 48055
on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font...


q: I'd like them to be easy to bundle, with few dependencies and easy to use.


q:
I have some products that belongs to the some category.

Each category can have different properties.

For example,

category cars has properties color,
power, ...

category pets have properties  weight, age, ...

Number of categories is about 10-15.
Number of properties in each category is 3-15.
Number of products is very big.

Main requirement for this app is very good search. We will select category, and enter criteria for each property in this category.

Have to design database for this scenario. (SQL Server 2005)

[A]
If the user of the application
has
to select a category before they can search, I would separate your products into different database tables by category.  This solution is also indicated by the fact that the categories themselves have so little in common.  Breaking it down by category will also make each search much faster, since time won't be wasted searching through cars when your user is looking for a pet.
Once you have the products split up in to categories, it should be easy to create the tables using the common properties of the products in each category.  The user interface of your application should be dynamic (I'm thinking of a web form), in that the properties the user can choose from should change when the user selects a category.
Please note that if you have products that you want listed in multiple categories, this solution will result in duplicate data in your tables.  There is a trade-off between speed and normalization when designing a database.  If you
don't
have products that fit in multiple categories, then I think this will be the fastest solution (in terms of search speed).


q:
I am building an ObjectQuery like this:

        string query = "select value obj from Entities.Class as obj " +
                       "where obj.Property = @Value";

        ObjectQuery<Class> oQuery = new ObjectQuery<Class>(query, EntityContext.Instance);
        oQuery.Parameters.Add(new ObjectParameter("Value", someVariable));

I can now assign this object as a DataSource for a control, or iterate with a foreach loop or even force a materialization to a List, however, I can I count the number of objects that will be returned, without forcing a materialization?

Do I need to create a companion query that will execute a count() or is there a function that will do that for me somewhere?

Thank you.

[A]
```
ObjectQuery<T>
```
implements
```
IQueryable<T>
```
, so can't you simply use the extension method:
```
```
int count = oQuery.Count();
```
```
What happens if you execute this? I would have expected the overall query to just do a Count()... (not that I've done much EF...).


q:
I'm thinking about using BlogEngine.NET to launch my blog. I'm a C# programmer and was wondering was BlogEngine.NET has in the belly.

Does it scale well? Is it caching properly? Is it memory intensive? Can you easily add/remove functionality?

I also accept any hosting recommendation :)

[A]
I'm running BlogEngine.Net. I don't know about scaling because my weblog isn't that popular (yet). I'm very happy with it.
I tried subtext before and I had some stability problems with it, it logged exceptions that I found hard to debug. I got an error exporting the database to BlogML and it messed up the order of my blogposts. BlogEngine.Net seems a lot more stable.
I'm running on a virtualized server hosted by a friend of mine. I have seen no performance issues but that might be because of the massive 15 visitors per day peak load. I've have some trouble where Live Writer posts blog entries twice, but I suspect this is Live Writer's fault.
I really like the extension model and the way you can drag and drop extensions on the design of your blog. There aren't much themes that support this yet but I created my own look and feel by changing the standard theme in about three hours.


q:
For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated.  How would you design this?

What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)?  Will the data types be timezone-aware?

What data types would you use in Java (Date, Calendar, long, ...)?

Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?

What annotations would you use for the mapping (e.g. @Temporal)?

I'm not only looking for a working solution, but for a safe and well-designed solution.

[A]
A good approach is to have a common base class for all your entities. In this base class, you can have your id property if it is commonly named in all your entities (a common design), your creation and last update date properties.
For the creation date, you simply keep a
java.util.Date
property. Be sure, to always initialize it with
new Date()
.
For the last update field, you can use a Timestamp property, you need to map it with @Version. With this Annotation the property will get updated automatically by Hibernate. Beware that Hibernate will also apply optimistic locking (it's a good thing).


q:
I have a c++ application which logs to some file using log4cxx (RollingFile appender). I want to log into the same file, at the same time, from another module written in c#; so i configured log4net to use the same file, but i can't get the new messages in. If i deactivate the c++ logging, i can see c# messages. So i think it is a locking issue, and looked for a configuration option to tell log4cxx not to lock the file. I came into MinimalLock model for log4net, but couldn't find anything in log4cxx... does anybody know if it could be done, and how?

thanks in advance,

Ernesto Cullen

[A]
I think that you might run into concurrency and contention problems no matter what configuration you use as long as you are attempting to have two different processes log to the same file.
You should look into sending log events from both processes to a third, centralized location - take a look at
RemotingAppender
in log4net, I assume log4cxx has something similar.


q: Enterprise Architect has a way to generate the documentation in HTML/RTF/etc. that you could publish, but you have to use its GUI to do that manually. When you have your *.eap files in a CVS/Subversion server, it would be useful to have a script that would check out daily the latest version and publish it in a web server. As long as I know, EA doesn't have a command line utility for this purpose. I found that you can automate almost anything using its COM interface, but that means it's necessary to write a small program to do that. Any ideas about the easiest/cleanest way to do that (without having to write code, if possible)?


q:
I want to make a generic class that accepts only serializable classes, can it be done with the where constraint?

The concept I'm looking for is this:

public class MyClass<T> where T : //[is serializable/has the serializable attribute]

[A]
Nope, I'm afraid not. The only things you can do with constraints are:
```
where T : class
```
- T must be a reference type
```
where T : struct
```
- T must be a non-nullable value type
```
where T : SomeClass
```
- T must be SomeClass or derive from it
```
where T : ISomeInterface
```
- T must be ISomeInterface or implement it
```
where T : new()
```
- T must have a public parameterless constructor
Various combinations are feasible, but not all. Nothing about attributes.


q:
This might be a old question: Why does IEnumerable<T> inherit from IEnumerable?

This is how .NET do, but it brings a little trouble. Every time I write a class implements IEumerable<T>, I have to write two GetEnumerator() functions, one for IEnumerable<T> and the other for IEnumerable.

And, IList<T> doesn't inherit from IList.

I don't know why IEnumerable<T> is designed in other way.

[A]
The answer for
```
IEnumerable
```
is: "because it can without affecting type safety".
```
IEnumerable
```
is a "readonly" interface - so it doesn't matter that the generic form is more specific than the nongeneric form. You don't break anything by implementing both.
```
IEnumerator.Current
```
returns
```
object
```
, whereas
```
IEnumerator<T>.Current
```
returns
```
T
```
- that's okay, as you can always legitimately convert to
```
object
```
, although it may mean boxing.
Compare this with
```
IList<T>
```
and
```
IList
```
- you can call
```
Add(object)
```
on an
```
IList
```
, whereas that may well be invalid for any particular
```
IList<T>
```
(anything other than
```
IList<object>
```
in fact).
Brad Abram's
blogged with Anders' answer
about this very question.


q: I've been searching a lot but couldn't find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?

[A]
For normal DateTimes,  if you don't initialize them at all then they will match
```
DateTime.MinValue
```
, because it is a value type rather than a reference type.
You can also use a nullable DateTime, like this:
```
```
DateTime? MyNullableDate;
```
```
Or the longer form:
```
```
Nullable<DateTime> MyNullableDate;
```
```
And, finally, there's a built in way to reference the default of any type.  This returns
```
null
```
for reference types, but for our DateTime example it will return the same as
```
DateTime.MinValue
```
:
```
```
default(DateTime)
```
```
or, in more recent versions of C#,
```
```
default
```
```


q: I have a MySQL database of keywords that are presently mixed-case. However, I want to convert them all to lowercase. Is there an easy command to do this, either using MySQL or MySQL and PHP?

[A]
```
SELECT LOWER(foo) AS foo FROM bar
```


q:
I want to learn MSBuild, was wondering if someone could get me started with a simple build script to filter out my vs.net 2008 project of all files with the .cs extension.

how do I run the build?

where do you usually store the build also?

[A]
```
```
C:\projects\_Play\SimpleIpService>type \\sysrdswbld1\public\bin\mrb-vs2008.cmd
@echo off

call "c:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"

echo %0 %*
echo %0 %* >> %MrB-LOG%
cd
if not ""=="%~dp1" pushd %~dp1
cd
if exist %~nx1 (
        echo VS2008 build of '%~nx1'.
        echo VS2008 build of '%~nx1'. >> %MrB-LOG%
        set MrB-BUILDLOG=%MrB-BASE%\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log
        msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release > %MrB-BUILDLOG%
        findstr /r /c:"[1-9][0-9]* Error(s)" %MrB-BUILDLOG%
        if not errorlevel 1 (
                echo ERROR: sending notification email for build errors in '%~nx1'.
                echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-LOG%
                call mrb-email "Mr Build isn't happy about build errors in '%~nx1'" %MrB-BUILDLOG%
        ) else (
                findstr /r /c:"[1-9][0-9]* Warning(s)" %MrB-BUILDLOG%
                if not errorlevel 1 (
                        echo ERROR: sending notification email for build warnings in '%~nx1'.
                        echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-LOG%
                        call mrb-email "Mr Build isn't happy about build warnings in '%~nx1'" %MrB-BUILDLOG%
                ) else (
                        echo Successful build of '%~nx1'.
                        echo Successful build of '%~nx1'. >> %MrB-LOG%
                )
        )
) else (
        echo ERROR '%1' doesn't exist.
        echo ERROR '%1' doesn't exist. >> %MrB-LOG%
)
popd
```
```


q:
I'm familiar with Sybase / SQL server, where I can create a temp. table like this:

SELECT *
INTO   #temp
FROM   tab1 ,
       tab2
WHERE  tab1.key = tab2.fkey

SELECT *
FROM   #temp
WHERE  field1 = 'value'

#temp only exists for the duration of this session, and can only be seen by me.

I would like to do a similar thing in Oracle, but I'm reading about "global temporary tables", which don't sound like the same thing.

How can I do the same thing in Oracle as I'm doing in Sybase?

Thanks :)

[A]
I believe
global temporary
tables are the same. They will give you private access to a temporary table that dies when the session ends:
The data in a global temporary table is private, such that data inserted by a session can only be accessed by that session. The session-specific rows in a global temporary table can be preserved for the whole session, or just for the current transaction. The ON COMMIT DELETE ROWS clause indicates that the data should be deleted at the end of the transaction.
After reading the question a few more times I believe it the main difference, and maybe your issue is that the temporary tables persist between sessions. So the exact equivalent is not possible as you would imagine in Oracle it would be something like:
```
```
CREATE GLOBAL TEMPORARY TABLE my_temp_table ON COMMIT DELETE ROWS select * from other table;
```
```
That table will live until it is dropped even through sessions although the data in it does not. Instead you would need to create the temporary table in advance.


q:
Basically I'm converting local dates stored in the database into UTC. But I've read somewhere that daylight saving rules have changed in 2007. So does the Date.ToUniversalTime() function still work correctly. Basically the dates before 2007(when the new rules came into effect) would be converted correctly but the dates after that would be not. Am I right here? Or would .Net take care of the conversion internally i.e. depending upon the different daylight saving rules?

EDIT: Dates are stored in DB as local times. I am converting it into UTC. So a date such as '9 March 2005' should be converted using day light rules of 2005 instead of today's rules. The rules changed in the US in 2007. So the date is coming out wrong by one hour.

[A]
I would expect
```
ToUniversalTime()
```
to take that into account. Have you tried and checked the result with dates from before and after the DST change?
EDIT
If you
know
the timezone offset of all the dates in your DB, I definitively recommend you to convert them to UTC at the table level. You get rid of a whole lot of headaches that way. Converting to local time for display purposes is easier.


q:
I have two BufferedImages I loaded in from pngs. The first contains an image, the second an alpha mask for the image.

I want to create a combined image from the two, by applying the alpha mask. My google-fu fails me.

I know how to load/save the images, I just need the bit where I go from two BufferedImages to one BufferedImage with the right alpha channel.

[A]
Actually, I've figured it out. This is probably not a
fast
way of doing it, but it works:
```
```
for (int y = 0; y < image.getHeight(); y++) {
    for (int x = 0; x < image.getWidth(); x++) {
        Color c = new Color(image.getRGB(x, y));
        Color maskC = new Color(mask.getRGB(x, y));
        Color maskedColor = new Color(c.getRed(), c.getGreen(), c.getBlue(),
            maskC.getRed());
        resultImg.setRGB(x, y, maskedColor.getRGB());
    }
}
```
```


q: I have heard that this is what JavaRebel does but is there any other good way to deploy a new version of an EAR while allowing users to remain active on the previous version?  We use JBoss for the application server...

[A]
It's not what JavaRebel does. JavaRebel (according to description) hot-replaces the classes in memory. It's not acceptable in the case of existing connections to the system, since the updated classes may break the client's logic.
Once a company I was working for had a similar problem, and it was solved this way:
a smart router was used as a load-balancer
the new version was deployed to 50% of the nodes of the (new) cluster
new connections were delivered strictly to these updated nodes, old ones were balanced between old nodes
old nodes were took off-line (one-by-one, to keep number of clients per node within limits)
at the same time, new version was deployed to off-line "old" nodes and they were brought up as new nodes
due to EJB clustering, the sessions and beans were picked up by other old nodes
eventually (in a few hours), only one old node left, having a single instance of old version and all clients using old version were connected to it
when the last old client got disconnected, that node was too brought down
Now, I'm not a networking guy, and cannot give you many details (like what was the router hardware and such). My understanding this can be set up pretty easy, except, if I remember right, we had to setup an additional Weblogic domain to deploy new versions of the application (otherwise it would be conflicting with the old one on JNDI names).
Hope that helps.
P.S. Ichorus provided a comment saying that the app is deployed on clients' servers. So the router trick may be not feasible. Now, I see only one viable solution right now ( it's 21:52 now, I may overlook things :) ) --
Develop new version with "versioned" JNDI names; e.g. if Customer bean was under ejb/Customer in version 1, in version 2 it would be under ejb/Customer2
Have a business facade in the application with a stable basic interface (Factory-style) which, when asked for Customer bean, tries to find the highest-versioned JNDI name (not on every call, of course, can cache for a hour or so). That facade could (and should) be deployed as a separate application -- and never or very rarely updated
Now every new client would get access to the latest application deployed, and the applications won't conflict.
This approach takes a careful planning and testing, but should work IMHO.
I recently modified a few applications in a similar way to let them coexist in the same domain (before they used the same JNDI name for different data sources).


q:
Is there a way to write an enumeration that can be extended.  I have several methods that I would like to always have available for my enumerations.  For example I use an enumeration for my database fields.  I include the actual field name in the database.

public enum ORDERFIELDS
        {
            OrderID("Order_ID");
            private String FieldName;

            private ORDERFIELDS(String fname)
                {
                    this.FieldName = fname;
                }

            public String getFieldName()
                {
                    return FieldName;
                }
        }

[A]
All enums implicitly extend
```
java.lang.Enum
```
. Since Java does not support multiple inheritance, an enum cannot extend anything else.


q: Do the clients need something else than a proper jdk and javafx compliant browser to visit javafx applets?

[A]
GetAdaptersInfo() is the official method, it enumerates all adapters even ones that are disconnected.
See this post for example code
codeguru


q:
I am getting a warning when trying to include the .net 3.5 sp1 prerequisite for my setup project.  The warning states Prerequisite could not found for bootstrapping.

Any suggestions?

Thanks

[A]
I followed the directions in 2.3.1.1 Enable Samesite for the .NET Framework 3.5 SP1 bootstrapper package  and now everything works perfect.
Thanks


q:
What is the prefered method for creating a byte array from an input stream?

Here is my current solution with .NET 3.5.

Stream s;
byte[] b;

using (BinaryReader br = new BinaryReader(s))
{
    b = br.ReadBytes((int)s.Length);
}

Is it still a better idea to read and write chunks of the stream?

[A]
It really depends on whether or not you can trust
```
s.Length
```
. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:
```
```
public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}
```
```
With .NET 4 and above, I'd use
```
Stream.CopyTo
```
, which is basically equivalent to the loop in my code - create the
```
MemoryStream
```
, call
```
stream.CopyTo(ms)
```
and then return
```
ms.ToArray()
```
. Job done.
I should perhaps explain why my answer is longer than the others.
```
Stream.Read
```
doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon.
```
BinaryReader.Read
```
will keep going until the end of the stream or your specified size, but you still have to know the size to start with.
The above method will keep reading (and copying into a
```
MemoryStream
```
) until it runs out of data. It then asks the
```
MemoryStream
```
to return a copy of the data in an array. If you know the size to start with - or
think
you know the size, without being sure - you can construct the
```
MemoryStream
```
to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by
```
MemoryStream.GetBuffer
```
) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.
See
this article
for more info (and an alternative implementation).


q:
I want to provide silverlight app to my customer while hosting the app at my own site for streamlined maintenance.

my Silverlight .xap  is hosted in, let say,  domain me-supplier.com

i want to embed it in, let say, domain my-customer.com

It works perfectly for http://my-customer.com, not for https://my-customer.com

i have added the (me-supplier.com hosted) cross domain silverlight policy file to allow my-customer.com

i have configured the mime types for .xap

the silverlight app needs html dom access so the iframe approach is not viable i believe.

this works for javascript code, so why not for silverlight ? any idea, workaround ?

[A]
The short story is that it isn't
easily
accomplished. That code is added to the header by the menu during the prerender phase.
A possible workaround might be overriding the menu's onprerender in a custom menu control and don't call base. You could then replace the default menu control with your own using
tagMappings
.
I'd suggest you stay clear of the menu control if you can.


q:
Possible Duplicate:

  ASP.NET MVC Performance

I know there is a learning curve, but what about performance? It seems to me that web forms would be less performant, but I havent tried MVC yet to know for sure. What is everyone else experiencing?

[A]
This is almost a duplicate question. Here are some similar discussions:
ASP.NET MVC Performance
What are the key differences between ASP.NET webforms and MVC
Biggest advantage to using ASP.Net MVC vs web forms


q:
What tools are there that I can test out a WCF service?

I am expecting allot of load so I want to have an idea how much a single server can handle.

[A]
Start with this:
http://www.codeplex.com/WCFLoadTest
It doesn't do everything possible with WCF, but it is the best tool to start with. Worse comes to worse, it's not that hard to write manual invocation code with web services. They are much easier to load test than web sites.


q:
I am creating an application in java which will be the part of an external application. My application contains a viewport which shows some polygons and stuff like that. The external application needs to get the image of the viewport in gif format. For that it calls a method in an interface (implemented by my application) and my application returns the image. The external application needs to store the image in database (or something related to it which I dont need to worry about).

My question is:- What should be the data container type of the image when my application send it to the external application? I mean what should be the return type of the method?
Currently my gif encoder class returns a byte array. Is there any other 'better' option?

[A]
A byte array could be appropriate if you expect the GIFs to be small, but you might consider using an
```
OutputStream
```
so you can stream bits more efficiently.
Even if today you just return a fully-populated
```
ByteArrayOutputStream
```
, this would allow you to change your implementation in future without affecting cilent code.


q: Pretty much what the title says. Is there a way to add files to a vsnet project from inside Vim? I work in a group of devs, and all of our code has solutions and projects as you would expect. I would like to use Vim, and was hoping for a way to maintain those project files when I added or removed files without having to go into vsnet.

[A]
The project and solution files are in xml and are hand-edittable.  (I often have to during an SVN merge.)  However, HUGE DISCLAIMER AHOY, adding stuff from scratch is a lot more dubious than an svn merge.  I get to see the lines and just move them in (or not) here or there.  To be confident that you're not destroying the proj and sln files, you would have to experiment with visual studio a little bit to make sure what has to be added.
There are more IDEs than visual studio... perhaps there's some clues in their guts.


q:
When adding a reference to a project I sometimes see the message...

"The Target Framework version for the project is higher than the current project Target Framework version. Would you like to add this reference to your project anyway?"

I understand what the message is indicating but can anyone explain what issues might arise from saying 'Yes'?

[A] Suppose you build an application where the exe targets 2.0, but some library targets 3.5. Someone with a .NET 2.0 machine looks at the main project and thinks they can run it - after all, the application targets 2.0, right? When the library is first loaded, they'll get a nasty surprise...


q:
How to format numbers in JavaScript?

JavaScript culture sensitive currency formatting

[A]
The best you have with JavaScript is toFixed() and toPrecision() functions on your numbers.
```
```
var num = 10;
var result = num.toFixed(2); // result will equal 10.00

num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000

num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2
```
```
Currency, commas, and other formats will have to be either done by you or a third party library.


q:
Lots of frameworks let me expose an ejb as a webservice.

But then 2 months after publishing the initial service I need to change the ejb or any part of its interface. I still have clients that need to access the old interface, so I obviously need to have 2 webservices with different signatures.

Anyone have any suggestions on how I can do this, preferably letting the framework do the grunt work of creating wrappers and copying logic (unless there's an even smarter way).

I can choose webservice framework on basis of this, so suggestions are welcome.

Edit: I know my change is going to break compatibility,and I am fully aware that I will need two services with different namespaces at the same time. But how can I do it in a simple manner ?

[A]
I'm not an EBJ guy, but I can tell you how this is generally handled in the web service world. If you have a non-breaking change to the contract (for instance, adding a property that is optional), then you can simply update the contract and consumers should be fine.
If you have a breaking change to a contract, then the way to handle it is to create a new service with a new namespace for it's types. For instance, if your first service had a namespace of:
http://myservice.com/2006
Your new one might have:
http://myservice.com/2009
Expose this contract to new consumers.
How you handle the old contract is up to you. You might direct all the requests to an old server and let clients choose when to upgrade to the new servers. If you can use some amount of logic to upgrade the requests to the format that the new service expects, then you can rip out the old service's logic and replace it with calls to the new. Or, you might just deprecate it all together and fail all calls to the old service.
PS: This is much easier to handle if you create message class objects rather than reusing domain entities.


q:
the WPF Popup control is nice, but somewhat limited in my opinion. is there a way to "drag" a popup around when it is opened (like with the DragMove() method of windows)?

can this be done without big problems or do i have to write a substitute for the popup class myself?
thanks

[A]
There is no DragMove for PopUp. Just a small work around, there is lot of improvements you can add to this.
```
```
<Popup x:Name="pop" IsOpen="True" Height="200" Placement="AbsolutePoint"  Width="200">
   <Rectangle Stretch="Fill" Fill="Red"/>
</Popup>
```
```
In the code behind , add this mousemove event
```
```
pop.MouseMove += new MouseEventHandler(pop_MouseMove);

   void pop_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            pop.PlacementRectangle = new Rect(new Point(e.GetPosition(this).X,
                e.GetPosition(this).Y),new Point(200,200));

        }
    }
```
```


q:
I have a ControlTemplate that is made up of a ToolBarTray and a ToolBar.  In my ToolBar, I have several buttons and then a label.  I want to be able to update the label in my toolbar with something like "1 of 10"

My first thought is to programatically find the label and set it, but I'm reading that this should be done with Triggers.  I am having a hard time understanding how to accomplish this.  Any ideas?

   <Style x:Key="DocViewerToolBarStyle" TargetType="{x:Type ContentControl}">
   <Setter Property="Template">
     <Setter.Value>
           <ControlTemplate TargetType="{x:Type ContentControl}">
              <ToolBarTray... />
              <ToolBar.../>
              <Button../>
              <Button..>

             <Label x:Name="myStatusLabel"  .. />

[A]
I would set the label to the "Content" attribute of your control e.g.
```
```
<Label x:Name="myStatusLabel"  Content="{TemplateBinding Content}"/>
```
```
Then you can set your label's text with your top level object's Content attribute.


q:
this is my first question here so I hope I can articulate it well and hopefully it won't be too mind-numbingly easy.

I have the following class SubSim which extends Sim, which is extending MainSim. In a completely separate class (and library as well) I need to check if an object being passed through is a type of MainSim. So the following is done to check;

Type t = GetType(sim);
//in this case, sim = SubSim
if (t != null)
{
  return t.BaseType == typeof(MainSim);
}

Obviously t.BaseType is going to return Sim since Type.BaseType gets the type from which the current Type directly inherits.

Short of having to do t.BaseType.BaseType to get MainSub, is there any other way to get the proper type using .NET libraries? Or are there overrides that can be redefined to return the main class?

Thank you in advance

[A]
```
```
if (sim is MainSim)
```
```
is all you need. "is" looks up the inheritance tree.


q:
I got this error when trying to run a query in SQL server query analyzer.
What is the reason?

[A]
If you're using cursors, then you've probably closed the cursor. Check out MSDN for more information (
http://support.microsoft.com/kb/15169
3)
If you're not using cursors, then it could be an issue with the server, check the log.


q:
The fixnum question brought my mind to an other question I've wondered for a long time.

Many online material about garbage collection does not tell about how runtime type information can be implemented. Therefore I know lots about all sorts of garbage collectors, but not really about how I can implement them.

The fixnum solution is actually quite nice, it's very clear which value is a pointer and which isn't. What other commonly used solutions for storing type information there is?

Also, I wonder about fixnum -thing. Doesn't that mean that you are being limited to fixnums on every array index? Or is there some sort of workaround for getting full 64-bit integers?

[A]
Basically to achieve accurate marking you need meta-data indicating which words are used as pointers and which are not.
This meta-data could be stored per reference, as emacs does. If for your language/implementation you don't care much about memory use, you could even make references bigger than words (perhaps twice as big), so that every reference can carry type information as well as its one-word data. That way you could have a fixnum the full size of a 32 bit pointer, at the cost of references all being 64 bit.
Alternatively, the meta-data could be stored along with other type information. So for example a class could contain, as well as the usual function pointer table, one bit per word of the data layout indicating whether or not the word contains a reference that should be followed by the garbage collector. If your language has virtual calls then you must already have a means of working out from an object what function addresses to use, so the same mechanism will allow you to work out what marking data to use - typically you add an extra, secret pointer at the start of every single object, pointing to the class which constitutes its runtime type. Obviously with certain dynamic languages the type data pointed to would need to be copy-on-write, since it is modifiable.
The stack can do similar - store the accurate marking information in data sections of the code itself, and have the garbage collector examine the stored program counter, and/or link pointers on the stack, and/or other information placed on the stack by the code for the purpose, to determine which code each bit of stack relates to and hence which words are pointers. Lightweight exception mechanisms tend to do a similar thing to store information about where try/catch occurs in the code, and of course debuggers need to be able to interpret the stack too, so this can quite possibly be folded in with a bunch of other stuff you'd already be doing to implement any language, including ones with built-in garbage collection.
Note that garbage collection doesn't necessarily need accurate marking. You could treat every word as a pointer, regardless of whether it really is or not, look it up in your garbage collector's "big list of everything" to decide whether it plausibly could refer to an object that has not yet been marked, and if so treat it as a reference to that object. This is simple, but the cost of course is that it's somewhere between "quite slow" and "very slow", depending on what data structures your gc uses for the lookup. Furthermore, sometimes an integer just so happens to have the same value as the address of an unreferenced object, and causes you to keep a whole bunch of objects which should have been collected. So such a garbage collector cannot offer strong guarantees about unreferenced objects ever being collected. This might be fine for a toy implementation or first working version, but is unlikely to be popular with users.
A mixed approach might, say, do accurate marking of objects, but not of regions of the stack where things get particularly hairy. For example if you write a JIT which can create code where a referenced object address appears only in registers, not in your usual stack slots, then you might need to non-accurately follow the region of the stack where the OS stored the registers when it descheduled the thread in question to run the garbage collector. Which is probably quite fiddly, so a reasonable approach (potentially resulting in slower code) would be to require the JIT to always keep a copy of all pointer values it's using on the accurately marked stack.


q:
I have encapsulated a backup database command in a Try/Catch and it appears that the error message is being lost somewhere.  For example:

BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak'

..gives error:

Could not locate entry in sysdatabases for database 'NonExistantDB'. No entry found with that name. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally.

Whereas:

BEGIN TRY
    BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak'
END TRY
BEGIN CATCH
    PRINT ERROR_MESSAGE()
END CATCH

... only gives error:  BACKUP DATABASE is terminating abnormally.

Is there a way to get the full error message or is this a limitation of try/catch?

[A]
It's a limitation of try/catch.
If you look carefully at the error generated by executing
```
```
BACKUP DATABASE NonExistantDB TO DISK = 'C:\TEMP\NonExistantDB.bak'
```
```
you'll find that there are two errors that get thrown. The first is msg 911, which states
Could not locate entry in sysdatabases for database 'NonExistantDB'. No entry
  found with that name. Make sure that the name is entered correctly.
The second is the 3013 message that you are displaying. Basically, SQL is only returning the last error.


q:
I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output.

Pulling the class dynamically from the global namespace works:

result = globals()[classname](param).html

And it's certainly more succinct than:

if classname == 'Foo':
    result = Foo(param).html
elif classname == 'Bar':
    ...

What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?

[A]
First of all, it sounds like you may be reinventing the wheel a little bit... most Python web frameworks (CherryPy/TurboGears is what I know) already include a way to dispatch requests to specific classes based on the contents of the URL, or the user input.
There is nothing
wrong
with the way that you do it, really, but in my experience it tends to indicate some kind of "missing abstraction" in your program.  You're basically relying on the Python interpreter to store a list of the objects you might need, rather than storing it yourself.
So, as a first step, you might want to just make a dictionary of all the classes that you might want to call:
```
```
dispatch = {'Foo': Foo, 'Bar': Bar, 'Bizbaz': Bizbaz}
```
```
Initially, this won't make much of a difference.  But as your web app grows, you may find several advantages: (a) you won't run into namespace clashes, (b) using
```
globals()
```
you may have security issues where an attacker can, in essence, access any global symbol in your program if they can find a way to inject an arbitrary
```
classname
```
into your program, (c) if you ever want to have
```
classname
```
be something other than the actual exact classname, using your own dictionary will be more flexible, (d) you can replace the
```
dispatch
```
dictionary with a more-flexible user-defined class that does database access or something like that if you find the need.
The security issues are particularly salient for a web app.  Doing
```
globals()[variable]
```
where
```
variable
```
is input from a web form is just
asking for trouble
.


q: The default value for the first item in a drop down list is the name of the database field. I need to change it to a more user friendly name. How do I change the value?

[A]
add a HTML Item onto the prompt page and add the following as an HTML item:
Example:
```
<script>
```
```
document.formWarpRequest._oLstChoicesMyList[0].text = '--SELECT A CITY--';
```
```
</script>
```
Replace 'MyList' with the name of the component.
from:
link text


q:
As the title suggests, is it correct or valid to import/export static data from within a C++ class?

I found out my problem - the author of the class I was looking at was trying to export writable static data which isn't supported on this platform.

Many thanks for the responses however.

[A]
Is it correct inasmuch as it'll work and do what you expect it to? Assuming that you are talking about using _declspec(dllexport/dllimport) on a class or class member, yes, you can do that and it should give you the expected result - the static data would be accessible outside your dll and other C++ code could access it provided that that C++ access specification (public/protected/private) wouldn't block outside access in the first place.
Is it a good idea? Personally I don't think so as you would be exposing class internals not only within your library but to the outside world, which means that it will be pretty much impossible to change what is an implementation detail at the end of the day. Ask yourself if you are 100% certain if the interface of this class and large parts of its implementation will never, ever change...


q: How can I use command line arguments in a creationComplete event handler? It seems the invoke event happens in my AIR app after creationComplete gets called, so I can't use the args in that function, although I really would like to. Any other event that might always fire after the invoke event happens?

[A]
I don't think that will be possible. I just checked the sources and the invokes are set up in an enterframe handler AFTER the creationcomplete event has fired. You could perhaps subclass WindowedApplication and try to change that order, but there will probably be a good reason why it is implemented that way.
You can find the WindowedApplication.as file in [FLEX_DIR]\sdks\3.1.0\frameworks\projects\airframework\src\mx\core
Interesting comment on line 2942:
Because of the behavior with the nativeApplication invoke event
we queue events up until windowComplete