Question:
in a C program I have an long* that I want to serialize (thus converting to chars). A long doesn't fit in a single char, and the size varies depending of the processor (can be 4 bytes or 8 bytes).

Theres a good way to make the serialization and de-serialization?

Answer:
If you create a char pointer that points to the beginning of the long array, when you increment through the char "array", you'll get 8 bits at a time. Be aware, though, that the long won't be null-terminated (necessarily, it might be), so you need to keep track where the end of it is.
For example:
```
```
long list[MAX];
char *serial = list;
int chunk = sizeof(long);
int k;
for(k=0; k<(MAX*chunk); k++){
  // do something with the "char"
}
```
```


Question:
For example, suppose I have a class:

class Foo
{
public:
    std::string& Name()
    {
        m_maybe_modified = true;
        return m_name;
    }

    const std::string& Name() const
    {
        return m_name;
    }
protected:
    std::string m_name;
    bool m_maybe_modified;
};

And somewhere else in the code, I have something like this:

Foo *a;
// Do stuff...
std::string name = a->Name(); // <-- chooses the non-const version

Does anyone know why the compiler would choose the non-const version in this case?

This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point.

Answer:
Two answers spring to mind:
The non-const version is a closer match.
If it called the const overload for the non-const case, then under what circumstances would it
ever
call the non-const overload?
You can get it to use the other overload by casting
```
a
```
to a
```
const Foo *
```
.
Edit:
From
C++ Annotations
Earlier, in section 2.5.11 the concept
of function overloading was
introduced. There it noted that member
functions may be overloaded merely by
their const attribute. In those cases,
the compiler will use the member
function
matching most closely the
const-qualification of the object:


Question:
I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.

I have no knowledge of deploying "real-life" Python applications, though I have used py2exe in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?

An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?

Thanks.

Answer:
Wow, there are a lot of questions in there:
It is possible to run the bytecode (.pyc) file directly from the Python interpreter, but I haven't seen any bytecode obfuscation tools available.
I'm not aware of any "all in one" deployment solution, but:
For Windows you could use NSIS(
http://nsis.sourceforge.net/Main_Page
).  The problem here is that while OSX/*nix comes with python, Windows doesn't.  If you're not willing to build a binary with py2exe, I'm not sure what the licensing issues would be surrounding distribution of the Python runtime environment (not to mention the technical ones).
You could package up the OS X distribution using the "bundle" format, and *NIX has it's own conventions for installing software-- typically a "make install" script.
Hope that was helpful.


Question:
I have two DataTables, A and B, produced from CSV files.  I need to be able to check which rows exist in B that do not exist in A.

Is there a way to do some sort of query to show the different rows or would I have to iterate through each row on each DataTable to check if they are the same?  The latter option seems to be very intensive if the tables become large.

Answer:
You can use the Merge and GetChanges methods on the DataTable to do this:
```
```
A.Merge(B); // this will add to A any records that are in B but not A
return A.GetChanges(); // returns records originally only in B
```
```


Question:
As far as I can tell there's no simple way of retrieving a character offset from a TextRange object in Internet Explorer. The W3C Range object has a node, and the offset into the text within that node. IE seems to just have pixel offsets. There are methods to create, extend and compare ranges, so it would be possible to write an algorithm to calculate the character offset, but I feel I must be missing something.

So, what's the easiest way to calculate the character offset of the start of an Internet Explorer TextRange?

Answer:
You can iterate through the body element's
```
TextRange.text
```
property using
```
String.substring()
```
to compare against the TextRange for which you want the character offset.
```
```
function charOffset(textRange, parentTextRange)
 { var parentTxt = parentTextRange.text;
   var txt       = textRange.text;
   var parentLen = parentTxt.length;

   for(int i=0; i < parentLen ; ++i)
    { if (parentTxt.substring(i, txt.length+i) == txt)
       { var originalPosition = textRange.getBookmark();

         //moves back one and searches backwards for same text
         textRange.moveStart("character",-1);
         var foundOther = textRange.findText(textRange.text,-parentLen,1);

         //if no others were found return offset
         if (!foundOther) return i;

         //returns to original position to try next offset
         else textRange.moveToBookmark(originalPosition);
       }
    }

   return -1;
 }
```
```
[
Reference for
```
findText()
```
]


Question:
Which is a better format to store graphic assets for a Flex application, SWF or SWC?

Are there any real differences, and if so what are they?

Answer:
SWC is what you use when you're looking for a library to compile into your app. You have access to the classes and can import individual parts. SWF is more likely what you're looking for when embedding graphics.
Here's the docs you might be interested in:
http://livedocs.adobe.com/flex/3/html/help.html?content=layoutperformance_06.html#223998
I've been having good success with SVG for images, but there's some caveats since Flex only implements a subset of the features.


Question:
If I want to construct a std::string with a line like:

std::string my_string("a\0b");

Where i want to have three characters in the resulting string (a, null, b), I only get one.  What is the proper syntax?

Answer:
I have no idea
why
you'd want to do such a thing, but try this:
```
```
std::string my_string("a\0b", 3);
```
```


Question:
The following code receives seg fault on line 2:

char *str = "string";
str[0] = 'z';  // could be also written as *str = 'z'
printf("%s\n", str);

While this works perfectly well:

char str[] = "string";
str[0] = 'z';
printf("%s\n", str);

Tested with MSVC and GCC.

Answer:
Because the type of
```
"whatever"
```
in the context of the 1st example is
```
const char *
```
(even if you assign it to a non-const char*), which means you shouldn't try and write to it.
The compiler has enforced this by putting the string in a read-only part of memory, hence writing to it generates a segfault.


Question:
Specifically, we've got some external JavaScript tracking code on our sites that throws itself into an infinite loop each time an anchor is clicked on.

We don't maintain the tracking code, so we don't know exactly how it works.  Since the code causes the browser to lock up almost immediately, I was wondering if there's anyway to log the results of Firebug's 'profile' functionality to an external file for review?

Answer:
Forget HTML and make a PDF. HTML printing is extremely variable - not just across browsers but across different versions of the same browser. PDF is a lot easier.
Even if you get it exactly right with one browser / font setup / printer / phase of the moon, it will be the most fragile thing you've ever had to maintain. No matter how long you think it will take to make a PDF (and it's not really that hard as there are some free libraries out there), HTML will ultimately take a lot more of your time. PDF readers are widely deployed and print more consistently than even Word files.


Question:
I have code from PowerBuilder 5 that can't be built. The compiler just stops before it is done without any error codes.

I would like to upgrade the code to the recent version of PowerBuilder but there are some intermediate versions of PowerBuilder that have binary dependencies to an old Microsoft java dll that Microsoft no longer can distribute due to some court case.

So, is there a way to get my code running in a newer environment?

/johan/

Answer:
Very unusual sounding problem.  You could give a try to migrating the code to a more recent version of PowerBuilder and see if it will compile or at least fail but give you some useful error messages.
I would also recommend posting this in the PowerBuilder section of the Sybase newsgroups. They are very active and full of some brilliant PB minds with lots of experience.  You can find them here:
http://forums.sybase.com


Question: We are trying to automate a build of one of our products which includes a step where it packages some things with WISE.  At one point WISE pops up a window with a progress bar on it to show how it is doing.  If one is connected to the machine with remote desktop the build works fine but if one is not connected the build stalls until you reconnect at which point the window opens and the build progresses.  Does anybody know of a work around for this?  Some way of tricking windows into believing that there is a desktop session connected?

Answer:
What version are you using?  Looking at the feature set, it looks like their "std" version might be limited.  Perhaps unattended installs require the Pro version?
That's just a guess....
Regardless, I wonder whether you could simply code up an auto-run task for the box that calls
CreateDesktop
to pretend there's an interactive login?
I found a
CreateDesktop example
that's about desktop switching, and
an example about unattended installs
-- you might be able to use one of them as a starting point to "fake out" WISE :)
It might be worth a try...


Question:
I need to get the Folder size and display the info on a report (SSRS). I need to do this for a number of Databases (loop!). These DB's are websites' backends.

Are any samples available for this? Does xp_filesize and the like the right solution?

Answer:
Could you clarify who should do what in your scenario? Do you want SQL Server do get the info or do you want Reporting Server do that?
What exactly do you mean by "folder size"? Is "one folder, sum up each file" enough or does it need to be recursive? Either way, I'd go for a little custom .NET function that uses
```
System.IO.Directory
```
and it's relatives.


Question:
Any XPath like /NodeName/position() would give you the position of the Node w.r.t it's parent node.

There is no method on the XElement (Linq to XML) object that can get the position of the Element. Is there?

Answer:
```
```
static int Position(this XNode node) {
  var position = 0;
  foreach(var n in node.Parent.Nodes()) {
    if(n == node) {
      return position;
    }
    position++;
  }
  return -1;
}
```
```


Question: How can I make my std::fstream object start reading a text file from the second line?

Answer:
Use getline() to read the first line, then begin reading the rest of the stream.
```
```
ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
   ...
```
```
(Changed to std::getline (thanks  dalle.myopenid.com))


Question:
I know there is done some research on TDD at the North Carolina State University. They have published a paper called 'An Initial Investigation of Test Driven Development in Industry'. Other publications by NCSU can be found here.

Can anybody point me to other good publications on this topic?

Answer:
The
ACM Digital Library
has quite a few papers on TDD.  Simply Search for Test Driven Development.
The top results from Google's
Test driven development academic research
:
Test-Driven Development: Concepts, Taxonomy, and Future Direction
in the IEEE Computer Society.
software Architecture Improvement through TDD
at the ACM


Question: For example, I'm writing a multi-threaded time-critical application that processes and streams audio in real-time. Interruptions in the audio are totally unacceptable. Does this mean I cannot use the STL because of the potential slow down when an exception is thrown?

Answer:
Generally, the only exceptions that STL containers will throw by themselves is an std::bad_alloc if new fails. The only other times are when user code (for example constructors, assignments, copy constructors) throws. If your user code never throws then you only have to guard against new throwing, which you would have had to do anyways most likely.
Other things that can throw exceptions:
- at() functions can throw std::out_of_range if you access them out of bounds. This is a serious program error anyways.
Secondly, exceptions aren't always slow. If an exception occurs in your audio processing, its probably because of a serious error that you will need to handle anyways. The error handling code is probably going to be significantly more expensive than the exception handling code to transport the exception to the catch site.


Question: I'm wondering if its possible to add new class data members at run-time in PHP?

Answer:
It is. You can add public members are run time with no additional code, and can affect protected/private members using the magical overloading methods __get() / __set(). See
here
for more details.


Question:
How can I print a message to the error console, preferably including a variable?

For example, something like:

print('x=%d', x);

Answer:
Install
Firebug
and then you can use
```
console.log(...)
```
and
```
console.debug(...)
```
, etc. (see
the documentation
for more).


Question:
I'm processing a file, line-by-line, and I'd like to do an inverse match.  For instance, I want to match lines where there is a string of six letters, but only if these six letters are not 'Andrea'. How should I do that?

I'm using RegexBuddy, but still having trouble.

Answer:
```
```
(?!Andrea).{6}
```
```
Assuming your regexp engine supports negative lookaheads...
...or maybe you'd prefer to use
```
[A-Za-z]{6}
```
in place of
```
.{6}
```
Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching; they leave that to whatever language you are using them with.


Question:
The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.

My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke.

If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.

UPDATE (the solution I used... thanks to ypnos' answer):

./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F

Answer:
I've actually done this a long time ago, but it wasn't petty.  What we did is use the
Sawfish window manager
and wrote a hook to recognize the flashplayer window, then strip all the decorations and snap it full screen.
This may be possible without using the window manager, by registering for X window creation events from an external application, but I'm not familiar enough with X11 to tell you how that would be done.
Another option would be to write a pygtk application that embedded the standalone flash player inside a gtk.Socket and then resized itself.  After a bit of thought, this might be your best bet.


Question: In .NET, if a class contains a member that is a class object, should that member be exposed as a property or with a method?

Answer:
Property. A Property is basically just a 'cheap' method. Getting or setting a reference to an object is pretty cheap.
Just to clarify, properties are usually supposed to represent the internal state of an object. However, the implementation of a member as a property or method tells the user how expensive the call is likely to be.


Question: Is there a library/software which can accept a number of keypoints and matches of them between images and produce a morph? Or any ideas/algorithms on how to do it?

Answer:
An older piece of software by
Gryphon Software
could do image morphing. I saw an article about it from 1994. I couldn't find a company site, so they may be abandon ware now.
Her is a quote from a Wikipedia article about a film editing
technique called Dissolve
.
In non-linear video editing, a dissolve is done in software, by interpolating gradually between the RGB values of each pixel of the image.
Hope that helps.


Question:
I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 database, Visual Studio 2005 and am quite OK with creating stored procedures and datasets.

Can someone please point me in the right direction for creating reports? I just can't seem work it out. Some examples would be a good start, or a simple How-to tutorial... anything really that is a bit better explained than the MSDN docs.

I'm using the CrystalDecisions.Windows.Forms.CrystalReportViewer control to display the reports, I presume this is correct.

If I'm about to embark on a long and complex journey, what's the simplest way to create and display reports that can also be printed?

Answer:
Crystal is one possible option for creating reports. It has been around a long time and a lot of people seem to like it.
You might want to take a look at SQL reporting services. I have used both but my preferance is SQL reporting services. Its pretty well integrated into studio and works similar to the other microsoft projects. Its also free with the sql express etc.
This is a good article on beginning reporting services:
http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/


Question:
How do I create a grails war file so that it doesn't have the version number

(e.g. foo-0.1.war)

attached to the end when I execute the 'grails war' command?

Answer:
I think you can specify the war name in the war command.
```
```
grails war foo.war
```
```
Also check the latest Grails documentation for where to set this as a configuration option. See the other answers for details.


Question:
In my C# source code I may have declared integers as:

int i = 5;

or

Int32 i = 5;

In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same?

int i = 5;
Int64 i = 5;

Answer:
No. The C# specification rigidly defines that
```
int
```
is an alias for
```
System.Int32
```
with exactly 32 bits. Changing this would be a
major
breaking change.


Question: I am building an ontology-processing tool and need lots of examples of various owl ontologies, as people are building and using them in the real world.  I'm not talking  about foundational ontologies such as Cyc, I'm talking about smaller, domain-specific ones.

Answer:
There's no definitive collection afaik, but these links all have useful collections of OWL and RDFS ontologies:
schemaweb.info
vocab.org
owlseek
linking open data constellation
RDF schema registry
(rather old now)
In addition, there are some general-purpose RDF/RDFS/OWL search engines you may find helpful:
sindice
swoogle
Ian


Question: What happens when the Office 2003 PIA prerequisite and launch condition in a Windows installer are run against an Office 2007 system?

Answer:
I believe the 2003 PIA require Office 2003 be installed (so I'm guessing it would fail). AFAIK, the 2003 interops won't work with the 2007 applications. More information about these types of scenarios can be found
here
. So even if it did install (pretty easy to test) you might not have a working application.
Are you trying to get some 2003 Add-ins to work with Office 2007?


Question: I just want to know the best way to emulate a C# style enumeration in Ruby.

Answer:
I don't think Ruby supports true enums -- though, there are still solutions available.
Enumerations and Ruby


Question:
There are lots of tools for creating installers on Windows (InstallShield, InnoSetup, NSIS, just to name a few). All tools I've seen fall in one or both of these categories

Point-and-click. Nice GUI for creating the installer, but the installer definition/project file can not be manually edited.

Textfile: No (official) GUI. The installer is compiled from a definition in a text-file which is manually edited.

The installers I'm building are all defined using a DSL (represented as YAML files), so using a GUI is out of the question, and creating is textfile is cumbersome although doable.

What I really would want is a tool which exposes a (complete) API, through which I can control the creation of the installer. Are there any such tools out there?

Edit: I'd love to hear about non-MSI based tools as well. MSI is not a requirement (rather the other way around...)

Answer:
Wix 3.0 beta
has .NET support included for this purpose. I don't know how well it works but it includes documentation. It's a framework of types for manipulating the installation creation process and all that goodness, so I don't think you even need to write a line of WiX XML if you don't want to.


Question:
How do you return values or structures from a Popup window in Powerbuilder 9.0? The CloseWithReturn is only valid for Response windows and thus is not available. When I set a value to the Message.PowerObjectParm, the value becomes null when the Popup window closes. I need to use a Popup window so the user can click back to the caller window and scroll through rows.

Program flow:
1) Window A OpenWithParm
2) Window B is now open
3) User interacts with both windows
3) User closes Window B
4) Window B needs to pass a structure back to window A

Answer:
You won't be able to accomplish this the way you are thinking.  Since the window you are opening from the parent is not a Response window, the two aren't explicitly linked together.
But you could accomplish this by having a public instance variable in the parent window that is of the type of your custom structure.  Then from the child window before you close it, explicitly set the variable in the parent window via something like this:
```
```
w_my_parent_window_name.istr_my_structure = lstr_my_structure
```
```
This should only be done if there will only be one instance of w_my_parent_window_name instantiated.


Question:
Consider the case of a simple news article web application that has a DB table column of "Status" that is accessible by a radio button set of:

Status - [x] Publish [ ] Draft [ ] Archive

...where "Publish" shows an article publicly and "Draft" and "Archive" do not.  Functionally "Draft" and "Archive" do the same thing but carry additional meta data meanings.  The two functional states of "show" and "hide" along with the meta data of "publish", "draft" and "archive" are intermixed in the same column of "status".

Is this a good practice?  While this is a very simple case, larger cases might reveal flaws with such a practice (or not...).

Answer:
In this instance, I would say that this is the appropriate functionality.
We've all seen WTF's in the media where someone accidentally hit show[x]
and draft[x] at the same time.
The way it is now, it is impossible to accidentally show a draft.  This is important in newspapers as reporters are notorious for stuff like:
John Doe, of StackOverflow  said, "---I can't remember what that ugly f*cker said - Check the tape and fill in later"
Which probably shouldn't be printed.


Question:
$array = explode(".", $row[copy]);
$a = $array.length -1;

I want to return the last element of this array but all i get from this is -1.

Answer:
I think your second line should be more like:
```
```
$index = count($array) - 1;
$a = $array[$index];
```
```
If you want an element from an array you need to use square brackets.


Question:
I've got an issue when accessing a web site, I can access it by using the NetBIOS name, but when accessing with the FQDN i get an error.

Any ideas on how to troubleshoot this?

(There is no DNS configured yet, we have modified the Hosts file to enter the related names and IP.)

Answer:
Just to make sure, you have something like this
```
```
192.168.100.5 othermachine othermachine.mydomain.local
```
```
with both the netbios and the FQDN in it and not just the IP and netbios name?


Question: Every time I try to create a new project or solution in visual studio (2005 and 2008), I get an error saying, "Project Creation failed."  I even tried running vs in administrative mode, but I still get the same answer. Anyone have any suggestions, in short of uninstalling all of VS and reinstalling it?

Answer:
It sounds like an Add-in behaving badly.  Can you launch it in safe mode?
```
```
devenv.exe /SafeMode
```
```


Question:
Vi and Vim allow for really awesome customization, typically stored inside a .vimrc file. Typical features for a programmer would be syntax highlighting, smart indenting and so on.

What other tricks for productive programming have you got, hidden in your .vimrc?

I am mostly interested in refactorings, auto classes and similar productivity macros, especially for C#.

Answer:
This isn't in my .vimrc file, but yesterday I learned about the
```
]p
```
command. This pastes the contents of a buffer just like
```
p
```
does, but it automatically adjusts the indent to match the line the cursor is on! This is excellent for moving code around.


Question:
The following snippet of C# code:

  int i = 1;
  string result = String.Format("{0},{1},{2}", i++, i++, i++);
  Console.WriteLine(result);

writes out: 1,2,3

Before I tried this in the compiler I was expecting the assignments to take place and then the evaluations, so my expected output was: 1,1,1

So my question is: Does this "pattern" (is it called a pattern?) of assign and then evaluate each parameter have a name?

EDIT: I'm referring to the pattern of evaluating and assigning the parameters to the String.Format() function. Not the incrementing of i.

(I may be incorrectly using the word evaluate in the question above because if the parameter was say (i + j) then we know that it would be evaluated before it was assigned. When using the word evaluate in that context I'm referring to the incrementing of i.)

Answer:
The
order of evaluation
of arguments is strictly left-to-right in C#.  When you evaluate the expression
```
i++
```
, what happens is the value of
```
i
```
is calculated and pushed, then the value of
```
i
```
is incremented.
The ++ operator on System.Int32 is effectively a function with the special name
```
++
```
and the special syntax of calling it by writing a reference to a variable and then the characters ++.
So in effect, what you wrote is
```
```
// assume this function is defined:
int Inc(ref int i)
{
  var old = i;
  i = i + 1;
  return old;
}

...
int i = 1;
string result = String.Format("{0},{1},{2}", Inc(ref i), Inc(ref i), Inc(ref i));
Console.WriteLine(result);
...
```
```
Since arguments are evaluated left-to-right,
```
Inc(ref i)
```
is called 3 times, each time incrementing
```
i
```
after passing the current value of
```
i
```
to
```
String.Format(...)
```
.  This is exactly what happens in your code, as well.


Question: How can I write from Java to the Windows Event Log?

Answer:
Log4J is a Java-based logging utility.  The class
```
NTEventLogAppender
```
can be used to "append to the NT event log system". See the documentation here:
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/nt/NTEventLogAppender.html
Edit:
There is a newer version,
Log4j 2
"that provides significant improvements over its predecessor."


Question:
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.

My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.

I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.

Answer:
The way I'd go about it is this:
Encrypt all of the code
Write an installer that contacts the server with the machine's hostname and license file and gets the decryption key, then decrypts the code and compiles it to python bytecode
Add (in the installer) a module that checks the machine's hostname and license file on import and dies if it doesn't match
This way the user only has to contact the server when the hostname changes and on first install, but you get a small layer of security.  You could change the hostname to something more complex, but there's really no need -- anyone that wants to pirate this will do so, but a simple mechanism like that will keep honest people honest.


Question: Is there a way to enable STRICT_ALL_TABLES for a single MySQL database?

Answer: Don't think you can do this directly but you might get close with setting Strict for the current session when working on a particular database. Could do this in the config files of specific users.


Question: I've searched for the solution to change the background color on the Compact Framework's MainMenu control, and the only answer I've found is that you need to create a custom control.  Does anyone have example code for this?

Answer:
There is no way of doing this.
Your right in that you'll probably need to create your own control.
This was something I was considering doing anyway to make the application go on Windows CE and Windows Mobile.
The problem with adding menus when the application needs to work with both is that the menu goes to the top of the screen on Windows CE and covers any controls that might be there.
It would be less hassle in the long run just make a new control.


Question:
When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.

Do I use a variation of .ToString() for this?

Answer:
```
```
decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m
```
```
or
```
```
decimalVar.ToString("0.##"); // returns "0.5"  when decimalVar == 0.5m
```
```
or
```
```
decimalVar.ToString("0.00"); // returns "0.50"  when decimalVar == 0.5m
```
```


Question:
What is the best way to find out if a primary key with a certain value already exists in a table?

I can think of:

SELECT key FROM table WHERE key = 'value';

and count the results, or:

SELECT SQL_CALC_FOUND_ROWS key FROM table WHERE key = 'value' LIMIT 1;
SELECT FOUND_ROWS();

Answer:
I think either of your suggestions in the question are suitable.
Depending on how you are using this though, you can potentially save time by doing an INSERT IGNORE, which allows you to insert a new row if the primary key doesn't exist. If it does exist, the error is ignored so you can continue as normal.
Other similar options depending on your usage include using the REPLACE or the INSERT ON DUPLICATE KEY UPDATE types of inserts. This allows you to update the existing entry if the primary key already exists, otherwise it just inserts your new entry.


Question:
I'm looking at introducing multi-lingual support to a mature CGI application written in Perl.  I had originally considered rolling my own solution using a Perl hash (stored on disk) for translation files but then I came across a CPAN module which appears to do just what I want (i18n).

Does anyone have any experience with internationalization (specifically the i18n CPAN module) in Perl?  Is the i18n module the preferred method for multi-lingual support or should I reconsider a custom solution?

Thanks

Answer:
There is a
Perl Journal article
on software localisation.  It will provide you with a good idea of what you can expect when adding multi-lingual support.  It's beautifully written and humourous.
Specifically, the article is written by the folks who wrote and maintain
```
Locale::Maketext
```
, so I would recommend that module simply based upon the amount of pain it is clear the authors have had to endure to make it work correctly.


Question:
I'm trying to determine the asymptotic run-time of one of my algorithms, which uses exponents, but I'm not sure of how exponents are calculated programmatically.

I'm specifically looking for the pow() algorithm used for double-precision, floating point numbers.

Answer:
The usual approach, to raise a to the b, for an integer exponent, goes something like this:
```
```
result = 1
while b > 0
  if b is odd
    result *= a
    b -= 1
  b /= 2
  a = a * a
```
```
It is generally logarithmic in the size of the exponent.  The algorithm is based on the invariant "a^b*result = a0^b0", where a0 and b0 are the initial values of a and b.
For negative or non-integer exponents, logarithms and approximations and numerical analysis are needed.  The running time will depend on the algorithm used and what precision the library is tuned for.
Edit: Since there seems to be some interest, here's a version without the extra multiplication.
```
```
result = 1
while b > 0
  while b is even
    a = a * a
    b = b / 2
  result = result * a
  b = b - 1
```
```


Question:
I have an Excel application in which I want to present the user with a list of the Data Source Names (ie: DSN's), whereby s/he can choose what data source to use.

Hopefully once I've got the list, I can easily access the DSN properties to connect to the appropriate database.

Please note, I do not want to use a DSN-less connection.

Answer:
The DSN entries are stored in the registry in the following keys.
```
HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data Sources
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources
```
This contains the list of all defined DSN. This acts as an global index and the specific details for each DSN are stored in a key with the DSN name under:
```
HKEY_CURRENT_USER\Software\ODBC\ODBC.INI
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI
```
Create some entries in both User DSN and System DSN tabs from Data Sources (ODBC) control panel applet and check how these values are stored in the registry.
The following example enumerate the DSN defined for the user trough Control Panel > Administrative Tools > Data Sources (ODBC) [User Dsn Tab].
http://support.microsoft.com/kb/178755
```
```
Option Explicit

  Private Declare Function RegOpenKeyEx Lib "advapi32.dll" _
      Alias "RegOpenKeyExA" _
      (ByVal hKey As Long, _
      ByVal lpSubKey As String, _
      ByVal ulOptions As Long, _
      ByVal samDesired As Long, phkResult As Long) As Long

  Private Declare Function RegEnumValue Lib "advapi32.dll" _
      Alias "RegEnumValueA" _
      (ByVal hKey As Long, _
      ByVal dwIndex As Long, _
      ByVal lpValueName As String, _
      lpcbValueName As Long, _
      ByVal lpReserved As Long, _
      lpType As Long, _
      lpData As Any, _
      lpcbData As Long) As Long

  Private Declare Function RegCloseKey Lib "advapi32.dll" _
      (ByVal hKey As Long) As Long

  Const HKEY_CLASSES_ROOT = &H80000000
  Const HKEY_CURRENT_USER = &H80000001
  Const HKEY_LOCAL_MACHINE = &H80000002
  Const HKEY_USERS = &H80000003

  Const ERROR_SUCCESS = 0&

  Const SYNCHRONIZE = &H100000
  Const STANDARD_RIGHTS_READ = &H20000
  Const STANDARD_RIGHTS_WRITE = &H20000
  Const STANDARD_RIGHTS_EXECUTE = &H20000
  Const STANDARD_RIGHTS_REQUIRED = &HF0000
  Const STANDARD_RIGHTS_ALL = &H1F0000
  Const KEY_QUERY_VALUE = &H1
  Const KEY_SET_VALUE = &H2
  Const KEY_CREATE_SUB_KEY = &H4
  Const KEY_ENUMERATE_SUB_KEYS = &H8
  Const KEY_NOTIFY = &H10
  Const KEY_CREATE_LINK = &H20
  Const KEY_READ = ((STANDARD_RIGHTS_READ Or _
                    KEY_QUERY_VALUE Or _
                    KEY_ENUMERATE_SUB_KEYS Or _
                    KEY_NOTIFY) And _
                    (Not SYNCHRONIZE))

  Const REG_DWORD = 4
  Const REG_BINARY = 3
  Const REG_SZ = 1

  Private Sub Command1_Click()
     Dim lngKeyHandle As Long
     Dim lngResult As Long
     Dim lngCurIdx As Long
     Dim strValue As String
     Dim lngValueLen As Long
     Dim lngData As Long
     Dim lngDataLen As Long
     Dim strResult As String

     lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, _
             "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources", _
              0&, _
              KEY_READ, _
              lngKeyHandle)

     If lngResult <> ERROR_SUCCESS Then
         MsgBox "Cannot open key"
         Exit Sub
     End If

     lngCurIdx = 0
     Do
        lngValueLen = 2000
        strValue = String(lngValueLen, 0)
        lngDataLen = 2000

        lngResult = RegEnumValue(lngKeyHandle, _
                                 lngCurIdx, _
                                 ByVal strValue, _
                                 lngValueLen, _
                                 0&, _
                                 REG_DWORD, _
                                 ByVal lngData, _
                                 lngDataLen)
        lngCurIdx = lngCurIdx + 1

        If lngResult = ERROR_SUCCESS Then
           strResult = strResult & lngCurIdx & ": " & Left(strValue, lngValueLen) & vbCrLf
        End If
     Loop While lngResult = ERROR_SUCCESS
     Call RegCloseKey(lngKeyHandle)

     Call MsgBox(strResult, vbInformation)
  End Sub
```
```


Question:
I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance:

Matches

CW3 9SS

SE5 0EG

SE50EG

se5 0eg

WC2H 7LT

No Match

aWC2H 7LT

WC2H 7LTa

WC2H

How do I solve this problem?

Answer:
```
```
^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$
```
```
Regular expression to match valid UK
  postcodes. In the UK postal system not
  all letters are used in all positions
  (the same with vehicle registration
  plates) and there are various rules to
  govern this. This regex takes into
  account those rules. Details of the
  rules: First half of postcode Valid
  formats [A-Z][A-Z][0-9][A-Z]
  [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9]
  [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z]
  [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions
  Position - First. Contraint - QVX not
  used Position - Second. Contraint -
  IJZ not used except in GIR 0AA
  Position - Third. Constraint -
  AEHMNPRTVXY only used Position -
  Forth. Contraint - ABEHMNPRVWXY Second
  half of postcode Valid formats
  [0-9][A-Z][A-Z] Exceptions Position -
  Second and Third. Contraint - CIKMOV
  not used
http://regexlib.com/REDetails.aspx?regexp_id=260


Question:
I need a simple table with a user name and password field in MySQL. Since user names must be unique, it makes sense to me to make them the primary key.

Is it better to use CHAR() or VARCHAR() as a primary key?

Answer:
may as well just use a user ID index, it's much faster for joins vs char/varchar. the two seconds it takes to add that now could save you a lot of time later if you accidently have to expand the functionality of your schema.
some pitfalls to think about:
say we add a few tables at a future date, what if someone wants to change a username?
say the app is more successful then we think, and we have to look at optimization, do you really want to redo your schema at this point to reduce the overhead of a varchar'ed index?


Question:
Using C# in Visual Studio 2008 and stepping through a function in the debugger I get to the end of a function and am on the final curly brace } and about to return. Is there a way to find out what value the function is about to return?

This is necessary if the return value is calculated such as:

return (x.Func() > y.Func());

Answer:
You can put
```
```
(x.Func() > y.Func())
```
```
in a watch window to evaluate it, and see the result.  Unless the statement is
```
```
return ValueChangesAfterEveryCall();
```
```
you should be fine.


Question:
I would like to upgrade my web projects on an IIS 5 server from .NET 2.0 to .NET 3.5.  These web applications live on a server with other web applications that will not be upgraded to .NET 3.5.  The server administrator is reluctant to install .NET 3.5 because he is afraid it will break the applications on that machine that are running 2.0 and 1.1.

As far as I know this WON'T be a problem since .NET 3.5 is an addition to 2.0 more than it is a new Framework.  I would like the communities help gathering evidence to show him that their concerns are moot and it won't hurt the other applications.

Thanks in advance.

Answer: It won't have any problem and you will be able to run your 2.0 and 3.5 application using the same server. This is because the code base for both of the frameworks is the same.


Question:
Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date?

I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date.  I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect.

Answer:
If you put an inverted comma at the start of the field, it will be interpreted as text.
Example:
```
25/12/2008
```
becomes
```
'25/12/2008
```
You are also able to select the field type when importing.


Question:
This is an excerpt of code from a class I am working with in Java (below). Obviously the code is defining a static variable named EPSILON with the data type double. What I don't understand is the "1E-14" part. What kind of number is that? What does it mean?

final double EPSILON = 1E-14;

Answer:
1E3 => 1000
1E-1 => 0.1
1E-2 => 0.01
It's a way for writing 1 * 10
-14


Question:
Anyone knows of a good error log beautifier? (should be able to handle apache error logs).

Should be open source / free, preferably with a web interface

Answer:
I use
http://www.librelogiciel.com/software/ScanErrLog/action_Presentation
It runs through the error log producing a summary webpage, or some other formats.  While it's best run from a regular cron-job (and it will keep a record of what it's parsed before to save effort), it can also be run as a CGI (though the demo appears to be broken).


Question:
I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate:

<table><tr><td class="case">123456</td></tr></table>

I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz).

So I'd like that "123456" to be changed to a link of this form:

<a href="http://bugs.example.com/fogbugz/default.php?123456">123456</a>

Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.

Answer:
Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript..
```
```
function makeCasesClickable(){
    var cells = document.getElementsByTagName('td')
    for (var i = 0, cell; cell = cells[i]; i++){
        if (cell.className != 'case') continue
        var caseId = cell.innerHTML
        cell.innerHTML = ''
        var link = document.createElement('a')
        link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId
        link.appendChild(document.createTextNode(caseId))
        cell.appendChild(link)
    }
}
```
```
You can apply it with something like
```
onload = makeCasesClickable
```
, or simply include it right at the end of the page.


Question:
The following code:

template <typename S, typename T>
struct foo {
   void bar();
};

template <typename T>
void foo <int, T>::bar() {
}

gives me the error

invalid use of incomplete type 'struct foo<int, T>'
declaration of 'struct foo<int, T>'

(I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument:

template <typename S>
struct foo {
   void bar();
};

template <>
void foo <int>::bar() {
}

then it compiles correctly.

Answer:
You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g.
```
template <typename U = T> struct Nested
```
) would work. Or else you can try deriving from another template that partially specializes (works if you use the
```
this->member
```
notation, otherwise you will encounter compiler errors).


Question:
What's wrong with Linq to SQL?

Or - what about Linq to SQL would make it unsuitable for a project, either new or existing? I want to hear about why you would not choose Linq to SQL for a particular project - including what project parameters make it unsuitable.

Answer:
Well, I have developed some applications using LINQ to SQL. One of the main problems that I find is having to layer your application. In LINQ to SQL the entity classes are tied very closely with the data access code. Also, there are some issues with DataContext which means that you can use a DataContext object to retrieve an item but you cannot transfer the item (object) to another DataContext (at least not easily).
LINQ to SQL will be useful if you don't care about layering your application properly and also if all you wanted is to create an application in a rapid manner also know as RAPID Application Development.


Question:
I work with a lot of offsite developers and contractors. I ask them daily to send me a quick 5 minute status of their work for the day. I have to sometimes consolidate the status of individuals into teams and sometimes consolidate the status of a week, for end-of-period reporting to my clients.

I want to learn:

Items accomplished and how much time was spent on each

Problems encountered and how much time was spent on each

Items that will be worked on next, their estimates (in man hours) and their target dates

Questions they have on the work

I'm looking for a format that will provide this information while:

Being quick for the developers to complete (5-10 minutes, without thinking too much)

Easy for me to read and browse quickly

Is uniform for each developer

What would you suggest?

Answer:
Just give them a template laid out in a format that you expect to see the data returned in.  You may also consider increasing the time they are going to devote to this and removing the "not thinking too much" clause if you are requiring estimates for future work. I wouldn't trust an estimate that someone came up with in 5 mins. without thinking.
If you are currently using any project management software, it should be trivial for the developers to record and review (or even just remember) what they have done compile it for you.  Ideally they would be recording issues or questions throughout the day and not trying to come up with them just to fill in the report.
It seems like your "I want to learn" list is an excellent starting point to generate a template from. Only you will know what the perfect format for you is.


Question:
I read in this article  that a company has created a software capable of using multiple GPU-based video cards in parallel to process hundreds of billions fixed-point calculations per second.

The program seems to run in Windows. Is it possible from Windows to assign a thread to a GPU? Do they create their own driver and then interact with it? Any idea of how they do it?

Answer:
I imagine that they are using a language like
CUDA
to program the critical sections of code on the GPUs to accelerate their computation.
The main function for the program (and its threads) would still run on the host CPU, but data are shipped off the the GPUs for processing of advanced algorithms.  CUDA is an extension to C syntax, so it makes it easier to programmer than having to learn the older shader languages like
Cg
for programming general purpose calculations on a GPU.


Question: Does SubSonic.SqlQuery have a between/and for date ranges?  If not, what would be the best way to get a range.

Answer:
Try something like this:
```
```
SqlQuery query = new SqlQuery().From("Table")
                               .WhereExpression("Column")
                               .IsBetweenAnd("1/1/2008", "12/31/2008");
DataSet dataSet = query.ExecuteDataSet();  // Or whatever output you need
```
```


Question:
In mysql, how do I get the primary key used for an insert operation, when it is autoincrementing.

Basically, i want the new autoincremented value to be returned when the statement completes.

Thanks!

Answer:
MySQL's
LAST_INSERT_ID()


Question:
I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix.

For example, the day this question was asked would display "Thu Oct 2nd".

I'm using Ruby 1.8.7, and Time.strftime just doesn't seem to do this.  I'd prefer a standard library if one exists.

Answer:
You can use active_support's ordinalize helper method on numbers.
```
```
>> 3.ordinalize
=> "3rd"
>> 2.ordinalize
=> "2nd"
>> 1.ordinalize
=> "1st"
```
```


Question:
I'm failing to understand exactly what the IF statement is doing, from what I can see it is checking if the variable x is equal to the int 0. If this is true the ABSOLUTE value of the variable y is returned... this is when I lose the plot, why would the return statement then go on to include <= ESPILON? Surely this means less than or equal to the value of epsilon? if so how is that working? If it doesn't mean that then what does it mean?

(JAVA CODE)

final double EPSILON = 1E-14;
if (x == 0)
    return Math.abs(y) <= EPSILON;

Answer:
It returns true if the absolute value of y is <= EPSILON, and false otherwise. The <= is evaluated before the return statement. This code is equivalent:
```
```
if(x == 0)
{
   boolean ret = Math.abs(y) <= EPSILON;
   return ret;
}
```
```
The code isn't simply read from left to right. A simpler example is
```
```
int x = 3 + 4 * 5;
```
```
After evaluating this, x is 23, not 35. The evaluation is 3 + (4*5), not (3+4)*5, because the * has a higher precedence than the +. The return statement in the original example has a very low precedence. All operators like +, -, <, >= are evaluated before it.


Question:
I have some c(++) code that uses sprintf to convert a uint_64 to a string.  This needs to be portable to both linux and Solaris.

On linux we use %ju, but there does not appear to be any equivalent on Solaris.  The closest I can find is %lu, but this produces incorrect output.  Some sample code:

#include <stdio.h>
#include <sys/types.h>

#ifdef SunOS
typedef uint64_t u_int64_t;
#endif

int main(int argc, char **argv) {
    u_int64_t val = 123456789123L;

#ifdef SunOS
    printf("%lu\n", val);
#else
    printf("%ju\n", val);
#endif
}

On linux, the output is as expected; on Solaris 9 (don't ask), it's "28"

What can I use?

Answer:
You can use
```
%llu
```
for long long. However, this is not very portable either, because
```
long long
```
isn't guaranteed to be 64 bits. :-)


Question:
How can I check the umask of a program which is currently running?

[update: another process, not the current process.]

Answer:
If you're the current process, you can write a file to /tmp and check its setting.  A better solution is to call umask(3) passing zero - the function returns the setting prior to the call - and then reset it back by passing that value back into umask.
The umask for another process doesn't seem to be exposed.


Question:
Although I played with it before, I'm finally starting to use Dvorak (Simplified) regularly. I've been in a steady relationship with Vim for several years now, and I'm trying to figure out the best way to remap the key bindings to suit my newfound Dvorak skills.

How do you remap Vim's key bindings to best work with Dvorak?

Explanations encouraged!

Answer:
I use one of the more
common recommended keybindings
:
```
```
Dvorak it!
no d h
no h j
no t k
no n l
no s :
no S :
no j d
no l n
no L N
Added benefits
no - $
no _ ^
no N <C-w><C-w>
no T <C-w><C-r>
no H 8<Down>
no T 8<Up>
no D <C-w><C-r>
```
```
Movement keys stay in the same location.  Other changes:
Delete 'd' -> Junk 'j'
Next 'n' -> Look 'l'
Previous 'N' -> Look Back 'L'
There were also some changes for familiarity, 's'/'S' can be used to access command mode (the old location of the :, which still works).
Added Benefits
End of line '$' -also- '-'
Beginning of line '^' -also- '_'
Move up 8 'T'
Move down 8 'H'
Next window
```
<C-w><C-w>
```
-also- 'N'
Swap windows
```
<C-w><C-r>
```
-also- 'D'
-Adam


Question:
If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of draw().

How can I force myimg not to be cached?

<html>
  <head>
    <script type="text/javascript">
      function draw(){
        var canvas = document.getElementById('canv');
        var ctx = canvas.getContext('2d');
        var rx;
        var ry;
        var i;

        myimg = new Image();
        myimg.src = 'http://ohm:8080/cgi-bin/nextimg'

        rx=Math.floor(Math.random()*100)*10
        ry=Math.floor(Math.random()*100)*10
        ctx.drawImage(myimg,rx,ry);
        window.setTimeout('draw()',0);
      }
    </script>
  </head>
  <body onload="draw();">
    <canvas id="canv" width="1024" height="1024"></canvas>
  </body>
</html>

Answer:
The easiest way is to sling an ever-changing querystring onto the end:
```
```
var url = 'http://.../?' + escape(new Date())
```
```
Some people prefer using
```
Math.random()
```
for that instead of
```
escape(new Date())
```
. But the correct way is probably to alter the headers the web server sends to disallow caching.


Question:
From the MSDN article on STAThread:

Indicates that the COM threading model for an application is single-threaded apartment (STA).

(For reference, that's the entire article.)

Single-threaded apartment... OK, that went over my head. Also, I read somewhere that unless your application uses COM interop, this attribute actually does nothing at all. So what exactly does it do, and how does it affect multithreaded applications? Should multithreaded applications (which includes anything from anyone using Timers to asynchronous method calls, not just threadpools and the like) use MTAThread, even if it's 'just to be safe'? What does STAThread and MTAThread actually do?

Answer:
What that does it it ensures that
```
CoInitialize
```
is called specifying COINIT_APARTMENTTHREADED as the parameter. If you do not use any COM components or ActiveX controls it will have no effect on you at all. If you do then it's kind of crucial.
Controls that are apartment threaded are effectively single threaded, calls made to them can only be processed in the apartment that they were created in.
Some more detail from MSDN:
Objects created in a single-threaded
  apartment (STA) receive method calls
  only from their apartment's thread, so
  calls are serialized and arrive only
  at message-queue boundaries (when the
  Win32 function PeekMessage or
  SendMessage is called).
Objects created on a COM thread in a
  multithread apartment (MTA) must be
  able to receive method calls from
  other threads at any time. You would
  typically implement some form of
  concurrency control in a multithreaded
  object's code using Win32
  synchronization primitives such as
  critical sections, semaphores, or
  mutexes to help protect the object's
  data.
When an object that is configured to
  run in the neutral threaded apartment
  (NTA) is called by a thread that is in
  either an STA or the MTA, that thread
  transfers to the NTA. If this thread
  subsequently calls CoInitializeEx, the
  call fails and returns
  RPC_E_CHANGED_MODE.


Question:
I'm trying to produce just the day number in a WPF text block, without leading zeroes and without extra space padding (which throws off the layout). The first produces the day number with a space, the second produces the entire date. According to the docs, 'd' should produce the day (1-31).

string.Format("{0:d }", DateTime.Today);
string.Format("{0:d}", DateTime.Today);

UPDATE:Adding % is indeed the trick. Appropriate docs here.

Answer:
See
here
d, %d
The day of the month. Single-digit days do not have a leading zero. The application specifies "%d" if the format pattern is not combined with other format patterns.
Otherwise d is interpreted as:
d - 'ShortDatePattern'
PS. For messing around with format strings, using
LinqPad
is invaluable.


Question:
I am having fickle of problem in Oracle 9i

select 1"FirstColumn" from dual;

Oracle throwing error while executing above query. ORA-03001: unimplemented feature in my Production server.

The Same query is working fine in my Validation server. Both servers are with Oracle 9i

Any one have Idea what's wrong...? Is this something configurable item in Oracle server.

Answer: What is the full Oracle version on both servers?  9i is a marketing label-- are you comparing a 9.0.1.x database to a 9.2.0.x database?


Question:
I'm looking for a way to validate the SQL schema on a production DB after updating an application version. If the application does not match the DB schema version, there should be a way to warn the user and list the changes needed.

Is there a tool or a framework (to use programatically) with built-in features to do that?
Or is there some simple algorithm to run this comparison?

Update: Red gate lists "from $395". Anything free? Or more foolproof than just keeping the version number?

Answer:
Make a table and store your version number in there. Just make sure you update it as necessary.
```
```
CREATE TABLE version (
    version VARCHAR(255) NOT NULL
)
INSERT INTO version VALUES ('v1.0');
```
```
You can then check the version number stored in the database matches the application code during your app's setup or wherever is convenient.


Question:
I need help on this following aspx code

aspx Code:

<asp:Label ID ="lblName" runat ="server" Text ="Name"></asp:Label>
<asp:TextBox ID ="txtName" runat ="server"></asp:TextBox>

Consider this is my aspx page content. I am going to populate the values for the TextBox only after the postback from server. But the label is also posting to the server (runat="server") even though it's not necessary. Should I write my code like this to save time from server with less load.

Corrected Code:

<label id ="lblNames">Name</label>
<asp:TextBox ID ="txtName" runat ="server"></asp:TextBox>

Only my server control will send to the server for postback and not my HTML control which has a static value.

Please suggest whether this is the correct way of coding.

Answer:
If you take the
```
runat='server'
```
out of the
```
<label>
```
element then it won't be parsed as a server control. If you're not going to do anything with
```
lblNames
```
from the server then it is perfectly okay to leave it out.


Question:
I have a "span" element inside a "table" "td" element.  The span tag has a Title.

I want to get the title of that span tag and pull it out to make it the "mouseover" tip for the "td" element.

For example:

I want to turn this:

<td>
    <a href="#"><span id="test" title="Acres for each province">Acres</span></a>
</td>

Into this:

<td onmouseover="tip(Acres for each province)">
    <a href="#"><span id="test">Acres</span></a>
</td>

EDIT: I don't think you guys understand.  I am trying to put the onmouseover function into the "td" tag.  I am NOT trying to put it into the "span" tag.

Answer:
something like:
```
```
$("span#test").mouseover( function () {
   tip($(this).attr("title"));
}
```
```


Question: I have seen member functions programed both inside of the class they belong to and outside of the class with a function prototype inside of the class.  I have only ever programmed using the first method, but was wondering if it is better practice to use the other or just personal preference?

Answer:
Assuming you mean C++, it is always better to define functions
outside
of the class, because if you put it inside the class, compiler may try to inline it, which is not always desirable:
Increase in code size (every object file that includes this header might end up with a copy of the function in their code).
Breaking binary compatibility when function definition changes.
Even with inline functions, it is
usually
better to put definitions outside the class to improve readability of class public interface, unless the function is a trivial accessor or some other one-liner.


Question:
How can I detect mouse clicks regardless of the window the mouse is in?

Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.

I found this on microsoft's site:
http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx

But I don't see how I can detect or pick up the notifications listed.

Tried using pygame's pygame.mouse.get_pos() function as follows:

import pygame
pygame.init()
while True:
    print pygame.mouse.get_pos()

This just returns 0,0.
I'm not familiar with pygame, is something missing?

In anycase I'd prefer a method without the need to install a 3rd party module.
(other than pywin32 http://sourceforge.net/projects/pywin32/ )

Answer:
The windows way of doing it is to handle the
```
WM_LBUTTONDBLCLK
```
message.
For this to be sent, your window class needs to be created with the
```
CS_DBLCLKS
```
class style.
I'm afraid I don't know how to apply this in Python, but hopefully it might give you some hints.


Question:
So i have a piece of assembly that needs to call a function with the fastcall calling convention on windows, but gcc doesn't (afaict) support it.  GCC does provide the regparm attribute but that expects the first 3 parameters to be passed in eax, edx and ecx, whereas fastcall expects the first two parameters to be passed in ecx and edx.

I'm merely trying to avoid effectively duplicating a few code paths, so this isn't exactly critical, but it would be great if it were avoidable.

Answer:
If you're calling the function from asm then surely you have complete control over how you call the function. What's stopping you from just loading up the registers and issuing a
```
CALL
```
?


Question: I would like to ask if it is possible to show Generalization relationship in UML for a Domain Model although I understand I can do that in a Class Diagram? I did not see much examples of Domain Model displaying Generalization Relationship except in Class Diagram. If not possible, what is the best way to display that an Entity in a Domain Model is either a Entity A or Entity B or Entity C or Entity D etc ?

Answer:
You need to clarify why you're distinguishing between a domain model and a class diagram.
On the one hand, your domain model could simply be a class diagram of everything that could map to your database, and consume it. Hence a generalization relationship could simply depict implementation inheritance or interface inheritance.
On the other hand, your domain model could simply express how you expect your classes to work. In which case, it could be any of the standard UML diagrams: class, sequence, collaboration, component, activity, etc.
ADD: are you talking about finding different ways to categorize your persistent entities like a tagging system? Or you could make it possible to have a persistent entity have many nodes in a category tree?


Question:
I have Windows Vista MCML app, and I need to figure out the current name of the file playing.

The Media Center SDK alludes to using MediaMetadata["Title"] to get this information, unfortunately this does not work with playlists (.wpl) files as there is no method for getting the position in the playlist.

Answer:
Have you tried:
```
```
MediaContext.GetProperty(TrackTitle)
```
```
I've also seen samples that in the markup for the media display layout file they specify an element such as:
```
```
<music-title duration = "2000" x="69" y="29" width="187" height="20"/>
```
```
Good Luck!


Question:
I have a list of times in a database column (representing visits to a website).

I need to group them in intervals and then get a 'cumulative frequency' table of those dates.

For instance I might have:

9:01
9:04
9:11
9:13
9:22
9:24
9:28

and i want to convert that into

9:05 - 2
9:15 - 4
9:25 - 6
9:30 - 7

How can I do that? Can i even easily achieve this in SQL? I can quite easily do it in C#

Answer:
Create a table
```
periods
```
describing the periods you wish to divide the day up into.
```
```
SELECT periods.name, count(time)
  FROM periods, times
 WHERE period.start <= times.time
   AND                 times.time < period.end
 GROUP BY periods.name
```
```


Question:
I have a Flex app that does a a fair amount of network traffic, it uses ExternalInterface to make some javascript calls (for SCORM), it loads XML files, images, video, audio and it has a series of modules that it could be loading at some point...

So the problem is - we now have a requirement where the user needs to run this content locally on a machine that is not connected to the internet (which means they can't connect to Adobe's site to change their security settings.)  As you can imagine, when the user doubles clicks on the html page to launch this thing, they are greeted with a security warning that the swf is trying to communicate with another domain other than the one it's in.  We can't wrap it in an exe or an AIR app so I unless there is some way to tweak some obscure security settings we may be hosed.  Any idea's?

Answer:
Did you try to specify the authorized domain with:
```
```
System.security.allowDomain("www.yourdomain.com");
```
```


Question:
I was wondering if there was a way to get at the raw HTTP request data in PHP running on apache that doesn't involve using any additional extensions. I've seen the HTTP functions in the manual, but I don't have the option of installing an extension in my environment.

While I can access the information from $_SERVER, I would like to see the raw request exactly as it was sent to the server. PHP munges the header names to suit its own array key style, for eg. Some-Test-Header becomes HTTP_X_SOME_TEST_HEADER. This is not what I need.

Answer:
Do you mean the information contained in
```
$_SERVER
```
?
```
```
print_r($_SERVER);
```
```
Edit:
Would this do then?
```
```
foreach(getallheaders() as $key=>$value)  {
    print $key.': '.$value."<br />";
}
```
```


Question: Whenever I use the signal/slot editor dialog box, I have to choose from the existing list of slots. So the question is how do I create a custom named slot?

Answer:
Unfortunately this is not possible in Qt4.
In Qt3 you could create custom slots which where then implemented in the ui.h file. However, Qt4 does not use this file so custom slots are not supported.
There is some discussion of this issue over on
QtForum


Question: How can I display a calendar control (date picker) in Oracle forms 9/10?

Answer:
Unfortunately this is not possible in Qt4.
In Qt3 you could create custom slots which where then implemented in the ui.h file. However, Qt4 does not use this file so custom slots are not supported.
There is some discussion of this issue over on
QtForum


Question:
I need to add a tooltip/alt to a "td" element inside of my tables with jquery.

Can someone help me out?

I tried:

var tTip ="Hello world";
$(this).attr("onmouseover", tip(tTip));

where I have verified that I am using the "td" as "this".

**Edit:**I am able to capture the "td" element through using the "alert" command and it worked.  So for some reason the "tip" function doesn't work.  Anyone know why this would be?

Answer:
```
```
$(this).mouseover(function() {
    tip(tTip);
});
```
```
a better way might be to put
```
title
```
attributes in your HTML. That way, if someone has javascript turned off, they'll still get a tool tip (albeit not as pretty/flexible as you can do with jQuery).
```
```

            Cell 1
            Cell 2

```
```
and then use this code:
```
```
$('#myTable td[title]')
    .hover(function() {
        showTooltip($(this));
    }, function() {
        hideTooltip();
    })
;

function showTooltip($el) {
    // insert code here to position your tooltip element (which i'll call $tip)
    $tip.html($el.attr('title'));
}
function hideTooltip() {
    $tip.hide();
}
```
```


Question: How to use data mining feature of SQL Server 2008 with ASP.Net

Answer:
Take a look at
SqlServerDataMining.com
, a site run by Microsoft's SQL Server Data Mining team.


Question:
I need a function to return a suffix for days when displaying text like the "th" in "Wednesday June 5th, 2008".

It only need work for the numbers 1 through 31 (no error checking required) and English.

Answer:
The following function works for C:
```
```
char *makeDaySuffix (unsigned int day) {
    //if ((day < 1) || (day > 31)) return "";
    switch (day) {
        case 1: case 21: case 31: return "st";
        case 2: case 22:          return "nd";
        case 3: case 23:          return "rd";
    }
    return "th";
}
```
```
As requested, it only works for the numbers 1 through 31 inclusive. If you want (possibly, but not necessarily) raw speed, you could try:
```
```
char *makeDaySuffix (unsigned int day) {
    static const char * const suffix[] = {
        "st","nd","rd","th","th","th","th","th","th","th",
        "th","th","th","th","th","th","th","th","th","th"
        "st","nd","rd","th","th","th","th","th","th","th"
        "st"
    };
    //if ((day < 1) || (day > 31)) return "";
    return suffix[day-1];
}
```
```
You'll note that I have bounds checking in there though commented out. If there's even the
slightest
possibility that an unexpected value will be passed in, you'll probably want to uncomment those lines.
Just keep in mind that, with the compilers of today, naive assumptions about what is faster in a high-level language may not be correct:
measure, don't guess.


Question:
Could you please explain what the practical usage is for the internal keyword in C#?

I know that the internal modifier limits access to the current assembly, but when and in which circumstance should I use it?

Answer:
When you have classes or methods which don't fit cleanly into the Object-Oriented Paradigm, which do dangerous stuff, which need to be called from other classes and methods under your control, and which you don't want to let anyone else use.
```
```
public class DangerousClass {
    public void SafeMethod() { }
    internal void UpdateGlobalStateInSomeBizarreWay() { }
}
```
```


Question:
The end() function in jQuery reverts the element set back to what it was before the last destructive change, so I can see how it's supposed to be used, but I've seen some code examples, eg: on alistapart (which were probably from older versions of jQuery - the article is from 2006) which finished every statement off with .end(). eg:

$( 'form.cmxform' ).hide().end();

Does this have any effect?

Is it something I should also be doing?

What does the above code even return?

Answer:
That
```
end()
```
doesn't do anything. There's no point to coding like that. It will return
```
$('#myBox')
```
-- the example is pretty poor. More interesting is something like this:
```
```
$('#myBox').show ().children ('.myClass').hide ().end ().blink ();
```
```
Which will show
```
myBox
```
, hide the specified children, and then blink the box. There are more interesting examples here:
http://simonwillison.net/2007/Aug/15/jquery/
such as:
```
```
$('form#login')
    // hide all the labels inside the form with the 'optional' class
    .find('label.optional').hide().end()
    // add a red border to any password fields in the form
    .find('input:password').css('border', '1px solid red').end()
    // add a submit handler to the form
    .submit(function(){
        return confirm('Are you sure you want to submit?');
    });
```
```


Question:
It seems pretty common to want to let your javascript know a particular dom node corresponds to a record in the database.  So, how do you do it?

One way I've seen that's pretty common is to use a class for the type and an id for the id:

<div class="thing" id="5">
<script> myThing = select(".thing#5") </script>

There's a slight html standards issue with this though -- if you have more than one type of record on the page, you may end up duplicating IDs.  But that doesn't do anything bad, does it?

An alternative is to use data attributes:

<div data-thing-id="5">
<script> myThing = select("[data-thing-id=5]") </script>

This gets around the duplicate IDs problem, but it does mean you have to deal with attributes instead of IDs, which is sometimes more difficult.  What do you guys think?

Answer:
```
```
<div class="thing" id="myapp-thing-5"/>

// Get thing on the page for a particular ID
var myThing = select("#myapp-thing-5");

// Get ID for the first thing on the page
var thing_id = /myapp-thing-(\d+)/.exec ($('.thing')[0].id)[1];
```
```


Question:
I have a question about locking. This doesn't have to be only about record locking, but anyway.

Let's say I'm writing a web accessible CMS. I am struggling with some ideas.

I could, on the moment when a user opens an article for editing, flag the article as being 'in use'. so far so good.

but when do I remove the flag? when the user saves the article? but what if the user doesn't feel like typing anymore and decides to close his browser and go to bed?

a time-out mechanism comes to mind, but how long does it take to write an article? 10 minutes too short, 30 minutes too long..

Maybe I am over-complicating this. I'd like to hear your thoughts on this subject.

Answer:
My vote is for
optimistic locking
wherever possible.
In one place, where I have implemented actual locks, I had an admin page to remove locks. There was also a service running on the server to unlock any locks which did not have a corresponding active session..


Question:
I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than ROT13 or Base64.

I'd prefer something that is already included in the .NET framework 2.0, so I don't have to worry about any external dependencies.

I really don't want to have to mess around with public/private keys, etc. I don't know much about encryption, but I do know enough to know that anything I wrote would be less than worthless... In fact, I'd probably screw up the math and make it trivial to crack.

Answer:
The namespace
```
System.Security.Cryptography
```
contains the
```
TripleDESCryptoServiceProvider
```
and
```
RijndaelManaged
```
classes
Don't forget to add a reference to the
```
System.Security
```
assembly.


Question:
I want to do some benchmarking of a C# process, but I don't want to use time as my vector - I want to count the number of IL instructions that get executed in a particular method call. Is this possible?

Edit I don't mean static analysis of a method body - I'm referring to the actual number of instructions that are executed - so if, for example, the method body includes a loop, the count would be increased by however many instructions make up the loop * the number of times the loop is iterated.

Answer:
Well, it won't be easy.   I
think
you could instrument your assembly post-compile with performance counter code that executed after blocks of IL.  For example, if you had a section of a method that loaded an int onto the stack then executed a static method using that int under optimized code, you could record a count of 2 for the int load and call.
Even using existing IL/managed assembly reading/writing projects, this would be a pretty daunting task to pull off.
Of course, some instructions that your counter recorded might get optimized away during just-in-time compiling to x86/ia64/x64, but that is a risk you'd have to take to try to profile based on an abstract lanaguage like IL.


Question:
What are opinions on the design of a "performance assertion checking" system?

The idea is that a developer makes some assertions about his/her code and use these to test the evolution of the performance of the code. What is the experience with such a system?

My current block is "What's a better way to translate these assertions, written in a specified language (that are to be checked against specified logs or runtime instrumentation) into, say, CLR, or assembly or bytecode that could be executed?"

Currently I have written a parser that parses the specification and holds it in a data structure.

Answer:
Do we embed performance checks in our application?  No.  The reason is that the performance checks themselves take time and our application is very sensitive to performance.
Instead, we make our performance checks a test.  And for that we use NUnit.  For our nightly builds, we run the test, we generate a log with detailed timing data as well as a pass/fail indication given our requirements.  Since we keep our logs around for some time -- forever for beta and production releases -- we can track performance over time as well.


Question:
How do you go about doing a daily build and striving for a zero-defect environment? Does it mean I never get to go home until I've killed all the bugs in my new code? Or does it mean I just don't check my code back in until I've fully tested it, which leaves the code effectively branched for a much longer time?

I'm working with a handful of programmers for the first time (as opposed to working on my own, or with just one other coder), so I'm just wrestling with decisions like this for the first time. Should we adopt a software development process?

Answer:
Simple: Never check in code with
(known)
bugs in it. This doesn't mean you check in once per day. Check in when you have a meaningful change implemented so the other developers can get access to it.
We always integrate locally, run our tests against the code, and when all passes, we check in.  I check in about 20-30 times a day when working.  The build server picks up changes and it runs builds against the system. Continous Integration (CI) is a good thing. :D
Continuous Integration - Automate Your Builds
Start out with building successfully and keep it that way as much as possible. It is essential in a team environment. Just remember that builds will break. It's expected that they break every once in awhile. It is a sign that you just inadvertently checked in something bad, and you stop what you are doing to make the build green again. A build server that never has broken builds is a warning sign!
I also agree with chadmyers' answer: Whatever you decide, it needs to be automatic and automated. The best thing about automating tools to do this kind of stuff for you is that you no longer have to think about it or remember to do it. Or like Chad said, you don't stop doing it.
I could recommend make a recommendation for CI tools but have a look here:
What tools do you use for Automated Builds / Automated Deployments? Why?
Once you have CI, you can get higher quality if you can inject some humor (and shame) by introducing a broken build token!
http://ferventcoder.com/archive/2008/08/20/continuous-integration-enhancement--the-broken-build-token.aspx
Use a Good Tool for Automated Builds
Most people in .NET land use NAnt or MSBuild scripts to have automated builds that they can later hook up to their CI server. If you are just starting out, my suggestion would be to use
UppercuT
, it is an insanely easy to use build framework that uses NAnt. Here is a second link with deeper explanations:
UppercuT
.
Branches vs Trunk for Active Development
You would not have to branch unless you leave trunk open only for releases (which means that everyone else is working in the same branch as you). But I would have CI on both the trunk and the active development branch.
Software Development Process
Also to answer the question on a software development process, the answer is a resounding yes. But don't rush into anything unless a drastic change is required. Pick a process you want to migrate towards and slowly start adopting processes. And evaluate, evaluate, evaluate. If the particular process is not working for your group, figure out if you are doing something wrong or if you just need to eliminate it.  And then do. Whatever process you end up with needs to work for you or it won't work.


Question:
Many of the questions asked here are relevant to research I'm doing. These questions and answers are widely dispersed and not always easy to find, doing manual browsing, and sometimes an insightful answer or comment occurs in unrelated topics as well.

I want to automate finding these relevant Q's & A's, based on sets of keywords, then use the information as pointers towards further in-depth research.

What tools, preferably open-source, are available that I can use for this type of site-mining? I am not a web guru & for me to try to develop them will take a long time and also impact on time I could have spent on my R&D.

Answer:
Human interaction tools might be useful in such case (no development cost, probably a more consistent outcome, and evolving requirements).
Couple comes to mind:
Mechanical Turk
.
Time Svr
(more expensive) -
experiment/review
.


Question:
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like obj.attr ? Or perhaps write get accessors ?
What are the accepted naming styles for such things ?

Edit:
Can you elaborate on the best-practices of naming attributes with a single or double leading underscore ? I see in most modules that a single underscore is used.

If this question has already been asked (and I have a hunch it has, though searching didn't bring results), please point to it - and I will close this one.

Answer:
I think most just access them directly, no need for get/set methods.
```
```
>>> class myclass:
...     x = 'hello'
...
>>>
>>> class_inst = myclass()
>>> class_inst.x
'hello'
>>> class_inst.x = 'world'
>>> class_inst.x
'world'
```
```
BTW, you can use the dir() function to see what attributes/methods are attached to your instance:
```
```
>>> dir(class_inst)
['__doc__', '__module__', 'x']
```
```
Two leading underbars, "__" are used to make a attribute or function private.
For other conventions refer to PEP 08:
http://www.python.org/dev/peps/pep-0008/


Question: Is there a way to step through a .bat script? The thing is, I have a build script , which calls a lot of other scripts, and I would like to see what is the order in which they are called, so that I may know where exactly I have to go about and add my modifications.

Answer:
The only way I can think of is spinkle the code with
```
echo
```
s and
```
pause
```
s.


Question: I have a windows mobile 5.0 app, written in C++ MFC, with lots of dialogs.  One of the devices I'm currently targetting does not have a tab key, so I would like to use another key to move between controls.  This is fine for buttons but not edit controls or combo boxes.  I have looked at a similar question but the answer does not really suit.  I've tried overriding the CDialog::OnKeyDown to no avail, and would rather not have to override the keystroke functionality for every control in every dialog.  My thoughts so far are to write new classes replacing CEdit and CComboBox, but as always am just checking if there is an easier way, such as temporarily re-programming another key.

Answer:
I don't know MFC
that good
, but maybe you could pull it off by subclassing window procedures of all those controls with a single class, which would only handle cases of pressing cursor keys and pass the rest of events to the original procedures.
You would have to provide your own mechanism of moving to an appropriate control, depending on which cursor key was pressed but it may be worth the usability gains.
If that worked, you could enumerate all dialog controls and subclass them automatically.
Windows Mobile 6 allows switching between dialog controls using cursors by default - it's a new, more "smartphoney" way of moving around the UI and it's incredibly convenient.


Question: What is meant by ‘value semantics’, and what is meant by ‘implicit pointer semantics’?

Answer:
Java is using implicit pointer semantics for Object types and value semantics for primitives.
Value semantics means that you deal directly with values and that you pass copies around.
The point here is that when you have a value, you can trust it won't change behind your back.
With pointer semantics, you don't have a value, you have an 'address'.
Someone else could alter what is there, you can't know.
Pointer Semantics in C++ :
```
```
void foo(Bar * b) ...
... b->bar() ...
```
```
You need an * to ask for pointer semantics and -> to call methods on the pointee.
Implicit Pointer Semantics in Java :
```
```
void foo(Bar b) ...
... b.bar() ...
```
```
Since you don't have the choice of using value semantics, the * isn't needed nor the distinction between -> and ., hence the implicit.


Question: So most Java resources when speaking of packages mention a com.yourcompany.project setup. However, I do not work for a company, and don't have a website. Are there any naming conventions that are common? An email address, perhaps?

Answer:
Use a top-level domain like 'bernard' or something else unique.   The important part is that the domain is unique so that you avoid clashes, and not that it starts with a real Internet top-level domain like org or com.   E.g.
```
```
import java.util.*;
import bernard.myProject.*;
import org.apache.commons.lang.*;
```
```


Question:
I have the following preprocessor divective:

#ifndef NDEBUG
#define TRACE printf
#else
#define TRACE(...)
#endif

and example of usage is:

TRACE("TRACE: some parameter = %i\n", param);

In C all works perfectly well when I build both debug and release versions, but in C++ compiler emits the following:

warning: invalid character in macro parameter name

error: badly punctuated parameter list in `#define'

and points these warning and error to the 'TRACE(...)' directive.

How to write this in C++ correctly?

Answer:
You could do:
```
```
inline void TRACE(...) {}
```
```


Question: What's the best available online resource.

Answer:
I have only played with the Mobile Framework briefly but a good start would be
Windows Mobile Developer Center
Also it is worth looking at some example open source projects on
CodePlex
.
Microsoft on every training event is encouraging people to use it, and from my experience you can find some interesting projects there at least in standard .Net. I suppose the same applies to Mobile


Question:
I'm interested: What is C#'s analog of std::pair in C++? I found System.Web.UI.Pair class, but I'd prefer something template-based.

Thank you!

Answer:
Tuples
are available since .NET4.0
and support generics:
```
```
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
```
```
In previous versions you can use
```
System.Collections.Generic.KeyValuePair<K, V>
```
or a solution like the following:
```
```
public class Pair<T, U> {
    public Pair() {
    }

    public Pair(T first, U second) {
        this.First = first;
        this.Second = second;
    }

    public T First { get; set; }
    public U Second { get; set; }
};
```
```
And use it like this:
```
```
Pair<String, int> pair = new Pair<String, int>("test", 2);
Console.WriteLine(pair.First);
Console.WriteLine(pair.Second);
```
```
This outputs:
```
```
test
2
```
```
Or even this chained pairs:
```
```
Pair<Pair<String, int>, bool> pair = new Pair<Pair<String, int>, bool>();
pair.First = new Pair<String, int>();
pair.First.First = "test";
pair.First.Second = 12;
pair.Second = true;

Console.WriteLine(pair.First.First);
Console.WriteLine(pair.First.Second);
Console.WriteLine(pair.Second);
```
```
That outputs:
```
```
test
12
true
```
```


Question:
Starting new .NET projects always involves a bit of work. You have to create the solution, add projects for different tiers (Domain, DAL, Web, Test), set up references, solution structure, copy javascript files, css templates and master pages etc etc.

What I'd like is an easy way of cloning any given solution.

If you use copy/paste, the problem is that you need to then go through renaming namespaces, assembly names, solution names, GUIDs etc.

Is there a way of automating this?

Something like this would be great:

solutionclone.exe --solution=c:\code\abc\template.sln --to=c:\code\xyz --newname=MySolution

I'm aware that Visual Studio has project templates, but I've not seen solution templates.

Answer:
As you already found out: Copy the .sln File and make sure the paths/guids match.
Because the .sln are
```
text/plain
```
just use your favourite scripting language to script a cloner.
Maybe this is a good time to learn Python/Ruby/Perl/
Windows Script Host
MSDN Solution (.sln) File Definition


Question:
If I want to call Bar() instead of Foo(), does Bar() return me a copy (additional overhead) of what Foo() returns, or it returns the same object which Foo() places on the temporary stack?

vector<int> Foo(){
    vector<int> result;
    result.push_back(1);
    return result;
}
vector<int> Bar(){
    return Foo();
}

Answer:
Normally it returns a copy of the returned
```
vector<int>
```
. However this highly depends on the optimization done by the compiler. See the following discussion.
Debug Build
```
```
vector<int> Foo(){
004118D0  push        ebp
004118D1  mov         ebp,esp
004118D3  push        0FFFFFFFFh
004118D5  push        offset __ehhandler$?Foo@@YA?AV?$vector@HV?$allocator@H@std@@@std@@XZ (419207h)
004118DA  mov         eax,dword ptr fs:[00000000h]
004118E0  push        eax
004118E1  sub         esp,0F4h
004118E7  push        ebx
004118E8  push        esi
004118E9  push        edi
004118EA  lea         edi,[ebp-100h]
004118F0  mov         ecx,3Dh
004118F5  mov         eax,0CCCCCCCCh
004118FA  rep stos    dword ptr es:[edi]
004118FC  mov         eax,dword ptr [___security_cookie (41E098h)]
00411901  xor         eax,ebp
00411903  push        eax
00411904  lea         eax,[ebp-0Ch]
00411907  mov         dword ptr fs:[00000000h],eax
0041190D  mov         dword ptr [ebp-0F0h],0
    vector<int> result;
00411917  lea         ecx,[ebp-24h]
0041191A  call        std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (411050h)
0041191F  mov         dword ptr [ebp-4],1
    result.push_back(1);
00411926  mov         dword ptr [ebp-0FCh],1
00411930  lea         eax,[ebp-0FCh]
00411936  push        eax
00411937  lea         ecx,[ebp-24h]
0041193A  call        std::vector<int,std::allocator<int> >::push_back (41144Ch)
    return result;
0041193F  lea         eax,[ebp-24h]
00411942  push        eax
00411943  mov         ecx,dword ptr [ebp+8]
00411946  call        std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (41104Bh)
0041194B  mov         ecx,dword ptr [ebp-0F0h]
00411951  or          ecx,1
00411954  mov         dword ptr [ebp-0F0h],ecx
0041195A  mov         byte ptr [ebp-4],0
0041195E  lea         ecx,[ebp-24h]
00411961  call        std::vector<int,std::allocator<int> >::~vector<int,std::allocator<int> > (411415h)
00411966  mov         eax,dword ptr [ebp+8]
}
```
```
Here we can see that for
```
vector<int> result;
```
a new object is created on the stack at
```
[ebp-24h]
```
```
```
00411917  lea         ecx,[ebp-24h]
0041191A  call        std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (411050h)
```
```
When we get to
```
return result;
```
a new copy is created in storage allocated by the caller at
```
[ebp+8]
```
```
```
00411943  mov         ecx,dword ptr [ebp+8]
00411946  call        std::vector<int,std::allocator<int> >::vector<int,std::allocator<int> > (41104Bh)
```
```
And the destructor is called for the local parameter
```
vector<int> result
```
at
```
[ebp-24h]
```
```
```
0041195E  lea         ecx,[ebp-24h]
00411961  call        std::vector<int,std::allocator<int> >::~vector<int,std::allocator<int> > (411415h)
```
```
Release Build
```
```
vector<int> Foo(){
00401110  push        0FFFFFFFFh
00401112  push        offset __ehhandler$?Foo@@YA?AV?$vector@HV?$allocator@H@std@@@std@@XZ (401F89h)
00401117  mov         eax,dword ptr fs:[00000000h]
0040111D  push        eax
0040111E  sub         esp,14h
00401121  push        esi
00401122  mov         eax,dword ptr [___security_cookie (403018h)]
00401127  xor         eax,esp
00401129  push        eax
0040112A  lea         eax,[esp+1Ch]
0040112E  mov         dword ptr fs:[00000000h],eax
00401134  mov         esi,dword ptr [esp+2Ch]
00401138  xor         eax,eax
0040113A  mov         dword ptr [esp+8],eax
    vector<int> result;
0040113E  mov         dword ptr [esi+4],eax
00401141  mov         dword ptr [esi+8],eax
00401144  mov         dword ptr [esi+0Ch],eax
    result.push_back(1);
    return result;
00401147  push        eax
00401148  mov         dword ptr [esp+28h],eax
0040114C  mov         ecx,1
00401151  push        esi
00401152  lea         eax,[esp+14h]
00401156  mov         dword ptr [esp+10h],ecx
0040115A  mov         dword ptr [esp+14h],ecx
0040115E  push        eax
0040115F  lea         ecx,[esp+1Ch]
00401163  push        ecx
00401164  mov         eax,esi
00401166  call        std::vector<int,std::allocator<int> >::insert (401200h)
0040116B  mov         eax,esi
}
0040116D  mov         ecx,dword ptr [esp+1Ch]
00401171  mov         dword ptr fs:[0],ecx
00401178  pop         ecx
00401179  pop         esi
0040117A  add         esp,20h
0040117D  ret
```
```
The line
```
vector<int> result
```
does not call the vector allocator because it is done at call site in
```
Bar
```
. The optimization makes no copy of the result from Foo.


Question:
How can I scale the content of an iframe (in my example it is an HTML page, and is not a popup) in a page of my web site?

For example, I want to display the content that appears in the iframe at 80% of the original size.

Answer:
I do not think HTML has such functionality. The only thing I can imagine would do the trick is to do some server-side processing. Perhaps you could get an image snapshot of the webpage you want to serve, scale it on the server and serve it to the client. This would be a non-interactive page however. (maybe an imagemap could have the link, but still.)
Another idea would be to have a server-side component that would alter the HTML. SOrt of like the firefox 2.0 zoom feature. this of course is not perfect zooming, but is better than nothing.
Other than that, I am out of ideas.


Question:
I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?

Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).

I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.

Answer:
There are various ways. You can put a try..catch block in the wxApplication::OnInit, however, that would not always work with Gtk.
A nice alternative would be to override the Application::HandleEvent in your wxApplication derived class, and write a code like this:
```
```
void Application::HandleEvent(wxEvtHandler* handler, wxEventFunction func, wxEvent& event) const
{
    try
    {
        wxAppConsole::HandleEvent(handler, func, event);
    }
    catch (const std::exception& e)
    {
        wxMessageBox(std2wx(e.what()), _("Unhandled Error"),
            wxOK | wxICON_ERROR, wxGetTopLevelParent(wxGetActiveWindow()));
    }
}
```
```
It's a C++ example, but you can surely translate to Python easily.


Question:
I'll regularly get an extract from a DB/2 database with dates and timestaps formatted like this:

2002-01-15-00.00.00.000000
2008-01-05-12.36.05.190000
9999-12-31-24.00.00.000000

Is there an easier way to convert this into the Excel date format than decomposing with substrings?

DB2date = DateValue(Left(a, 4) + "/" + Mid(a, 6, 2) + "/" + Mid(a, 9, 2))

thanks for your help!

Answer:
I'm sure you could cook something up with Regex's if you really cared to. It wouldn't be any 'better' though, probably worse.
If you'll forgive a bit of C# (I havn't touched VB in years, so I don't know the function calls anymore) you could also do:
```
```
DB2string = "2002-01-15-00.00.00.000000";
DB2date = DateValue(DB2string.SubString(0, 10).Replace('-', '/'));
```
```
But again, you're not really gaining anything. Can you give an example of where your current code would break?


Question:
I might be an exception here but I have never worked on a team with more than three developers and / or five people. Still we could manage to get the job done (somehow).

Is there a software development process which fits this "extreme" scenario? And, if you work as a standalone programmer is there something you can adapt to your daily life to make it more predicatable, coherent, documented and still get the job done?

Answer:
The
agile methodologies
are a good starting point because, imho, they are better suited for small groups.
As for keeping your personal working pace I'd recommend a method based on TODO lists and some tool like
Task2Gather
. You might want to look at
GTD
, too.
Things I would never give up even for a team of me:
source version control
backups
TODO
unit testing/
TDD
code documentation
refactoring/code reviews


Question:
Tcl/Tk is a simple way to script small GUIs.

Can anyone give a nice example with a button and a text widget. When the button is pressed should a shell command be executed and the output piped to the text widget.

If you have other nice and clean examples for useful tasks, please add them too.

Answer:
I can give a start...please suggest improvements. I.e I'd like it to scroll as the command is outputting
```
```
#!/usr/bin/wish

proc push_button {} {
    put_text
    .main see end
}

proc put_text {} {
  set f [ open "| date" r]
  while {[gets $f x] >= 0} {
    .main insert end "$x\n"
  }
  catch {close $f}
}

button .but -text "Push Me" -command "push_button"
text .main -relief sunken -bd 2 -yscrollcommand ".scroll set"
scrollbar .scroll -command ".main yview"

pack .but
pack .main -side left -fill y
pack .scroll -side right -fill y
```
```