q:
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through db.TextProperty and db.BlobProperty.

I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done.

[A]
You can not store files as there is not a traditional file system.  You can only store them in their own DataStore (in a field defined as a
BlobProperty
)
There is an example in the previous link:
```
```
class MyModel(db.Model):
  blob = db.BlobProperty()

obj = MyModel()
obj.blob = db.Blob( file_contents )
```
```


q:
If I understand correctly, ClickOnce only checks for prerequisites with the first install of an application through the setup.exe file that contains the prerequisite information. If the user opens the app in the future it will check for new versions, but it does not launch the setup.exe again, thus not checking for any NEW prerequisites that might have been added.

Is there any way to force ClickOnce to check the prerequisites again or does anyone have a good solution without asking the user to run the setup.exe again?

[A]
Unfortunately, your users will have to re-run the setup.exe to check and install all the new prerequisites that you have added.
Applications deployed using ClickOnce only check for application updates (if enabled), not prerequisites as it's the bootstrapper's job to make sure all dependencies are installed before the application is installed.
I found this at
Microsoft's site
:
The Setup.exe (bootstrapper) is
  responsible for installing all
  dependencies before your application
  runs. This bootstrapper runs as a
  separate process that is independent
  of the ClickOnce run-time engine.

s: huggingface

c: devops

d: intermediate


q:
I am developing an ASP.NET mobile website using .NET 3.5 and mobile controls that come with the framework. I have a login form where the system will authenticate the user so he/she can access certain restricted pages.

In a standard ASP.NET website, I can use a session to store some flag after a user had logined, but I wonder can I do the same for the mobile version? Is session variable (or cookies) being support by those mobile device's browser? Is there any standard pratice also on doing authentication for mobile pages?

[A]
Session variables are stored in the server so you can forget the device browser capabilities.
I've not practice developing for mobile device, but 4 years ago I was using a service that used cookie authentication and the phone was not top-notch so... I think you can take for granted the cookie availability. Full futured browsers for mobile are taking on so... invest in the future, don't spend energy with old techologies soon to be deprecated...
In my opinion, prefer cookie authentication, it's more standard, and you can save the cookie on the phone preventing further authentications....


q:
I'm writing a J2SE desktop application that requires one of its components to be pluggable. I've already defined the Java interface for this plugin. The user should be able to select at runtime (via the GUI) which implementation of this interface they want to use (e.g. in an initialisation dialog). I envisage each plugin being packaged as a JAR file containing the implementing class plus any helper classes it may require.

What's the best technology for doing this type of thing in a desktop Java app?

[A]
One approach I'm considering is having my application start up a lightweight OSGi container, which if I understand correctly would be able to discover what plugin JAR files exist in a designated folder, which in turn would let me list them for the user to choose from. Is this feasible?
I also found
this article
by Richard Deadman, but it looks a little dated (2006?) and mentions neither OSGi (at least not by name) nor the
```
java.util.jar
```
package


q:
I need an encoder that can convert mp3 files to he-aac (aka aac+).
So far the best one I have found is nero aac encoder .
I have two problemes with it :
  - Only one input format : wav . It is a little bit slow to transform mp3 files to wav and then to he-aac.
  - a free license for non commercial use.

Too bad ffmpeg does not support he-aac ...
There is a commercial solution, on2 flix, but it seems to be a golden hammer for the simple task I need to do.

[A]
Nero AAC is the only one as far as I know.  Even if FAAC supported HE-AAC it would be useless, since as an encoder its pretty awfully designed and its quality is not even competitive with LAME, let alone a good AAC encoder.
Kostya on the FFMPEG team is currently working on an AAC encoder but it has a long way to go--its not ready for primetime with LC-AAC, let alone HE-AAC (its not even committed to the repository yet).  The first step before anything will be to get the ffmpeg decoder to support HE-AAC; currently it can only be decoded through FAAD.
I don't believe there is
any
HE-AAC encoder on any platform with a more permissive license than Nero's at this point in time.


q: I had a discussion with a developer earlier today re identifying TCP packets going out on a particular interface with the same payload. He told me that the probability of finding a TCP packet that has an equal payload (even if the same data is sent out several times) is very low due to the way TCP packets are constructed at system level. I was aware this may be the case due to the system's MTU settings (usually 1500 bytes) etc., but what sort of probability stats am I really looking at? Are there any specific protocols that would make it easier identifying matching payloads?

[A]
EDIT: Sorry, my original idea was ridiculous.
You got me interested so I googled a little bit and found
this
. If you wanted to write your own tool you would probably have to inspect each payload, the easiest way would probably be some sort of hash/checksum to check for identical payloads. Just make sure you are checking the payload, not the whole packet.
As for the statistics I will have to defer to someone with greater knowledge on the workings of TCP.


q:
I have settled a web synchronization between SQLSERVER 2005 as publisher and SQLEXPRESS as suscriber. Web synchro has to be launched manually through IE interface (menu tools/synchronize) and to be selected among available synchronizations.

Everything is working fine except that I did not find a way to automate the synchro, which I still have to launch manually. Any idea?

I have no idea if this synchro can be launched from SQLEXPRESS by running a specific T-SQL code (in this case my problem could be solved indirectly).

[A]
Maybe detach the process from the current shell process by calling
```
disown
```
?


q:
There doesn't seem to be a dictionary.AddRange() method. Does anyone know a better way to copy the items to another dictionary without using a foreach loop.

I'm using the System.Collections.Generic.Dictionary. This is for .NET 2.0.

[A]
There's the
```
Dictionary
```
constructor that takes another
```
Dictionary
```
.
You'll have to cast it
```
IDictionary
```
, but there is an
```
Add()
```
overload that takes
```
KeyValuePair<TKey, TValue>
```
. You're still using foreach, though.


q:
We have in the process of upgrading our application to full Unicode comptibility as we have recently got Delphi 2009 which provides this out of the box.  I am looking for anyone who has experience of upgrading an application to accept Unicode characters.  Specifically answers to any of the following questions.

We need to change VarChars to NVarchar, Char to NChar.  Are there any gotchas here.

We need to update all sql statements to include N in front of any sql strings.  So Update tbl_Customer set Name = 'Smith' must become Update tbl_Customer set Name = N'Smith' .  Is there any way to default to this for certain Fields.  It seems extraordinary this is still required.

Is it possible to get any defaults set up in SQLServer that will make this simpler?

ps We also need to upgrade our Oracle code

[A]
Damien
I'm not sure how useful your answer is.  We have a large 700,000 lines of compiled codebase that was written over the last ten years which contains a large number of sql queries.  Most are standardised down to a few functions which are the basis for most of the updates on the database.  These can be updated quite simply.   However we also need to check every where clause for CustomerName = '%s'  which should now be CustomerName = N'%s'
This is a real question which needs a real answer.


q: If my email id receives an email from a particular sender, can I ask sendmail to trigger a different program and pass on the newly arrived email to it for further processing? This is similar to filters in gmail. Wait for some email to arrive, see if it matches the criteria and take some action if it does.

[A]
We handle this by having a cron process running on the mail server which watches the inbox directory and scans any new messages (files) every 10 minutes or so.
When the process finds an email of interest, it fires the information off to another process which then reacts to the new message (and, in our case, removes the message from the inbox).
--edit--
Finding the email inbox depends on your implementation - check the 'manual' your version of sendmail for details - we direct incoming email to a special directory or have parameters to work out the inbox details. I don't feel it would be useful to be more specific as the answer to 'where is the inbox' is 'it depends'.
As for the pattern to search for - we decode the email message (a text file) into a DOM that we can manipulate. For example, we can then look for specific words in property 'subject'.


q:
I am using Qt Dialogs in one of my application.
I need to hide/delete the help button. But i am not able to locate where exactly I get the handle to his help button. Not sure if its a particular flag on the Qt window.

[A]
By default the
Qt::WindowContextHelpButtonHint
flag is added to dialogs.
You can control this with the
WindowFlags
parameter to the dialog constructor.
For instance you can specify only the
TitleHint
and
SystemMenu
flags by doing:
```
```
QDialog *d = new QDialog(0, Qt::WindowSystemMenuHint | Qt::WindowTitleHint);
d->exec();
```
```
If you add the
Qt::WindowContextHelpButtonHint
flag you will get the help button back.
In PyQt you can do:
```
```
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])
d = QtGui.QDialog(None, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint)
d.exec_()
```
```
More details on window flags can be found on the
WindowType enum
in the Qt documentation.


q:
I want:
all links which not contained filename (not .html, .jpg, .png, .css) redirect with state 301 to directory, for example: http://mysite.com/article -> http://mysite.com/article/
But http://mysite.com/article/article-15.html not redirects.
What regulat expression I must write to .htaccess for adding slash to virtual directories?

[A]
Clarification needed:
Given the url:
http://server/path/file
Does that get redirected to:
http://server/path/
Or does it get redirected to:
http://server/path/file/
As in: Do you want the redirects to go to the parent path, or do you just want to add a slash and assume directory out of the current path?


q:
What is the most efficient, secure way to pipe the contents of a postgresSQL database into a compressed tarfile, then copy to another machine?

This would be used for localhosting development, or backing up to a remote server, using *nix based machines at both ends.

[A]
This page
has a complete backup script for a webserver, including the pg_dump output.
Here is the syntax it uses:
```
```
BACKUP="/backup/$NOW"
PFILE="$(hostname).$(date +'%T').pg.sql.gz"
PGSQLUSER="vivek"
PGDUMP="/usr/bin/pg_dump"

$PGDUMP -x -D -U${PGSQLUSER} | $GZIP -c > ${BACKUP}/${PFILE}
```
```
After you have gzipped it, you can transfer it to the other server with
scp
,
rsync
or
nfs
depending on your network and services.


q:
We have a NET app that gets installed to the Program Files folder.
The app itself writes some files and creates some directories to its app folder.
But when a normal windows user tries to use our application it crashes because that user does not have permission to write to app folder.
Is there any folder in both WinXP and WinVista to which all users have writing permissions by default? All User folder or something like that?

[A]
I'm not sure that there is a single path to which all non-administrator users have permission to write to.
I think the correct one would be
```
<User>\Application Data
```


q:
I am trying to use MinGW to compile a C program under Windows XP. The gcc.exe gives the following error:

stdio.h : No such file or directory

The code (hello.c) looks like this:

#include < stdio.h >

void main()
{
    printf("\nHello World\n");
}

I use a batch file to call gcc. The batch file looks like this:

@echo off
set OLDPATH=%PATH%
set path=C:\devtools\MinGW\bin;%PATH%
set LIBRARY_PATH=C:\devtools\MinGW\lib
set C_INCLUDE_PATH=C:\devtools\MinGW\include

gcc.exe hello.c

set path=%OLDPATH%

I have tried the option -I without effect. What do I do wrong?

[A]
Try changing the first line to:
```
```
#include <stdio.h>
```
```
without the spaces. It is trying to look for a file called " stdio.h " with a space at the beginning and end.


q:
For example:

int a = 12;
cout << typeof(a) << endl;

Expected output:

int

[A]
Try:
```
```
#include <typeinfo>

// …
std::cout << typeid(a).name() << '\n';
```
```
You might have to activate RTTI in your compiler options for this to work. Additionally, the output of this depends on the compiler. It might be a raw type name or a name mangling symbol or anything in between.


q: Just want to know what is better way to get start developing faccebook app?Any tutorial recommnedation?And which is better to start up -php or rails?

[A]
Start with their docs:
http://developer.facebook.com/get_started.php?tab=tutorial
There are libraries floating around for lots of different languages and frameworks so I say: whatever you're happiest with is where you should start.


q:
I have a script that works fine on my test server (using IIS6). The script processes an ajax request and sends a response with the following line:

header( 'application/javascript' );

But on my live server, this line crashes the page and causes a 500 error.

Do I need to allow PHP to send different MIME types in IIS7? If so, how do I do this? I can't find any way on the interface.

[A]
The header is incorrect, try this instead:
```
```
header('Content-Type: application/javascript');
```
```


q:
I use Virtual PC to create fresh environments for testing my installer. But I must be doing something wrong because a VPC image with Vista or XP inside is taking around 15GB of disk space (that includes VS2005/S2008 installed in them).

To create a new copy for testing I copy and paste the folder that has the .vhd, .vmc and .vsv files inside. After using the new VPC image for testing I then delete that copied folder. This works but it takes a looong time to copy 15GB each time. Is there some faster/more efficent approach?

[A]
Doesn't VirtualPC have a fake-write/snapshot mode? That way it should not write to your original disk at all unless you say so at the end of the session.
If it doesn't, you might seriously want to consider VMWare or VirtualBox as these do have this feature and it's REALLY useful for things like this.
Edit: it looks like VPC does have a feature like this called differencing disks. Have a look at this:
http://www.andrewconnell.com/blog/articles/UseVirtualPCsDifferencingDisksToYourAdvantage.aspx


q: Is there a way to hide the google toolbar in my browser programmable?

[A]
You haven't said which browser you are using so I'm going to assume Internet Explorer* and answer No.
If JavaScript on a web page could manipulate the browser, it would be a serious security hole and could create a lot of confusion for users.
So no... for a good reason: Security.
*. If you were using Firefox, and were talking about JavaScript within an extension to manipulate and theme the window chrome then this would be a different story.


q:
I have xml where some of the element values are unicode characters. Is it possible to represent this in an ANSI encoding?

E.g.

<?xml version="1.0" encoding="utf-8"?>
<xml>
<value>受</value>
</xml>

to

<?xml version="1.0" encoding="Windows-1252"?>
<xml>
<value>&#27544;</value>
</xml>

I deserialize the XML and then attempt to serialize it using XmlTextWriter specifying the Default encoding (Default is Windows-1252). All the unicode characters end up as question marks. I'm using VS 2008,  C# 3.5

[A]
If I understand the question, then yes. You just need a
```
;
```
after the
```
27544
```
:
```
```
<?xml version="1.0" encoding="Windows-1252"?>
<xml>
<value>殘</value>
</xml>
```
```
Or are you wondering how to generate this XML programmatically? If so, what language/environment are you working in?


q:
Given the following JSON Date representation:

"\/Date(1221644506800-0700)\/"

How do you deserialize this into it's JavaScript Date-type form?

I've tried using MS AJAX JavaScrioptSerializer as shown below:

Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/")

However, all I get back is the literal string date.

[A]
The big number is the standard JS time
```
```
new Date(1221644506800)
```
```
Wed Sep 17 2008 19:41:46 GMT+1000 (EST)


q:
I have a version number of the following form:

version.release.modification

where version, release and modification are either a set of digits or the '*' wildcard character. Additionally, any of these numbers (and any preceding .) may be missing.

So the following are valid and parse as:

1.23.456 = version 1, release 23, modification 456
1.23     = version 1, release 23, any modification
1.23.*   = version 1, release 23, any modification
1.*      = version 1, any release, any modification
1        = version 1, any release, any modification
*        = any version, any release, any modification

But these are not valid:

*.12
*123.1
12*
12.*.34

Can anyone provide me a not-too-complex regex to validate and retrieve the release, version and modification numbers?

[A]
This might work:
```
```
^(\*|\d+(\.\d+){0,2}(\.\*)?)$
```
```
At the top level, "*" is a special case of a valid version number. Otherwise, it starts with a number. Then there are zero, one, or two ".nn" sequences, followed by an optional ".*". This regex would accept 1.2.3.* which may or may not be permitted in your application.
The code for retrieving the matched sequences, especially the
```
(\.\d+){0,2}
```
part, will depend on your particular regex library.


q:
In a digital signal acquisition system, often data is pushed into an observer in the system by one thread.

example from Wikipedia/Observer_pattern:

foreach (IObserver observer in observers)
    observer.Update(message);

When e.g. a user action from e.g. a GUI-thread requires the data to stop flowing, you want to break the subject-observer connection, and even dispose of the observer alltogether.

One may argue: you should just stop the data source, and wait for a sentinel value to dispose of the connection.  But that would incur more latency in the system.

Of course, if the data pumping thread has just asked for the address of the observer, it might find it's sending a message to a destroyed object.

Has someone created an 'official' Design Pattern countering this situation?  Shouldn't they?

[A]
You could send a message to all observers informing them the data source is terminating and let the observers remove themselves from the list.
In response to the comment, the implementation of the subject-observer pattern should allow for dynamic addition / removal of observers. In C#, the event system is a subject/observer pattern where observers are added using
```
event += observer
```
and removed using
```
event -= observer
```
.


q: I know it's possible to place a PyCairo surface inside a Gtk Drawing Area. But I think Qt is a lot better to work with, so I've been wondering if there's anyway to place a PyCairo surface inside some Qt component?

[A]
Qt's own OpenGL based surfaces (using QPainter) are known to be much faster than Cairo. Might you explain why you want specifically Cairo in Qt?
For the basics of using QPainter see
this excerpt
from the book "C++ GUI Programming with Qt4", and while it's C++ code, the PyQt implementation will be parallel.
As for joining Cairo with Qt...
This article in ArsTechnica
sheds some light - it seems nothing that could help you exists currently (iow., nobody tried such marriage).


q:
I've got a webapp whose original code base was developed with a hand crafted hibernate mapping file.  Since then, I've become fairly proficient at 'coding' my hbm.xml file.  But all the cool kids are using annotations these days.

So, the question is: Is it worth the effort to refactor my code to use hibernate annotations?  Will I gain anything, other than being hip and modern?  Will I lose any of the control I have in my existing hand coded mapping file?

A sub-question is, how much effort will it be?  I like my databases lean and mean.  The mapping covers only a dozen domain objects, including two sets, some subclassing, and about 8 tables.

Thanks, dear SOpedians, in advance for your informed opinions.

[A]
One thing you'll gain from using annotations instead of an external mapping file is that your mapping information will be on classes and fields which improves maintainability. You add a field, you immediately add the annotation. You remove one, you also remove the annotation. you rename a class or a field, the annotation is right there and you can rename the table or column as well. you make changes in class inheritance, it's taken into account. You don't have to go and edit an external file some time later. this makes the whole thing more efficient and less error prone.
On the other side, you'll lose the global view your mapping file used to give you.


q:
Problem:

html file on local server (inside our organization) with link to an exe on the same server.

clicking the link runs the exe on the client. Instead I want it to offer downloading it.

Tried so far:

Changed permissions on the exe's virtual directory to be read and script.

Added Content-disposition header on the exe's directory.

I can't change settings in the browser. It's intended for a lot of people to consume.

[A]
You need to set
```
content-disposition
```
in the HTTP header.
This Microsoft Knowledge Base entry
has more detail on how to do this.


q:
I want to place a Webpart on a page that holds a subfolder of the Document Library in SharePoint, but somehow, the only thing I get is the root folder of the document library.

Is there a Webpart that fills this need?

[A]
By default I don't think that is possible.
The list web part that would show the Shared Documents understands how to render the library, but doesn't understand how to filter to only show the contents of one subfolder.
It would be nice to create a Filter Web Part and to provide that filter to the List web part so that it filters according to the sub folder defined within the fileref field of the document library. However the filters it appears to be able to consume are Type, Modified and Modified By. So you could filter it to just the documents you touched, but not the ones in a given location.
End result: Roll your own web part.


q:
I am using C# to process a message in my Outlook inbox that contains attachments.  One of the attachments is of type olEmbeddeditem.  I need to be able to process the contents of that attachment.  From what I can tell I need to save the attachment to disk and use CreateItemFromTemplate which would return an object.

The issue I have is that an olEmbeddeditem can be any of the Outlook object types MailItem, ContactItem, MeetingItem, etc.  How do you know which object type a particular olEmbeddeditem attachment is going to be so that you know the object that will be returned by CreateItemFromTemplate?

Alternatively, if there is a better way to get olEmbeddeditem attachment contents into an object for processing I'd be open to that too.

[A]
I found the following code on Google Groups for determining the type of an Outlook object:
```
```
Type t = SomeOutlookObject.GetType();
string messageClass = t.InvokeMember("MessageClass",
  BindingFlags.Public |
  BindingFlags.GetField |
  BindingFlags.GetProperty,
  null,
  SomeOutlookObject,
  new object[]{}).ToString();
Console.WriteLine("\tType: " + messageClass);
```
```
I don't know if that helps with an olEmbedded item, but it seems to identify regular messages, calendar items, etc.


q:
Given the problem that a stored procedure on SQL Server 2005, which is looping through a cursor, must be run once an hour and it takes about 5 minutes to run, but it takes up a large chunk of processor time:

edit: I'd remove the cursor if I could, unfortunatly, I have to be doing a bunch of processing and running other stored procs/queries based on the row.

Can I use
   WAITFOR DELAY '0:0:0.1'
before each fetch to act as SQL's version of .Net's Thread.Sleep? Thus allowing the other processes to complete faster at the cost of this procedure's execution time.

Or is there another solution I'm not seeing?

Thanks

[A]
I'm not sure if that would solve the problem.  IMHO the performance problem with cursors is around the amount of memory you use to keep the dataset resident and loop through it, if you then add a waitfor inside the loop you're hogging resources for longer.
But I may be wrong here, what I would suggest is to use perfmon to check the server's performance under both conditions, and then make a decision whether it is worth-it or not to add the wait.
Looking at the tag, I'm assuming you're using MS SQL Server, and not any of the other flavours.


q:
If I have a table in my database called 'Users', there will be a class generated by LINQtoSQL called 'User' with an already declared empty constructor.

What is the best practice if I want to override this constructor and add my own logic to it?

[A]
It doesn't look like you can override the empty constructor. Instead, I would create a method that performs the functionality that you need in the empty constructor and returns the new object.
```
```
// Add new partial class to extend functionality
public partial class User {

  // Add additional constructor
  public User(int id) {
    ID = id;
  }

  // Add static method to initialize new object
  public User GetNewUser() {
    // functionality
    User user = new User();
    user.Name = "NewName";
    return user;
  }
}
```
```
Then elsewhere in your code, instead of using the default empty constructor, do one of the following:
```
```
User user1 = new User(1);
User user2 = User.GetNewUser();
```
```


q:
Why is the following C# code not allowed:

public abstract class BaseClass
{
    public abstract int Bar { get;}
}

public class ConcreteClass : BaseClass
{
    public override int Bar
    {
        get { return 0; }
        set {}
    }
}

CS0546 'ConcreteClass.Bar.set': cannot override because 'BaseClass.Bar' does not have an overridable set accessor

[A]
Because at the IL level, a read/write property translates into two (getter and setter) methods.
When overriding, you have to keep supporting the underlying interface. If you could add a setter, you would effectively be adding a new method, which would remain invisible to the outside world, as far as your classes' interface was concerned.
True, adding a new method would not be breaking compatibility per se, but since it would remain hidden, decision to disallow this makes perfect sense.


q:
How can I figure out the state of the files in my client, I want to know if the file needs an updated, or patched, or modified etc. In CVS, I used to simply run "cvs -n -q update . > file". Later look for M,U,P,C attributes to get the current status of the file.

In perforce, "p4 sync -n" doesn't give output like "cvs -n -q update". How can I see the current status of files, in case of Perforce?

[A]
Not quite sure what you mean.  If you are talking about seeing what files need "resolving" (in perforce language) then you can use:
```
```
p4 resolve -n
```
```
See the p4 command line manual website here:
http://www.perforce.com/perforce/doc.current/manuals/cmdref/resolve.html#1040665
Also P4V has a nice feature to highlight unsubmitted and dirty files, if you use that client.  Right-click on a fodler in the workspace view, and select "reconcile offline work."  After a bit of processing you'll get a list of files that are out of sync with the depot.
Hope this helps.


q:
I was checking out Intel's "whatif" site and their Transactional Memory compiler (each thread has to make atomic commits or rollback the system's memory, like a Database would).

It seems like a promising way to replace locks and mutexes but I can't find many testimonials. Does anyone here have any input?

[A]
In some cases I can see this as being useful and even necessary.
However, even if the processor has special instructions that make this process easier there is still a large overhead compared to a mutex or semaphore.  Depending on how it's implemented it may also impact realtime performance (have to either stop interrupts, or prevent them from writing into your shared areas).
My expectation is that if this was implemented, it would only be needed for portions of a given memory space, though, and so the impact could be limited.
-Adam


q:
I find the concept of the programmable, tiling, keyboard-focuessed window manager ion3 very appealing, but I think it takes some time to customize it to your needs until you can really evaluate this totally different UI-concept.

Therefore, I would like to read reviews of people who tried it for a longer time as environment for programming (in particular using emacs/gcc).

(The policies of the ion3-author concerning linux-distros are not easy to follow for me, but this should not be the point here...)

[A]
I've used it off and on for the last few years, I think its a great window manager, but I keep crawling back to kde3 whatever I use.
Its however difficult to put into quantifiable terms why this happens, but its right up there with the gnome-vs-kde battle. Neither side can understand the other.
I would also just love to have kicker + ion3, but they don't gel awfully well.
Moving applications between tiles ( something I tend to do lots ) also is a bit inefficient ( too addicted to the mouse )
( Kicker + Evilwm is a good combination, but evilwm just can't handle stacking in a user-friendly way )


q:
I have a template class that I serialize (call it C), for which I want to specify a version for boost serialization. As BOOST_CLASS_VERSION does not work for template classes. I tried this:

namespace boost {
namespace serialization {
    template< typename T, typename U >
    struct version< C<T,U> >
    {
        typedef mpl::int_<1> type;
        typedef mpl::integral_c_tag tag;
        BOOST_STATIC_CONSTANT(unsigned int, value = version::type::value);
    };
}
}

but it does not compile. Under VC8, a subsequent call to BOOST_CLASS_VERSION gives this error:

error C2913: explicit specialization; 'boost::serialization::version' is not a specialization of a class template

What is the correct way to do it?

[A]
```
```
#include <boost/serialization/version.hpp>
```
```
:-)


q:
How can I figure out, how many files needs to be recompiled before I start the build process.

Sometimes I don't remember how many basic header files I changed so a Rebuild All would be better than a simple build. There seams to be no option for this, but IMHO it must be possible (f.e. XCode give me this information).

Update:

My problem is not, that Visual Studio doesn't know what to compile. I need to know how much it will compile so that I can decide if I can make a quick test with my new code or if I should write more code till I start the "expensive" build process. Or if my boss ask "When can I have the new build?" the best answer is not "It is done when it is done!".

It's really helpful when the IDE can say "compile 200 of 589 files" instead of "compile x,y, ..."

[A]
If you try this, what happens?
```
```
print myresolver.query('sources.org', 'ANY', 'RRSIG')
```
```


q:
This answer says that Linq is targeted at a slightly different group of developers than NHibernate, Castle, etc.

Being rather new to C#, nevermind all the DB stuff surrounding it:

Are there other major, for lack of a better term, SQL wrappers than NHibernate, Castle, Linq?

What are the differences between them?

What kind of developers or development are they aimed at?

-Adam

[A]
When you say Castle I assume you mean Castle Active Record?
The difference is NHibernate is an OR/M and is aimed at developers who want to focus on the domain rather than the database. With linq to sql, your database is pre-existing and you're relationships and some of programming will be driven by how your database is defined.
Now between NHibernate and Castle ActiveRecord -- they are similar in that you're driving your application design from the domain but with NHibernate you provide mapping xml files (or mapping classes with fluent NHibernate) where in Active Record you are using the convention over configuration (using attributes to define any columns and settings that don't fit naturally). Castle Active record is still using NHibernate in the background.
One OR/M is not necessarily the 'one true way' to go. It depends on your environment, the application your developing and your team.
You may also want to check out
SubSonic
. It's great for active record but it is not for project where you want to focus mainly on your Domain. Depending on the project, I usually use either NHibernate (with Castle Active Record) or Subsonic


q: Is it possible to use Microsoft Entity Framework with Oracle database?

[A]
DevArt's OraDirect provider now supports entity framework. See
http://devart.com/news/2008/directs475.html


q:
By default tomcat will create a session cookie for the current domain.

If you are on www.example.com, your cookie will be created for www.example.com (will only work on www.example.com). Whereas for example.com it will be created for .example.com (desired behaviour, will work on any subdomain of example.com as well as example.com itself).

I've seen a few Tomcat valves which seem to intercept the creation of session cookies and create a replacement cookie with the correct .example.com domain, however none of them seem to work flawlessly and they all appear to leave the existing cookie and just create a new one. This means that two JSESSIONID cookies are being sent with each request.

I was wondering if anybody has a definitive solution to this problem.

[A]
I've run into this at $DAYJOB. In my case I wanted to implement SSL signon then redirect to a non SSL page. The core problem in tomcat is the method (from memory) SessionManager.configureSessionCookie which hard codes all the variables you would like to get access to.
I came up with a few ideas, including a particularly egregious hack using mod_headers in apache to rewrite the cookie based on regex substitution.
The definative way to solve this would be to submit a patch to the tomcat developers that adds configurable parameters to the SessionManager class.


q: I have seen examples of printing from a windows application but I have not been able to find a good example of any way of doing this.

[A]
If you just need to print your web page from the client-side use
```
window.print()
```
. Sample could be found here:
http://www.javascriptkit.com/howto/newtech2.shtml
. I would suggest preparing a special version of your page first with no dynamic content and with a layout which would look nice on print.
If you need to send something to printer on the server-side that would be a
little bit
more complicated. Check out this
MSDN
article on how to do the basic printing.


q:
If I open files I created in Windows, the lines all end with ^M.

How do I delete these characters all at once?

[A]
```
```
:%s/\r\+//g
```
```
In Vim, that strips all carriage returns, and leaves only newlines.


q: How do I check whether a file exists or not, without using the try statement?

[A]
```
```
import os

if os.path.isfile(filepath):
   print("File exists")
```
```


q:
If I am in a function in the code behind, and I want to implement displaying a "Loading..." in the status bar the following makes sense, but as we know from WinForms is a NoNo:

StatusBarMessageText.Text = "Loading Configuration Settings...";
LoadSettingsGridData();
StatusBarMessageText.Text = "Done";

What we all now from WinForms Chapter 1 class 101, is the form won't display changes to the user until after the Entire Function completes... meaning the "Loading" message will never be displayed to the user.  The following code is needed.

Form1.SuspendLayout();
StatusBarMessageText.Text = "Loading Configuration Settings...";
Form1.ResumeLayout();

LoadSettingsGridData();

Form1.SuspendLayout();
StatusBarMessageText.Text = "Done";
Form1.ResumeLayout();

What is the best practice for dealing with this fundamental issue in WPF?

[A]
The easiest way to get this to work is to add the LoadSettingsGridData to the dispatcher queue.  If you set the operation's DispatcherPriority sufficiently low enough, the layout operations will occur, and you will be good to go.
```
```
StatusBarMessageText.Text = "Loading Configuration Settings...";
this.Dispatcher.BeginInvoke(new Action(LoadSettingsGridData), DispatcherPriority.Render);
this.Dispatcher.BeginInvoke(new Action(() => StatusBarMessageText.Text = "Done"), DispatcherPriority.Render);
```
```


q:
What files can we modify so that our solution is still supported by Microsoft?

Is it allowed to customize error pages?
Can we modify the web.config files to use custom HTTPHandlers?

[A]
You can certainly edit the web.config file for your sites.  The one thing that you should be aware of, however, is that when you start editing files manually on the file system, you will have to remember to manually make those changes across all servers in the farm (assuming a farm exists).  In addition to this, when you edit files in the 12 hive, it's important to understand that you will be making a change to all SharePoint sites hosted on the server(s) for which the files were edited.
Personally, if I were going to create a custom error page, I would simply add a <customErrors> section to my web.config.  I avoid
editing
any
existing
files in the 12 hive, but I have
added
files (though it's rare).


q:
I am curious about how many of you folks incorporate mocking of objects (frameworks like JMock, NMock, RhinoMocks hand in hand with unit testing frameworks) into your daily development process. What are your experiences?

You see, I develop on top of a GIS (geographic information systems) platform, in which most of work pertains to some way of handling data. As its data object model is quite complex (many many classes and interfaces, all COM-based), it is also quite difficult and cumbersome to mock. In this case, mocking incurs a great deal of overhead when writing test suites. I wonder if there are people in similar situation, or just, how does mocking (in whatever situation you are in) work for you.

[A]
In my situation mocks work
really nice.
But I'm using Python, which is so dynamic that it makes many things involving testing much, much easier.
In situation like yours, when application is mainly
data-driven
(as far as I see), mocks may not be as useful. Just passing data in and watching it come out should be enough for testing. I would just make sure that application is
modularized enough
, so this approach can be applied to reasonably small components.


q: What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the ATTACH command on the SQLite 3 command line tool?

[A]
It appears you need to go through the
sqlite_master
table, like this:
```
```
SELECT * FROM dbname.sqlite_master WHERE type='table';
```
```
And then manually go through each table with a
```
SELECT
```
or similar to look at the rows.
The
```
.DUMP
```
and
```
.SCHEMA
```
commands doesn't appear to see the database at all.


q: Visual studio is pretty good but doesn't create stored procedures automatically.  Iron Speed designer does supposedly.  But is it any good?

[A]
I have used it for convenience for a very small project. It did what I wanted and saved me a couple of days work.
The main problem I found was when it came to customising or extending the generated project. You have to spend quite a bit of time trying to understand Ironspeed's way of doing things which, I'll admit, is not my way.
I'd use it again for a small project if I knew in advance I wouldn't have to customise it much after.


q:
I have a PHP application that displays a list of options to a user.  The list is generated from a simple query against SQL 2000.  What I would like to do is have a specific option at the top of the list, and then have the remaining options sorted alphabetically.

For example, here's the options if sorted alphabetically:

Calgary
Edmonton
Halifax
Montreal
Toronto

What I would like the list to be is more like this:

**Montreal**
Calgary
Edmonton
Halifax
Toronto

Is there a way that I can do this using a single query?  Or am I stuck running the query twice and appending the results?

[A]
```
```
SELECT name FROM options ORDER BY name = "Montreal", name;
```
```
Note: This works with MySQL, not SQL 2000 like the OP requested.


q:
Have you used pipes.yahoo.com to quickly and easily do... anything? I've recently created a quick mashup of StackOverflow tags (via rss) so that I can browse through new questions in fields I like to follow.

This has been around for some time, but I've just recently revisited it and I'm completely impressed with it's ease of use. It's almost to the point where I could set up a pipe and then give a client privileges to go in and edit feed sources... and I didn't have to write more than a few lines of code.

So, what other practical uses can you think of for pipes?

[A]
It's nice for aggregating feeds, yes, but the other handy thing to do is filtering the feeds. A while back, I created a feed for Digg (before Digg fell into the Fark pit of dispair). I didn't care about the overwhelming Apple and Ubuntu news, so I filtered those keywords out of Technology, which I then combined with Science and World & Business feeds.
Anyway, you can do a lot more than just combine things. If you wanted to be smart about it,  you could set up per-subfeed and whole-feed filters to give granular or over-arching filtering abilities as the news changes and you get bored with one topic or another.


q: I have a rails application which is still showing the cachebusting numeric string at the end of the URL for static mode, even though I have put it into the production environment. Can someone tell me what config option I need to set to prevent this behaviour...

[A]
That file isn't there to break the cache during day-to-day operations. At least in theory, proxy servers are allowed to cache HTTP GET requests (as long the parameters remain the same).
Instead, that number is there to allow you to smoothly upgrade your CSS and JavaScript files from one version to the next. As I understand it, it's supposed to remain on in production mode. The numbers should only change when the timestamps on your files change.
Are you seeing common proxy servers that completely fail to cache any HTTP GET request with a single parameter?


q:
is there a solution for batch insert via hibernate in partitioned postgresql table?  currently i'm getting an error like this...

ERROR org.hibernate.jdbc.AbstractBatcher - Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
   at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
   at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
   at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)....

i have found this link http://lists.jboss.org/pipermail/hibernate-dev/2007-October/002771.html but i can't find anywhere on the web is this problem solved or how it can be get around

[A]
You might want to try using a custom Batcher by setting the hibernate.jdbc.factory_class property. Making sure hibernate won't check the update count of batch operations might fix your problem, you can achieve that by making your custom Batcher extend the class BatchingBatcher, and then overriding the method doExecuteBatch(...) to look like:
```
```
@Override
    protected void doExecuteBatch(PreparedStatement ps) throws SQLException, HibernateException {
        if ( batchSize == 0 ) {
            log.debug( "no batched statements to execute" );
        }
        else {
            if ( log.isDebugEnabled() ) {
                log.debug( "Executing batch size: " + batchSize );
            }

            try {
//              checkRowCounts( ps.executeBatch(), ps );
                ps.executeBatch();
            }
            catch (RuntimeException re) {
                log.error( "Exception executing batch: ", re );
                throw re;
            }
            finally {
                batchSize = 0;
            }

        }

    }
```
```
Note that the new method doesn't check the results of executing the prepared statements. Keep in mind that making this change might affect hibernate in some unexpected way (or maybe not).


q:
I have a layered application in Java which has a multi thread data access layer which is invoked from different points. A single call to this layer is likely to spawn several threads to parallelize requests to the DB.

What I'm looking for is a logging tool that would allow me to define "activities" that are composed by various threads. Therefore, the same method in the data access layer should log different outputs depending on its caller. The ability to group different outputs to summarize the total cost of an operation is also important.

Although the application is in Java, language is not a restriction; what I need are the design guidelines so to eventually implement it. We are currently using log4j, but can't get this behaviour from it.

[A]
In log4j you can log the thread name with the "%t" pattern. See
log4j Pattern Layout
.


q: Is there an open source library that will help me with reading/parsing PDF documents in .NET/C#?

[A]
You could look into this:
http://www.codeproject.com/KB/showcase/pdfrasterizer.aspx
It's not completely free, but it looks very nice.
Alex


q:
I know there is no "right" heap size, but which heap size do you use in your applications (application type, jdk, os)?

The JVM Options -Xms (initial/minimum) and -Xmx (maximum) allow for controlling the heap size. What settings make sense under which circumstances? When are the defaults appropriate?

[A]
Typically i try not to use heaps which are larger than 1GB.
It will cost you on major garbage collections.
Sometime it is better to split your application to a few JVM on the same machine and not you large heap sizes.
Major collection with a large heap size can take >10 mintues (on unoptimized GC applications).


q:
Some API returns me XmlCursor pointing on root of XML Document. I need to insert all of this into another org.w3c.DOM represented document.

At start:
XmlCursor poiting on

<a>
  <b>
    some text
  </b>
</a>

DOM Document:

<foo>

</foo>

At the end I want to have original DOM document changed like this:

<foo>

  <someOtherInsertedElement>

    <a>
  <b>
    some text
  </b>
</a>

  </someOtherInsertedElement>

</foo>

NOTE: document.importNode(cursor.getDomNode()) doesn't work - Exception is thrown: NOT_SUPPORTED_ERR: The implementation does not support the requested type of object or operation.

[A]
Try something like this:
```
```
Node originalNode = cursor.getDomNode();
Node importNode = document.importNode(originalNode.getFirstChild());
Node otherNode = document.createElement("someOtherInsertedElement");
otherNode.appendChild(importNode);
document.appendChild(otherNode);
```
```
So in other words:
Get the DOM Node from the cursor. In this case, it's a DOMDocument, so do getFirstChild() to get the root node.
Import it into the DOMDocument.
Do other stuff with the DOMDocument.
Append the imported node to the right Node.
The reason to import is that a node always "belongs" to a given DOMDocument. Just adding the original node would cause exceptions.


q: I've seen this done in a few sites, an example is artofadambetts.com. The scroll bar on the page scrolls only an element of the page, not the entire page. I looked at the source and havent't been able to figure it out yet. How is this done?

[A]
To put scroll bars on an element such as a div:
```
<div style="overflow-x: auto; overflow-y: auto;>the content</div>
```
If you only want a horizontal or vertical scroll bar, only use whichever of overflow-x and overflow-y you need.


q:
I'm looking for a key/value pair object that I can include in a web service.

I tried using .NET's System.Collections.Generic.KeyValuePair<> class, but it does not properly serialize in a web service. In a web service, the Key and Value properties are not serialized, making this class useless, unless someone knows a way to fix this.

Is there any other generic class that can be used for this situation?

I'd use .NET's System.Web.UI.Pair class, but it uses Object for its types. It would be nice to use a Generic class, if only for type safety.

[A]
Just define a struct/class.
```
```
[Serializable]
public struct KeyValuePair<K,V>
{
  public K Key {get;set;}
  public V Value {get;set;}
}
```
```


q:
I have  a RHEL 5 system with a fresh new hard drive I just dedicated to the MySQL server. To get things started, I used "mysqldump --host otherhost -A | mysql", even though I noticed the manpage never explicitly recommends trying this (mysqldump into a file is a no-go. We're talking 500G of database).

This process fails at random intervals, complaining that too many files are open (at which  point mysqld gets the relevant signal, and dies and respawns).

I tried upping it at sysctl and ulimit, but the problem persists. What do I do about it?

[A]
mysqldump by default performs a per-table lock of all involved tables. If you have many tables that can exceed the amount of file descriptors of the mysql server process.
Try --skip-lock-tables or if locking is imperative --lock-all-tables.
http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html
```
--lock-all-tables, -x
Lock all tables across all databases. This is achieved by acquiring a global read lock for the duration of the whole dump. This option automatically turns off --single-transaction and --lock-tables.
```


q:
Say I've got this array:
MyArray(0)="aaa"
MyArray(1)="bbb"
MyArray(2)="aaa"

Is there a .net function which can give me the unique values? I would like something like this as an output of the function:
OutputArray(0)="aaa"
OutputArray(1)="bbb"

[A]
You could use a dictionary to add them with a key, and when you add them check if the key already exists.
```
```
string[] myarray = new string[] { "aaa", "bbb", "aaa" };
            Dictionary mydict = new Dictionary();
            foreach (string s in myarray) {
                if (!mydict.ContainsKey(s)) mydict.Add(s, s);
            }
```
```


q: I have some code documentation in MS Powerpoint 2003 that I'm revision-controlling in an SVN repository. I'd like to auto-insert the latest revision number into this document whenever I open it. I am using TortoiseSVN. I've been able to google up a macro or two that might work but wanted advice from experts. :) Thanks!

[A]
I think it should be possible to use the $Rev$ macro inside it with the Office 2007 XML formats, but I am not too sure what will happen with older formats that might contain binary data. You might need to tweak svn settings a bit so it sees .ppt files as text and not binary for this to work, I am not sure what is the default behavior. See svn:mime-type for this :
http://svnbook.red-bean.com/en/1.2/svn.advanced.props.html
Read this for detailed infos on $Rev$ replacement:
http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html


q:
As a consultant I get to toy around with many different products and APIs as the customer demands we use X and Y. I think it is great fun and I learn a lot from it.

What will make a great developer over time is, in my opinion, the will to understand and learn new things. Therefore, I will always try to understand what happens "behind the scenes" when I am using 3rd party products.

I spend around 10-15% of my time in Reflector to learn what the heck I'm really doing when I call method X.

How much time do you spend on average? This may also apply to reading (open) source code, documentation etc.

[A]
Since I develop for both .net and compact .net framework, I sometimes decompile the full .net assemblies to "copy" existing functionality to the compact framework.
Other than that I don't spend that much time decompiling libs. Mostly only when something doesn't works and the problem clearly points to an assebmly and I don't want to bug someone else before I'm really shure.
If you want me to stick an number to it, I would say 5% of my time.


q: What is the difference between TrueType fonts and Type-1 fonts?

[A]
Type-1 is the older format, and dates back to the days when Adobe where pioneering DTP with PostScript and vector fonts. At the time Type 1 and Type 3 were the only formats understood by PostScript printers, and only Type 1 could include hints needed to make fonts look good, and the format was a trade secret. This way Adobe relegated other font foundries to non-hinted fonts using Type 3 format.
TrueType was invented by Microsoft as a way (a) to break Adobe's monopoly on hinted font formats, (b) to avoid using a format associated with the Macintosh and PostScript on Windows. Internally TrueType used quadratic curves rather than cubic beziers, thus making them faster to render on the screen and on the cheaper non-PostScript-capable printeres used on Windows sytems. TrueType also has better support for Unicode and other things invented since the creation of Type 1. Modern Macs support TrueType as well.
The new format OpenType combines TrueType and Type 1 (the vector data is permitted to be in quadratic or cubic form, so you can directly convert either of the old formats to the OpenType). OpenType also has support for fancy automatic ligatures and glyph substitution, which is nice in English text and vital for text using Arabic or Indian scripts.


q:
I have a ~23000 line SQL dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want.

Does anyone know a Unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file?

[A]
You could use 'vi' and then the following command:
```
```
:16224,16482w!/tmp/some-file
```
```
Alternatively:
```
```
cat file | head -n 16482 | tail -n 258
```
```
EDIT:- Just to add explanation, you use
head -n 16482
to display first 16482 lines then use
tail -n 258
to get last 258 lines out of the first output.


q:
I have a rails application running on a Linux server. I would like to interact with Outlook/Exchange 2003 appointments from the rails application. For example, certain actions should trigger sending an appointment, and then preferably accepting/canceling the appointment in Outlook should trigger events in the application.

Failing this, is it possible to publish calendars that Outlook 2003 can read without requiring Outlook plugins? I note that Outlook 2003 does not support ical without plugins for example. Similarly, if this is not easily doable in Ruby, but is in another language (such as Perl for example) running on Linux then those suggestions would be welcome.

Any advice on how to achieve this, or where to start looking for answers would be gratefully received.

[A]
Outlook appointments are just e-mails with special header information. There's some information in
this tutorial
on the required parts.  I sent a few meeting invites from my Outlook to my Gmail account and took a look at the raw headers there - you can figure most of the protocol out from that.
The
iCalendar specs
may help you, as well.


q:
I am looking for a good JavaScript library for parsing XML data. It should be much easier to use than the built-in XML DOM parsers bundled with the browsers.

I got spoiled a bit working with JSON and am looking forward to something on similar lines for XML.

[A]
I use
jQuery
for this.  Here is a good example:
(EDIT: Note - the following blog seems to have gone away.)
http://blog.reindel.com/2007/09/24/jquery-and-xml-revisited/
There are also lots and lots of good examples in the
jQuery
documentation:
http://www.webmonkey.com/tutorial/Easy_XML_Consumption_using_jQuery?oldid=20032
EDIT: Due to the blog for my primary example going away, I wanted to add another example that shows the basics and helps with namespace issues:
http://www.zachleat.com/web/selecting-xml-with-javascript/


q:
I'm quoting part of an answer which I received for another question of mine:

In the PHP/MySQL world I would say
  stored procedures are no-go

I would like to know: Is that so? Why? Why not?

[edit]I mean this as a general question without a specific need in mind[/edit]

[A]
Do you have a specific need in mind which makes you consider them? Stored procedures are much less portable than "plain" SQL, that's usually why people don't want to use them. Also, having written a fair share of PL/SQL, I must say that the procedural way of writing code adds complexity and it's just not very modern or testable. They might be handy in some special cases where you need to optimize, but I'd certainly think twice. Jeff has
similar opinions
.


q: What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?

[A]
From
gamedev
```
```
string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
```
```


q:
Working with a SqlCommand in C# I've created a query that contains a IN (list...) part in the where clause. Instead of looping through my string list generating the list I need for the query (dangerous if you think in sqlInjection). I thought that I could create a parameter like:

SELECT blahblahblah WHERE blahblahblah IN @LISTOFWORDS

Then in the code I try to add a parameter like this:

DataTable dt = new DataTable();
dt.Columns.Add("word", typeof(string));
foreach (String word in listOfWords)
{
    dt.Rows.Add(word);
}
comm.Parameters.Add("LISTOFWORDS", System.Data.SqlDbType.Structured).Value = dt;

But this doesn't work.

Questions:

Am I trying something impossible?

Did I took the wrong approach?

Do I have mistakes in this approach?

Thanks for your time :)

[A]
You want to think about where that list comes from.  Generally that information is in the database somewhere.  For example, instead of this:
```
```
SELECT * FROM [Table] WHERE ID IN (1,2,3)
```
```
You could use a subquery like this:
```
```
SELECT * FROM [Table] WHERE ID IN ( SELECT TableID FROM [OtherTable] WHERE OtherTableID= @OtherTableID )
```
```


q:
I'm trying to write a stored procedure to select employees who have birthdays that are upcoming.

SELECT * FROM Employees WHERE Birthday > @Today AND Birthday < @Today + @NumDays

This will not work because the birth year is part of Birthday, so if my birthday was '09-18-1983' that will not fall between '09-18-2008' and '09-25-2008'.

Is there a way to ignore the year portion of date fields and just compare month/days?

This will be run every monday morning to alert managers of birthdays upcoming, so it possibly will span new years.

Here is the working solution that I ended up creating, thanks Kogus.

SELECT * FROM Employees
WHERE Cast(DATEDIFF(dd, birthdt, getDate()) / 365.25 as int)
    - Cast(DATEDIFF(dd, birthdt, futureDate) / 365.25 as int)
<> 0

[A]
You could use
DATE_FORMAT
to extract the day and month parts of the birthday dates.
EDIT: sorry i didn't see that he wasn't using MySQL.


q:
I have a decimal number (let's call it goal) and an array of other decimal numbers (let's call the array elements) and I need to find all the combinations of numbers from elements which sum to goal.

I have a preference for a solution in C# (.Net 2.0) but may the best algorithm win irrespective.

Your method signature might look something like:

public decimal[][] Solve(decimal goal, decimal[] elements)

[A]
I think you've got a
bin packing problem
on your hands (which is NP-hard), so I think the only solution is going to be to try every possible combination until you find one that works.
Edit: As pointed out in a comment, you won't
always
have to try
every
combination for
every
set of numbers you come across. However, any method you come up with has worst-case-scenario sets of numbers where you
will
have to try
every
combination -- or at least a subset of combinations that grows exponentially with the size of the set.
Otherwise, it wouldn't be NP-hard.


q:
I need to write a program used internally where different users will have different abilities within the program.

Rather than making users have a new username and password, how do I tie into an existing domain server's login system?

Assume .NET  (C#, VB, ASP, etc)

-Adam

[A]
For WinForms, use System.Threading.Thread.CurrentPrincipal with the IsInRole() method to check which groups they are a member of. You do need to set the principal policy of the AppDomain to WindowsPrincipal first.
Use this to get the current user name:
```
```
private string getWindowsUsername()
{
    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    return Thread.CurrentPrincipal.Identity.Name;
}
```
```
And then something like this to check a role:
```
```
if (Thread.CurrentPrincipal.IsInRole("Domain Users") == true)
{}
```
```
In ASP.NET, the thread will belong to IIS, so instead you should
Set the virtual folder or website to require authentication
Get the user name supplied by the browser with Request.ServerVariables("LOGON_USER")
Use the
DirectorySearcher
class to find the users groups


q:
I am wondering what makes sense in relation to what objects to expose through a WCF service - should I add WCF Serialization specifications to my business entities or should I implement a converter that maps my business entities to the DataContracts that I want to expose through my WCF service?

Right now I have entities on different levels: DataAccess, Business and Contract. I have converters in place that can map entities from DataAccess to Business and from Business to Contract and vice versa. Implementing and Maintaining those is time consuming and pretty tedious. What are best practices in relation to this?

If I were using an OR/M such as NHibernate or Entity Framework should I be exposing the entities from the ORM directly or should I abstract them the same way I am doing now?

[A]
In general, I think from a best practices standpoint, you should not expose the structure of your business objects as data contracts, but rather define "data contract-specific" classes and convert Business to Contract.  It may require extra work, but from a separation of concerns and protection from change standpoint the extra work is probably worth it.
The
Microsoft patterns & practices "Service Factory Modeling Edition"
implements this, and also provides tooling to auto-generate Business <=> Contract converter classes -- it's an excellent VS add-in, and also represents Microsoft's best practices for WCF.


q:
The following returns

Type of conditional expression cannot be determined because there is no implicit conversion between 'double' and '<null>'

aNullableDouble = (double.TryParse(aString, out aDouble) ? aDouble : null)

The reason why I can't just use aNullableBool instead of the roundtrip with aDouble is because aNullableDouble is a property of a generated EntityFramework class which cannot be used as an out par.

[A]
```
```
aNullableDouble = (double.TryParse(aString, out aDouble)?new Nullable<double>(aDouble):null)
```
```


q:
I want to find records on a combination of created_on >= some date AND name IN some list of names.

For ">=" I'd have to use sql condition. For "IN" I'd have to use a hash of conditions where the key is :name and the value is the array of names.

Is there a way to combine the two?

[A]
You can use named scopes in rails 2.1 and above
```
```
Class Test < ActiveRecord::Base
  named_scope :created_after_2005, :conditions => "created_on > 2005-01-01"
  named_scope :named_fred, :conditions => { :name => "fred"}
end
```
```
then you can do
```
```
Test.created_after_2005.named_fred
```
```
Or you can give named_scope a lambda allowing you to pass in arguments
```
```
Class Test < ActiveRecord::Base
  named_scope :created_after, lambda { |date| {:conditions => ["created_on > ?", date]} }
  named_scope :named, lambda { |name| {:conditions => {:name => name}} }
end
```
```
then you can do
```
```
Test.created_after(Time.now-1.year).named("fred")
```
```


q: Generally, what's the best way to tackle a layout bug in IE6? What are the most common bugs or problems that one should look for when trying to figure out why your page suddenly looks like a monkey coded it?

[A]
The box model is usually the culprit.  Basically what this means is that any div you are trying to position and use unsupported CSS with will cause this problem.
You may find it happens if you are using min-{width,height} or max-{width,height}.
this provides a great reference for checking compadibility with different versions.
http://www.aptana.com/reference/html/api/CSS.index.html


q: Does any one know any good resources for creating Visual Slick macros?

[A]
I'd start with the
official community forum
for SlickEdit macros.


q: What interrupt would you hook from DOS to get the real-time clock?

[A]
Read up on the
Intel 8259
family of Programmable Interrupt Controllers.  According to this, it's interrupts 8 (master) and 112 (slave).  Here's a very technical document on the 8259A:
http://pdos.csail.mit.edu/6.828/2008/readings/hardware/8259A.pdf


q: I need to enable/disable completely network interfaces from a script in Windows XP. I'm looking for a python solution, but any general way (eg WMI, some command-line à la netsh, some windows call) is welcome and will be adjusted. Thanks.

[A]
The
devcon
tool can control the NIC, but not the interface directly. It's a command-line version of the Device Manager applet.
```
```
devcon disable (id or portion of name)
devcon enable (id or portion of name)
```
```


q: I'm trying to create a server control, which inherits from TextBox, that will automatically have a CalendarExtender attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality.

[A]
I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and the CalendarExtender.
In the
```
CreateChildControls
```
method of the CompositeControl I use code similar to this:
```
```
TextBox textbox = new TextBox();
textbox.ID = this.ID + "Textbox";
textbox.Text = this.EditableField.TextValue;
textbox.TextChanged += new EventHandler(HandleTextboxTextChanged);
textbox.Width = new Unit(100, UnitType.Pixel);
CalendarExtender calExender = new CalendarExtender();
calExender.PopupButtonID = "Image1";
calExender.TargetControlID = textbox.ID;
this.Controls.Add(textbox);
this.Controls.Add(calExender);
```
```
Of course make sure that the form containing this CompositeControl has a toolkit script manager.


q: All I know about the constraint is it's name (SYS_C003415), but I want to see it's definition.

[A]
Looks like I should be querying
```
ALL_CONSTRAINTS
```
.
```
```
select OWNER, CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME, SEARCH_CONDITION from ALL_CONSTRAINTS where CONSTRAINT_NAME = 'SYS_C003415';
```
```


q:
Where is the option in Visual Studio to make the Home key go to the start of the line?

Right now you have to do

Home,Home

or

Home, Ctrl+Left Arrow

i'd prefer that home goes to the start of the line. i saw it before, but now i cannot find it.

[A]
In Tools/Customize/Keyboard,  Reassign the "Home" key from Edit.LineStart" to "Edit.LineFirstColumn"
Edit by OP:
You must change
Scope
to
Text Editor
before this will work.
Visual Studio 2010
Visual Studio 2010 removed the
"scope"
option. Instead you want the
"Use new shortcut in"
option:


q:
I have a string coming from a table like "can no pay{1},as your payment{2}due on {3}". I want to replace {1} with some value , {2} with some value and {3} with some value .

Is it Possible to replace all 3 in one replace function ? or is there any way I can directly write query and get replaced value ?   I want to replace these strings in Oracle stored procedure the original string is coming from one of my table I am just doing select on that table

and then I want to replace {1},{2},{3} values from that string to the other value that I have from another table

[A]
Although it is not one call, you can nest the
```
replace()
```
calls:
```
```
SET mycol = replace( replace(mycol, '{1}', 'myoneval'), '{2}', mytwoval)
```
```


q: I want to find a way to develop database projects quickly in Visual Studio.  Any ideas?

[A]
I have a method of creating and updating database projects in Visual Studio 2005 that I thought was common knowledge. After asking a few coworkers if they knew how to update their database projects with this method and receiving no's, I thought I would blog about it and pass along some helpful hints and best practices.
I work a lot with databases and especially stored procedures that are built to be used with business logic/data access .NET framework. I enjoy working with databases and always create database projects to live with my .NET projects. I am psychotic about keeping database projects up to date.  I have been burned too many time in my younger years where I needed to create a stored procedure that was deleted or was out of sync with the application using the database.
After creating your database project in Visual Studio 2005 as shown:
alt text http://www.cloudsocket.com/images/image-thumb16.png
Create 3 new directories in the projects: Tables, Stored Procedures and Functions. I usually only stored these for my projects.
alt text http://www.cloudsocket.com/images/image-thumb17.png
I now open the Server Explorer in Visual Studio and create a new connection to my desired database. I am using Northwind as my example. I am not going to walk through the creation of the connection for this example.
alt text http://www.cloudsocket.com/images/image-thumb18.png
I will use a stored procedure as my example on how to update the database project. First I expand the "Stored Procedures" directory in the Server Explorer for the Northwind database. I select a stored procedure.
alt text http://www.cloudsocket.com/images/image-thumb19.png
I drag the stored procedure to the "Stored Procedures" directory in the Solution Explorer and drop it.
alt text http://www.cloudsocket.com/images/image-thumb20.png
alt text http://www.cloudsocket.com/images/image-thumb21.png
If you open the file for the dragged stored procedures you will find that the IDE created the script as followed:
```
```
/****** Object:  StoredProcedure [dbo].[CustOrdersOrders]    Script Date: 08/25/2007 15:22:59 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CustOrdersOrders]
GO
/****** Object:  StoredProcedure [dbo].[CustOrdersOrders]    Script Date: 08/25/2007 15:22:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CustOrdersOrders]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE CustOrdersOrders @CustomerID nchar(5)
AS
SELECT OrderID,
    OrderDate,
    RequiredDate,
    ShippedDate
FROM Orders
WHERE CustomerID = @CustomerID
ORDER BY OrderID
'
END
GO
```
```
You can now drag over all the tables, functions and remaining stored procedures from your database. You can also right click on each script in the Solution Explorer and run the scripts on your database project's referenced database.


q:
Below is an example class hierarchy and code. What I'm looking for is a way to determine if 'ChildClass1' or 'ChildClass2' had the static method whoAmI() called on it without re-implementing it in each child class.

<?php

abstract class ParentClass {

    public static function whoAmI () {

        // NOT correct, always gives 'ParentClass'
        $class = __CLASS__;

        // NOT correct, always gives 'ParentClass'.
        // Also very round-about and likely slow.
        $trace = debug_backtrace();
        $class = $trace[0]['class'];

        return $class;
    }
}

class ChildClass1 extends ParentClass {

}

class ChildClass2 extends ParentClass {

}

// Shows 'ParentClass'
// Want to show 'ChildClass1'
print ChildClass1::whoAmI();
print "\n";

// Shows 'ParentClass'
// Want to show 'ChildClass2'
print ChildClass2::whoAmI();
print "\n";

[A]
I believe what you're referring to is a known php bug. Php 5.3 is aiming to address this issue with a new Late Static Binding feature.
http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html


q:
We have several jobs that run concurrently that have to use the same config info for log4j.  They are all dumping the logs into one file using the same appender.  Is there a way to have each job dynamically name its log file so they stay seperate?

Thanks

Tom

[A]
You could programmatically configure log4j when you initialize the job.
You can also set the log4j.properties file at runtime via a system property. From the
manual
:
Set the resource string variable to the value of the
log4j.configuration
system property. The preferred way to specify the default initialization file is through the log4j.configuration system property. In case the system property log4j.configuration is not defined, then set the string variable resource to its default value "log4j.properties".
Assuming you're running the jobs from different java commands, this will enable them to use different log4j.properties files and different filenames for each one.
Without specific knowledge of how your jobs are run it's difficult to say!


q:
foreach ($_GET as $field => $label)
{
   $datarray[]=$_GET[$field];
   echo "$_GET[$field]";
   echo "<br>";
}
print_r($datarray);

This is the output I am getting. I see the data is there in datarray but when
I echo $_GET[$field]

I only get "Array"

But print_r($datarray) prints all the data. Any idea how I pull those values?

OUTPUT

Array (
        [0] => Array (
                 [0] => Grade1
                 [1] => ln
                 [2] => North America
                 [3] => yuiyyu
                 [4] => iuy
                 [5] => uiyui
                 [6] => yui
                 [7] => uiy
                 [8] => 0:0:5
                 )
)

[A]
Use
```
<pre>
```
tags before
```
print_r
```
, then you will have a tree printed (or just look at the source. From this point you will have a clear understanding of how your array is and will be able to pull the value you want.
I suggest further reading on
```
$_GET
```
variable and
arrays
, for a better understanding of its values


q:
Test the following code:

#include <stdio.h>
#include <stdlib.h>
main()
{
    const char *yytext="0";
    const float f=(float)atof(yytext);
    size_t t = *((size_t*)&f);
    printf("t should be 0 but is %d\n", t);
}

Compile it with:

gcc -O3 test.c

The GOOD output should be:

"t should be 0 but is 0"

But with my gcc 4.1.3, I have:

"t should be 0 but is -1209357172"

[A]
Use the compiler flag -fno-strict-aliasing.
With strict aliasing enabled, as it is by default for at least -O3, in the line:
```
```
size_t t = *((size_t*)&f);
```
```
the compiler assumes that the size_t* does NOT point to the same memory area as the float*. As far as I know, this is standards-compliant behaviour (adherence with strict aliasing rules in the ANSI standard start around gcc-4, as Thomas Kammeyer pointed out).
If I recall correctly, you can use an intermediate cast to char* to get around this. (compiler assumes char* can alias anything)
In other words, try this (can't test it myself right now but I think it will work):
```
```
size_t t = *((size_t*)(char*)&f);
```
```


q: Sometimes my Oracle database on Windows gets hosed. How do I do a manual uninstall of Oracle?

[A]
Assuming a unix type OS and that you properly installed it using an account named oracle...
find / -user oracle -exec rm -fr {} \;
That having been said, this must be done as root and you had better not mind loss of any and all files that belong to oracle.  There will be no... NO recovery from this method.


q:
example:

a_list = [1, 2, 3]
a_list.len() # doesn't work
len(a_list) # works

Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object.
Plus I keep trying the wrong solution since it appears as the logical one to me

[A]
Maybe you're looking for
```
__len__
```
.  If that method exists, then len(a) calls it:
```
```
>>> class Spam:
...   def __len__(self): return 3
...
>>> s = Spam()
>>> len(s)
3
```
```


q:
It's common to want browsers to cache resources - JavaScript, CSS, images, etc. until there is a new version available, and then ensure that the browser fetches and caches the new version instead.

One solution is to embed a version number in the resource's filename, but will placing the resources to be managed in this way in a directory with a revision number in it do the same thing? Is the whole URL to the file used as a key in the browser's cache, or is it just the filename itself and some meta-data?

If my code changes from fetching /r20/example.js to /r21/example.js, can I be sure that revision 20 of example.js was cached, but now revision 21 has been fetched instead and it is now cached?

[A]
depends. it is supposed to be the full URL, but some browsers (Opera, Safari
2
) apply a different cache strategy for urls with different params.
best bet is to change the name of the file
.
There is a very clever solution here (uses PHP, Apache)
http://verens.com/archives/2008/04/09/javascript-cache-problem-solved/
Strategy notes:
“According the letter of the HTTP caching specification, user agents should never cache URLs with query strings. While Internet Explorer and Firefox ignore this, Opera and Safari don’t - to make sure all user agents can cache your resources, we need to keep query strings out of their URLs.”
http://www.thinkvitamin.com/features/webapps/serving-javascript-fast


q:
Do you guys know how I can use the Curl command line to POST SOAP to test a web service?

I have a file (soap.xml) which has all the soap message attached to it I just don't seem to be able to properly post it.

Thanks!

[A]
Posting a string:
```
```
curl -d "String to post" "http://www.example.com/target"
```
```
Posting the contents of a file:
```
```
curl -d @soap.xml "http://www.example.com/target"
```
```


q: I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c# examples would be fine as well if they get the idea across. Thanks.

[A] Idiomatic code is code that does a common task in the common way for your language.  It's similar to a design pattern, but at a much smaller scale.  Idioms differ widely by language.  One idiom in C# might be to use an iterator to iterate through a collection rather than looping through it.  Other languages without iterators might rely on the loop idiom.


q:
Here's a challenge that I was tasked with recently. I still haven't figured out the best way to do it, maybe someone else has an idea.

Using PHP and/or HTML, create a page that cycles through any number of other pages at a given interval.

For instance, we would load this page and it would take us to google for 20 seconds, then on to yahoo for 10 seconds, then on to stackoverflow for 180 seconds and so on an so forth.

[A]
Use a separate iframe for the content, then use Javascript to
```
delay()
```
a period of time and set the iframe's
```
location
```
property.


q:
I'm running in a windows environment with Trac / SVN and I want commits to the repository to integrate to Trac and close the bugs that were noted in the SVN Comment.

I know there's some post commit hooks to do that, but there's not much information about how to do it on windows.

Anyone done it successfully?  And what were the steps you followed to achive it?

Here's the hook I need to put in place in SVN, but I'm not exactly sure how to do this in the Windows environment.

Trac Post Commit Hook

[A]
Post commit hooks live in the "hooks" directory where ever you have the repository living on the server side.  I don't know where you have them in your environment, so this is just an example
e.g. (windows):
```
```
C:\Subversion\repositories\repo1\hooks\post-commit
```
```
e.g. (llinux/unix):
```
```
/usr/local/subversion/repositories/repo1/hooks/post-commit
```
```


q: I would like to be able to loop through all of the defined parameters on my reports and build a display string of the parameter name and value.  I'd then display the results on the report so the user knows which parameters were used for that specific execution.  The only problem is that I cannot loop through the Parameters collection.  There doesn't seem to be an indexer on the Parameters collection, nor does it seem to implement IEnumerable.  Has anyone been able to accomplish this?  I'm using SSRS 2005 and it must be implemented within the Report Code (i.e., no external assembly).  Thanks!

[A]
Unfortunately, it looks like there's no simple way to do this.
See
http://www.jameskovacs.com/blog/DiggingDeepIntoReportingServices.aspx
for more info. If you look at the
comments of that post
, there are some ways to get around this, but they're not very elegant. The simplest solution will require you to have a list of the report parameters somewhere in your Report Code, which obviously violates the
DRY
principle, but if you want the simplest solution, you might just have to live with that.
You might want to rethink your constraint of no external assembly, as it looks to me that it would be much easier to do this with an external assembly. Or if your report isn't going to change much, you can create the list of parameter names and values manually.


q: In a C# windows forms application. I have a splash screen with some multi-threaded processes happening in the background. What I would like to do is when I display the splash screen initially, I would like to have it appear to "fade in". And then, once all the processes finish, I would like it to appear as though the splash screen is "fading out". I'm using C# and .NET 2.0. Thanks.

[A] You can use the Opacity property for the form to alter the fade (between 0.0 and 1.0).


q: How do I use RelativeSource with WPF bindings and what are the different use-cases?

[A]
Don't forget TemplatedParent:
```
```
<Binding RelativeSource="{RelativeSource TemplatedParent}"/>
```
```
or
```
```
{Binding RelativeSource={RelativeSource TemplatedParent}}
```
```


q:
How do I get a a complete list of all the urls that my rails application could generate?

I don't want the routes that I get get form rake routes, instead I want to get the actul URLs corrosponding to all the dynmically generated pages in my application...

Is this even possible?

(Background: I'm doing this because I want a complete list of URLs for some load testing I want to do, which has to cover the entire breadth of the application)

[A]
You could pretty quickly hack together a program that grabs the output of
```
rake routes
```
and then parses the output to put together a list of the URLs.
What I have, typically, done for load testing is to use a tool like
WebLOAD
and script several different types of user sessions (or different routes users can take).  Then I create a mix of user sessions and run them through the website to get something close to an accurate picture of how the site might run.
Typically I will also do this on a total of 4 different machines running about 80 concurrent user sessions to realistically simulate what will be happening through the application.  This also makes sure I don't spend overly much time optimizing infrequently visited pages and can, instead, concentrate on overall application performance along the critical paths.


q:
I'm connecting to an AS/400 stored procedure layer using the IBM iSeries Access for Windows package. This provides a .NET DLL with classes similar to those in the System.Data namespace. As such we use their implementation of the connection class and provide it with a connection string.

Does anyone know how I can amend the connection string to indicate the default library it should use?

[A]
Are you using the Catalog Library List parameter for OLE DB? This is what my connection string typically looks like:
```
```
<add name="AS400ConnectionString" connectionString="Data Source=DEVL820;Initial Catalog=Q1A_DATABASE_SRVR;Persist Security Info=False;User ID=BLAH;Password=BLAHBLAH;Provider=IBMDASQL.DataSource.1;**Catalog Library List="HTSUTST, HTEUSRJ, HTEDTA"**" providerName="System.Data.OleDb" />
```
```


q:
I have a core file generated on a remote system that I don't have direct access to.  I also have local copies of the library files from the remote system, and the executable file for the crashing program.

I'd like to analyse this core dump in gdb.

For example:

gdb path/to/executable path/to/corefile

My libraries are in the current directory.

In the past I've seen debuggers implement this by supplying the option "-p ." or "-p /=."; so my question is:

How can I specify that libraries be loaded first from paths relative to my current directory when analysing a corefile in gdb?

[A]
Start gdb without specifying the executable or core file, then type the following commands:
```
```
set solib-absolute-prefix ./usr
file path/to/executable
core-file path/to/corefile
```
```
You will need to make sure to mirror your library path exactly from the target system.  The above is meant for debugging targets that don't match your host, that is why it's important to replicate your root filesystem structure containing your libraries.
If you are remote debugging a server that is the same architecture and Linux/glibc version as your host, then you can do as
fd
suggested:
```
```
set solib-search-path <path>
```
```
If you are trying to override some of the libraries, but not all then you can copy the target library directory structure into a temporary place and use the
```
solib-absolute-prefix
```
solution described above.


q:
Visual Studio 2003 and 2005 (and perhaps 2008 for all I know) require the command line user to run in the 'Visual Studio Command Prompt'.  When starting this command prompt it sets various environment variables that the C++ compiler, cl, uses when compiling.

This is not always desirable.  If, for example, I want to run 'cl' from within Ant, I'd like to avoid having to run Ant from within the 'Visual Studio Command Prompt'.  Running vcvars32.bat isn't an option as the environment set by vcvars32.bat would be lost by the time cl was run (if running from within Ant).

Is there an easy way to run cl without having to run from within the Visual Studio command prompt?

[A]
You can simply run the batch file which sets the variables yourself. In VS08 it's located at:-
```
```
C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat
```
```


q:
Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?

Something like the opposite of String#to_i:

"0A".to_i(16) #=>10

Like perhaps:

"0A".hex #=>10

I know how to roll my own, but it's probably more efficient to use a built in Ruby function.


q: in XSLT processing, is there a performance difference between apply-template and call-template? In my stylesheets there are many instances where I can use either, which is the best choice?

[A]
apply-template and call-template do not perform the same task, performance comparison is not really relevant here.
call-template takes a template name as a parameter whereas apply-template takes an xpath expression. Apply-template is therefore much more powerful since you do not really know which template will be executed.
You will get performance issues if you use complex xpath expressions. Avoid "//" in your xpath expressions since every node of your input document will be evaluated.


q:
For example I want to be able to programatically hit a line of code like the following where the function name is dynamically assigned without using Evaluate(). The code below of course doesn't work but represents what I would like to do.

application.obj[funcName](argumentCollection=params)

The only way I can find to call a function dynamically is by using cfinvoke, but as far as I can tell that instantiates the related cfc/function on the fly and can't use a previously instantiated cfc.

Thanks

[A]
According to the docs, you can do something like this:
```
```
<!--- Create the component instance. --->
<cfobject component="tellTime2" name="tellTimeObj">
<!--- Invoke the methods. --->
<cfinvoke component="#tellTimeObj#" method="getLocalTime" returnvariable="localTime">
<cfinvoke component="#tellTimeObj#" method="getUTCTime" returnvariable="UTCTime">
```
```
You should be able to simply call it with method="#myMethod#" to dynamically call a particular function.


q: Is there some built-in way to share files between Xen guests?  I don't currently need to share the actual images, just some data files.

[A]
Do you mean between Xen and the host or between different guests?
If guests, I don't think there is something provided but you should probably use NFS as it is the best supported file system that supports a decent number of permissions and attributes but assumes a trusted network.


q:
Personally I like this one:

P.S. Do not hotlink the cartoon without the site's permission please.

[A]
I like this one:
http://xkcd.com/149/
(Proper User Policy apparently means Simon Says.)


q:
I would like to be able to predict what will be in the resulting binary when I call Write in Ada to serialize a record. Do you know where I can look this up?

I have some legacy Ada software that produces a binary file by Write-ing a record, and I need to debug a C++ program that is supposed to write a compatible binary file. So, I would like to understand what rules Ada follows when it serializes a record, so that I can make sure that the C++ code will produce a functionally equivalent record.

[A]
The
Ada95 Language Reference Manual
says (section 13.13.2):
"For elementary types, the representation in terms of stream elements is implementation defined. For composite types, the Write or Read attribute for each component is called in a canonical order. The canonical order of components is last dimension varying fastest for an array, and positional aggregate order for a record."


q:
I use the jQuery extend function to extend a class prototype.

For example:

MyWidget = function(name_var) {
  this.init(name_var);
}

$.extend(MyWidget.prototype, {
   // object variables
   widget_name: '',

   init: function(widget_name) {
     // do initialization here
     this.widget_name = widget_name;
   },

   doSomething: function() {
     // an example object method
     alert('my name is '+this.widget_name);
   }
});

// example of using the class built above
var widget1 = new MyWidget('widget one');
widget1.doSomething();

Is there a better way to do this?  Is there a cleaner way to create the class above with only one statement instead of two?

[A]
I quite like John Resig's
Simple JavaScript Inheritance
.
```
```
var MyWidget = Class.extend({
  init: function(widget_name){
    this.widget_name = widget_name;
  },

  doSomething: function() {
    alert('my name is ' + this.widget_name);
  }
});
```
```
NB: The "Class" object demonstrated above isn't included in jQuery itself - it's a 25 line snippet from Mr. jQuery himself, provided in the article above.


q:
This is an Eclipse question, and you can assume the Java package for all these Eclipse classes is org.eclipse.core.resources.

I want to get an IFile corresponding to a location String I have:

 "platform:/resource/Tracbility_All_Supported_lib/processes/gastuff/globalht/GlobalHTInterface.wsdl"

I have the enclosing IWorkspace and IWorkspaceRoot.  If I had the IPath corresponding to the location above, I could simply call IWorkspaceRoot.getFileForLocation(IPath).

How do I get the corresponding IPath from the location String?  Or is there some other way to get the corresponding IFile?

[A]
```
```
String platformLocationString = portTypeContainer
        .getLocation();
String locationString = platformLocationString
        .substring("platform:/resource/".length());
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot workspaceRoot = workspace.getRoot();
IFile wSDLFile = (IFile) workspaceRoot
        .findMember(locationString);
```
```


q: I am writting JAVA programme using JDBC for database conntectivity , I am calling one stored procedure in that which is returning ORACLE REF CURSOR , IS there any way I can handle that without importing ORACLE PACKAGES ?

[A]
I think I tried to do this a while ago and kind of gave up (I guess you could figure out what int value the OracleTypes.REF_CURSOR is and then use that int value, but that's a hack). If you got the patience you could define a record (or object) type and define the the cursor as a cursor with type since that can be cast using table to a value that is selectable like regular tables, ie
```
```
select * from table( sp_returning( ? ) )
```
```
I did a quick google on ref cursor and jdbc and it looks like it might be an oracle extension which would explain why there is no standard way to access the data.


q: has anyone else seen this error message. a quick check with google doesn't show me much.

[A]
You are probably trying to do something like this....
```
```
alert($("#myElement").tagName);
```
```
You should do this...
```
```
alert($("#myElement")[0].tagName);
```
```


q: How do you create a "dockable" form, similar to the windows in Visual Studio?

[A]
I've used Weifen Luo's "DockPanel Suite" to good effect. It's an open source library that mimics Visual Studio's docking system very well, including nested docking, floating windows, tabbed windows, etc. You can download his source and see his approach there, if you'd prefer your own, simpler solution.
Sourceforge project here:
http://sourceforge.net/projects/dockpanelsuite


q: I have an ASP.NET 1.1 application, and on my local machine the submit button on my page works fine, but when I deploy it to our development application server, I click on Submit and nothing happens.. I'm assuming that the Page_Validate() function is failing and disabling the POSTBACK, but how do I debug this and determine what is failing?  It sounds like some config problem since it works great on my local machine but not on the remote server...

[A]
I remember back in the day with 1.1 Visual Studio used to destroy my event handler hookups occasionally.
If you are using Visual Studio 2003, make certain that the "generated" code still contains the event handler wireup for your control.


q:
I am trying to create an XML file based on data fields from a table, and I want to have the nodes named based on the value in a field from the table. The problem is that sometimes values entered in that column contain spaces and other characters not allowed in Node names.

Does anyone have any code that will cleanup a passed in string and repalce invalid characters with replacement text so that it can be reversed on the other end and get the original value back?

I am using .net (vb.net but I can read/convert c#)


q: Should I use Named Pipes, or .NET Remoting to communicate with a running process on my machine?

[A] .net remoting is built into .net to do inner process communication.  If you use that, they will continue to support and possibly enhance it in future versions.  Named pipes doesn't give you the promise of enhancements in future versions of .net


q:
I'm using the RxTx library over usbserial on a Linux distro. The RxTx lib seems to behave quite differently (in a bad way) than how it works over serial.

One of my biggest problems is that the RxTx SerialPortEvent.OUTPUT_BUFFER_EMPTY does not work on linux over usb serial.

How do I know when I should write to the stream?  Any indicators I might have missed?

So far my experience with writing and reading concurrently have not been great.  Does anyone know if I should lock the DATA_AVAILABLE handler from being invoked while I'm writing on the stream?  Or RxTx accepts concurrent read/writes?

[A]
Using RxTx over usb-to-serial you can't set notifyOnOutput to true otherwise it locks up completely.
I've learned this the hard way.  This problem is documented on a few web sites over the internet.
I'm running it on Linux and I believe that this is a Linux only issue, although I can't confirm that.
As for the link you've given me... I've seen the SimpleReader and SimpleWriter examples, but these don't represent a real world application.  It is not multi-threaded, assumes a read has the full data it needs instead of buffering reads, etc.
Thanks,
Jeach!


q:
I'm about to inherit a set of large and complex set of stored procedures that do monthly processing on very large sets of data.

We are in the process of debugging them so they match the original process which was written in VB6. The reason they decided to re write them in t-sql is because the vb process takes days and this new process takes hours.

All this is fine, but how can I make these now massive chunks of t-sql code(1.5k+ lines) even remotely readable / maintainable.

Any experience making t-sql not much of head ache is very welcome.

[A]
First, create a directory full of .sql files and maintain them there. Add this set of .sql files to a revision control system. SVN works well. Have a tool that loads these into your database, overwriting any existing ones.
Have a testing database, and baseline reports showing what the output of the monthly processing should look like. Your tests should also be in the form of .sql files under version control.
You can now refactor your procs as much as you like, and run your tests afterward to confirm correct function.