Question:
I have the following (pretty standard) table structure:

Post <-> PostTag <-> Tag

Suppose I have the following records:

PostID Title
1,     'Foo'
2,     'Bar'
3,     'Baz'

TagID Name
1,    'Foo'
2,    'Bar'

PostID TagID
1      1
1      2
2      2

In other words, the first post has two tags, the second has one and the third one doesn't have any.

I'd like to load all posts and it's tags in one query but haven't been able to find the right combination of operators. I've been able to load either posts with tags only or repeated posts when more than one tag.

Given the database above, I'd like to receive three posts and their tags (if any) in a collection property of the Post objects. Is it possible at all?

Thanks

Answer:
I've answered this in another post :
About eager loading
. In your case it would probably be something like :
```
```
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Post>(p => p.PostTag);
options.LoadWith<PostTag>(pt => pt.Tag);
```
```
Though be careful - the DataLoadOptions must be set BEFORE ANY query is sent to the database - if not, an exception is thrown (no idea why it's like this in Linq2Sql - probably will be fixed in a later version).


Question: I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage.  The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters.  I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last word before 200 chars.

Answer:
By using the
wordwrap
function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:
```
```
substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
```
```
One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:
```
```
if (strlen($string) > $your_desired_width)
{
    $string = wordwrap($string, $your_desired_width);
    $string = substr($string, 0, strpos($string, "\n"));
}
```
```
The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:
```
```
function tokenTruncate($string, $your_desired_width) {
  $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
  $parts_count = count($parts);

  $length = 0;
  $last_part = 0;
  for (; $last_part < $parts_count; ++$last_part) {
    $length += strlen($parts[$last_part]);
    if ($length > $your_desired_width) { break; }
  }

  return implode(array_slice($parts, 0, $last_part));
}
```
```
Also, here is the PHPUnit testclass used to test the implementation:
```
```
class TokenTruncateTest extends PHPUnit_Framework_TestCase {
  public function testBasic() {
    $this->assertEquals("1 3 5 7 9 ",
      tokenTruncate("1 3 5 7 9 11 14", 10));
  }

  public function testEmptyString() {
    $this->assertEquals("",
      tokenTruncate("", 10));
  }

  public function testShortString() {
    $this->assertEquals("1 3",
      tokenTruncate("1 3", 10));
  }

  public function testStringTooLong() {
    $this->assertEquals("",
      tokenTruncate("toooooooooooolooooong", 10));
  }

  public function testContainingNewline() {
    $this->assertEquals("1 3\n5 7 9 ",
      tokenTruncate("1 3\n5 7 9 11 14", 10));
  }
}
```
```
EDIT :
Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:
```
$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);
```


Question:
I have a string which is like this:

this is "a test"

I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:

['this', 'is', 'a test']

PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.

Answer:
You want
```
split
```
, from the built-in
```
shlex
```
module.
```
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
```
This should do exactly what you want.
If you want to preserve the quotation marks, then you can pass the
```
posix=False
```
kwarg.
```
```
>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']
```
```


Question:
If you were writing a new application from scratch today, and wanted it to scale to all the cores you could throw at it tomorrow, what parallel programming model/system/language/library would you choose?  Why?

I am particularly interested in answers along these axes:

Programmer productivity / ease of use (can mortals successfully use it?)

Target application domain (what problems is it (not) good at?)

Concurrency style (does it support tasks, pipelines, data parallelism, messages...?)

Maintainability / future-proofing (will anybody still be using it in 20 years?)

Performance (how does it scale on what kinds of hardware?)

I am being deliberately vague on the nature of the application in anticipation of getting good general answers useful for a variety of applications.

Answer:
For .NET application I choose "
.NET Parallel Extensions (PLINQ)
" it's extremely easy to use and allows me to parallelize existing code in minutes.
It's simple to learn
Used to perform complex operations over large arrays of objects, so I can't comment on other applications
Supports tasks and piplines
Should be supported for a next couple of years, but who knows for sure?
CTP version has some performance issues, but already looks very promising.
Mono
will likely get
support for PLINQ, so it could be a cross-platform solution as well.


Question: Can you provide an example of a byte buffer transferred between two java classes via UDP datagram?

Answer:
Hows' this ?
```
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Server {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000));
        byte[] message = new byte[512];
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength()));
    }
}
```
```
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Client {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();
        socket.connect(new InetSocketAddress(5000));
        byte[] message = "Oh Hai!".getBytes();
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket.send(packet);
    }
}
```


Question:
My friends and I are starting a game like Pokemon and we wanted to know how will we add monsters to the game?  We're using VisualBasic because my friend's brother said it would be easier.

So far we can put pictures of the monsters on the screen and you can click to attack and stuff.

Right now when we want to add a monster we have to make a new window.  This will take us a long time to make all the windows for each type of monster.  Is there a tool or something to make this go faster?  How do game companies do this?

Answer:
I'd suggest making a list of all the attributes you would need for each monster and store all of that in a database like
MySQL
. This way you don't need to make windows for each monster, only each time a monster appears (in which case you'd just get the necessary info from the database).
If you're not familiar with any database, check out the
MySQL tutorial
to get up and going.


Question: Desinging web application and for reporting iam using crystal reports.sometimes the crystal reports gives runtimes error. What can i do to make my report faster. Retrieving around 1MB of data. It is the month end sales report. what is the best method to solve this issue.

Answer:
1Mb sounds like far too much data for a report -
I would try to filter it down more on the server


Question: How do I do a diff of two strings or arrays in Ruby?

Answer:
diff.rb is what you want, which is available at
http://users.cybercity.dk/~dsl8950/ruby/diff.html
via internet archive:
http://web.archive.org/web/20140421214841/http://users.cybercity.dk:80/~dsl8950/ruby/diff.html


Question: I am currently programming a scheduling application which loosely based on iCalendar standard. Does anyone knows in which property can I store the event creator's information? By browsing through the iCalendar RFC 2445, I find this property: Organizer. can I store the event creator's information in the property even if he/she is the only person involved in the event? or there is already a field to store the event creator's information???!

Answer:
```
ORGANIZER;CN="Sally Example":mailto:sally@example.com
```
Looks like the answer


Question:
Java is one of my programming languages of choice.  I always run into the problem though of distributing my application to end-users.

Giving a user a JAR is not always as user friendly as I would like and using Java WebStart requires that I maintain a web server.

What's the best way to distribute a Java application?  What if the Java application needs to install artifacts to the user's computer?  Are there any good Java installation/packaging systems out there?

Answer:
For simple Java apps I like to use Jar's.  It is very simple to distribute one file that a user can just click on (Windows), or
```
```
java -jar jarname.jar
```
```
IMHO, jar is the way to go when simplicity is a main requirement.


Question:
Our team is setting up nightly and continuous integration builds.  We own Team Foundation Server and could use Team Foundation Build.  I'm more familiar with CC.Net and lean that way but management sees all the money spent on TFS and wants to use it.

Some things I like better about CC.Net is the flexibility of notifications as well as the ease of implementing custom scripts.

If you have experience with both products, which do you prefer and why?

Answer:
We've been using CruiseControl.net since June '07 and it's worked great for us.  Best part, it integrates to SVN easily which is a far superior source control provider.
So our setup is:
Cruise Control.Net
SVN
Trac
- for bug reports and project management (integrates perfectly with SVN)
nunit - for unit testing
We've had some major parallel development going and the branching and merging experience was spectacular.  If you have the choice I'd go with the setup above!


Question:
This is somewhat similar to this question.

However, rather than wanting to hide a column all together, I am just looking to hide the column on the List.aspx page.

My specific example is that fields that are long (or at least nvarchar(MAX)) automatically hide from the List.aspx page as is but are still visible on the Edit.aspx page.

I would like to replicate this behaviour for other (shorter) columns.

Is this possible?

Answer:
You can create a custom page for the particular table you want to change.  There's an example
here
.
Within your custom page, you can then set
```
AutoGenerateColumns="false"
```
within the
```
asp:GridView
```
control, and then define exactly the columns you want, like this:
```
```
<Columns>
    ...
    <asp:DynamicField DataField="Product" HeaderText="Product" />
    <asp:DynamicField DataField="Colour" HeaderText="Colour" />
</Columns>
```
```


Question:
I can't seem to find much documentation on X-Sendfile or example code for PHP (there is some rails code).

Anyone used it before and would mind giving a quick snippet of code and a brief description?

Answer:
X-Sendfile is an HTTP header, so you want something like this:
```
```
header("X-Sendfile: $filename");
```
```
Your web server picks it up if correctly configured.  Here's some more details:
http://www.jasny.net/articles/how-i-php-x-sendfile/


Question:
I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p>

Now I want to insert an element in to the text so that it will become:

<p>Hello <span id=span1>new</span> world!</p>

I need the span tag because I want to handle it later.Show or hide.
But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world".

Answer:
Include the class definition that's defined in CSS on your JavaScript version of the
```
<span>
```
tag as well.
```
```
<span class="class_defined_in_css">
```
```
(where this
```
<span>
```
tag would be part of your JavaScript code.)


Question:
Application frameworks such as DotNetNuke, Eclipse, Websphere and so forth are available today which offer customizable frameworks that can be used as dashboard applications.  Do you use these or do you and your peers keep writing amazing, modular, maintainable dashboard frameworks which you support yourselves?

Are there any good web based, OS independent frameworks out there that you suggest using to build your own enterprise class infrastructure around?

Answer:
The one I use is Oracle Application Development Framework. It's a complete, fully supported framework, and Oracle use it themselves to build their own enterprise applications. It comes with a lot of JSF components that are very easy to bind to the underlying data objects.
I'd recommend this  for all Java applications that need database data.
You find a discussion of it on the Oracle Wiki:
http://wiki.oracle.com/page/ADF+Methodology+-+Work+in+Progressent


Question: How can I get all implementations of an interface through reflection in C#?

Answer:
Do you mean all interfaces a Type implements?
Like this:
```
```
ObjX foo = new ObjX();
Type tFoo = foo.GetType();
Type[] tFooInterfaces = tFoo.GetInterfaces();
foreach(Type tInterface in tFooInterfaces)
{
  // do something with it
}
```
```
Hope tha helpts.


Question: How do I preview a url using ajax? I have seen this done with search engine plug ins and would like to learn how to do this. Specifically, I would like to be able to mouse over a link and see the preview of the webpage using ajax.

Answer:
There's the
easy
solution, the
hard
solution, and the
use-a-library
solution.
use-a-library
: I prefer always doing the use-a-library solution unless you have a darn good reason otherwise.  One possible site which wraps the "hard solution" as a service for you:
http://thumbnails.iwebtool.com/demo/
easy
: The easy solution is to just load the target webpage as a downscaled AJAXy window.  You can use many of the Lightbox-class plugins for this task, particularly the ones which allow you to target arbitrary HTTP content for the Lightbox window.
GreyBox
is my favorite of those which I have used before.
Lightbox Gone Wild
is also nice.
hard
: Then there is the hard solution: you need to render the web page server side, cache the rendering as an image, and then serve up that image using Lightbox-esque Javascript (which is trivial next to the other requirements).  How you would go about doing this is outside the scope of this box.  Why would you do it this way?  The preview generates MUCH faster for the client, and it hermetically seals the client's session away from things which might bust it in the target website -- poorly behaving Javascript and/or malware can cause Really Bad Things when you open them, even in an AJAXy window-within-a-window.


Question:
I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.

What would be the best approach?

Answer:
Something like this?
```
```
$vals = explode(':', $duration);

if ( $vals[0] == 0 )
   $result = $vals[1] . ' minutes, ' . $vals[2] . ' seconds';
else
   $result = $vals[0] . 'hours, ' . $vals[1] . ' minutes, ' . $vals[2] . ' seconds';
```
```


Question:
In C++0x I would like to write a function like this:

template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
    //Put things into the tuple
}

I first tried to use a for loop on int i and then do:

get<i>(my_tuple);

And then store some value in the result. However, get only works on constexpr.

If I could get the variables out of the tuple and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without get. Any ideas on how to do that? Or does anyone have another way of modifying this tuple?

Answer:
Since the "i" in
```
```
get<i>(tup)
```
```
needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values.  Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too.


Question: Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail.

Answer:
Using
```
scan
```
should do the trick:
```
```
string.scan(/regex/)
```
```


Question:
I am having trouble deciding on whether to classify my application as 'real time' or 'near real time', or perhaps even something else.

The software receives data immediately as it is generated from the source, then based on certain rules, raises an alert when certain conditions are met. It takes the approach of checking the last 30 seconds of data every 30 seconds to see whether the criteria for a rule has been met.

Is that real time? What are the thresholds for the definitions of real time vs. near real-time?

EDIT

I think this is a duplicate of Define realtime on the web for business.

Please decide if the above thread is insufficient to answer your question.

Answer: I am in agreement with John, in your scenario you are looking at least 30 seconds of delay, I would say that it is nearly real time.


Question:
Code I have:

cell_val = CStr(Nz(fld.value, ""))
Dim iter As Long
For iter = 0 To Len(cell_val) - 1 Step 1
    If Asc(Mid(cell_val, iter, 1)) > 127 Then
        addlog "Export contains ascii character > 127"
    End If
Next iter

This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA.

Answer:
I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following:
```
```
For iter = 1 To Len(cell_val)
    If Asc(Mid(cell_val, iter, 1)) > 127 Then
        addlog "Export contains ascii character > 127"
    End If
Next
```
```


Question: What are futures? It's something to do with lazy evaluation.

Answer:
A Future encapsulates a deferred calculation, and is commonly used to shoehorn lazy evaluation into a non-lazy language. The first time a future is evaluated, the code required to evaluate it is run, and the future is replaced with the result.
Since the future is replaced, subsequent evaluations do not execute the code again, and simply yield the result.


Question:
I need to concatenate two String arrays in Java.

void f(String[] first, String[] second) {
    String[] both = ???
}

Which is the easiest way to do this?

Answer:
Here's a simple method that will concatenate two arrays and return the result:
```
```
public <T> T[] concatenate(T[] a, T[] b) {
    int aLen = a.length;
    int bLen = b.length;

    @SuppressWarnings("unchecked")
    T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
    System.arraycopy(a, 0, c, 0, aLen);
    System.arraycopy(b, 0, c, aLen, bLen);

    return c;
}
```
```
Note that it will not work with primitive data types, only with object types.
The following slightly more complicated version works with both object and primitive arrays. It does this by using
```
T
```
instead of
```
T[]
```
as the argument type.
It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.
```
```
public static <T> T concatenate(T a, T b) {
    if (!a.getClass().isArray() || !b.getClass().isArray()) {
        throw new IllegalArgumentException();
    }

    Class<?> resCompType;
    Class<?> aCompType = a.getClass().getComponentType();
    Class<?> bCompType = b.getClass().getComponentType();

    if (aCompType.isAssignableFrom(bCompType)) {
        resCompType = aCompType;
    } else if (bCompType.isAssignableFrom(aCompType)) {
        resCompType = bCompType;
    } else {
        throw new IllegalArgumentException();
    }

    int aLen = Array.getLength(a);
    int bLen = Array.getLength(b);

    @SuppressWarnings("unchecked")
    T result = (T) Array.newInstance(resCompType, aLen + bLen);
    System.arraycopy(a, 0, result, 0, aLen);
    System.arraycopy(b, 0, result, aLen, bLen);

    return result;
}
```
```
Here is an example:
```
```
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));
Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));
```
```


Question:
I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file.

There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results.

I am running my tests using the *Tests.dll mask and NOT using Test Lists (.vsmdi).

Answer:
How are you running the tests?  Are you using a .vsmdi file or just specifying that you run all tests in *Tests.dll assemblies?
If it is the latter and you are using TFS 2008, then you need to add the following to the and of the first PropertyGroup in your TFSBuild.proj file for the build.
```
```
<RunConfigFile>$(SolutionRoot)\TestRunConfig.testrunconfig</RunConfigFile>
```
```
This points the build at your .testrunconfig so it can pick up the instructions to run code coverage.


Question:
The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.

For instance, how would I find out that there are 10 week days in between 31/08/2008 and 13/09/2008?

Answer:
One way would be to convert the dates to unix timestamps using strtotime(...), subtracting the results and div'ing with 86400 (24*60*60):
```
```
$dif_in_seconds = abs(strtotime($a) - strtotime($b));
$daysbetween = $dif_in_seconds / 86400;
```
```
ETA: Oh.. You meant weekdays as in Mon-Fri.. Didn't see that at first..


Question: Please consider both commercial and free debuggers. Would like to see also the pros and cons for each.

Answer:
I haven't used it myself, so I can't comment on the pros/cons , but one commercial alternative is
TotalView
.
There is also
DDD
that gives you a frontend to GDB, but i guess you have already tried/used that?


Question:
public class Test {
    public static void main(String[] args) {

    }
}

class Outer {
    void aMethod() {
        class MethodLocalInner {
            void bMethod() {
                System.out.println("Inside method-local bMethod");
            }
        }
    }
}

Can someone tell me how to print the message from bMethod?

Answer:
You can only instantiate
```
MethodLocalInner
```
within
```
aMethod
```
. So do
```
```
void aMethod() {

    class MethodLocalInner {

            void bMethod() {

                    System.out.println("Inside method-local bMethod");
            }
    }

    MethodLocalInner foo = new MethodLocalInner(); // Default Constructor
    foo.bMethod();

}
```
```


Question:
While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.

This led me to think about the best way to group 'helper' functions together.  The Java/C# way would be to use a class of static functions with a private constructor, e.g.:

class Helper
{
private:
  Helper() { }
public:
  static int HelperFunc1();
  static int HelperFunc2();
};

However, being C++ you could also use a namespace:

namespace Helper
{
  int HelperFunc1();
  int HelperFunc2();
}

In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are.  If used the class approach for example, would there be any overheads?

Answer:
The main advantage to using a namespace is that you can reopen it and add more stuff later, you can't do that with a class.  This makes this approach better for loosely coupled helpers (for example you could have a Helpers namespace for your entire library, much like all of STL is in ::std)
The main advantage of a class is that you can nest it inside the class using it, you can't nest a namespace in a class.  This makes this approach better for tightly coupled helpers.
You won't have any extra overhead having them in a class vs a namespace.


Question:
Events are synchronous in C#. I have this application where my main form starts a thread with a loop in it that listens to a stream. When something comes along on the stream an event is fired from the loop to the main form.

If the main form is slow or shows a messagebox or something the loop will be suspended. What is the best way around this? By using a callback and invoke on the main form?

Answer:
Since you're using a form, the easier way is to use the
BackgroundWorker
component.
The BackgroundWorker class allows you
  to run an operation on a separate,
  dedicated thread. Time-consuming
  operations like downloads and database
  transactions can cause your user
  interface (UI) to seem as though it
  has stopped responding while they are
  running. When you want a responsive UI
  and you are faced with long delays
  associated with such operations, the
  BackgroundWorker class provides a
  convenient solution.


Question:
What is the difference between == and ===?

How exactly does the loosely == comparison work?

How exactly does the strict === comparison work?

What would be some useful examples?

Answer:
Difference between
```
==
```
and
```
===
```
The difference between the loosely
```
==
```
equal operator and the strict
```
===
```
identical operator is exactly explained in the
manual
:
Comparison Operators
Example
Name
Result
$a ==  $b
Equal
TRUE if $a is equal to $b after type juggling.
$a === $b
Identical
TRUE if $a is equal to $b, and they are of the same type.
Loosely
```
==
```
equal comparison
If you are using the
```
==
```
operator, or any other comparison operator which uses loosely comparison such as
```
!=
```
,
```
<>
```
or
```
==
```
, you always have to look at the
context
to see what, where and why something gets converted to understand what is going on.
Converting rules
Converting to boolean
Converting to integer
Converting to float
Converting to string
Converting to array
Converting to object
Converting to resource
Converting to NULL
Type comparison table
As reference and example you can see the comparison table in the
manual
:
TRUE
FALSE
1
0
-1
"1"
"0"
"-1"
NULL
array()
"php"
""
TRUE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
TRUE
1
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
0
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
-1
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
"1"
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
"0"
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
"-1"
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
NULL
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
TRUE
TRUE
FALSE
TRUE
array()
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
TRUE
FALSE
FALSE
"php"
TRUE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
""
FALSE
TRUE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
TRUE
Strict
```
===
```
identical comparison
If you are using the
```
===
```
operator, or any other comparison operator which uses strict comparison such as
```
!==
```
or
```
===
```
, then you can always be sure that the types won't
magically
change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value.
Type comparison table
As reference and example you can see the comparison table in the
manual
:
Strict comparisons with
```
===
```
TRUE
FALSE
1
0
-1
"1"
"0"
"-1"
NULL
array()
"php"
""
TRUE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
1
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
0
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
-1
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
"1"
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
"0"
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
FALSE
"-1"
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
NULL
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
array()
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
"php"
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
FALSE
""
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
FALSE
TRUE
Editor's note
- This was properly quoted previously, but is more readable as a markdown table. This is not plagiarism


Question: How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it?

Answer:
The MSDN link is nice, but the security information there isn't complete. The handler registration should contain "%1", not %1. This is a security measure, because some URL sources incorrectly decode %20 before invoking your custom protocol handler.
PS. You'll get the entire URL, not just the URL parameters. But the URL might be subject to some mistreatment, besides the already mentioned %20->space conversion. It helps to be conservative in your URL syntax design. Don't throw in random // or you'll get into the mess that file:// is.


Question:
I may be wrong, but if you are working with SmtpClient.SendAsync in ASP.NET
2.0 and it throws an exception, the thread processing the request waits
indefinitely for the operation to complete.

To reproduce this problem, simply use an invalid SMTP address for the host
that could not be resolved when sending an email.

Note that you should set Page.Async = true to use SendAsync.

If Page.Async is set to false and Send throws an exception the thread
does not block, and the page is processed correctly.

TIA.

Answer:
Note that you should set Page.Async = true to use SendAsync.
Please explain the rationale behind this. Misunderstanding what Page.Async does may be the cause of your problems.
Sorry, I was unable to get an example working that reproduced the problem.
See
http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
(WICKED CODE: Asynchronous Pages in ASP.NET 2.0)
EDIT:
Looking at your code example, I can see that you're not using
```
RegisterAsyncTask()
```
and the
```
PageAsyncTask
```
class. I think you must do this when executing asynchronous tasks on a Page where
```
@Async
```
is set to true. The example from MSDN Magazine looks like this:
```
```
protected void Page_Load(object sender, EventArgs e)
{
    PageAsyncTask task = new PageAsyncTask(
        new BeginEventHandler(BeginAsyncOperation),
        new EndEventHandler(EndAsyncOperation),
        new EndEventHandler(TimeoutAsyncOperation),
        null
        );
    RegisterAsyncTask(task);
}
```
```
Inside
```
BeginAsyncOperation
```
, then, should you send a mail asynchronously.


Question: Does anyone know how to get/set the call divert settings in codes running on Windows mobile 5/6? I am new to windows mobile development and wonder if there is anyway to do it using C# and .NET CF?

Answer:
I assume you mean call forwarding?  In general terms, the
Telephony API (TAPI)
is used for programmatically controlling the phone interface.  Call forwarding is specifically handled by
TSPI_lineForward
.
Microsoft does not offer any built-in or SDK tools for managed developers to use TAPI, and the structures TAPI uses are cumbersome and difficult to P/Invoke.  There are a some
3rd-party libraries
that do provide some level of TAPI interaction that you might also investigate.


Question:
In the process of learning TinyOS I have discovered that I am totally clueless about makefiles.

There are many optional compile time features that can be used by way of declaring preprocessor variables.

To use them you have to do things like:

CFLAGS="-DPACKET_LINK"        this enables a certain feature.

and

CFLAGS="-DPACKET_LINK" "-DLOW_POWER" enables two features.

Can someone dissect these lines for me and tell me whats going on? Not in terms of TinyOS, but in terms of makefiles!

Answer:
Somewhere in the makefile the CFLAG will be used in compilation line like this:
```
$(CC) $(CFLAGS) $(C_INCLUDES) $<
```
and eventually in the execution will be translated to :
```
gcc -DPACKET_LINK -DLOW_POWER -c filename.c -o filename.o
```
This define will be passed to the source code as it was define in the header file


Question: One of the best tips for using vim that I have learned so far has been that one can press Ctrl+C or Ctrl+[ instead of the Esc key. However I use a dvorak keyboard so Ctrl+[ is a little out of reach for me as well so I mostly use Ctrl+C. Now I've read somewhere that these two key combinations don't actually have exactly the same behaviour and that it is better to use Ctrl+[. I haven't come across any problems so far though so I'd like to know what exactly is the difference between the two?

Answer:
According to Vim's documentation,
Ctrl
+
C
does not check for abbreviations and does not trigger the
```
InsertLeave
```
autocommand event while
Ctrl
+
[
does.
One option is to use the following to remap
Ctrl
+
C
```
```
inoremap <C-c> <Esc><Esc>
```
```


Question:
Phantom References serve for post-mortem operations.
The Java specification states that a phantom referenced object will not be deallocated until the phantom-reference itself is cleaned.

My question is: What purpose does this feature (object not deallocated) serve?

(The only idea i came up with, is to allow native code to do post-mortem cleanup on the object, but it isn't much convincing).

Answer:
Edit, since I've misunderstand the question first:
Quoted from here
http://www.memorymanagement.org/glossary/p.html
:
The Java specification says that the
  phantom reference is not cleared when
  the reference object is enqueued, but
  actually, there's no way in the
  language to tell whether that has been
  done or not. In some implementations,
  JNI weak global references are weaker
  than phantom references, and provide a
  way to access phantom reachable
  objects.
But I found no other references which would say the same.


Question:
I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that

void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
    for(int x = x0; x < x1; x += step)
    {
         MoveToEx(dc, x, y0, NULL);
         LineTo(dc, x, y1);
    }
}
void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)
{
    for(int y = y0; y < y1; y += step)
    {
         MoveToEx(dc, x0, y, NULL);
         LineTo(dc, x1, y);
    }
}

So if I decide to add some fancy stuff, like antialiasing or merely change drawing pencil or whatever I'll have to put the same code in both of them and it's code duplication and it's bad we all know why.

My question is how would you rewrite these two functions into a single one to avoid this problem?

Answer:
Here is my own solution
```
```
class CoordGenerator
{
public:
    CoordGenerator(int _from, int _to, int _step)
        :from(_from), to(_to), step(_step), pos(_from){}
    virtual POINT GetPoint00() const = 0;
    virtual POINT GetPoint01() const = 0;
    bool Next()
        {
            if(pos > step) return false;
            pos += step;
        }
protected:
    int from;
    int to;
    int step;
    int pos;
};

class GenX: public CoordGenerator
{
public:
    GenX(int x0, int x1, int step, int _y0, int _y1)
        :CoordGenerator(x0, x1, step),y0(_y0), y1(_y1){}
    virtual POINT GetPoint00() const
        {
            const POINT p = {pos, y0};
            return p;
        }
    virtual POINT GetPoint01() const
        {
            const POINT p = {pos, y1};
            return p;
        }
private:
    int y0;
    int y1;
};

class GenY: public CoordGenerator
{
public:
    GenY(int y0, int y1, int step, int _x0, int _x1)
        :CoordGenerator(y0, y1, step),x0(_x0), x1(_x1){}
    virtual POINT GetPoint00() const
        {
            const POINT p = {x0, pos};
            return p;
        }
    virtual POINT GetPoint01() const
        {
            const POINT p = {x1, pos};
            return p;
        }
private:
    int x1;
    int x0;
};

void DrawScale(HDC dc, CoordGenerator* g)
{
    do
    {
        POINT p = g->GetPoint00();
        MoveToEx(dc, p.x, p.y, 0);
        p = g->GetPoint01();
        LineTo(dc, p.x, p.y);
    }while(g->Next());
}
```
```
But I it seems to me too complicated for such a tiny problem, so I'm looking forward to still see your solutions.


Question:
public static Logger getLogger() {
    final Throwable t = new Throwable();
    final StackTraceElement methodCaller = t.getStackTrace()[1];
    final Logger logger = Logger.getLogger(methodCaller.getClassName());
    logger.setLevel(ResourceManager.LOGLEVEL);
    return logger;
}

This method would return a logger that knows the class it's logging for.
Any ideas against it?

Many years later: https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java

Answer:
You could of course just use Log4J with the appropriate pattern layout:
For example, for the class name "org.apache.xyz.SomeClass", the pattern %C{1} will output "SomeClass".
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html


Question: I want to find 2nd, 3rd, ... nth maximum value of a column.

Answer:
You could sort the column into descending format and then just obtain the value from the nth row.
EDIT::
Updated as per comment request.
WARNING
completely untested!
```
```
SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6
```
```
Something like the above should work for Oracle ... you might have to get the syntax right first!


Question: Any ideas how to determine the number of active threads currently running in an ExecutorService?

Answer:
Use a
ThreadPoolExecutor
implementation and call
getActiveCount()
on it:
```
```
int getActiveCount()
// Returns the approximate number of threads that are actively executing tasks.
```
```
The ExecutorService interface does not provide a method for that, it depends on the implementation.


Question:
I've been doing some work with the JAX-RS reference implementation (Jersey).
I know of at least two other frameworks (Restlet & Apache CXF).

My question is: Has anyone done some comparison between those frameworks and if so, which framework would you recommend and why?

Answer:
My colleague mentions why we are using RESTeasy for our current project in
RESTful web services in Java EE with RESTeasy (JAX-RS)
:
Its reference implementation, Jersey, was not chosen because we had trouble integrating it well with EJB3 and Seam 2.0.
We are using the RESTeasy implementation of JAX-RS, because we had no trouble integrating it with our EJBs and Seam. It also has sufficient documentation.
There is another implementation from Apache, but I haven’t tried it because it uses an older version of JAX-RS.
Finally there is yet another framework for RESTful web services for Java called Restlet but we did not favour it because at the time of this writing, it is using a custom architecture, even though proper JAX-RS support is in the works.


Question:
I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript?

for (var i = 0; i < 1000; ++i) {
    myObjects[i].onMyEvent = function() {
        // do something
    };
}

vs

function myEventHandler() {
    // do something
}

for (var i = 0; i < 1000; ++i) {
    myObjects[i].onMyEvent = myEventHandler;
}

The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times?

Answer:
As a general design principle, you should avoid implimenting the same code multiple times. Instead you should lift common code out into a function and execute that (general, well tested, easy to modify) function from multiple places.
If (unlike what you infer from your question) you are declaring the internal function once and using that code once (and have nothing else identical in your program) then an anonomous function
probably
(thats a guess folks) gets treated the same way by the compiler as a normal named function.
Its a very useful feature in specific instances, but shouldn't be used in many situations.


Question:
On a file path field, I want to capture the directory path like:

textbox1.Text = directory path

Anyone?

Answer:
There is a FolderBrowserDialog class that you can use if you want the user to select a folder.
http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx
```
```
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result.Equals(get_DialogResult().OK)) {
    textbox1.Text = folderBrowserDialog1.get_SelectedPath();
}
```
```
If all you want is to get the direcotory from a full path, you can do this:
```
```
textbox1.Text = Path.GetDirectoryName(@"c:\windows\temp\myfile.txt");
```
```
This will set the Text-property to "c:\windows\temp\"


Question:
I have an Access 2007 form that is searchable by a combobox.  When I add a new record, I need to update the combobox to include the newly added item.

I assume that something needs to be done in AfterInsert event of the form but I can't figure out what.

How can I rebind the combobox after inserting so that the new item appears in the list?

Answer:
I assume your combobox is a control on a form, not a combobox control in a commandBar. This combobox has a property called rowsource, that can be either a value list (husband;wife;son;girl) or a SQL SELECT instruction (SELECT relationDescription FROM Table_relationType).
I assume also that your form recordset has something to do with your combobox recordset. What you'll have to do is, once your form recordset is
properly updated
(afterUpdate event I think), to reinitialise the rowsource property of the combobox control
if the recordsource is an SQL instruction:
```
```
myComboBoxControl.recordsource = _
    "SELECT relationDescription FROM Table_relationType"
```
```
or if it is a value list
```
```
myComboBoxControl.recordsource = myComboBoxControl.recordsource & ";nephew"
```
```
But over all I find your request very strange. Do you have a reflexive (parent-child) relationship on your table?


Question:
As the local subversion czar i explain to everyone to keep only source code and non-huge text files in the repository, not huge binary data files.  Smaller binary files that are parts of tests, maybe.

Unfortunately i work with humans!  Someone is likely to someday accidentally commit a 800MB binary hulk. This slows down repository operations.

Last time i checked, you can't delete a file from the repository; only make it not part of the latest revision.  The repository keeps the monster for all eternity, in case anyone ever wants to recall the state of the repository for that date or revision number.

Is there a way to really delete that monster file  and end up with a decent sized repository?   I've tried the svnadmin dump/load thing but it was a pain.

Answer:
To permanently delete monster files from a svn repository, there is no other solution than using svnadmin dump/load. (
SVN Book: dump command
)
To prevent huge files from being committed, a hook script can be used. You could have, for example, a script that ran "pre-commit" whenever someone tried to commit to the repository. The script might check filesize, or filetype, and reject the commit if it contained a file or files that were too large, or of a "forbidden" type.
More typical uses of hook scripts are to check (pre-commit) that a commit contains a log message, or (post-commit) to email details of the commit or to update a website with the newly committed files.
A hook script is a script that runs in response to response to repository events (
SVN Book: Create hooks
).


Question:
I am trying to use Zend_Db_Select to write a select query that looks somewhat like this:

SELECT * FROM bar WHERE a = 1 AND (b = 2 OR b = 3)

However, when using a combination of where() and orWhere(), it seems impossible to use condition grouping like the above.

Are there any native ways in Zend Framework to achieve the above (without writing the actual query?)

Answer:
From
the manual
(Example 11.61. Example of parenthesizing Boolean expressions)
```
```
// Build this query:
//   SELECT product_id, product_name, price
//   FROM "products"
//   WHERE (price < 100.00 OR price > 500.00)
//     AND (product_name = 'Apple')

$minimumPrice = 100;
$maximumPrice = 500;
$prod = 'Apple';

$select = $db->select()
             ->from('products',
                    array('product_id', 'product_name', 'price'))
             ->where("price < $minimumPrice OR price > $maximumPrice")
             ->where('product_name = ?', $prod);
```
```


Question:
I'm writing a Rails application which will monitor data quality over some specific databases. In order to do that, I need to be able to execute direct SQL queries over these databases - which of course are not the same as the one used to drive the Rails application models. In short, this means I can't use the trick of going through the ActiveRecord base connection.

The databases I need to connect to are not known at design time (i.e.: I can't put their details in database.yaml). Rather, I have a model 'database_details' which the user will use to enter the details of the databases over which the application will execute queries at runtime.

So the connection to these databases really is dynamic and the details are resolved at runtime only.

Answer:
You may be able to do this through
```
self.establish_connection
```
.


Question:
I am seeing strange behaviour with the flash.media.Sound class in Flex 3.

var sound:Sound = new Sound();
try{
sound.load(new URLRequest("directory/file.mp3"))
} catch(e:IOError){
 ...
}

However this isn't helping. I'm getting a stream error, and it actually sees to be in the Sound constructor.

Error #2044: Unhandled IOErrorEvent:.
  text=Error #2032: Stream Error.   at... ]

I saw one example in the Flex docs where they add an event listener for IOErrorEvent, SURELY I don't have to do this, and can simply use try-catch? Can I set a null event listener?

Answer:
You will need to add a listener since the URLRequest is not instantaneous. It will be
very
fast if you're loading from disk, but you will still need the Event-listener.
There's a good example of how to set this up (Complete with IOErrorEvent handling) in the
livedocs
.


Question:
I am trying to write some JavaScript RegEx to replace user inputed tags with real html tags, so [b] will become <b> and so forth. the RegEx I am using looks like so

var exptags = /\[(b|u|i|s|center|code){1}]((.){1,}?)\[\/(\1){1}]/ig;

with the following JavaScript

s.replace(exptags,"<$1>$2</$1>");

this works fine for single nested tags, for example:

[b]hello[/b] [u]world[/u]

but if the tags are nested inside each other it will only match the outer tags, for example

[b]foo [u]to the[/u] bar[/b]

this will only match the b tags. how can I fix this? should i just loop until the starting string is the same as the outcome? I have a feeling that the ((.){1,}?) patten is wrong also?

Thanks

Answer:
AFAIK you can't express recursion with regular expressions.
You can however do that with .NET's System.Text.RegularExpressions using balanced matching. See more here:
http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx
If you're using .NET you can probably implement what you need with a callback.
If not, you may have to roll your own little javascript parser.
Then again, if you can afford to hit the server you can use the full parser. :)
What do you need this for, anyway? If it is for anything other than a preview I highly recommend doing the processing server-side.


Question:
As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?

import atexit

def helloworld():
    print("Hello World!")

atexit.register(helloworld)

raise Exception("Good bye cruel world!")

outputs

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    raise Exception("Good bye cruel world!")
Exception: Good bye cruel world!
Hello World!

Answer:
If you call
```
```
import os
os._exit(0)
```
```
the exit handlers will not be called, yours or those registered by other modules in the application.


Question:
In the KornShell (ksh) on AIX UNIX Version 5.3 with the editor mode set to vi using:

set -o vi

What are the key-strokes at the shell command line to autocomplete a file or directory name?

Answer:
ESC\ works fine on AIX4.2 at least.  One thing I noticed is that it only autocompletes to the unique part of the file name.
So if you have the files x.txt, x171go and x171stop, the following will happen:
```
```
Press keys:           Command line is:
x                     x
<ESC>\                x
1                     x1
<ESC>\                x171
g<ESC>\               x171go
```
```


Question:
What free and commercial garbage collection libraries are available for C++, and what are the pros and cons of each?

I am interested in hard-won lessons from actual use in the field, not marketing or promotional blurb.

There is no need to elaborate on the usual trade offs associated with automatic garbage collection, but please do mention the algorithms used (reference counting, mark and sweep, incremental, etc.) and briefly summarise the consequences.

Answer:
The Boehm garbage collector
is freely available, and supposedly rather good (no first hand experience myself)
Theoretical paper (in PDF) about
C++0x proposal for the Boehm garbage collector
It was originally said to make C++0x
, but will not make it after all
(due to time constraints I suppose).
Proprosal N2670
(minimal support for garbage collectors) did get approved in june 2008 though, so as compiler implementations pick up on this, and the standard gets finalised, the garbage collection world out there for C++ is sure to change...


Question:
Possible Duplicate:

  How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?

I'd like to have multiple global hotkeys in my new app (to control the app from anywhere in windows), and all of the given sources/solutions I found on the web seem to provide with a sort of a limping solution (either solutions only for one g.hotkey, or solutions that while running create annoying mouse delays on the screen).

Does anyone here know of a resource that can help me achive this, that I can learn from?
Anything?

Thanks !  :)

Answer:
http://www.codeproject.com/KB/cs/CSLLKeyboardHook.aspx
If you're not using .net 3.5.


Question: What is the best, preferably free/open source tool for auto-generating Java unit-tests? I know, the unit-tests cannot really serve the same purpose as normal TDD Unit-Tests which document and drive the design of the system. However auto-generated unit-tests can be useful if you have a huge legacy codebase and want to know whether the changes you are required to make will have unwanted, obscure side-effects.

Answer:
To be honest, I probably wouldn't do this.  Unit tests are isolated and you won't actually know if you have "unwanted, obscure side-effects" because everything is walled off from the other things that cause the side effects.  As a result, you need integration or system testing and
that
is not something you can automate.
Build a few high-level, end-to-end system tests which give you a degree of confidence and then use coverage testing to find out what you've missed,  The downside is that when bugs crop up, it will be harder to point to their exact cause, but the upside is that you'll be far more likely to see the bugs.
Once you find bugs, write unit tests just for them.  As you move forward, you can use TDD for the bits you want to refactor.
I know this probably wasn't the answer you want to hear, but I've been testing for many, many years and this is a solid approach (though I would hardly call it the only approach :)


Question: Which built in (if any) tool can I use to determine the allocation unit size of a certain NTFS partition ?

Answer:
Open an administrator command prompt, and do this command:
```
```
fsutil fsinfo ntfsinfo [your drive]
```
```
The Bytes Per Cluster is the equivalent of the allocation unit.


Question:
I know the combination Ctrl+A to jump to the beginning of the current command, and Ctrl+E to jump to the end.

But is there any way to jump word by word, like Alt+←/→ in Cocoa applications does?

Answer:
Here's how you can do it
By default, the Terminal has these shortcuts to move (left and right) word-by-word:
esc
+
B
(left)
esc
+
F
(right)
You can configure
alt
+
←
and
→
to generate those sequences for you:
Open Terminal preferences (
cmd
+
,
);
At Settings tab, select Keyboard and double-click
```
⌥ ←
```
if it's there, or add it if it's not.
Set the modifier as desired, and type the shortcut key in the box:
esc
+
B
, generating the text
```
\033b
```
(you can't type this text manually).
Repeat for word-right (
esc
+
F
becomes
```
\033f
```
)
Alternatively, you can refer to this blog post over at textmate:
http://blog.macromates.com/2006/word-movement-in-terminal/


Question:
The question says it all basically.

I want in a

class MyClass

to listen to a routed event. Can it be done ?

Answer:
If you can create an
inner
class of MyClass (call it MyInnerClass) that derives from FrameworkElement while retaining the capability to access an enclosing MyClass object, your problem will be solved. You can then implement a 'getListener' method within MyClass that returns the embedded MyInnerClass that you will use to actually listen to events.


Question: How do people usually detect the MIME type of an uploaded file using ASP.NET?

Answer:
in the aspx page:
```
```
<asp:FileUpload ID="FileUpload1" runat="server" />
```
```
in the codebehind (c#):
```
```
string contentType = FileUpload1.PostedFile.ContentType
```
```


Question:
I re-image one of my machines regularly; and have a script that I run after the OS install completes to configure my machine; such that it works how I like.

I happen to have my data on another drive...and I'd like to add code to my script to change the location of the Documents directory from "C:\Users\bryansh\Documents" to "D:\Users\bryansh\Documents".

Does anybody have any insight, before I fire up regmon and really roll up my sleeves?

Answer:
in the aspx page:
```
```
<asp:FileUpload ID="FileUpload1" runat="server" />
```
```
in the codebehind (c#):
```
```
string contentType = FileUpload1.PostedFile.ContentType
```
```


Question:
struct foo { unsigned x:1; } f;
printf("%d\n", (int)sizeof(f.x = 1));

What is the expected output and why?  Taking the size of a bitfield lvalue directly isn't allowed. But by using the assignment operator, it seems we can still take the size of a bitfield type.

What is the "size of a bitfield in bytes"?  Is it the size of the storage unit holding the bitfield?  Is it the number of bits taken up by the bf rounded up to the nearest byte count?

Or is the construct undefined behavior because there is nothing in the standard that answers the above questions?  Multiple compilers on the same platform are giving me inconsistent results.

Answer:
Wouldn't
```
```
(f.x = 1)
```
```
be an expression evaluating to true (technically in evaluates to result of the assignment, which is 1/true in this case), and thus,
```
```
sizeof( f.x = 1)
```
```
is asking for the size of true in terms of how many chars it would take to store it?
I should also add that the Wikipedia article on
sizeof
is nice.  In particular, they say "sizeof is a compile-time operator that returns the size, in multiples of the size of char, of the variable or parenthesized type-specifier that it precedes."
The article also explains that sizeof works on expressions.


Question:
Is there a way to change the encoding used by the String(byte[]) constructor ?

In my own code I use String(byte[],String) to specify the encoding but I am using an external library that I cannot change.

String src = "with accents: é à";
byte[] bytes = src.getBytes("UTF-8");
System.out.println("UTF-8 decoded: "+new String(bytes,"UTF-8"));
System.out.println("Default decoded: "+new String(bytes));

The output for this is :

UTF-8 decoded: with accents: é à
Default decoded: with accents: Ã© Ã

I have tried changing the system property file.encoding but it does not work.

Answer:
Quoted from
defaultCharset()
The default charset is determined
  during virtual-machine startup and
  typically depends upon the locale and
  charset of the underlying operating
  system.
In most OSes you can set the charset using a environment variable.


Question: What do you think of Quagga compared to XORP as a dynamic software routing engine? What are the technical merits of each engine comparatively? Additionally, what do most people think of them from a programming view. Who has manipulated networks using these enginers? I was wondering from an OSPF, routing, BGP protocol user's perpspective.

Answer:
What do you think of Quagga compared to XORP as a dynamic software routing engine?
It is one of many options, but not particularly of very much use to you based upon your questions/information that you posted here. Have you tried looking into some of the alternatives such as (nothing comes to  mind)?
What are the technical merits of each engine comparatively?
Small, fast, oddly placed, optimized, super-heroic and more filler for a resume.
Additionally, what do most people think of them from a programming view.
I can't speak for most people, but I for myself do not give it much credit or merit, or well... you know what I mean.
Who has manipulated networks using these enginers?
I could not find specific references, but I do remember reading that both Disney and the 'famous' YUV corporation of South Africa both played with this notion before. I believe Disney abandoned it with the fall of Michael Eisner.
I was wondering from an OSPF, routing, BGP protocol user's perpspective.
I am a BGP protocol user's prospective. Hopefully we hear from OSPF and routing user's perspectives shortly.
Good question.


Question: What are the private IP address ranges?

Answer:
You will find the answers to this in
RFC 1918
. Though, I have listed them below for you.
```
```
10.0.0.0        -   10.255.255.255  (10/8 prefix)
 172.16.0.0      -   172.31.255.255  (172.16/12 prefix)
 192.168.0.0     -   192.168.255.255 (192.168/16 prefix)
```
```
It is a common misconception that 169.254.0.0/16 is a private IP address block. This is not true. It is link local, basically it is meant to be only used within networks, but it isn't official RFC1918. Additional information about IPv4 addresses can be found in
RFC 3300
.
On the other hand IPv6 doesn't have an equivalent to RFC1918, but any sort of site-local work should be done in fc00::/7. This is further touched on in
RFC 4193
.


Question:
Currently I am using NetTiers to generate my data access layer and service layer. I have been using NetTiers for over 2 years and have found it to be very useful. At some point I need to look at LINQ so my questions are...

Has anyone else gone from NetTiers to LINQ To SQL?

Was this switch over a good or bad thing?

Is there anything that I should be aware of?

Would you recommend this switch?

Basically I would welcome any thoughts
.

Answer:
NetTiers is very good for generating a heavy and robust DAL, and we use it internally for core libraries and frameworks.
As I see it, LINQ (in all its incarnations, but specifically as I think you're asking to SQL) is fantastic for quick data access, and we generally use it for more agile cases.
Both technologies are quite inflexible to change without regeneration of the code or dbml layer.
That being said, used properly LINQ 2 SQL is quite a robust solution, and you might even start using it for future development due to it's ease of use, but I wouldn't throw away your current DAL for it - if it aint broke ...


Question:
If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte").

byte a = 23;
byte b = 34;
byte c = a + b;

In this example, the compile error is on the third line.

Answer:
Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators.
To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type.
```
byte a = 23;
byte b = 34;
byte c = (byte) (a + b);
```
Here's a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.)
Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int.


Question: I've got a site that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limitation?

Answer:
you could always petition wp to add your widget to their 'approved' list, but who knows how long that would take. you're talking about a way to circumvent the rules they have in place about posting arbitrary script. myspace javascript exploits in particular have increased awareness of the possibility of such workarounds, so you might have a tough time getting around the restrictions - however, here's a classic ones to try:
put the javascript in a weird place, like anywhere that executes a URL. for instance:
```
```
<div style="background:url('javascript:alert(this);');" />
```
```
sometimes the word 'javascript' gets cut out, but occasionally you can sneak it through as java\nscript, or something similar.
sometimes quotes get stripped out - try String.fromCharCode(34) to get around that. Also, in general, using eval("codepart1" + "codepart2") to get around restricted words or characters.
sneaking in javascript is a tricky business, mostly utilizing unorthodox (possibly un-documented) browser behavior in order to execute arbitrary javascript on a page. Welcome to hacking.


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

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

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

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


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

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

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


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

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

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


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

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

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


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

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

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


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

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


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

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

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

Answer:
Maybe detach the process from the current shell process by calling
```
disown
```
?


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

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

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


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

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

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

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

ps We also need to upgrade our Oracle code

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


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

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


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

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


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

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


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

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

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

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


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

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


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

stdio.h : No such file or directory

The code (hello.c) looks like this:

#include < stdio.h >

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

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

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

gcc.exe hello.c

set path=%OLDPATH%

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

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


Question:
For example:

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

Expected output:

int

Answer:
Try:
```
```
#include <typeinfo>

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


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

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


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

header( 'application/javascript' );

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

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

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


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

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

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


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

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


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

E.g.

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

to

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

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

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


Question:
Given the following JSON Date representation:

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

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

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

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

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

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


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

version.release.modification

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

So the following are valid and parse as:

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

But these are not valid:

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

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

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


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

example from Wikipedia/Observer_pattern:

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

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

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

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

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

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


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

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


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

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

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

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

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


Question:
Problem:

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

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

Tried so far:

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

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

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

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


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

Is there a Webpart that fills this need?

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


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

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

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

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


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

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

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

Or is there another solution I'm not seeing?

Thanks

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


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

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

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

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

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


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

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

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

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

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


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

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

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


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

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

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


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

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

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

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


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

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

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

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

What is the correct way to do it?

Answer:
```
```
#include <boost/serialization/version.hpp>
```
```
:-)


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

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

Update:

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

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

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


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

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

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

What are the differences between them?

What kind of developers or development are they aimed at?

-Adam

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


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

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