Question:
At the moment, I have some functions which look like this:

private bool inFunction1 = false;
public void function1()
{
    if (inFunction1) return;
    inFunction1 = true;

    // do stuff which might cause function1 to get called
    ...

    inFunction1 = false;
}

I'd like to be able to declare them like this:

[NoReEntry]
public void function1()
{
    // do stuff which might cause function1 to get called
    ...
}

Is there an attribute I can add to a function to prevent reentry?  If not, how would I go about making one?  I've heard about AOP attributes that can be used to add code before and after function calls; would they be suitable?

Answer:
There is no such attribute predefined. You can make new attributes, but that won't help you. The issue is making the custom attribute prevent the method being called again, which I don't think is doable.
The lock statement is not what you want, since that will cause calls to block and wait, not return immediately.
PS: use a try ... finally block in the above sample. Otherwise, if an exception is thrown in the middle of the function, inFunction1 will be left true and all calls will return immediately.
e.g. :
```
```
if (inFunction1)
   return;

try
{
  inFunction1 = true;

  // do stuff which might cause function1 to get called
  ...
}
finally
{
  inFunction1 = false;
}
```
```


Question:
I have a Java Swing application, developed on Mac OS X 10.5 using Java 1.5.

I'm trying to make a custom cursor appear when the user moves the mouse over some text in a dialog. The cursor never changes, though.

When I don't use a JFrame instead of a JDialog, the cursor does change. But then I'll have to write all the dialog code myself.

How can I get the cursor to appear?

Here's the simplest code I could create to demonstrate the problem:

import javax.swing.*;
import java.awt.*;

public class CursorTest {

    public static void main(String[] args) {
        JLabel label = new JLabel("Move mouse here for hand cursor");
        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        JOptionPane pane = new JOptionPane(label);
        pane.setOptions(new Object[]{"OK"});

        JDialog dialog = pane.createDialog(null, "Test Dialog");
        dialog.setVisible(true);
    }
}

Answer:
Looks like it is a bug in Java 1.5: I first tried with Java 1.6.0_07 and it worked as expected (on Windows XP). Then I recompiled with Java 1.5.0_06 and indeed the cursor remains in default state.
Knowing the difficulties of Java 1.6 on MacOS, I see it will be hard to fix that...
Bug ID: 5079694 JDialog doesn't respect setCursor
They give a workaround...
[EDIT] Tested workaround:
```
```
public class CursorTest extends JFrame
{
  private CursorTest()
  {
  }

  private void ShowDialog()
  {
        JLabel label = new JLabel("Move mouse here for hand cursor");
        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        JOptionPane pane = new JOptionPane(label);
        pane.setOptions(new Object[] { "OK" } );

        JDialog dialog = pane.createDialog(this, "Test Dialog");
        dialog.setVisible(true);
  }

  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new Runnable()
    {
      public void run()
      {
        CursorTest testFrame = new CursorTest();
        testFrame.setTitle("Test GUI");
        testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        testFrame.setSize(500, 300);
        testFrame.setVisible(true);
        testFrame.ShowDialog();
      }
    });
  }
}
```
```
Works fine with my JDK & system.


Question:
I've got a 1-based array of four items which I need to traverse. For a given index in the array, I need to work out the index of the next item, and the index of the previous item. This sounds simple but the array needs to wrap around. So when you are at the beginning of the array, the previous item is considered to be the last item. Likewise, if you are at the end of the array, the next item is considered to be the first item.

I realise this can be solved by using conditional statements, but I wondered if it was possible to do it using mathematical equations. I've got one that works nicely for the next item

NextItem = Modulus(CurrentItem, 4) + 1

(the modulus function returns the remainder of one number divided by another).

Has anyone got any ideas as to how I can work out the previous item?

Answer:
Since modulo always works better on 0-based ranges, you can turn it into one of these using
```
CurrentItem - 1
```
.
Then, with modulo 4, adding 3 is the same as subtracting 1 but has the advantage of never going negative (some modulo operators may not like negatives).
Then you once again add 1 to get back to a 1-based number.
This gives:
```
```
PrevItem = Modulus(CurrentItem - 1 + 3, 4) + 1
```
```
or, simplified:
```
```
PrevItem = Modulus(CurrentItem + 2, 4) + 1
```
```


Question:
class Score
{
    var $score;
    var $name;
    var $dept;
    var $date;

    function Score($score, $name, $dept, $date)
    {
        $this->scores = ($score);
        $this->name = ($name);
        $this->dept = ($dept);
        $this->date = ($date);
    }

    function return_score(){
        return $this->scores;
        return $this->name;
        return $this->dept;
        return $this->date;
    }
}

$newscore = new Score("131313","James", "Marketing", "19/05/2008");
echo $newscore->return_score();

The above code is only echoing 131313. I am just beginning to learn OO PHP so please go easy! Totally lost, so any help would be much appreciated.

Answer:
You can only return one value in each function or method.
In your situation, you should have a method for each of the class members:
```
```
public function getScore() {
   return $this->score;
}

public function getName() {
   return $this->name;
}

public function getDept() {
   return $this->dept;
}

public function getDate() {
   return $this->date;
}
```
```
Edit after the comments:
You could also need a method that returns all the members as a single string:
```
```
public function getAll() {
   return $this->getScore(). " " .$this->getName() . " " .$this->getDept(). " " .$this->getDate();
}
```
```


Question:
I am working in a project where there are configuration files, one in number for each of the environments where the application would be deployed.

When a developer modifies one of these files, the developer should not be allowed to check-in the file individually, but check-in all the files together or at least the developer should be informed that this needs to be done.

How can we achieve it?

Answer:
I would think you could write a pre-commit hook to do this - just have a list of files where if one is committed then they must all be committed.
You can write hooks in any language that you can write a command-line application in.  The only gotcha is that they run in the context of the SVN server, and (at least traditionally, I don't know if this is improved), they aren't given much environment when they start - you can be caught out by a lack of 'PATH' for example.
Your repository will have example batchfile/shell-script hooks in the 'hooks' directory, but I've also written them in C# in the past.
This
http://wordaligned.org/articles/a-subversion-pre-commit-hook
looks like a good general introduction to pre-commit hooks.


Question:
I'm currently using the following SQL for retrieving the last seven days worth of entries from a table:

purchased >= date_sub(now() ,interval 7 day)

However, I need to change this so it retrieves the last full weeks worth of entries (midnight Saturday to midnight Saturday). So basically, throughout the week the results never change, but when someone visits on Sunday morning they will have refreshed.

I just can't get my head around how to work out the days etc. Also, are there built in MySQL functions for doing this?

I hope I've explained that clearly enough.
This is in a PHP application.

Answer:
MySQL has a
WEEK()
function, that allows you to get the numeric week of the year from a date.  You can get (the week of today) -1, and compare that to the week of your records you are filtering on.


Question:
I want to convert a std::string to lowercase. I am aware of the function tolower(). However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a std::string would require iterating over each character.

Is there an alternative which works 100% of the time?

Answer:
Boost provides a string algorithm for this
:
```
```
#include <boost/algorithm/string.hpp>

std::string str = "HELLO, WORLD!";
boost::algorithm::to_lower(str); // modifies str
```
```
Or, for non-in-place
:
```
```
#include <boost/algorithm/string.hpp>

const std::string str = "HELLO, WORLD!";
const std::string lower_str = boost::algorithm::to_lower_copy(str);
```
```


Question:
I have been given a .Hive file from a registry which i have to parse and use the contents as part of a html report(from this i assume i have to convert to text somehow). The whole thing must be done within the program so i cant just convert the hive file and then run it through my program. I currently have no idea how to even start this so any help on this would be great.

Any ideas would be fantastic!

Answer:
Without seeing the input, it is hard to tell what the best approach is.  You are probably going to need to use the RegExp class to parse out your keys and values.  If you can get clean enough paths to the values, you might be able to get away with string.Split() to split the path into arrays of keys and walk the registry using those values.
Does the input set include the type of values, or can you assume that the values already exist in the registry?
A little more information on the input set would be useful.  An example, possibly?


Question:
When I am single stepping through one thread of a multi threaded program, the debugger gets interrupted with:

0x(some hex ref) : tdb_event_death      : ret
dbx: thread has exited -- next aborted

My guess is a thread somewhere in the program I am debugging has stopped, but it's not the one I'm debugging so I can't see why I have to restart the debugging process to continue.

I have a work around,  I set a breakpoint on the next line then rerun, which works but is very annoying, it is really slowing down my debugging. Does anyone know a better way ?  (single step ALL threads for example)

Answer:
Without seeing the input, it is hard to tell what the best approach is.  You are probably going to need to use the RegExp class to parse out your keys and values.  If you can get clean enough paths to the values, you might be able to get away with string.Split() to split the path into arrays of keys and walk the registry using those values.
Does the input set include the type of values, or can you assume that the values already exist in the registry?
A little more information on the input set would be useful.  An example, possibly?


Question:
This is a contrived example, but lets say I have declared objects:

CustomObj fooObj;
CustomObj barObj;
CustomObj bazObj;

And I have an string array:

string[] stringarray = new string[] {"foo","bar","baz"};

How can I programmatically access and instantiate those objects using the string array, iterating using something like a foreach:

foreach (string i in stringarray) {
    `i`Obj = new CustomObj(i);
}

Hope the idea I'm trying to get across is clear. Is this possible in C#?

Answer:
You need to be clear in your mind about the difference between an object and a variable. Objects themselves don't have names. Variable names are decided at compile-time. You can't access variables via an execution-time-determined name except via reflection.
It sounds like you
really
just want a
```
Dictionary<string, CustomObj>
```
:
```
```
Dictionary<string, CustomObj> map = new Dictionary<string, CustomObj>();

foreach (string name in stringArray)
{
    map[name] = new CustomObj(name);
}
```
```
You can then access the objects using the indexer to the dictionary.
If you're really trying to set the values of variables based on their name at execution time, you'll have to use reflection (see
Type.GetField
). Note that this won't work for local variables.


Question:
I have a function which searches an STL container then returns the iterator when it finds the position, however I am getting some funny error messages, can tell me what I am doing wrong?

Function:

std::vector< CClass >::iterator CClass::SearchFunction( const std::string& strField )
{
...

   return it;

...
}

Error:

error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'std::_Vector_const_iterator<_Ty,_Alloc> *__w64 ' to 'const std::_Vector_iterator<_Ty,_Alloc> &'

Answer:
Your search function is returning a const_iterator. You should either return the same type, i.e.
```
std::vector< CClass >::const_iterator
```
, or cast it to a
```
std::vector< CClass >::iterator
```
if you intend the caller to be able to modify the found item through the iterator.
EDIT: after seeing your update, it seems the problem is your iterator (it) has a different type than your function return. They should be the same.
```
```
std::vector< CClass >::iterator it;
```
```


Question:
My understanding is that you have to write unit tests that isolate functionality. So given a repository class that has this method:

Entity GetById(Guid id)

and a fake implementation (using a Dictionary for storage), how would you write a test without first adding an entity? Is it ok to use a known set of guids for testing? Then in the fake repository constructor I could fill the dictionary with a couple of entities where the guids follow a pattern, so that I can test the GetById() method with a guid that I know will return an entity.

Thanks for reading!

PS. This is my first time writing unit tests.

Answer:
Yes, you could use known test ids in your test - that is what I would do.  Although I have become a fan of
Rhino Mocks
which lets you put more directly in the test about what you'd expect to the mock object to do.
For example just before your call to the repository, you would do this:
```
```
Expect.Call(repository.GetById("someObject")).Return(new RepositoryThing());
```
```
It appeals to me anyway :)


Question: Windows Programming: How to put a file that is frequently accessed in the OS cache?

Answer:
Disclaimer : I dont work all that much under Windows
In the general case, you shouldnt mess with your OS cache. It should be smart enough to cache data that are accessed often. If it isnt, you should use an application level cache. I dont know which language you are using, but most probably there is a good cache framework for your language.


Question:
I know there is some similar issue.

But, still the question is not answered! I need to modify the connection string not add a new one.

Answer:
This will help you out!
```
```
/// <summary>
        /// Add a connection string to the connection
        /// strings section and store it in the
        /// configuration file.
        /// </summary>
        /// <param name="csName">The name of the property.</param>
        /// <param name="connectionString">The connectionstring as specified.</param>
        public static void AddConnectionStrings(string csName, string connectionString)
        {

            // Get the configuration file.
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            // Add the connection string.
            ConnectionStringsSection csSection = config.ConnectionStrings;
            csSection.ConnectionStrings.Add(
                new ConnectionStringSettings(csName,
                    connectionString, "System.Data.SqlClient"));

            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Full);
        }
```
```
Well for updating it was hard to find any usefull
code to update a connectionstring. It wasn't possible
to update a connectionstring, so I had the remove the
connectionstring, and add a new one. Well isn't that odd??
Microsoft left something undone... Well maybe it isn't usefull
to change your app.config, but well, I had to make it anyhow.
So dynamic app.config or web.config files is little bit strange, because you can't dynamically update it. No you have to remove it first by the configurationmanager.
```
```
/// <summary>
        /// First remove the old connectionstring and after that
        /// add a connection string to the connectionstrings
        /// section and store it in the configuration file.
        /// </summary>
        /// <param name="csName">The name of the property.</param>
        /// <param name="connectionString">The connectionstring as specified.</param>
        public static void UpdateConnectionStrings(string csName, string connectionString)
        {
            // Get the configuration file
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

            // Remove the existing connectionstring.
            config.ConnectionStrings.ConnectionStrings.Remove(csName);
            // Add the connectionstring
            ConnectionStringsSection csSection = config.ConnectionStrings;
            csSection.ConnectionStrings.Add(
                new ConnectionStringSettings(csName,
                connectionString, "System.Data.SqlClient"));

            // Save the configuration file
            config.Save(ConfigurationSaveMode.Full);
        }
```
```


Question:
Is there a way to get MVEL 2.0 ( http://mvel.codehaus.org/ ) to work with functions with optional parameters?

I would like to be able to eval this:

trunc('blahblah',2)

but also

trunc('blahblah',2,'[...]');

Now i have tried:

def trunc(param1,param2,param3) { ... impl ... }

That gives an exception if i try to call it with only 3 parameters.
I also tried:

def trunc(param1,param2,param3) { ... impl ... }
def trunc(param1,param2) { ... impl ... }

But the second one seems to completely overwrite the first definition.

Thanks

Answer:
In java you can declare multiple methods with the same name, but a different arguments.
That way you can support (in a limited way) optional parameters.
Eg.:
```
```
private void method(Object obj1) {
    Object obj2 = new Object("Default");
    method(obj1, obj2);
}

private void method(Object obj1, Object obj2) {
    doStuff(...);
}
```
```
Calling method() is possible with one or two arguments :)


Question:
How can I make this java generic cast ?

public interface IField {

}

class Field implements IField { // package private class

}

public class Form {
  private List<Field> fields;

  public List<IField> getFields() {
    return this.fields;

  }

}

The return statement throws a compiler error (I know the reason - I read the generics tutorial) but it would be very handy to write such code.

If I declared "fields" as List I would need to use a lot of casts to Field in other methods of a Form class .

Can I force that damn compiler to bend it's rules and compile that return statement ?

Thanks in advance.

Answer:
As it happens, you can, because Java generics are just grafted on, not part of the type system.
You can do
```
```
return (List<IField>)(Object)this.fields;
```
```
because all
```
List<T>
```
objects are the same underlying type.
Bear in mind that this allows anyone to put any type implementing
```
IField
```
in your list, so if your collection is not read-only, you may run into difficulties.


Question:
With PHP, I can make numerous PHP websites locally and then upload each of them to its own sub-directory of my PHP hosting service.

However, with ASP.NET, it seems that I can only upload my ASP.NET to the root of my hosting service. If I upload to a sub-directory, I get an error in

section registered as allowDefinition='MachineToApplication' beyond application level
<authentication mode="Windows"/>

is there a way to get around this so I can have numerous ASP.NET websites each in its own directory?

if not, would using ASP.NET MVC be able to get around this problem?

or is it generally not possible to FTP multiple ASP.NET sites to a shared hosting provider?

Answer:
As it happens, you can, because Java generics are just grafted on, not part of the type system.
You can do
```
```
return (List<IField>)(Object)this.fields;
```
```
because all
```
List<T>
```
objects are the same underlying type.
Bear in mind that this allows anyone to put any type implementing
```
IField
```
in your list, so if your collection is not read-only, you may run into difficulties.


Question:
I am looking for a good Environment (GUI based Editor) for blackberry webapps.
e.g., is there a Eclipse plugin out there ?

Answer:
The Blackberry Applications are developed in Java and RIM provides the needed tools and simulators here:
http://na.blackberry.com/eng/developers/resources/devtools.jsp


Question:
I'm trying to create a pimped-out version of the slider that has a user control in the "thumb"-part (meaning: the moving thingy on the slider) that reacts to the slider's movements. Basically my current demo / development version is just a UserControl with 5 visual states that just make it change a smiley face to an angry face in 5 phases. I'd like to put that user control into the thumb.

My only problem is as follows: I can get the UserControl into the thumb no problem, by editing the Slider-control's template in Expression Blend. However, once the UserControl is in the ControlTemplate, it's no longer visible to the new user control class and thus is not changeable with VisualStateManager.

So basically, my question is two-fold:

Is there any better way to replace the thumb of the Slider-control than editing it's template?

If not, how can I access stuff I've added to the template?

Thanks for any answers!

Answer:
I'm answering myself. After visiting every single page on the internet, I finally figured out a solution by myself!
I added a Loaded-event handler to my control in the ControlTemplate and in that event handler I took the reference to that control for the actual class! After that I was able to refer to that control with that reference and for example visualstate changes worked like a charm!
I've now got a hopped-up slider that has a smiley in the handle part and the face on the smiley changes in relation to the position of the slider! Pretty cool!


Question:
Here's a simplified version of my scenario:

I have a table named Project that I reference via an 'id' field.

I have a table named Photo that has a field named 'project_id' which I use to relate multiple photos to a single project. The Photo table also has an auto-incrementing 'id' field that I use for ordering, amongst other things.

Here's what I want to accomplish: For a collection of Project id values, I wish to retrieve the last 5 photos added to each project -- ideally in a single query, of course. :-)

Put another way, instead of imposing a single query limit, I would ideally like to specify a per project limit on the number of photos returned.

I am currently implementing this as one-query per project, so N projects = N queries (a good caching strategy will certainly reduce the hurt, but that'll come later).

Anyone have a solution?

Thanks.

Answer:
For the "last n items" problem in MySQL, take look here:
How to select maximum 3 items per users in MySQL?
(it's right in the top answer).
When you take it from there, all you are missing is a JOIN with your
```
Projects
```
table, which should be easy to do.


Question: I'm looking for way to grab the content of my opengl (as UIImage) and then save it into a file. I'm now giving glReadPixels a try though I'm not sure I'm doing the right thing as of what kind of malloc I should be doing. I gather that on OSX it's GL_BGRA but on the iPhone that doesn't work...

Answer:
All OpenGL|ES complient GL-implementations have to support GL_RGBA as a parameter to glReadPixels.
If your OpenGL|Es supports the
```
```
GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES
```
```
extension you can also query the native format. glReadPixels will understand this format as a parameter to glReadPixels and allows you to directly get the pixel-data in native format. This is usually a bit faster than GL_RGBA.
Take a look at the header-file or query the extension-support via glGetString.


Question:
My Cocoa app needs some small dynamically generated windows. How can I programmatically create Cocoa windows at runtime?

This is my non-working attempt so far. I see no result whatsoever.

NSRect frame = NSMakeRect(0, 0, 200, 200);
NSUInteger styleMask =    NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];

NSWindow * window =  [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreRetained    defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window display];

Answer:
This is what I've come up with myself:
```
```
NSRect frame = NSMakeRect(100, 100, 200, 200);
NSUInteger styleMask =    NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];
NSWindow * window =  [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreBuffered    defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window makeKeyAndOrderFront: window];
```
```
This displays a blue window. I hope this is the optimal approach.


Question: I have an application that needs to send a moderately high volume of messages between a number of AppDomains.  I know that I could implement this using remoting, but I have also noticed that there are cross-domain delegates.  Has anyone looked at this kind of problem?

Answer:
This is just a quick thought, but I heard that even for cross-domain communication
WCF
would be the recommended approach, starting from .NET 3.0 of course. Actually this makes sense, as remoting is just another technology wrapped by WCF.


Question:
I am getting an vba error 3271; Invalid property value.  This happens when trying to append a memo field in a querydef.  Any ideas on how to get around this?

Example:

public sub TestMemoField
    Dim qdf As QueryDef
    Set qdf = CurrentDb.QueryDefs("AppendRecord")
    qdf.Parameters("@SomeBigText").value = string(1000,"A")
    qdf.Execute
end sub

Thanks in advance.

Answer:
Apparently you cannot have a parameter longer than 255 characters (
http://support.microsoft.com/kb/275116
).
It is possible to use a recordset, or to use:
```
```
qdf.SQL="INSERT INTO Sometable (SomeField) Values('" & String(1000, "A") & "')"
```
```


Question:
I am using Oracle BPEL Process manager and have a task assigned to a group of users.
I try to mark it approved using Java class oracle.bpel.services.workflow.task.ITaskService.updateTaskOutcome(). This works if the task is assigned to an individual user, but if the task is assigned to a group of users, I get an error message about the task not being acquired.

If I acquire the task using oracle.bpel.services.workflow.task.ITaskService.acquireTask(), I get an error message when trying to mark it approved: "The task has been acquired by some other user".

Can anybody point to sample code that changes status of an Oracle BPEL task assigned to a group programmatically?

Answer:
use
```
updateTaskOutcomes()
```
method instead of
```
updateTaskOutcome()
```
when it is assigned to multiple users


Question:
I have two tables: a source table and a target table.  The target table will have a subset of the columns of the source table.  I need to update a single column in the target table by joining with the source table based on another column.  The update statement is as follows:

UPDATE target_table tt
SET special_id = ( SELECT source_special_id
                   FROM source_table st
                   WHERE tt.another_id = st.another_id )

For some reason, this statement seems to run indefinitely.  The inner select happens almost immediately when executed by itself.  The table has roughly 50,000 records and its hosted on a powerful machine (resources are not an issue).

Am I doing this correctly?  Any reasons the above wouldn't work in a timely manner?  Any better way to do this?

Answer:
Update:
Ok, now that the query has been fixed -- I've done this exact thing many times, on unindexed tables well over 50K rows, and it worked fine in Oracle 10g and 9i.  So something else is going on here; yes, you are calling for nested loops, but no, it shouldn't run forever, even so.  What are the  primary keys on these tables? Do you by any chance have multiple rows from the second table matching the same row for the first table?  You could be trying to rewrite the whole table over and over, throwing the locking system into a fit.
Original Response
That statement doesn't really make sense -- you are telling it to update all the rows where ids match, to the same id (meaning, no change happens!).
I imagine the real statement looks a bit different?
Please also provide table schema information (primary keys for the 2 tables, any available indexes, etc).


Question:
I have a rather large (many gigabytes) table of data in SQL Server that I wish to move to a table in another database on the same server.

The tables are the same layout.

What would be the most effecient way of going about doing this?

This is a one off operation so no automation is required.

Many thanks.

Answer:
If it is a one-off operation, why care about
top
efficiency so much?
```
```
SELECT * INTO OtherDatabase..NewTable FROM ThisDatabase..OldTable
```
```
or
```
```
INSERT OtherDatabase..NewTable
SELECT * FROM ThisDatabase..OldTable
```
```
...and let it run over night. I would dare to say that using SELECT/INSERT INTO on the same server is not far from the best efficiency you can get anyway.


Question:
I've looked this up a thousand times, and I always forget it, so, here for eternity:

Solaris has a bit of an awkward syntax for tail.

How do I do the equivalent of BSD's tail -nN?

What I want are the last N lines from tail's input.

Answer:
Just remove the "n"
```
```
tail -100
```
```


Question: Which is a better way to force GC on ThreadLocal instance?

Answer:
Simple answer: you can't force the GC in java. Some may posts tricks but all in all you simply can't.
Well, in fact you can. With exit!


Question:
Say I have a file with any number of lines, say, 125. I want to get all the lines except the first n, say, 20. So, I want lines 21–125.

Is there a way to do this with with tail/head, or some other tool?

Answer:
Try
```
```
tail -n +21 myfile.txt
```
```


Question: How to generate the Symbols file of a PowerBuilder program for dump analysis?

Answer:
Try
```
```
tail -n +21 myfile.txt
```
```


Question:
I need to upgrade my current version of DNN this week. I am currently using 2.1.1. I don't want to do everything twice, so, I have several questions.

Is there an upgrade tool or some scripts somewhere that will help me to do an upgrade.

Am I better off installing 4.9 or 5.0. It is production.

If I go with 4.9, will I be able to upgrade to 5.0 when it releases?

Answer: To be honest, I don't know.  But I see that the DNN download page very strongly states that the 5.0 release-candidates are "NOT RECOMMENDED FOR PRODUCTION USE".


Question:
I am using an Infragistics UltraGrid in a WinForms application.

Which event is raised on "check change" of checkbox in Infragistics UltraGrid?

Answer:
The AfterUpdate event of the checkbox is what you'll want to use.
If you're not able to trigger it, though, try adding this as well:
```
```
Private Sub YourGridcontrol_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseDown
    YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.EnterEditMode)
End Sub

Private Sub YourGridcontrol_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles YourGridcontrol.MouseUp
    YourGridcontrol.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.ExitEditMode)
End Sub
```
```
By default, just toggling the checkbox doesn't seem to trigger an Update. By making it enter/exit edit mode, the AfterUpdate should work as you want.
UPDATE: Or, like Vincent suggested, doing the PerformAction on the CellChange event should work, too.  The gist is the same.


Question:
How do you parse a CSV file using gawk?  Simply setting FS="," is not enough, as a quoted field with a comma inside will be treated as multiple fields.

Example using FS="," which does not work:

file contents:

one,two,"three, four",five
"six, seven",eight,"nine"

gawk script:

BEGIN { FS="," }
{
  for (i=1; i<=NF; i++) printf "field #%d: %s\n", i, $(i)
  printf "---------------------------\n"
}

bad output:

field #1: one
field #2: two
field #3: "three
field #4:  four"
field #5: five
---------------------------
field #1: "six
field #2:  seven"
field #3: eight
field #4: "nine"
---------------------------

desired output:

field #1: one
field #2: two
field #3: "three, four"
field #4: five
---------------------------
field #1: "six, seven"
field #2: eight
field #3: "nine"
---------------------------

Answer:
Here's what I came up with.  Any comments and/or better solutions would be appreciated.
```
```
BEGIN { FS="," }
{
  for (i=1; i<=NF; i++) {
    f[++n] = $i
    if (substr(f[n],1,1)=="\"") {
      while (substr(f[n], length(f[n]))!="\"" || substr(f[n], length(f[n])-1, 1)=="\\") {
        f[n] = sprintf("%s,%s", f[n], $(++i))
      }
    }
  }
  for (i=1; i<=n; i++) printf "field #%d: %s\n", i, f[i]
  print "----------------------------------\n"
}
```
```
The basic idea is that I loop through the fields, and any field which starts with a quote but does not end with a quote gets the next field appended to it.


Question:
What is the simplest way to read a full line in a C console program
The text entered might have a variable length and we can't make any assumption about its content.

Answer:
You need dynamic memory management, and use the
```
fgets
```
function to read your line. However, there seems to be no way to see how many characters it read. So you use fgetc:
```
```
char * getline(void) {
    char * line = malloc(100), * linep = line;
    size_t lenmax = 100, len = lenmax;
    int c;

    if(line == NULL)
        return NULL;

    for(;;) {
        c = fgetc(stdin);
        if(c == EOF)
            break;

        if(--len == 0) {
            len = lenmax;
            char * linen = realloc(linep, lenmax *= 2);

            if(linen == NULL) {
                free(linep);
                return NULL;
            }
            line = linen + (line - linep);
            linep = linen;
        }

        if((*line++ = c) == '\n')
            break;
    }
    *line = '\0';
    return linep;
}
```
```
Note
: Never use gets ! It does not do bounds checking and can overflow your buffer


Question:
Why use a GlobalClass? What are they for? I have inherited some code (shown below) and as far as I can see there is no reason why strUserName needs this. What is all for?

public static string strUserName
    {
        get { return m_globalVar; }
        set { m_globalVar = value; }
    }

Used later as:

GlobalClass.strUserName

Thanks

Answer:
When you want to use a
static
member of a type, you use it like
```
ClassName.MemberName
```
. If your code snippet is in the same class as the member you're referring (in this example, you're coding in a GlobalClass member, and using strUserName) you
can
omit the class name. Otherwise, it's required as the compiler wouldn't have any knowledge of what class you're referring to.


Question:
How can I go through each of the properties in my custom object? It is not a collection object, but is there something like this for non-collection objects?

For Each entry as String in myObject
    ' Do stuff here...
Next

There are string, integer and boolean properties in my object.

Answer:
By using reflection you can do that. In C# it looks like that;
```
```
PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();
```
```
Added a VB.Net translation:
```
```
Dim info() As PropertyInfo = myobject.GetType().GetProperties()
```
```


Question:
I am using Visual Studio 2005 and StarTeam 2008 (cross-platform client and VS integration). At some point, I added an 'App.config' to a project. I notice now that this file will not check-in.

The 'StarTeam Pending Checkins' window in VS reports the file 'Not in View'. Selecting it for check in and clicking 'Check In Files' causes a dialog to appear - 'Any operation... requires completing the pending renames/deletes'. I click 'Yes' to proceed and nothing happens.

The StarTeam client reports this file as 'Modified'. If I check-in from the client, I get no 'complete pending renames/deletes' dialog and the file quickly appears with a 'Current' status.

Refreshing StarTeam from VS, I still see the file as 'Not in View'.

I have tried forcing the check-in. I completely removed my working files and pulled the solution fresh in hopes that the StarTeam status ('Current') would apply in VS.

Answer:
By using reflection you can do that. In C# it looks like that;
```
```
PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();
```
```
Added a VB.Net translation:
```
```
Dim info() As PropertyInfo = myobject.GetType().GetProperties()
```
```


Question:
If you call a web service from Silverlight like this:

MyServiceClient serviceClient = new MyServiceClient();
void MyMethod()
{
  serviceClient.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(serviceClient_GetDataCompleted);
  serviceClient.GetDataAsync();

  // HOW DO I WAIT/JOIN HERE ON THE ASYNC CALL, RATHER THAN BEING FORCE TO LEAVE THIS METHOD?

}

I would rather wait/join with the asych service thread inside "MyMethod" rather than leaving "MyMethod" after calling "GetDataAsync", what is the best way to do this?

Thanks,
Jeff

Answer:
To do this you would use a
ManualResetEvent
in your class (class level variable) and then wait on it.
```
```
void MyMethod()
{
  wait = new ManualResetEvent(false);
  // call your service
  wait.WaitOne();
  // finish working
}
```
```
and in your event handler code
```
```
void serviceClient_GetDataCompleted(...)
{
  // Set values you need from service
  wait.Set();
}
```
```


Question:
In Team Build 2008, the Drop Location for a build is no longer specified in the .proj file, and instead is stored in the database and maintained in the GUI tool.

The GUI tool only accepts a network path as a drop location (i.e. \\server\share) and will not accept a local path.

Our build server also hosts the dropped files, so it seems that forcing a file copy operation to go through the network share introduces a lot of lag time when copying a large number of files. I would like to override this feature so that I can specify a local directory for drop location, but I can't figure out how.

Answer:
The connections only seem to stay in the pool and not being reused in case you get an exception, just like the example. If you increase the timeout the connection will be reused.
A workaround to this problem is to clear the connection pool in case you get an exception like this:
```
```
using (SqlConnection con = new SqlConnection(connectionString))
{
    con.Open();
    try
    {
        Console.WriteLine("Server is {0}", con.ServerVersion);
        Console.WriteLine("Clr is {0}", Environment.Version);
        for (int i = 0; i < 5; i++)
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandText = "insert into TXTEST values ( " + i + " )";
                cmd.ExecuteNonQuery();
            }
            Console.WriteLine("Row inserted");
        }
        Thread.Sleep(TimeSpan.FromSeconds(1));
    }
    catch
    {
        SqlConnection.ClearPool(con);
        throw;
    }
}
```
```
In most cases the transaction will complete within the timeout and everything will be fine and dandy. When the transaction
actually do
timeout you clear the pool in order to clean up the dirty connections that won't get reused. This will of course affect other connections in the pool that isn't affected by this problem.
This is a ugly workaround but it seems to work.


Question: Is there an easy way to generate an array containing the letters of the alphabet in C#? It's not too hard to do it by hand, but I was wondering if there was a built in way to do this.

Answer:
I don't think there is a built in way, but I think the easiest would be
```
```
char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
```
```


Question:
I'm looking for articles, forum or blog posts dealing with SharePoint and thread safety? I'm quite sure there are some special aspects regarding thread safety that have to be considered when working with the SharePoint object model.

Actually I didn't find many information about this, yet.

So I'm looking forward to your answers.

Bye,
Flo

Answer:
There are much worse pitfalls in the SharePoint OM than just plain old thread safety. Pay particular attention to working with objects retrieved from properties. You should
always
keep a pointer to an object while you work on it; example:
```
```
var list = web.List["MyList"]
list.Items[0]["Field1"] = "foo"
list.Items[0]["Field2"] = "bar"
list.Items[0].Update() // nothing is updated!
```
```
You might expect Field1 and Field2 to be updated by the final Update() call, but nope. Each time you use the indexer, a NEW reference to the SPListItem is returned.
Correct way:
```
```
SPListItem item = list.Items[0]
item["Field1"] = "foo"
item["Field2"] = "bar"
item.Update() // updated!
```
```
Just a start. Also google for pitfalls around the IDisposabe/Dispose pattern.
-Oisin


Question:
I am fetching data in  from an SQL table using a DataSet in VB.Net. When there is data in table, it displays the data properly in the grid, but when there is no data in the table, it only shows the UltraGrid's basic view.

How can I display the column names of the table as headings of the UltraGrid even when there is no data in Table?

Thanks for the reply, but I think the problem that JD is having is a bit different from mine - in my application the data got fetched properly from SQL Server. My problem is that when there is no data in the table, I want to display the columns of the table as the headings of the grid with 0 rows. This is not happening.

It just shows a message box saying that no data is found, and the UltraGrid shows as it does by default in the application.

Answer:
Have you checked to make sure that the Active Directory change has propagated to TFS?  I've seen issues before where users information is changed and TFS doesn't pick up the change and gets confused about your user.
Also take a look at the following blog post.  It details how to sync up TFS with a user name change in Active Directory
http://blogs.msdn.com/teams_wit_tools/archive/2007/03/15/handling-display-name-changes-in-team-foundation-server.aspx


Question:
I've got an array of char* in a file.
The company I work for stores data in flat files.. Sometimes the data is sorted, but sometimes it's not.
I'd like to sort the data in the files.

Now I could write the code to do this, from scratch.
Is there an easier way?

Of course an in-place sort would be the best option. I'm working on large files and have little RAM. But I'll consider all options.

All strings are the same length.

This is some sample data:

the data is of fixed length
the Data is of fixed length
thIS data is of fixed lengt

This would represent three records of length 28. The app knows the length. Each record ends with CRLF (\r\n), though it shouldn't matter for this sort.

Answer:
```
```
template<size_t length> int less(const char* left, const char* right) {
    return memcmp(left, right, length) < 0;
}

std::sort(array, array + array_length, less<buffer_length>);
```
```


Question:
I have an xml web service which I use at work to make a request to. This request, an xml document, includes information such as recipients, subject, body, etc (as a newsletter would contain).

I have an ASP.NET form to enter the above information to, to form the Xml document, and I can type foreign characters (non latin - Japanese, Chinese, Russian etc).

If I step through my code, the foreign characters are displayed ok. The xml has an encoding of utf-8 and I load the strings into the attributes of my xml document so I shouldn't need to do anything at a string level with encoding.

I am on webmail because of an unrelated technical matter, but my boss has Outlook 2007 Pro and hasn't got an email with a foreign text subject line. However, if the xml is manually posted via the internal test harness, as opposed to the .NET way of methods/variables (OOP) etc, it will work. So there is a failing in .NET somewhere.

Any ideas?

Answer:
```
```
template<size_t length> int less(const char* left, const char* right) {
    return memcmp(left, right, length) < 0;
}

std::sort(array, array + array_length, less<buffer_length>);
```
```


Question:
Possible Duplicate:

  How do I mark a method as Obsolete/Deprecated? - C#

How do you mark a class as deprecated? I do not want to use a class any more in my project, but do not want to delete it before a period of 2 weeks.

Answer:
You need to use the
```
[Obsolete]
```
attribute.
Example:
```
```
[Obsolete("Not used any more", true)]
public class MyDeprecatedClass
{
    //...
}
```
```
The parameters are optional. The first parameter is for providing the reason it's obsolete, and the last one is to throw an error at compile time instead of a warning.


Question:
When obtaining the DPI for the screen under Windows (by using ::GetDeviceCaps) will the horizontal value always be the same as the vertical?  For example:

HDC dc = ::GetDC(NULL);
const int xDPI = ::GetDeviceCaps(dc, LOGPIXELSX);
const int yDPI - ::GetDeviceCaps(dc, LOGPIXELSY);
assert(xDPI == yDPI);
::ReleaseDC(NULL, dc);

Are these values ever different?

Answer:
I have never seen them be different, but on
this
MSDN page I see a comment that suggests that they might be:
```
```
int nHorz = dc.GetDeviceCaps(LOGPIXELSX);
   int nVert = dc.GetDeviceCaps(LOGPIXELSY);

   // almost always the same in both directions, but sometimes not!
```
```


Question:
I'm code reviewing a change one of my co-workers just did, and he added a bunch of calls to Date.toMonth(), Date.toYear() and other deprecated Date methods.  All these methods were deprecated in JDK 1.1, but he insists that it's ok to use them because they haven't gone away yet (we're using JDK 1.5) and I'm saying they might go away any day now and he should use Calendar methods.

Has Sun/Oracle actually said when these things are going away, or does @deprecated just mean you lose style points?

Answer:
They're not going away.  That said, they're usually deprecated because a) they're dangerous ala Thread.stop(), or b) there is a better or at least more accepted way to do it.  Usually deprecated method javadoc will give you a hint as to the better way.  In your case, Calendar is the recommended way to do this.
While it's conceivable that they will be removed at some point in the future, I wouldn't bet on it.  If anyone ever forks Java however, they'll probably be the first thing to go...


Question:
In Linqtosql how do I show items from multiple rows in a single field.

eg I have a 3 table setup for tagging(entity, tag, entitytag) all linked via foreign keys.

For each entity I would like to return the name in one field and then all relevant tags in 2nd field.

eg Item1, tag1; tag2; tag3
   Item2, tag4, tag5....

VB statements preferred.

Thanks
Geoff

Answer:
Okay, not sure if this is the most efficient way but it works.
```
```
Dim dc As New DataContext

Dim query = From i In dc.Items _
            Let tags = (From t In dc.ItemTags _
                        Where t.ItemID = i.ID _
                        Select t.Tag.Name).ToArray _
            Select i.ItemName, Tags = String.Join(" | ", tags)
```
```


Question:
I'm trying to use route constraints in an Asp.Net MVC Application.

routes.MapRoute(
    "theRoute",
    "MyAction/{page}",
    new { controller = "TheController", action = "MyAction", page = 1 },
    new { page = @"[0-9]" });

When I enter an url like ~/MyAction/aString, an YSOD is shown with an invalid operation exception. What can I do to redirect invalid url to the 404 page?

I know I can solve the issue with a string parameter in the controller action and int.TryParse, but then the route constaint is useless.

How can I choose the exceptiontype that is thrown by the route constraints?

Answer:
The problem is that you do not have a route that matches the route that ends in a string.
Modify your routes similar to:
```
```
routes.MapRoute(
    "Default",                                              // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = 0 },
    new { id = "[0-9]" }// Parameter defaults
);
routes.MapRoute(
    "Default2",                                              // Route name
    "{controller}/{action2}/{sid}",                           // URL with parameters
    new { controller = "Home", action = "Index2", sid = "" }  // Parameter defaults
);
```
```
and modify your controller
```
```
public ActionResult Index(int id)
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = "Welcome to ASP.NET MVC! Your id is: "+ id.ToString();

        return View();
    }

    public ActionResult Index2(string sid)
    {
        ViewData["Title"] = "Home Page 2."+sid.ToString();
        ViewData["Message"] = "Welcome to ASP.NET MVC! \"" + sid.ToString() +"\" is an invalid id";

        return View("index");
    }
```
```
now when you pass a string for the ID, Index2 will be called and you can do whatever you need to do to handle the incorrect parameter.


Question:
Can somebody please give me an example of a unidirectional @OneToOne primary-key mapping in Hibernate ? I've tried numerous combinations, and so far the best thing I've gotten is this :

@Entity
@Table(name = "paper_cheque_stop_metadata")
@org.hibernate.annotations.Entity(mutable = false)
public class PaperChequeStopMetadata implements Serializable, SecurityEventAware {

private static final long serialVersionUID = 1L;

@Id
@JoinColumn(name = "paper_cheque_id")
@OneToOne(cascade = {}, fetch = FetchType.EAGER, optional = false, targetEntity = PaperCheque.class)
private PaperCheque paperCheque;
}

Whenever Hibernate tries to automatically generate the schema for the above mapping, it tries to create the primary key as a blob, instead of as a long, which is the id type of PaperCheque.  Can somebody please help me ?  If I can't get an exact solution, something close would do, but I'd appreciate any response.

Answer:
I saved
this discussion
when I implemented a couple of @OneToOne mappings, I hope it can be of use to you too, but we don't let Hibernate create the database for us.
Note the GenericGenerator annotation.
Anyway, I have this code working:
```
```
@Entity
@Table(name = "message")
public class Message implements java.io.Serializable
{
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "message_id")
    public MessageContent getMessageContent()
    {
        return messageContent;
    }
}

@Entity
@Table(name = "message_content")
@GenericGenerator(name = "MessageContent", strategy = "foreign",
    parameters =
    {
      @org.hibernate.annotations.Parameter
      (
        name = "property", value = "message"
      )
    }
)
public class MessageContent implements java.io.Serializable
{
    @Id
    @Column(name = "message_id", unique = true, nullable = false)
    // See http://forum.hibernate.org/viewtopic.php?p=2381079
    @GeneratedValue(generator = "MessageContent")
    public Integer getMessageId()
    {
            return this.messageId;
    }
}
```
```


Question:
I have written a program in C to parse large XML files and then create files with insert statements.  Some other process would ingest the files into a MySQL database.
This data will serve as a indexing service so that users can find documents easily.

I have chosen InnoDB for the ability of row-level locking.  The C program will be generating any where from 500 to 5 million insert statements on a given invocation.

What is the best way to get all this data into the database as quickly as possible?  The other thing to note is that the DB is on a separate server.  Is it worth moving the files over to that server to speed up inserts?

EDIT:  This table won't really be updated, but rows will be deleted.

Answer:
I'd do at least these things according to
this link
:
Move the files there and connect over the unix socket
Generate, instead of the INSERTS, a
LOAD DATA INFILE
file
Disabling indexes during the loading


Question:
I have a bunch of generic interfaces and classes

public interface IElement {
// omited
}

class Element implements IElement {
// omited
}

public interface IElementList<E extends IElement>  extends Iterable {
   public Iterator<E> iterator();
}

class ElementList implements IElementList<Element> {

    public Iterator<Element> iterator() {
       // omited
       }
}

public interface IElementListGroup<E extends IElementList<? extends IElement>> {
    public E getChosenElementList();
}

class ElementListGroup implements IElementListGroup<ElementList> {
    public ElementList getChosenElementList() {
        // omited
    }
}

And then a simple code

ElementListGroup group;

for(Element e : group.getChosenElementList())
{
 // omited
}

And the line with for keyword throwe a "cannot convert from element type Object to Element" compiler error.

Thanks in advance.

Answer:
```
IElementList
```
needs to implement
```
Iterable<E>
```
. Otherwise, the interface specifies
```
Iterator iterator()
```
, not
```
Iterator<E> iterator()
```
. This makes the compiler think that you're iterating over
```
Object
```
s.
I made this change, and it compiled fine (after adding some null returns).


Question:
If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

<div class="selDiv">
  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>
</div>

Answer:
Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.
```
```

Update

        <select class="opts">
            <option selected value="DEFAULT">Default</option>
            <option value="SEL1">Selection 1</option>
            <option value="SEL2">Selection 2</option>
        </select>

```
```


Question:
I'm trying to get a regex that will match:

somefile_1.txt
somefile_2.txt
somefile_{anything}.txt

but not match:

somefile_16.txt

I tried

somefile_[^(16)].txt

with no luck (it includes even the "16" record)

Answer:
Some regex libraries allow lookahead:
```
```
somefile(?!16\.txt$).*?\.txt
```
```
Otherwise, you can still use multiple character classes:
```
```
somefile([^1].|1[^6]|.|.{3,})\.txt
```
```
or, to achieve maximum portability:
```
```
somefile([^1].|1[^6]|.|....*)\.txt
```
```
```
[^(16)]
```
means: Match any character but braces, 1, and 6.


Question:
I have this rewrite rule

RewriteEngine On
RewriteBase /location/
RewriteRule ^(.+)/?$ index.php?franchise=$1

Which is suppose to change this URL

http://example.com/location/kings-lynn

Into this one

http://example.com/location/index.php?franchise=kings-lynn

But instead I am getting this

http://example.com/location/index.php?franchise=index.php

Also, adding a railing slash breaks it. I get index.php page showing but none of the style sheets or javascript are loading.

I'm clearly doing something very wrong but I have no idea what despite spending all day R'ingTFM and many online primers and tutorials and questions on here.

Answer:
Your problem is you are redirecting twice.
```
'location/index.php'
```
matches the regex
```
^(.+)/?$
```
You want to possibly use the "if file does not exist" conditional to make it not try mapping a second time.
```
```
RewriteEngine on
RewriteBase /location/
RewriteCond %{REQUEST_FILENAME} !-f   # ignore existing files
RewriteCond %{REQUEST_FILENAME} !-d   # ignore existing directories
RewriteRule ^(.+)/?$ index.php?franchise=$1  [L,QSA]
```
```
And additonally, theres the [L,QSA] which tries to make it the "last" rule ( Note, this is not entirely obvious how it works ) and append the query string to the query, so that
```
```
location/foobar/?baz=quux  ==> index.php?franchise=$1&baz=quux
```
```
( i think )


Question:
Every example I've seen of CGI/Perl basically a bunch of print statements containing HTML, and this doesn't seem like the best way to write a CGI app.  Is there a better way to do this?  Thanks.

EDIT: I've decided to use CGI::Application and HTML::Template, and use the following tutorial: http://docs.google.com/View?docid=dd363fg9_77gb4hdh7b.  Thanks!

Answer:
Absolutely (you're probably looking at tutorials from the 90s). You'll want to pick a framework. In Perl-land these are the most popular choices:
CGI::Application
- very lightweight with lots of community plugins
Catalyst
- heavier with more bells and whistles
Jifty
- more magical than the above


Question:
I've got a maintenance plan that executes weekly in the off hours. It's always reporting success, but the old backups don't get deleted. I don't want the drive filling up.

DB Server info: SQL Server Standard Edition 9.00.3042.00

There is a "Maintenance Cleanup Task" set to

"Search folder and delete files based on an extension"

and "Delete files based on the age of the file at task run time" is checked and set to 4 weeks.

The only thing I can see is that my backups are each given their own subfolder and that this is not recursive. Am I missing something?

Also: I have seen the issues pre-SP2, but I am running service pack 2.

Answer:
My understanding is that you can only include the first level of subfolders.  I am assuming that you have that check-box checked already.
Are your backups deeper than the just one level?
Another thought is, do you have one single maintenance plan that you run to delete backups of multiple databases?  The reason I ask this is because the way I could see that you would have to do that would be to point it to a folder that was one level higher meaning that your "include first-level subfolders" would not be deep enough.
The way I have mine set up is that the Maintenance Cleanup Task is part of my backup process.  So once the backup completes for a specific database the Maintenance Cleanup Task runs on that same database backup files.  This allows me to be more specific on the directory so I don't run into the directory structure being too deep.  Since I have the criteria set the way I want, items don't get deleted till I am ready for them to be deleted either way.
Tim


Question:
Given a collection of user specified tags how do I determine which ones are not in the tags table with 1 SQL Statement?

Assuming a table schema tags (id, tag) and I'm using mysql, if there's an optimization I'm unaware of.

thanks

Answer:
```
```
select * from canonical_list_of_tags where tag not in (select tag from used_tags)
```
```
At least that works in T-SQL for SQL Server ...
Edit:
Assuming that the table
```
canonical_list_of_tags
```
is populated with the result of "
Given a collection of user specified tags
"


Question: How do I make an instance of gwtext.client.widgets.Window  appear at specific DIV in my html ? I tried window.anchorTo(DOM.getElementById("Some_Div"),"left", new int[]{0,0}), thinking the window will anchor itself to div id="Some_Div"   in my html. it didnt.

Answer:
I haven't used the gwt-ext library in a couple of months, but you might want to try this if you haven't already. It
should
attach the widget where you want it. That said, there are some cases where the gwt-ext widgets react in ways that are not intuitive to someone who really understands the normal GWT widgets.
```
```
RootPanel.get("Some_Div_Id").add( someWidget )
```
```


Question:
How would you handle cross database queries in different environments.  For example, db1-development and db2-development, db1-production and db2-production.

If I want to do a cross-database query in development from db2 to db1 I could use the fully qualified name, [db1-development].[schema].[table].  But how do I maintain the queries and stored procedures between the different environments?  [db1-development].[schema].[table] will not work in production because the database names are different.

I can see search and replace as a possible solution but I am hoping there is a more elegant way to solve this problem. If there are db specific solutions, I am using SQL Server 2005.

Answer:
Why are the database names different between dev and prod? It'd, obviously, be easiest if they were the same.
If it's a single table shared, then you could create a view over it - which only requires that you change that view when moving to production.
Otherwise, you'll want to
create a SYNONYM
for the objects, and make sure to always reference that. You'll still need to change the SYNONYM creation scripts, but that can be done in a build script fairly easily, I think.


Question:
With the age of text messages and things like that, what's a good way to store phone numbers in a database?

In the USA, text messages are handled by phone numbers but in other countries I hear they use email addresses so I guess there needs to be a way to differentiate between countries that use cell phone numbers as their address.

Addition:
For example, people in the USA might use 432-342-3333 or 1-432-342-3333 while in the UK they might use +44 800 400000 or they might even leave out the 44.  The 44 and the 1 makes a difference when automatically sending out SMS.  However, checking the phone number for each country can get tedious.  In this case, would you split the country code or would you merge it into a single column and deal it with it there?

Answer:
I don't know if you have read these two questions, but they might help you a little.
Phone Number Columns in a Database
Is there a standard for storing normalized phone numbers in a database?
Perhaps it would be wise to store the type of number (landline, cell, fax) and/or the messages that can be received on it (voice, text, email). Note that in the US, it is also possible to send text messages to a phone via email, but I believe that is dependent on the carrier.


Question:
Does anyone know of a simple way of getting the raw xml that is returned from querying a webservice?

I have seen a way of doing this via Web Services Enhancements, but I don't want an added dependency.

Answer:
I don't know if you have read these two questions, but they might help you a little.
Phone Number Columns in a Database
Is there a standard for storing normalized phone numbers in a database?
Perhaps it would be wise to store the type of number (landline, cell, fax) and/or the messages that can be received on it (voice, text, email). Note that in the US, it is also possible to send text messages to a phone via email, but I believe that is dependent on the carrier.


Question: I keep finding files which show a size of 10kb but a size on disk on 10gb.  Trying to figure out how this is done, anyone have any ideas?

Answer:
You can make sparse files on NTFS, as well as on any real filesystem. :-)
Seek to (10 GB - 10 kB), write 10 kB of data. There, you have a so-called 10 GB file, which in reality is only 10 kB big. :-)


Question:
I have an application for which log4j logging is configured in a log4j.properties file.  Currently, this application runs on UNIX and creates a log file in /tmp.  This application needs to run on Windows, and on that platform I would like for it to select the correct temporary directory, which I believe is C:\temp.

How can I change my log4j.properties file to make this happen?  Do I need to switch to using an XML configuration file?

Answer:
I think you would just use
```
${java.io.tmpdir}
```
in place of a hard-coded path.


Question:
I'm running Xorg and my (Qt) program daemonises itself. Now I log out and restart the X server. When I log in again my process is still running fine, but I can't see it.

Is there a way of attatching the new incarnation of the X server to the old process?
If I don't restart the whole server, but log out and in again, is there a way to look at the old process?

Thanks

Answer:
After the connection to the X server is lost, it is not possible to regain it.
There was an xserver proxy called xmove, but it is quite deprecated and doesn't work with several newer X extension, which are likely used by modern toolkits.
You could try to run your process in another virtual X server like xvnc or (better) NX. NX is a X proxy technology developed by NoMachine. There exist free implementations of NX servers as well.
If you run your program inside such a server, it is possible to attach and detach from it from arbitrary graphical environments.


Question:
Googling has turned up little to nothing.

I need to develop some heavy stuff in m4 and I'd love to do it in my favorite environment with all the bells and whistles thereof.

There are packages for running m4 on just about every platform, such as windows. So I know at the very least I can create a default project and test from the CLI. But I'd rather not :)

Answer:
I'm not aware of any specific editing support for m4. However, if you have some time to spare (!) and the BNF for m4, then you could use Xtext (
http://wiki.eclipse.org/Xtext
) to create a syntax-coloring and -completing editor, with an outline view.
Updated
an answer below suggests that m4 doesn't have a BNF, or is not BNeFfable, and certainly a short search of the literature shows no claims that an m4 BNF is available - and it appears, though not explicitly stated, that the m4 language is inexpressible in this way.
Obviously this negates my suggestion, so I must retract it, unless of course Xtext has been extended to deal with such languages. Consult the Xtext website linked above for FAQs and mailing list links.


Question:
In a legacy project that I'm on, we have several processing that are preformed via DTS. DTS is not something I worked with a lot back in its hey day.... I was in college.

More specificity, these process are in ActiveX code blocks -- which is basically VBScript for database. It is really hard to debug.

Anyway, I'm wondering if any past or present experienced DTS professionals can offer tips on how to deal with debugging, troubleshooting or otherwise dealing with DTS package development.

This this question is marked as community wiki, I'm hoping to have general and targeted ideas and methods for all types of DTS package implementations.

Answer:
In the scripting portion, I have used the MsgBox to display "I got here" or "xfer worked" or whatever you want to indicate something happened which is not so obvious at run time.
You can also use conditional statements to branch off to an 'End' if you are testing a particular portion of the flow.
If you are stuck working with DTS, but are also running a SQL Server 2005 instance, you might see if you cant upgrade the DTS packages to DTSX (SQL Server Integration Services) and re-do them there.  I know this isn't a 'trick' but you work in the VS2005 IDE, can write in .NET and also you can set break-points and will make life in 'DTS' world much easier.
There are also some articles here:
http://www.databasejournal.com/article.php/1503191
Scroll down and you will see the "SQL Server 2000 DTS" articles.


Question:
So, I'd like to be able to set the max log file size to 64M, but after doing so with innodb_log_file_size=64M MySQL starts OK, but nothing seems to work properly.

EDIT: and by properly I mean not at all. Setting other InnoDB variables aren't causing any problems.

How should I go about troubleshooting this one?

Answer:
Make sure MySQL shuts down cleanly, and delete (or move elsewhere) all
```
ib_logfile*
```
files from MySQL data directory (
```
/var/lib/mysql/
```
usually).
I've tested it and worked for me. Here's
source of this hint
.
InnoDB reports some errors in
```
show table status
```
comment field. You'll find other problems in MySQL error log (
```
hostname.err
```
in MySQL data directory).


Question:
I am working on a windows form application. How do i use the find method of a datatable to find a row if the datatable has a compound key?

Table Structure
Col A, Col B, Col C

Col A and Col B make up the compound key.
I want to find the row where the value in Col A is 6 and Col B is 5

Answer:
When you "set" the Primary key of the datatable, the parameter value is an array of DataColumns...
if your datatable is in variable dt...,
```
```
dt.PrimaryKey = new DataColumn[] {dt.Columns["ColA"], dt.Columns["ColB"]};
```
```
Then pass an array of object values to the Find() method
```
```
object[] keyVals = new object[] {6, 5};
DataRow dr = dt.Rows.Find(keyVals);
```
```
or, just
```
```
DataRow dr = dt.Rows.Find(new object[] {6, 5});
```
```


Question:
I have two SQL scripts which get called within a loop that accept a number parameter. Here is what I'm currently using:

for /l %%i in (1, 1, 51) do (
    sqlplus u/p@name @script.sql a%%i.html %%i
    sqlplus u/p@name @script.sql b%%i.html %%i
)

Everything works fine, but it seems like a waste of time and resources to connect twice for each pass through. Is there a way I could simply log into sqlplus, run the for loop, then exit? I tried many alternatives such as putting

sqlplus u/p@name

before the for loop, but then it would simply hang at the SQL> prompt without executing any of my two scripts.

Thank you.

Answer:
You can create a masterscript.sql that contains your two script.sql statements.
The only thing I'm not sure about is if it will pass in your variables.
MasterScript.sql would contain:
```
```
@@script1.sql
@@script2.sql
```
```
and neither of your sub-scripts should contain an exit.
Differences between "@" and "@@"
:
http://www.orafaq.com/wiki/SQL
*Plus_FAQ#What_is_the_difference_between_.40_and_.40.40.3F


Question: Can I export multiple calendar events into a single iCalendar file?

Answer:
You simply make an iCalendar file with multiple VEVENT sections. For example:
```
```
BEGIN:VCALENDAR
BEGIN:VEVENT
DESCRIPTION:
DTEND:20071202T220000Z
DTSTAMP:20081124T220920Z
DTSTART:20071202T200000Z
LOCATION:Wherever
STATUS:CONFIRMED
SUMMARY:An event
UID:event-the-first
END:VEVENT
BEGIN:VEVENT
DESCRIPTION:Doing whatever, because for no good reason.
DTEND:20071209T210000Z
DTSTAMP:20081124T220920Z
DTSTART:20071207T190000Z
LOCATION:A specific place
STATUS:CONFIRMED
SUMMARY:Something, somewhere
UID:event-the-second
END:VEVENT
END:VCALENDAR
```
```


Question:
If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.

What's the best practice to achieve this?  Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?

Answer:
```
```
Boolean a = true;
Boolean b = false;
Boolean c = null;
```
```
I would use that. It's the most straight-forward.
Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:
```
```
public enum ThreeState {
    TRUE,
    FALSE,
    TRALSE
};
```
```
There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass
```
true
```
and
```
false
```
. If you don't like the
```
null
```
, since it's telling rather little about its meaning here, you can still make a
```
public static final Boolean tralse = null;
```
in your class.


Question:
I have an application in which HttpRuntime.AppDomainAppPath returns the correct path with the wrong casing.

I am then trying to use this in a String.Replace and it does not find the path in the filename due to casing.

I am aware that I can use Regex.Replace but would prefer not to.

I have this problem only on the production machine even though the folder in question has the same casing in dev.

I have just noticed that Server.MapPath also returns the wrong casing.

Any ideas?

Answer:
A few things:
If you don't care about casing, use .ToUpper or .ToLower, and replace on that.
```
```
Dim path As String = HttpRuntime.AppDomainAppPath.ToUpper
Dim newpath As String = Replace(path, "fnd", "rplc")
```
```
If that is not an option try changing the compare method in your replace function.
You didn't specify a language, so I cannot give a specific example.


Question:
Here's a simple (hopefully) L10N question:

Do all locales want this format:

Sunday, Nov 23, 2008

with the weekday before the date, or do some locales want it after the date like this?

Nov 23, 2008, Sunday

Answer:
I can't answer for all locales, but in French, we say "dimanche 23 novembre 2008", so for us, the answer is yes.
Now, I don't know your purpose, but you probably shouldn't make any guess like that anyway...
[EDIT] Funnily, I found an example in analyzing how the zh_TW locale is setting the date/time formats in Java 1.4. I found the format for this locale to be (after decompiling it):
```
```
"ahh'\u6642'mm'\u5206'ss'\u79D2' z",
"ahh'\u6642'mm'\u5206'ss'\u79D2'",
"a hh:mm:ss",
"a h:mm",
"yyyy'\u5E74'M'\u6708'd'\u65E5' EEEE",
"yyyy'\u5E74'M'\u6708'd'\u65E5'",
"yyyy/M/d",
"yyyy/M/d",
"{1} {0}"
```
```
while default, for US (found on the Net), is:
```
```
"h:mm:ss a z", // full time pattern
"h:mm:ss a z", // long time pattern
"h:mm:ss a", // medium time pattern
"h:mm a", // short time pattern
"EEEE, MMMM d, yyyy", // full date pattern
"MMMM d, yyyy", // long date pattern
"MMM d, yyyy", // medium date pattern
"M/d/yy", // short date pattern
"{1} {0}" // date-time pattern
```
```
See the full date pattern, the EEEE (day in week) is at the end for Taiwan...


Question:
I'm using shared ASP.NET hosting and I have no remote-desktop access to the web server.  I only have the ability to FTP ASP.NET related files to the server.

In this scenario, how would I see how much memory my ASP.NET application is consuming?

Answer: Could you create a page that listed various performance counters in a password-protected part of the site?  That would be my suggestion, along with making sure that somewhere on the page, a machine name or IP is listed so that should the site move among various servers, this can be noted somewhere.  Another idea would be to either write to a log file or send an e-mail with various performance counters so that you could see a history of how the server is doing, but be careful on the e-mail that this could become spam-like if you do it too frequently.


Question: Wanting to deploy my project on different servers I would prefer to be able to specify a connect string using a relative path. I can't seem to get that to work and want to know if there is some trick to it...?

Answer:
A suggestion
You could build the absolute path in the app and pass that in the connection string.
So, if you know that the database file is in the
```
database
```
subfolder of the application folder, you could do something like this (C#):
```
```
string relativePath = @"database\myfile.s3db";
    string currentPath;
    string absolutePath;
    string connectionString;

    currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    absolutePath = System.IO.Path.Combine(currentPath,relativePath);

    connectionString = string.Format("DataSource={0}", absolutePath);

    SQLiteConnection cnn = new SQLiteConnection(connectionString);
```
```
(Someone can probably correct me on how to get the current path).


Question:
I have a string

var s:String = "This is a line \n This is another line.";
this.txtHolder.text = s; //.text has \n, not a new line

and i want to put it into a text area, but the new line character is ignored. How can i ensure that the text breaks where i want it to when its assigned?

Answer:
Try
```
```
"This is a line {\n} This is another line."
```
```
Alternatively, use the htmlText attribute and use
```
```
"This is a line <br> This is another line."
```
```


Question:
There doesn't seem to be much info on this topic so I'm going to outline my specific problem then maybe we can shape the question and the answer into something a bit more universal.

I have this rewrite rule

RewriteEngine On
RewriteBase /bookkeepers/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/?$ index.php?franchise=$1

Which is changes this URL

http://example.com/location/kings-lynn

Into this one

http://example.com/location/index.php?franchise=kings-lynn

The problem I am having is that if I add a trailing slash

http://example.com/location/kings-lynn/

then the query string is returned as

franchise=kings-lynn/

and for some reason none of my CSS and Javascript files are being loaded.

Any ideas?

Answer:
It looks like the (.+) is being greedy matched.  In that case, you could try
```
```
RewriteRule ^(.+[^/])/?$ index.php?franchise=$1
```
```
This makes sure that the first group (in the brackets) doesn't end in a slash.


Question: Is it possible to intercept every request made from a page using javascript? i.e. Clicking on a link, loading an image, ajax request...

Answer:
In a word, no.  There's no place you can hook into to get all the requests.
Having said that, you can us javascript to place event handlers on the links, look at the src attribute of image tags and so on.  There's no "generic" way to hook into all the AJAX requests - it depends on the library you're using.
There are other things to consider, such as CSS background images, Flash (what if a flash file makes a request?).
If possible you should be using the browser itself (e.g.
Firebug
) or a proxy (e.g.
Fiddler
) or a packet sniffer (e.g. Ethereal... seems to be
WireShark
now)


Question:
In the past, when I've worked on long-running C++ daemons I've had to deal with heap fragmentation issues.  Tricks like keeping a pool of my large allocations were necessary to keep from running out of contiguous heap space.

Is this still an issue with a 64 bit address space?  Perf is not a concern for me, so I would prefer to simplify my code and not deal with things like buffer pools anymore.  Does anyone have any experience or stories about this issue?  I'm using Linux, but I imagine many of the same issues apply to Windows.

Answer:
If your process genuinely needs gigabytes of virtual address space, then upgrading to 64-bit really does instantly remove the need for workarounds.
But it's worth working out how much memory you expect your process to be using. If it's only in the region of a gigabyte or less, there's no way even crazy fragmentation would make you run out of 32-bit address space - memory leaks might be the problem.
(Windows is more restrictive, by the way, since it reserves an impolite amount of address space in each process for the OS).


Question: Are the formulas represented in a syntax tree then recalculated using a design pattern like the Visitor pattern? How would you go about reproducing the recalculation process in code?

Answer:
Probably, as you say, one guess is that Excel creates a bunch of ASTs, one for each indipendent group of cells, where the leaves are the originating, static data, and the nodes are formulas.
Then it calculates the result for each node, with a
post-order
tree traversal algorithm.
You have to take into account leaf/node cancellation, partial recalculation, ecc. If I'm not wrong, I read somewhere that Excel could benefit of multicore processors to recalculate a sheet in parallel.


Question:
I know it makes little difference to a project but, assuming you use #defined header guards for your C++ code, what format do you use?  e.g. assuming a header called foo.hpp:

#ifndef __FOO_HPP__
...

#ifndef INCLUDED_FOO_HPP
...

#ifndef SOME_OTHER_FORMAT

I'm sold on the idea of upper-case #defines but cannot settle on a format for these guards.

Answer:
I always use
```
INCLUDED_FOO_HPP
```
I wouldn't use the double underscore one, because starting things with double underscores is reserved.


Question:
I'm reading through K&R and came to the small section on register variables, and was wondering if people here have some good examples of this put into practice.

From section 4.7 in K&R:

The register declaration looks like

       register int  x;

       register char c;

To be clear, I'm just hoping to see some cool code samples. I (am pretty sure that I) understand the subject matter so don't feel the need to type up a verbose explanation (unless you want to).

Answer:
There is no good example of register usage when using modern compilers (read: last 15+ years, and note that this answer is from 2008) because it almost never does any good and can do some bad.  When you use register, you are telling the compiler "I know how to optimize my code better than you do" which is almost never the case.  One of three things can happen when you use register:
The compiler ignores it, this is most likely.  In this case the only harm is that you cannot take the address of the variable in the code.
The compiler honors your request and as a result the code runs slower.
The compiler honors your request and the code runs faster, this is the least likely scenario.
Even if one compiler produces better code when you use register, there is no reason to believe another will do the same.  If you have some critical code that the compiler is not optimizing well enough your best bet is probably to use assembler for that part anyway but of course do the appropriate profiling to verify the generated code is really a problem first.


Question:
I have read around 4-5 books on design patterns, but still I don't feel I have come closer to intermediate level in design patterns?

How should I go studying design patterns?

Is there any good book for design patterns?

I know this will come only with experience but there must be some way to master these?

Answer:
The best way is to begin coding with them.  Design patterns are a great concept that are hard to apply from just reading about them.  Take some sample implementations that you find online and build up around them.
A great resource is the
Data & Object Factory
page.  They go over the patterns, and give you both conceptual and real world examples.  Their reference material is great, too.


Question: I am sure there are many developers out here who have team spread across different time zones. What are some of the challenges people face and whats the best way to tackle them?

Answer:
In all honesty, any company that has split development of a project across time zones is out of touch with the realities of engineering.  The MBAs, in an attempt to save themselves a buck or two, foist upon their engineers the unenviable position of altering the schedules of their lives - leading to high stress, longer work hours, lower morale, and higher turnover.  Quality suffers, ship dates suffer, feature lists suffer.  The only increase you'll see in your project is the bug count.
You can have engineering projects split up like this if you don't have any need for low-latency communication between project units.  In other words - if they are working on almost entirely independent segments of the system.


Question: Is there a command, or a set of tables I can look at to determine which tables, stored procedures and views in SQL Server server 2005 have a certain user defined data type?

Answer:
Tables are relatively easy, sys.columns and sys.types allow you to link columns to types.  The query below will get this out.
```
```
select s.name
      ,o.name
      ,c.name
      ,t.name
  from sys.schemas s
  join sys.objects o
    on o.schema_id = s.schema_id
  join sys.columns c
    on c.object_id = o.object_id
  join sys.types t
    on c.user_type_id = t.user_type_id
 where t.name = 'Foo'
```
```
EDIT: as G Mastros has shown above, you can get parameters with a similar query.
```
```
select s.name
      ,o.name
      ,p.name
      ,t.name
  from sys.schemas s
  join sys.objects o
    on o.schema_id = s.schema_id
  join sys.parameters p
    on p.object_id = o.object_id
  join sys.types t
    on p.user_type_id = t.user_type_id
 where t.name = 'Foo'
```
```


Question:
I will explain problem with an example:

There is two table in my database, named entry, tags

There is a column named ID_ENTRY in both table. When I add a record to table, entry, I have to take the ID_ENTRY of last added record and add it to table, tags. How can I do it?

Answer:
I would probably do this with an INSERT trigger on the named entry table, if you have all of the data you need to push to the tags table available.  If not, then you might want to consider using a stored procedure that creates both inside a transaction.
If you want to do it in code, you'll need to be more specific about how you are managing your data.  Are you using DataAdapter, DataTables, LINQ, NHibernate, ...?  Essentially, you need to wrap both inserts inside a transaction of some sort so that either inserts get executed or neither do, but the means to doing that depend on what technology you are using to interact with the database.


Question:
I have a dll that was written in c++, I need to use this dll in my c# code. After searching I found that using P/Invoke would give me access to the function I need, but these functions are defined with in a class and use non-static private member variables. So I need to be able to create an instance of this class to properly use the functions. How can I gain access to this class so that I can create an instance? I have been unable to find a way to do this.

I guess I should note that the c++ dll is not my code.

Answer:
There is no way to directly use a C++ class in C# code.  You can use PInvoke in an indirect fashion to access your type.
The basic pattern is that for every member function in class Foo, create an associated non-member function which calls into the member function.
```
```
class Foo {
public:
  int Bar();
};
extern "C" Foo* Foo_Create() { return new Foo(); }
extern "C" int Foo_Bar(Foo* pFoo) { return pFoo->Bar(); }
extern "C" void Foo_Delete(Foo* pFoo) { delete pFoo; }
```
```
Now it's a matter of PInvoking these methods into your C# code
```
```
[DllImport("Foo.dll")]
public static extern IntPtr Foo_Create();

[DllImport("Foo.dll")]
public static extern int Foo_Bar(IntPtr value);

[DllImport("Foo.dll")]
public static extern void Foo_Delete(IntPtr value);
```
```
The downside is you'll have an awkward IntPtr to pass around but it's a somewhat simple matter to create a C# wrapper class around this pointer to create a more usable model.
Even if you don't own this code, you can create another DLL which wraps the original DLL and provides a small PInvoke layer.


Question:
What is the most recommended/best way to stop multiple instances of a setTimeout function from being created (in javascript)?

An example (psuedo code):

function mouseClick()
{
   moveDiv("div_0001", mouseX, mouseY);
}

function moveDiv(objID, destX, destY)
{
   //some code that moves the div closer to destination
   ...
   ...
   ...

   setTimeout("moveDiv(objID, destX, destY)", 1000);
   ...
   ...
   ...
}

My issue is that if the user clicks the mouse multiple times, I have multiple instances of moveDiv() getting called.

The option I have seen is to create a flag, that only allows the timeout to be called if no other instance is available...is that the best way to go?

I hope that makes it clear....

Answer:
```
```
var timeout1 = window.setTimeout('doSomething();', 1000);
var timeout2 = window.setTimeout('doSomething();', 1000);
var timeout3 = window.setTimeout('doSomething();', 1000);

// to cancel:
window.clearTimeout(timeout1);
window.clearTimeout(timeout2);
window.clearTimeout(timeout3);
```
```


Question:
Suppose you have a GridView with a few columns like:

| Foo | Bar | Total |

and you use a style sheet to make the alternating rows different colors, say light blue and white.

Is there a good way to make a particular column alternate in a different color?  For example, I might want the Total column to alternate in medium and light red to bring attention to it in a large grid.

BTW, I know you can programmatically change the color of a cell.  I'd like to stick to CSS if it all possible, however, so all my style stuff is in one place.  I also don't see an easy way to tell if I'm in an alternating row when I'm inside the event handler.

Answer:
If you're using jQuery, you can do it pretty easily.
```
```
$("table#myTable col:odd").css("background-color:#ffe");
```
```
the
```
:odd
```
selector is not available in most current browsers, but jQuery gives it to us today.
For rows, you can do it with the built-in AlternatingRowStyle element.
Edit: found a good resource for some different ways of doing this:
http://css-discuss.incutio.com/?page=StylingColumns


Question:
I have a directory to which a process uploads some .pdf files. This process is out of my control.

I need to make those files available through the website using Tomcat.

I have a directory /var/lib/tomcat5/webapps/test1 available to the web and I can see the files in it with a browser.

So, I created a symbolic link pointing at the directory with the .pdf files:
/var/lib/tomcat5/webapps/test1/files/, but I can't see anything in that directory.

How can I enable symlinks in the test1 directory only?  I don't want to enable symlinks everywhere, just so that directory with .pdf files is available to the web.

Answer:
Create a context.xml file in a
```
META-INF
```
directory in your web app containing:
```
```
<?xml version="1.0" encoding="UTF-8"?>

<Context path="/myapp" allowLinking="true">

</Context>
```
```
more here:
http://www.isocra.com/2008/01/following-symbolic-links-in-tomcat/


Question:
I am a junior programmer. Since my supervisor told me to sit in with the client, I joined. I saw the unsatisfied face of the client despite the successful (from my programmer's perspective) delivery of the project!

Client: You could have included this!

Us: Was not in the specification!

Client: Common Sense!

As a programmer, how do you respond in this situation?

Answer:
What you should do to avoid this situation:
Explicitly spec out what will be included and what will not be included.
The problem probably comes down to the unspecified parts of the spec:
The client thinks that unspecified stuff should be in, i.e. it was implied.
The developer thinks that unspecified stuff should not be in.
For future specs that you have, you should have a catch all statement, that explicitly states that if something is not specified in this document, it can be done after the original specification is done at an additional cost.
What you should do in the current situation:
Other than learning from your experiences, you should come to some compromise with the client.
Example: I will do this feature that you feel is common sense, but for all future additions/changes it will have to be spec'ed out explicitly.
I.e. you will have to do a little more work, but it is worth it in return for the catch all explicitly spec'ed agreement your client will enter into.
Bad spec?
Was it necessarily a bad spec? No.
It is impossible to mention everything your clients may expect, so it is critical to have this catch all statement mentioned above stated clearly and explicitly in your spec/contract.
Other ways to reduce the problem:
Involve the client early, show them early prototypes.  Even if they don't demand it.
Try not to sell the client an end product, but more of a service for working on his product.
Consider an agile development model or something similar so that tasks are well defined, small, paid for, and indisputable.


Question: There might be applications that are not suited for Core Data - image manipulation programs like Photoshop or Gimp for example. But for applications that are suited for Core Data, say Address Book or iCal, what is the criteria to choose Core Data over a custom model?

Answer:
I recently started a project where I decided to use Core Data for the first time in a real world application. My application is actually version 2.0 of an older app that uses a custom data model, so I spent a lot of time debating this question. Here are some of the things I asked myself.
The time to learn how Core Data works in a non-trivial application and fixing the little bugs and idiosyncrasies that pop up when you're learning a new technology. This may include a prototype or two, since you don't want to jump into using something like Core Data that will be responsible for such as large chunk of your application.
Whether or not Core Data will solve problems that are hard to address when using a custom data model, for example storing and holding in memory very large sets of data.
Whether or not you want to share code with a platform where Core Data is not available, for instance Cocoa Touch. Along the same lines, if you want the resulting data files to be compatible without having to build a separate exporter.
If learning Core Data will help improve yourself as a programmer, whether its making your more attractive to Mac development shops or just for your own use.
If your data model is simple enough that you don't really need things like undo manager support or relationships, the areas where core data really shines.
If you're using external libraries or other technologies such as Distributed Objects, where you might not want to use NSManagedObject.


Question: I need to share SSO information between two different domains with a cookie, can this be done in PHP and how?

Answer:
On both domains, place an image or other web element that is pulled from the other domain.  Use the URL to notify the other domain that user X is on domain A, and let domain B associate that user ID with that user on their system.
It's a little complex to carry out correctly, but if you think it through it'll work out very well.
Vinko points out in a comment (thanks!) that I shouldn't take it for granted that you understand the security risks involved.  If this information is of any value to anyone, then you should make sure you use proper encryption, authentication, etc to avoid releasing sensitive information and to avoid various attacks (replay, man in the middle, etc).  This shouldn't be too onerous since you control both websites and you can select a secure secret key for both, since the communication is only going between the two servers via this special URL.  Keep it in mind though.
-Adam


Question:
I want to start using Nunit (finally), I am using Visual Studio 2008.

Is it as simple as importing Nunit into my test project?

I remember seeing a GUI for NUnit, does that do the exact same thing that a separate test project would do, except show you the pass/fail visually?

Answer:
Yes, that's basically it. Personally I find the unit test runner which comes with
ReSharper
to be excellent - and the tool itself is well worth the licence feel. Alternatively there's
TestDriven.NET
.
Having a test project which runs nunit-gui or nunit-console separately is all very well, but you really want the whole unit testing experience to be as seamless as possible. The easier it is to write and run tests, the more likely you are to do it - which is a very good thing. Don't underestimate the gradual build-up of frustration due to a
slightly
poorer user experience, flipping between windows etc.


Question:
Is there anything to use, to determine if a type is actually a anonymous type? For example an interface, etc?

The goal is to create something like the following...

//defined like...
public static T Get<T>(this IAnonymous obj, string prop) {
    return (T)obj.GetType().GetProperty(prop).GetValue(obj, null);
}
//...

//And then used like...
var something = new { name = "John", age = 25 };
int age = something.Get<int>("age");

Or is that just the beauty of an anonymous type? Nothing to identify it self because it takes a new shape?

Note - I realize that you can write an extension method for the object class, but that seems like a little overkill, in my opinion.

Answer:
As I recall, there is a
```
[CompilerGenerated]
```
marker... 2 secs
Plus the name will be freaky, and it will be a generic type ;-p
Actually, for a "get" etc I would probably just use a static (non-extension) method.
If you just want a way to get the value from an instance of an anon-type (at a later point in time), a lambda is probably the best option - note you need a few tricks to pull this off:
```
```
static void Main()
    {
        var foo = new { name = "John", age = 25 };
        var func = Get(foo, x => x.age);
        var bar = new { name = "Marc", age = 30 };
        int age = func(bar);
    }
    // template here is just for type inference...
    static Func<TSource, TValue> Get<TSource, TValue>(
        TSource template, Func<TSource, TValue> lambda)
    {
        return lambda;
    }
```
```
(edit re the comment) There definitely
is
this attribute:
```
```
var foo = new { A = "B" };
        Type type = foo.GetType();

        CompilerGeneratedAttribute attrib = (CompilerGeneratedAttribute) Attribute.GetCustomAttribute(
            type, typeof(CompilerGeneratedAttribute)); // non-null, therefore is compiler-generated
```
```


Question:
I'm trying to use the FolderBrowserDialog from my WPF application - nothing fancy. I don't much care that it has the Windows Forms look to it.

However, when I call ShowDialog, I want to pass the owner window which is an IWin32Window. How do I get this from my WPF control?

Actually, does it matter? If I run this code and use the ShowDialog overload with no parameters it works fine. Under what circumstances do I need to pass the owner window?

Thanks,

Craig

Answer:
If you specify Owner, you will get a Modal dialog over the specified WPF window.
To get WinForms compatible Win32 window create a class implements IWin32Window like this
```
```
public class OldWindow : System.Windows.Forms.IWin32Window
{
    IntPtr _handle;

    public OldWindow(IntPtr handle)
    {
        _handle = handle;
    }

    #region IWin32Window Members

    IntPtr System.Windows.Forms.IWin32Window.Handle
    {
        get { return _handle; }
    }

    #endregion
}
```
```
And use an instance of this class at your WinForms
```
```
IntPtr mainWindowPtr = new WindowInteropHelper(this).Handle; // 'this' means WPF Window
        folderBrowserDialog.ShowDialog(new OldWindow(mainWindowPtr));
```
```


Question:
Is it possible?
By debug I mean setting breakpoints, inspect values and advance step by step.

Answer:
I haven't used web2py, but if it runs in a terminal window, you can use standard pdb stuff. Add this line somewhere in your code:
```
```
import pdb; pdb.set_trace()
```
```
This will invoke the debugger and break.  Then you can use
PDB
commands: n to step to the next line, l to list code, s to step into a function, p to print values, etc.