Question:
I have a form with a <textarea> and I want to capture any line breaks in that textarea on the server-side, and replace them with a <br/>.

Is that possible?

I tried setting white-space:pre on the textarea's CSS, but it's still not enough.

Answer:
Have a look at the
```
nl2br()
```
function. It should do exactly what you want.


Question:
So, following a tutorial I found on MSDN I've created what you might call an "engine" using DirectX and C#. I haven't seen a lot of this sort of thing (Personally, that is) done in C# and the majority seem to favour C/C++ so I'm curious as to whether using C# will come back to bite me, or whether I should just go ahead?

The reason I ask is that the tutorial stopped rather suddenly and so there's a basis of something but it's small enough to be ported without much hassle. I like C# myself, but I don't know whether there's something everyone else knows that I don't.

Answer:
I suggest staying with what you are familiar with.  Use of C or C++ should only be considered in your situation if you intend to do some lower level functionality, like implement your own image processing or create custom filters or transforms (depending on what you are using directx for).
Graphic applications can have computationally intensive aspects.  Most of these have been addressed in the DirectX api- which is just as fast if you use it from C++ or from C#.
Where you would consider lower level language: If you are creating some image processing which could perform quicker natively- this only applies if it is not offered by the directx api, such as creating some custom encoders/decoders.  In this case you could create the custom component in another language- and then load it in your C# application separately.  If you are- look into using C++ Intrinsics, which allow you to program for your CPU, and also take a look at GPGPU API's like CUDA.


Question: What is the point of an action returning ActionResult?

Answer: ActionResult is the base class for many different types of controller results.  By returning the base class, the controller action can return different types of results depending on the outcome of the method -- a ViewResult, a RedirectToActionResult, etc.  ActionResult contains all of the data needed by the View or new Action that is the result of the current controller action.


Question:
I have an Excel macro that deletes a sheet, copies another sheet and renames it to the same name of the deleted sheet. This works fine when run from Excel, but when I run it by calling the macro from Python I get the following error message:

Run-time error '1004' - Cannot rename a sheet to the same name as
  another sheet, a referenced object library or a workbook referenced by
  VisualBasic.

The macro has code like the following:

Sheets("CC").Delete
ActiveWindow.View = xlPageBreakPreview
Sheets("FY").Copy After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = "CC"

and the debugger highlights the error on the last line where the sheet is renamed. I've also tried putting these calls directly in python but get the same error message.

Any suggestions are much appreciated!

Thanks.

Answer:
I ran the code inside Excel VBA.
I am guessing that the following line is failing.
```
Sheets("CC").Delete
```
And that is the reason, you can't give the new sheet same name as existing (non-deleted) sheet.
Put
```
Application.DisplayAlerts = False
```
before
```
Sheets("CC").Delete
```
and
```
Application.DisplayAlerts = True
```
once you are finished with the code.
I haven't used python but it seems the library is swallowing that error for you and letting you go ahead to the next statement.
Hope that helps.


Question:
I've inherited a rather large application that really could use some cleanup. There is data access code littered throughout the application. In code behinds, some in business logic classes, some inline in in classic asp pages.

What I'd like to do is refactor this code, removing all the data access code into a few DAL classes.

All the data access is done through stored procedures (Microsoft SQL 2000). There are 300-400 of them.

It seems like there should be an automated way to analyse the store procedures, and automatically generate c# methods for each of them, mapping the Method parameters to the stored procedure parameters, with a method returning a datatable.

I don't have any experience with ORM products, and I'm not sure if what I'm looking for is a full blown ORM, or just a 3rd party utility that will help generate simple wrappers around the sp calls.

Answer:
If you have access to .NET Framework 3.5 and Linq to SQL, you can do it very easily, check this video:
LINQ to SQL: Using Stored Procedures
Using existing stored procedures and
  functions is easy with LINQ. We simply
  drag the stored procedures onto the
  O/R mapping surface and call them from
  the generated Data Context object.


Question: Is there any HTML5 support in IE8?  Is it on the IE8 roadmap?

Answer:
According to
http://msdn.microsoft.com/en-us/library/cc288472(VS.85).aspx#html
, IE8 will have "strong" HTML 5 support. I haven't seen anything discussing exactly what "strong support" entails, but I can say that yes, some HTML5 stuff is going to make it into IE8.


Question:
Forgive me for a potentially silly question here, but in other programming languages (scripting ones like PHP or Perl) it is often easy to dump everything contained within a variable.

For instance, in PHP there are the var_dump() or print_r() functions. Perl has the Data::Dumper CPAN class, etc etc.

Is there something like this for Objective-C? It would be very convenient in a few cases to be able to dump everything like that, instead of using gdb to inspect each variable.

Answer:
Use NSLog() to dump contents of objects. For example:
```
```
NSData* myData = //... assume this exists
NSLog(@"Contents of myData: %@", myData);
```
```
NSLog has a printf-style format string (expects an NSString object) followed by a variable list of parameters, just like printf. The replacement character %@ represents an object the description method on an object. This is useful for dumping most Objective-C objects in Cocoa.
If you want to dump the contents of an object using gdb (I see you tagged this with gdb), use the special "po" directive instead of print. For example:
```
```
gdb) po myData
```
```
will cause gdb to dump the myData object. po is a shortcut for print-object.


Question:
I have included <zlib.h> in my iphone application and the source code I was mocking up the sample code of Molecules provided by Brad Larson, however, when I build the project, it returns the error as below.  Can anyone point out for me whether this is a library linking problem or am I missing something else?

"_deflate", referenced from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o "_inflateEnd",
referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "inflateInit2",
referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "_inflate",
referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "_deflateEnd",
referenced from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o "deflateInit2", referenced
from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o ld: symbol(s) not found collect2: ld
returned 1 exit status

Answer:
In your Target's
```
Build Settings
```
tab, scroll down to the
```
Other Linker Flags
```
section and make sure
```
-lz
```
is in the field. This will link against the built-in zlib, and your error should go away.
After changing the Linker Flags you must select
```
Clean
```
from the
```
Product
```
menu before building again.


Question:
If I have a string "12 23 34 56"

What's the easiest way to change it to "\x12 \x23 \x34 \x56"?

Answer:
```
```
string s = "12 23 34 45";
stringstream str(s), out;
int val;
while(str >> val)
    out << "\\x" << val << " "; // note: this puts an extra space at the very end also
                               //       you could hack that away if you want

// here's your new string
string modified = out.str();
```
```


Question:
Say I have two lists:

var list1 = new int[] {1, 2, 3};
var list2 = new string[] {"a", "b", "c"};

Is it possible to write a LINQ statement that will generate the following list:

var result = new []{
    new {i = 1, s = "a"},
    new {i = 1, s = "b"},
    new {i = 1, s = "c"},
    new {i = 2, s = "a"},
    new {i = 2, s = "b"},
    new {i = 2, s = "c"},
    new {i = 3, s = "a"},
    new {i = 3, s = "b"},
    new {i = 3, s = "c"}
};

?

Edit: I forgot to mention I didn't want it in query syntax. Anyway, based on preetsangha's answer I've got the following:

var result = list1.SelectMany(i =>  list2.Select(s => new {i = i, s = s}));

Answer:
```
```
var result = from l1 in list1
             from l2 in list2
             select new { i = l1, s = l2};
```
```


Question:
I want to output a timestamp with a PST offset (e.g., 2008-11-13T13:23:30-08:00). java.util.SimpleDateFormat does not seem to output timezone offsets in the hour:minute format, it excludes the colon. Is there a simple way to get that timestamp in Java?

// I want 2008-11-13T12:23:30-08:00
String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").format(new Date());
System.out.println(timestamp);
// prints "2008-11-13T12:23:30-0800" See the difference?

Also, SimpleDateFormat cannot properly parse the example above. It throws a ParseException.

// Throws a ParseException
new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").parse("2008-11-13T13:23:30-08:00")

Answer:
```
```
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ss.SZ");
```
```
Is not what exactly you need?


Question:
I am getting the following error when trying to install Visual Studio 2005 on my 64bit, Vista computer:

"1305.Error reading from file
  C:\Program Files (x86)\Microsoft
  Visual Studio 8\Microsoft Visual
  Studio 2005 Standard Edition -
  ENU\SITSetup.dll"

I have successfully used the same DVD's to install Visual Studio on my old XP machine, and I can find the file (SITSetup.dll) on the DVD...and copy it off...so I don't think this is a case of having a bad DVD. At the time the error message pops up, I can see the file on my hard-drive, but it has a 0 size.

I've Googled this problem, and found some ideas, but nothing has worked thus far. Any suggestions would be appreciated.

Answer:
I just installed it yesterday on my Vista box (32-bit, which may be the problem). It seemed to go through fine so I don't know what to tell you other than than when I first launched the app it notified me of "known compatibility issues" and recommended that I install both the SP1 and Vista SP! updates. No further issues past that.
As such, I would suspect either a problem with the 64 bit OS (though
Microsoft says it's fine...
) or other software on your machine. If you have a virus scanner running, for instance, disable it while installing.


Question:
I'm currently using Rcov to get C0 code coverage analysis for a rails project that I'm working on.

However, those results are practically meaningless- I have 100% coverage according to rcov (as it only covers C0 analysis) and I've barely written half the test cases for the functionality that exists thus far.

I'm used to the useful results from the code coverage in Visual Studio 2008 Team, which has C1 coverage.  Are there any tools that provide similar coverage for ruby?

Answer:
At the moment, there are no C1 coverage tools for Ruby. In fact, there aren't
any
coverage tools other than RCov.
Until recently, it was only possible to write tools like this by patching or extending the MRI interpreter in C. Since approximately two years ago, it is also possible to extend JRuby in Java, and there is actually since last month a port of RCov for JRuby. However, this requires both a knowledge of Ruby
and
C, and a pretty deep knowledge at that, because fiddling around with the internals of MRI is not for the faint at heart.
But only with Rubinius will it be possible to write dynamic analysis tools such as code coverage tools in Ruby itself, making tool writing accessible to a much larger portion of the Ruby community. My hope is that this, coupled with the substantial financial backing of tool vendors (many major IDE vendors are either working on or have already introduced Ruby IDEs, including CodeGear (ex-Borland), IntelliJ, NetBeans, Eclipse, SapphireSteel (Ruby in Steel for Visual Studio) and even Microsoft) will lead to rapid innovation in the Ruby tooling space in 2009 and we will see things like C1, C2 coverage, NPath complexity, much more fine-grained profiling and so on.
Until then, the only idea I have is to use Java tools. The JRuby guys try to emit the proper magic metadata to make their generated bytecode at least penetrable by the Java tools. So, maybe it is possible to use Java coverage tools with JRuby. However, I have no idea whether that actually works, nor if it is supposed to work.


Question:
I was remote debugging a stack overflow from a recursive function. The Visual Studio IDE only showed the first 1,000 frames (all the same function), but I needed to go up further too see what the cause was.

Does anybody know how to get VS to 'move up' in a stack listing?

Thanks.

Answer:
I do not believe there is a way to do this via the UI (or even a registry hack).  My guess at the reason is showing all of the frames in a stack overflow situation can have a very negative performance impact.
Most stack frames are the result of bad recursion.  If this is the case, you can likely set a conditional breakpoint on the target function.  Set it to break only when the hit count reaches a certain level.  I'd start with a count of around 1,000.  You may have to experiment a bit to get the right count but it shouldn't take more than a few tries.


Question:
Can anyone tell me what is the difference between XSDObjectGen.exe & XSD.exe?

Is there any way to make XSDObjectGen.exe work in dot net 2.0?

Answer:
Looks like you can use it with VS2005 at least (according to
this article, anyway
)
Just add it to your External Tools collection of VS2005 under "Tools>>External Tools...".
Set your parameters as the following
For VB: $(ItemPath) /l:vb
/f:$(ItemFileName).vb /c /d /t
For C#: $(ItemPath) /l:cs
/f:$(ItemFileName).vb /c /d /t
It does appear that XSD and XSDObjectGen will yield different classes.  In fact, comments in this Rick Strahl article say "
they yield
very
different classes
" in the
article here
.


Question: What is the keyboard short cut in Eclipse to jump to the closing brace of a scope?

Answer:
Place the cursor next to an opening
or closing
brace and punch
Ctrl
+
Shift
+
P
to find the matching brace. If Eclipse can't find one you'll get a
"No matching bracket found"
message.
edit:
as
mentioned by Romaintaz below
, you can also get Eclipse to auto-select all of the code between two curly braces simply by double-clicking to the immediate right of a opening brace.


Question:
I have a string that I would like to tokenize.
But the C strtok() function requires my string to be a char*.
How can I do this simply?

I tried:

token = strtok(str.c_str(), " ");

which fails because it turns it into a const char*, not a char*

Answer:
Duplicate the string, tokenize it, then free it.
```
```
char *dup = strdup(str.c_str());
token = strtok(dup, " ");
free(dup);
```
```


Question:
I was reading about App Engine on wikipedia and came across some GQL restrictions:

JOIN is not supported

can SELECT from at most one table at a time

can put at most 1 column in the WHERE clause

What are the advantages of these restrictions?

Are these restrictions common in other places where scalability is a priority?

Answer:
The datastore that GQL talks to is:
not a relational database like MySQL or PostgreSQL
is a Column-oriented DBMS called BigTable
One reason to have a database like this is to have a very high performance database that you can scale across hundreds of servers.
GQL is not SQL it is SQL-like.
Here are some references:
http://en.wikipedia.org/wiki/Column-oriented_DBMS
http://en.wikipedia.org/wiki/BigTable
http://code.google.com/appengine/docs/datastore/overview.html
http://code.google.com/appengine/docs/datastore/gqlreference.html


Question: What is the difference between request, response and server?

Answer:
A client (web user) makes a
Request
to a
Server
which processes the
Request
and determines the appropriate
Response


Question:
When I'm writing some tight loop that needs to work fast I am often bothered by thoughts about how the processor branch prediction is going to behave. For instance I try my best to avoid having an if statement in the most inner loop, especially one with a result which is not somewhat uniform (say evaluates to true or false randomly).

I tend to do that because of the somewhat common knowledge that the processor pre-fetches instructions and if it turned out that it mis-predicted a branch then the pre-fetch is useless.

My question is - Is this really an issue with modern processors? How good can branch prediction expected to be?

What coding patterns can be used to make it better?

(For the sake of the discussion, assume that I am beyond the "early-optimization is the root of all evil" phase)

Answer:
My answer is:
The reason AMD has been as fast or better than Intel at some points is the past is simply that they had better branch prediction.
If your code has no branch prediction, (Meaning it has no branches), then it can be expected to run faster.
So, conclusion: avoid branches if they're not necessary. If they are, try to make it so that one branch is evaluated 95% of the time.


Question:
I know about code-behind files, but what is the best real-world way of Designers that are using DreamWeaver or other Design Tools to work with Visual Studio programmers?

For example, say you have a basic website with user interface forms hitting the database... the database work is definitely done by the developer but how to tie the designed forms with the database coding or client-side logic that may involve events on controls, or other GUI related tie-ins.  Are the graphic designers also controlling application flow?  There seems to be a large disconnect that needs addressed - especially when it comes time to tweak the design after it's been implemented.

Answer:
The best way is to make sure that your designers have some knowledge of what kind of HTML they will be working with.
Every ASP.NET developer is aware of MS-HTML, that lovely nesting of HTML tables, but designers aren't. Designers have their own requirements to meet and they'll do them in the best manner possible. Sadly it's not often good for us.
I am always frustrated when I receive a design from our UI team which shows radio-buttons nicely layed out in a grid using floating div's. Then I have to shatter their dreams that no, I can't generate you that HTML (ok, I can with the use of ControlAdapters, but every time they are different designs!).
Try and have a 90%/ 10% rule, where 90% of the design is done before the ASP.NET starts and the 10% is done once the ASP.NET is completed, and done against ASP.NET generated HTML.
And make sure you're using source control! Code doesn't exist unless it's in source control! And thanks to the latest TFS PowerTools there's a lovely Windows Shell integration component so you don't need to use VS to check in and out now more :D


Question:
Basically, I'm trying to write the following (pseudocode) in an ASP.NET HttpModule:

*pre-code*
try { handler.ProcessRequest(...) }
catch (Exception) { *error-code* }
finally { *post-code* }

I've found that I can hook into HttpModule.PreExecuteHandler for "pre-code" and .Error for "error-code".  But PostExecuteHandler doesn't seem to be running reliably.

BeginRequest and EndRequest run reliably but are too early for the code I need to write, which requires inspection of the handler that was chosen to execute.  The handler isn't chosen until after BeginRequest.

Is there a best practice for writing this kind of wrapper?

Thanks!

Answer:
Add this to your Global.asax file:
```
```
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
    //
}

protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
    //
}
```
```
That should work 100%.


Question: How can I prevent the user from being able to resize an image in designMode?  (disable the handles when image is clicked)

Answer:
Say you turn contentEditable on like this:
```
```
document.body.contentEditable = true;
```
```
All you have to do is turn it off for all (or some) images.
```
```
var imgs = document.getElementsByTagName("IMG");
for (var i = 0; i < imgs.length; ++i) {
    imgs[i].contentEditable = false;
}
```
```


Question:
I'm making a Java application with an application-logic-thread and a database-access-thread.
Both of them persist for the entire lifetime of the application and both need to be running at the same time (one talks to the server, one talks to the user; when the app is fully started, I need both of them to work).

However, on startup, I need to make sure that initially the app thread waits until the db thread is ready (currently determined by polling a custom method dbthread.isReady()).
I wouldn't mind if app thread blocks until the db thread was ready.

Thread.join() doesn't look like a solution - the db thread only exits at app shutdown.

while (!dbthread.isReady()) {} kind of works, but the empty loop consumes a lot of processor cycles.

Any other ideas? Thanks.

Answer:
This applies to all languages:
You want to have an event/listener model.  You create a listener to wait for a particular event.  The event would be created (or signaled) in your worker thread.  This will block the thread until the signal is received instead of constantly polling to see if a condition is met, like the solution you currently have.
Your situation is one of the most common causes for deadlocks- make sure you signal the other thread regardless of errors that may have occurred.  Example- if your application throws an exception- and never calls the method to signal the other that things have completed.  This will make it so the other thread never 'wakes up'.
I suggest that you look into the concepts of using events and event handlers to better understand this paradigm before implementing your case.
Alternatively you can use a blocking function call using a mutex- which will cause the thread to wait for the resource to be free.  To do this you need good thread synchronization- such as:
```
```
Thread-A Locks lock-a
Run thread-B
Thread-B waits for lock-a
Thread-A unlocks lock-a (causing Thread-B to continue)
Thread-A waits for lock-b
Thread-B completes and unlocks lock-b
```
```


Question:
Is it possible to set some image as title of Navigation bar?

I think NYTimes application used a Navigation bar and title is look like image file (the reason why it's seems UINavigationBar is because they use right button to search).

Answer:
You can use an
```
UIImageView
```
for the
```
UINavigationItem.titleView
```
property, something like:
```
```
self.navigationItem.titleView = myImageView;
```
```


Question:
Try as I might, I'm unable to resolve an address to IP. The code snippet is shown below. I keep getting the No such host is known exception, even though I could access google with my browser (The DNS server is almost certainly working). I'm however behind company's firewall.

try
{
   foreach (IPAddress address in Dns.GetHostAddresses("www.google.com"))
   {
      Console.WriteLine(address.ToString());
   }
}
catch (SocketException e)
{
   Console.WriteLine("Source : " + e.Source); // System
   Console.WriteLine("Message : " + e.Message); // No such host is known
}

Answer:
There is nothing wrong with your code.  Given that you can access www.google.com from a web browser the next most likely problem is that the web browser is using a proxy server.  The web browser is actually accessing www.google.com through the proxy server which is allowed through the firewall.  The simple application you wrote is not allowed through the firewall and is resulting in an exception.
You can verify this by looking at the proxy settings in Internet Explorer.
Tools -> Options -> Connections -> Lan Settings
There will be a proxy server group of settings.  If there is a value present, this is almost certainly your problem.


Question:
I just uploaded my first ASP.NET (as part of my learning of vb.net) and got into awful mess with the connection pooling (funny things happen when there are more than 1 user of your web site) all sorted now by better use of the try catch statements (well the idea was to learn) BUT I was wondering if this is the best / final method, now if the try fails, then a LOT of the detail on the page isn't placed/updated, so if you are doing some database work and the try fails, do you reload the page ... redirect to self and hope it work the next time ... or just inform the user there was a error and they should try again ?

Thanks

Answer:
You could create an app that looks for contiguous block of text disregarding formatting tags (if required).  You could do this by using a DOM parser and walking the tree, keeping track of the immediate parent (because that is your output).
Start form parent nodes and traverse the tree for each node that is just formatting, it would continue the 'count' within that sub block.  It would count the characters of the content.
Once you find the most content block, traverse back up the tree to its parent to get your answer.
I think your solution relies on how you traverse the DOM and keep track of the nodes that you are scanning.
What language are you using? Any other details for your project?  There may be language specific or package specific tools you could use as well.


Question:
I mean what the most efficient way to get information about the quantity of your page's items and make sql query with LIMIT that you need. or I should get all items and then crop array with php functions?

now I do 2 queries: first to count all items and second to get items that I need with LIMIT.

OK, I'll be more concrete. For example I need to show a question on my page and 20 answers to this question. At the bottom there shold be page control: links to the next, prev page and so on. I want to show proper number of links (number of answers/20) and when I go to any link I want to recieve proper answers (for example 41 to 60 on the 3d page). So what's the best way to get number of items (answers) to show proper number of links and to get proper answers for each link?

Answer:
I'm assuming you want a count of the number of rows you'll be reading so as to do some pagination or similar? I don't understand your need for the LIMIT in the context of your question. However, if you just want a count of how many rows have been found, use one of the following.
You select the count of all rows such as:
```
```
select count(*) as counted, name, address
from contact
```
```
Or found rows:
```
```
SELECT SQL_CALC_FOUND_ROWS, name, address
from contact
```
```
This may be mysql specific I'm not sure.
Update:
For pagination you would do something like the following - (Psuedocode)
$rows = array($result)
$num_rows = sql_calc_found_rows
$per_page = 20
$pages = ceil($num_rows / $per_page)
page
$rows_this_page = array()
$rows_this_page = get_values($rows, (min index)$page_number * $per_page - $per_page, (max index)$page_number * $per_page - 1)


Question:
I have two machines setup to run Visual Studio 2008 (SP1) & NET Framework 3.5 (SP1). If I create a .tt file in a console appliaction on machine #1 it automatically creates the sub .cs file for me, however if I do the exact same on machine #2 then no sub .cs file is created.

I have tried toggling the "Show All Files" option, restarting visual studio (multiple times), added new .tt files (with the same outcome), tried it in both a C# and a VB.NET project and Google is drawing up blanks.

Is it possible for T4 text templates to have been disabled somehow? If so, then how the heck do I turn them back on, it's annoying :-).?

Answer:
I'm assuming you want a count of the number of rows you'll be reading so as to do some pagination or similar? I don't understand your need for the LIMIT in the context of your question. However, if you just want a count of how many rows have been found, use one of the following.
You select the count of all rows such as:
```
```
select count(*) as counted, name, address
from contact
```
```
Or found rows:
```
```
SELECT SQL_CALC_FOUND_ROWS, name, address
from contact
```
```
This may be mysql specific I'm not sure.
Update:
For pagination you would do something like the following - (Psuedocode)
$rows = array($result)
$num_rows = sql_calc_found_rows
$per_page = 20
$pages = ceil($num_rows / $per_page)
page
$rows_this_page = array()
$rows_this_page = get_values($rows, (min index)$page_number * $per_page - $per_page, (max index)$page_number * $per_page - 1)


Question:
I've recently had my PC upgraded to Vista, which means it includes IIS7. The problem is that the ASP.NET website we're working on doesn't work anymore. I get an error because the application is trying to connect to the SQL Server with NT AUTHORITY/ANONYMOUS LOGON instead of my domain user, and anonymous isn't authorized. I've tried several things, but no solution yet:
- install and enable the 'IIS Metabase and IIS 6 configuration compatibility'
- enable Windows Authentication for this website
- created a different Application Pool with managed pipeline mode set to Classic
- enabled IIS6 WMI compatibility and IIS6 management console (getting desperate here)

In our web.config there's  and in our machine.config there's . I've tried putting impersonate to false and entering my domain  user and password in the machine.config (it used to be like this) but that didn't help either.

Are there things I'm missing? Has anyone else had a similar problem?

Answer: How does your application authenticate with SQL Server? Does it use SQL or Windows Auth? I hope you are trying to use Windows Auth. In that case, your IIS worker process should be running under that Windows user account. If not, it should at the least impersonate a Windows user account that has necessary access rights to SQL Server. If you have impersonation enabled and if you are using the right Windows user account and if SQL Server authenticates using Windows auth and if you are still unable to access SQL Server, you may be running into the classic double hop issue. In other words, you are trying to authenticate to IIS once and you are using the same crdentials to authenticate to the SQL Server over a network next(which is your second hop) and Windows does not allow that for security reasons.


Question:
I have an object I am using to store document meta data into a table.  The body text of the document can be very large, sometimes > 2GB so I will be storing it into a nvarchar(max) field in SQL 2008.  I'll use SQL 2008 later to index that field.  I won't be using filestreams because they are very restrictive to the database and prevents certain types of concurrency locking schemes.

This object is exposed to the developer via LinqToSQL.  My concern is that the field will be to large and I have seen .Net bomb out with an OutOfMemory exception if the text is > 1.5 GB.

So I am wondering, can I treat this blob as a stream with Linq?  Or do I have to bypass Linq altogether if I want to use a blob?

Answer:
Given the answer to
"Can a LINQ query retrieve BLOBs [...]"
I
suspect
you're out of luck. The
System.Data.Linq.Binary
type doesn't have any mechanism for streaming - basically it's just an immutable byte array representation.
There may be some deep LINQ mojo you could invoke, but I suspect it would really have to be pretty deep.
It's possible that the Entity Framework would handle it - I haven't investigated that.


Question:
How do I run a batch file each time windows boots up also I need to run it in the back ground(without that command window getting displayed)? I use Windows Xp.
My actuall requirement is I want to start the Tracd server using the command line commands whenever Windows boots up.

Answer:
Add your program in the
registry
:
Run - These are the most common startup locations for programs to install auto start from. By default these keys are not executed in Safe mode. If you prefix the value of these keys with an asterisk, *, is will run in Safe Mode.
Registry Keys:
```
```
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run registry key
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run registry key
```
```
Then you can launch your batch in an
invisible mode
:
```
```
wscript.exe "C:\yourpath\invis.vbs" "your_file.bat"
```
```
In invis.vbs put...
```
```
CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False
```
```


Question: When interviewing for a programming position, did you ever get an answer to your question that you didn't quite expect? The answer could've been quite smart that you didn't even know or it could've been a dumbest answer you never expected. I'm expecting technical type of questions but anything interesting is fine.

Answer:
As an interviewer I had not been surprised very often.  Most of the people have been respectful and intelligent.  I had only been surprised by how quiet and nervous some people get or how little they tried to answer some of the technical questions.
As an interviewee I've given answers that were not expected.  There was one occasion where I gave an answer at an early stage interviewer for large multinational company- and they simply did not understand the solution.  Lesson learned: never give a 'different' or 'out of the box' answer unless it is in writing and the person receiving it is technical in that area.  Otherwise, they may simply regard it as incorrect.  Give the answer you think will be the norm- because in most cases the early interviewer has a very short list of the 'possible' answers.
Update:
The interview I was referring to was a 4th or 5th stage phone screen- so I guess it is not as applicable.  The question was one of those ones that involve 'assume you have infinite memory' so I played on that coming up with some strange 'what if' scenario.  The 'best' answer was one that was more to the point using traditional methods.


Question: How do I make icons for my exe file when compiling my Python program?

Answer:
I was searching for this a while ago, and found this:
http://www.mail-archive.com/pygame-users@seul.org/msg05619.html
Quote from above link:
The setup.py File: PY_PROG =
'trek10.py' APP_NAME = 'Trek_Game'
cfg = {
```
```
'name':APP_NAME,
'version':'1.0',
'description':'',
'author':'',
'author_email':'',
'url':'',

'py2exe.target':'',
'py2exe.icon':'icon.ico', #64x64
'py2exe.binary':APP_NAME, #leave off the .exe, it will be added

'py2app.target':'',
'py2app.icon':'icon.icns', #128x128

'cx_freeze.cmd':'~/src/cx_Freeze-3.0.3/FreezePython',
'cx_freeze.target':'',
'cx_freeze.binary':APP_NAME,
}
```
```
--snip--


Question:
I want to use Oracle exception to handle errors that might happen in the code below. If a user provides the book ID and/or employee ID that doesn't exist in the database,  NO_DATA_FOUND exception will be raised. Thus, how can I know which statement raises this exception.

CREATE OR REPLACE PROCEDURE TEST_EXCEPTION
(
    book_id_in IN book.book_id%TYPE,
    emp_id_in IN emp.emp_id%TYPE
)
IS

v_book_desc book.description%TYPE;
v_emp_name emp.emp_name%TYPE;

BEGIN

SELECT description into v_book_desc FROM book WHERE book_id = book_id_in;

...

SELECT emp_name into v_emp_name FROM emp WHERE emp_id = emp_id_in;

...

EXCEPTION
     WHEN NO_DATA_FOUND THEN
         /* Do something */

END TEST_EXCEPTION;

I appreciate any suggestion or guidance. Thank you.

Answer:
You can set a variable before the given statements. Like;
```
```
CREATE OR REPLACE PROCEDURE TEST_EXCEPTION ( book_id_in IN book.book_id%TYPE, emp_id_in IN emp.emp_id%TYPE ) IS

v_book_desc book.description%TYPE; v_emp_name emp.emp_name%TYPE;
statementIndex number(1, 0);

BEGIN

statementIndex := 1;
SELECT description into v_book_desc FROM book WHERE book_id = book_id_in;

...

statementIndex := 2;
SELECT emp_name into v_emp_name FROM emp WHERE emp_id = emp_id_in;

...

EXCEPTION WHEN NO_DATA_FOUND THEN
if statementIndex = 1
then
/* Do something */
else
/* Do something */
endif;

END TEST_EXCEPTION;
```
```


Question:
I have checked in a huge Eclipse project from my desktop computer to the SVN server.  I did it using the command line.  However, by mistake I committed all the compiled classes also in the server.

For every plug-in, there is a directory /bin/ that contains the compiled classes.

Is there a way to quickly delete in the server all directories that match this pattern using the command line?

Additionally, is there a way to tell svn to ignore bin directories by default?

Answer:
From
here
(for the 'additionally part'):
Click on Window -> Preferences
Select Team -> Ignored Resources
Click on Add Pattern and enter "bin"
Click on Apply and then OK
For the bin directories, do you have svn 1.5 ?
Because if you do,
```
'svn rm --keep-local'
```
allows to pull them from version control but
not
delete it from your machine.
You can do it with
Tortoise
(Delete (keep local))


Question: The C++ standard dictates that member variables inside a single access section must be layed out in memory in the same order they were declared in.  At the same time, compilers are free to choose the mutual ordering of the access sections themselves.  This freedom makes it impossible in theory to link binaries created by different compilers.  So what are the remaining reasons for the strict in-section ordering?  And does the <s>upcoming C++09</s> new C++11 standard provide a way to fully determine object layouts "by hand"?

Answer:
This freedom makes it impossible in theory to link binaries created by different compilers.
It's impossible for a number of reasons, and structure layout is the most minor. vtables, implementations of
```
operator new
```
and
```
delete
```
, data type sizes...
So what are the remaining reasons for the strict in-section ordering?
C compatibility, I would have thought, so that a struct defined in C packs the same way it does in C++
for a given compiler set
.
And does the new C++
09
11 standard provide a way to fully determine object layouts "by hand"?
No, no more than the current standard does.
For a
```
class
```
or
```
struct
```
with no vtable and entirely private (or public) fields, though, it's already possible if you use the
```
[u]int[8|16|32|64]_t
```
types. What use case do you have for more than this?


Question: I looked it up in Wikipedia, and there is only one line there. Anyone have a more detailed description for it? Ubuntu releases their OS with this notation, but I was unable to find a detailed description over what it means/includes. I've already read the Ubuntu notation but need a more general description, not how Ubuntu has implemented it.

Answer:
From the Ubuntu Wiki:
LTS is an abbreviation for “Long Term
  Support”.
We issue a new desktop and server
  release every six months. That means
  you'll always have the latest and
  greatest applications that the open
  source world has to offer.
Ubuntu is designed with security in
  mind. You get free security updates
  for at least 18 months on the desktop
  and server.
With the Long Term Support (LTS)
  version you get three years support on
  the desktop, and five years on the
  server. There is no extra fee for the
  LTS version, we make our very best
  work available to everyone on the same
  free terms. Upgrades to new versions
  of Ubuntu are and always will be free
  of charge.


Question:
The C++ standard imposes an ordering on class member variables in memory.  It says that the addresses of member variables have to increase in the order of declaration, but only inside one access section.  Very specifically, this does not seem to prevent compilers from laying out access sections in an interleaved way.  For example:

class X {
public:
   int i;
   int j;
private:
   int k;
   int n;
}

Does the standard allow compilers to lay out the data members in the order i, k, j, n?  This would give compilers some (limited) freedom in optimizing object layout without violating the standard.

Answer:
And no, i think he is NOT trying to spam. This is a valid question and quite interesting i think.
Ok now i think compilers can do that. The standard says in 9.2. p12:
```
Implementation alignment require-
ments might cause two adjacent members not to be allocated immediately after each other; so might
requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
```


Question:
How can I check which version of Apache is installed on a Debian machine?

Is there a command for doing this?

Answer:
Try apachectl -V:
```
```
$ apachectl -V
Server version: Apache/2.2.9 (Unix)
Server built:   Sep 18 2008 21:54:05
Server's Module Magic Number: 20051115:15
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
... etc ...
```
```
If it does not work for you, run the command with
```
sudo
```
.


Question:
As being quite a newbie in linux, I have the follwing question.
I have list of files (this time resulting from svn status) and i want to create a script to loop them all and replace tabs with 4 spaces.

So I want from

....
D      HTML/templates/t_bla.tpl
M      HTML/templates/t_list_markt.tpl
M      HTML/templates/t_vip.tpl
M      HTML/templates/upsell.tpl
M      HTML/templates/t_warranty.tpl
M      HTML/templates/top.tpl
A  +   HTML/templates/t_r1.tpl
....

to something like

for i in <files>; expand -t4;do cp $i /tmp/x;expand -t4 /tmp/x > $i;done;

but I dont know how to do that...

Answer:
I would use sed, like so:
```
```
for i in files
do
    sed -i 's/\t/    /' "$i"
done
```
```
That big block in there is four spaces. ;-)
I haven't tested that, but it
should
work.  And I'd back up your files just in case.  The -i flag means that it will do the replacements on the files in-place, but if it messes up, you'll want to be able to restore them.
This assumes that $files contains the filenames.  However, you can also use Adam's approach at grabbing the filenames, just use the sed command above without the "$i".


Question:
HI,

I have 3 tables: Clips, Books and relationships between ClipBook

Problem is:
i need get book that has bookID=4 with some clips i mean many-to-many

in simple text sql it will be something like this:

select * from Clips where clipID in (select clipID from ClipBook where bookID=4)

Question is:

How can i do this with Linq without operator Join of course

Answer:
I would use sed, like so:
```
```
for i in files
do
    sed -i 's/\t/    /' "$i"
done
```
```
That big block in there is four spaces. ;-)
I haven't tested that, but it
should
work.  And I'd back up your files just in case.  The -i flag means that it will do the replacements on the files in-place, but if it messes up, you'll want to be able to restore them.
This assumes that $files contains the filenames.  However, you can also use Adam's approach at grabbing the filenames, just use the sed command above without the "$i".


Question:
It's a simple case of a javascript that continuously asks "are there yet?" Like a four year old on a car drive.. But, much like parents, if you do this too often or, with too many kids at once, the server will buckle under pressure..

How do you solve the issue of having a webpage that looks for new content in the order of every 5 seconds and that allows for a larger number of visitors?

Answer:
stackoverflow does it some way, don't know how though.
The more standard way would indeed be the javascript that looks for new content every few seconds.
A more advanced way would use a
push-like
technique, by using
Comet
techniques (long-polling and such). There's a lot of interesting stuff under that link.
I'm still waiting for a good opportunity to use it myself...
Oh, and here's a link from stackoverflow about it:
Is there some way to PUSH data from web server to browser?


Question:
How do I get the difference in days between 2 dates in SQLite? I have already tried something like this:

SELECT Date('now') - DateCreated FROM Payment

It returns 0 every time.

Answer:
```
```
SELECT julianday('now') - julianday(DateCreated) FROM Payment;
```
```


Question:
I have hit a classic problem of needing to do a string replace on a text field in an sql 2000 database. This could either be an update over a whole column or a single field I'm not fussy.

I have found a few examples of how to use updatetext to achieve it but they tend to be in stored procedures, does anyone know of a similar thing that is wrapped into a function so I can use it like I would usually use Replace(). The problem with the Replace() function for anyone who isn't aware is that it doesn't support text fields.

Edit: I realised I could probably get away with varchar(8000) so have swapped the fields to this type which fixes the issue. I never found a true solution.

Answer:
I am afraid you cannot do it within a function
When you try to declare a function like:
```
```
create function dbo.textReplace(
@inText as text)
returns text
as
begin
    return 'a' -- just dummy code
end
```
```
You will get the following error:
```
```
The text data type is invalid for return values.
```
```
In other words you could not write a simple equivalent of REPLACE function for the text data type


Question:
I am writing unit tests for a class, which has a static final variable.
However, since the state of the static final var is modified in each test, I need some way to reinitialize it.

How would this be possible? Would i need to use some sort of a custom classloader?

The variable is initialized as -

 static final CountdownLatch latch = new CountdownLatch(1);

Answer:
One (not very efficient) approach assuming you are using junit and ant.
You could create a separate class for each test method, and then use a forkmode of
```
perTest
```
.
As the
Ant junit task documentation
states:
Controls how many Java Virtual Machines get created if you want to fork some tests. Possible values are "perTest" (the default), "perBatch" and "once". "once" creates only a single Java VM for all tests while "perTest" creates a new VM for each TestCase class. "perBatch" creates a VM for each nested <batchtest> and one collecting all nested <test>s. Note that only tests with the same settings of filtertrace, haltonerror, haltonfailure, errorproperty and failureproperty can share a VM, so even if you set forkmode to "once", Ant may have to create more than a single Java VM. This attribute is ignored for tests that don't get forked into a new Java VM. since Ant 1.6.2


Question:
Since MySQL doesn't seem to have any 'boolean' data type, which data type do you 'abuse' for storing true/false information in MySQL?

Especially in the context of writing and reading from/to a PHP script.

Over time I have used and seen several approaches:

tinyint, varchar fields containing the values 0/1,

varchar fields containing the strings '0'/'1' or 'true'/'false'

and finally enum Fields containing the two options 'true'/'false'.

None of the above seems optimal. I tend to prefer the tinyint 0/1 variant, since automatic type conversion in PHP gives me boolean values rather simply.

So which data type do you use? Is there a type designed for boolean values which I have overlooked? Do you see any advantages/disadvantages by using one type or another?

Answer:
I use TINYINT(1) in order to store boolean values in Mysql.
I don't know if there is any advantage to use this... But if i'm not wrong, mysql can store boolean (BOOL) and it store it as a tinyint(1)
http://dev.mysql.com/doc/refman/5.0/en/other-vendor-data-types.html


Question:
I'm just starting to try out phpunit on some existing code. The naming convention we use is that the MyClass class should be in MyClass.class.php. PHPUnit seems to require that the file should be called MyClass.php.

Is there any way around this?

I noticed it while trying to generate a skeleton test class:

phpunit --skeleton-test MyClass.class

PHPUnit 3.3.4 by Sebastian Bergmann.

Could not find class "MyClass.class" in "/home/jd/skeleton/classes/MyClass.class.php".
Fatal error: Call to a member function getOutClassName() on a non-object in /usr/share/php/PHPUnit/TextUI/Command.php on line 470

Answer:
Its not a requirement, its just assumptive. You can write your own test-cases.
Skeleton just makes a mock-up one "the easy way" that makes dummy functions for all your classes dummy functions.
Also,
```
```
phpunit --skeleton-test MyClass  MyClass.class.php
```
```
Might do what you want.
```
```
Usage: phpunit [switches] UnitTest [UnitTest.php]
       phpunit [switches] <directory>

--skeleton-class         Generate Unit class for UnitTest in UnitTest.php.
--skeleton-test          Generate UnitTest class for Unit in Unit.php.
```
```
so by that reasoning, if you don't tell it what file the class is in it will try guess, if you do tell it what file the class is in, it wont guess.


Question:
During navigation of the java.lang.reflect.Method class I came across the method isBridge. Its Javadoc says that it returns true only if the Java spec declares the method as true.

Please help me understand what this is used for! Can a custom class declare its method as a bridge if required?

Answer:
A bridge method may be created by the compiler when extending a parameterized type whose methods have parameterized arguments.
You can find in this class
BridgeMethodResolver
a way to get the actual Method referred by a 'bridge method'.
See
Create Frame, Synchronize, Transfer Control
:
As an example of such a situation, consider the declarations:
```
```
class C<T> { abstract T id(T x); }
class D extends C<String> { String id(String x) { return x; } }
```
```
Now, given an invocation
```
```
C c = new D();
c.id(new Object()); // fails with a ClassCastException
```
```
The erasure of the actual method being invoked,
```
D.id(String)
```
differs in its signature from that of the compile-time method declaration,
```
C.id(Object)
```
. The former takes an argument of type String while the latter takes an argument of type Object. The invocation fails with a ClassCastException before the body of the method is executed.
Such situations can only arise if the program gives rise to an unchecked warning (
§5.1.9
).
Implementations can enforce these semantics by creating bridge methods. In the above example, the following bridge method would be created in class D:
```
```
Object id(Object x) { return id((String) x); }
```
```
This is the method that would actually be invoked by the Java virtual machine in response to the call
```
c.id(new Object())
```
shown above, and it will execute the cast and fail, as required.
See also
Bridge
:
as mentioned in the comment, bridge methods are also needed for
covariant overriding
:
In Java 1.4, and earlier, one method can override another if the signatures match
exactly.
In Java 5, a method can override another if the arguments match exactly
but the return type
of the overriding method, if it is a
subtype
of the return type of the other method.
Typically, a method
```
Object clone()
```
can be overridden by a
```
MyObject clone()
```
, but a bridge method will be generated by the compiler:
```
```
public bridge Object MyObject.clone();
```
```


Question:
how do i make an autocomplete textbox in asp?
but i need to get the autocomplete data by querying the database.
I dont really know how to explain this, sory if theres not enough detail.
i cant use ajax, because i think i will have compability issues with my old app.
so im thinking of doing this using java script. or is there a way to do this by using .net?
im using C# for codebehind. thanks

Answer:
It's going to be a lot of effort without using some third party autocomplete I think - not sure what you mean by 'I can't use ajax', but how about using the
ASP.NET AJAX autocomplete control
, setting the
```
ServiceMethod
```
property to a static Page Method in your code behind? That keeps it contained within your page at least.
The Page Method can go off to your database, and return a String[] of results.
If you decide to use it, you'll need to set the
```
EnablePageMethods
```
property to
```
true
```
in the
```
<asp:ScriptManager>
```
control.


Question:
I have a webservice running under sharepoint, on a bog-standard Server2003/IIS6 setup.  This webservice needs to open and read a file from a share on another machine in the same domain. At the moment I am getting a

System.UnauthorizedAccessException: Access to the path '\strand\DROPBOXES\MattTrinder\SharepointShared\bd116dfa-be0e-4c58-93e6-3fb93fa0ef22.tmp' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

What permissions do I need to grant to which accounts to allow this webservice to open and read the file ?

Using "\\sharepointserver\c$" works fine...

Thanks

Matt

Answer:
The account you grant access to, has to exist on the target (where the share exists) as well (either the same domain account, or a local account with the same password). Since the IIS-user normally has an auto-generated password and is local, this is hard.
The way we solve this, is to run the website as a different user (that we created ourselves), and grant this user permissions to access the share on the remote PC. Note that both the sharing permissions have to be correct, and the file system permissions.


Question: What is the best way to convert an Int value to the corresponding Char in Utf16, given that the Int is in the range of valid values?

Answer:
```
```
int i = 65;
char c = Convert.ToChar(i);
```
```


Question:
I have an arraylist that contains items called Room. Each Room has a roomtype such as kitchen, reception etc.
I want to check the arraylist to see if any rooms of that type exist before adding it to the list.
Can anyone recommend a neat way of doing this without the need for multiple foreach loops?

(.NET 2.0)

I havent got access to the linq technology as am running on .net 2.0. I should have stated that in the question.
Apologies

Answer:
```
```
if (!rooms.Any (r => r.RoomType == typeToFind /*kitchen, ...*/))
  //add it or whatever
```
```


Question: I have installed m2eclipse plugin from http://m2eclipse.codehaus.org/. Now I want to use that as a standalone build tool but I am unable to find the installation directory. Can anyone help me in this?

Answer:
I am not sure to understand what you want.
m2eclipse is a
plugin
for Eclipse, thus it must be run inside Eclipse.
To have a standalone build tool, I suggest that you just download directly the
Maven2 binaries files
, and install it on your computer, if it is not already done!
For your information, all plugins are stored in the eclipse-dir/plugins directory, as a subdirectory or as a JAR file.


Question:
What is the best approach to play a sequence of flv video files in Flash (with actionscript)? My goal is to have the transitions occur as smoothly as possible.

Currently i'm using the netStream class and capturing the onStatus events to play the next video when the current video has reached it's end duration. Althought this approach works fine, there is still a small gap between the ending of the current video and start of the next. Any ideas on how to optimize this method?

Thanks in advance :)

Answer:
The problem is not the linq itself,
you need to be sure that the context or provider object is able to fetch the data.
try testing the
```
```
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
```
```
objects and see if they are populated or if they behaving as required.
you may want to search the generated code for c__DisplayClass1 and see what you can see there. some times the generated code dose some weird things.
when you step into you code check the locals and the variable values. this may also give you some clues.
Edit :
Have you tried to return a List<> collection ? or an Enumerable type?
Edit :
What is the real type of the
item
and query may not be iterable


Question:
Why EAccessViolation is raised when executing the code below?

uses
  Generics.Collections;
  ...

var
  list: TList<TNotifyEvent>;
  ...

begin
  list := TList<TNotifyEvent>.Create();
  try
    list.Add(myNotifyEvent);
    list.Remove(myNotifyEvent);  // EAccessViolation at address...
  finally
    FreeAndNil(list);
  end;
end;

procedure myNotifyEvent(Sender: TObject);
begin
  OutputDebugString('event');  // nebo cokoliv jineho
end;

Answer:
the above code is used in TForm1 ...
```
```
uses
  Generics.Collections;

procedure TForm1.Button1Click(Sender: TObject);
var
  list: TList<TNotifyEvent>;
begin
  list := TList<TNotifyEvent>.Create();
  try
    list.Add(myNotifyEvent);
    list.Remove(myNotifyEvent);  // EAccessViolation at address...
  finally
    FreeAndNil(list);
  end;
end;
procedure TForm1.myNotifyEvent(Sender: TObject);
begin
  OutputDebugString('event');  // nebo cokoliv jineho
end;
```
```


Question:
In OOP languages like C# or VB.NET, if I make the properties or methods in a super class protected I can't access them in my Form - they can only be accessed in my class that inherits from that super class.

To access those properties or methods I need to make them public, which defeats encapsulation, or re-write them into my class, which defeats inheritance.

What is the right way to do this?

Answer:
If you have code which needs to ask an Class to perform a specific operation but the class does not present your code with a means to do that then the Class doesn't fulfill you codes requirements.
Its bit like saying I've got a Car (Automobile) that has a protected steering wheel so I can't access it.  The car is no use to me.
Either make those members Public (or at least internal) and use them or ditch the class and use one that gives your consuming code the features it needs.
Perhaps what you are really looking for is an interface.  The interface contains the members your code needs and you implement that interface on your class.  The advantage here is that your class can determine that the members are being accessed via this Interface rather than an inheriting subclass.


Question:
Why must Type.Equals(t1, t2) be used to determine equivalent types, and not the equality operator (e.g. for VB.NET, t1 = t2)?

It seems inconsistent with other parts of the .NET API.

Example in VB.NET:

If GetType(String) = GetType(String) Then
    Debug.Print("The same, of course")
End If

causes a compile-time error of "Operator '=' is not defined for types 'System.Type' and 'System.Type'."

Answer:
Given the way types are loaded, that surprises me. Where did you hear this from?
The
docs for System.Type.Equals(Type)
suggest that it's comparing via the
UnderlyingSystemType
property, but I'm not sure under what circumstances two different Type objects would have the same underlying system type.
I'd be really interested to see an example where this mattered... my
guess
is that from anywhere in "user code" they'll be the same thing, but there may be some cunning BCL code where it matters.


Question: There is a space of x*y for text to go on $im (GD Image Resource) how can I choose a font size (or write text such that) it does not overflow over that area?

Answer:
Given the way types are loaded, that surprises me. Where did you hear this from?
The
docs for System.Type.Equals(Type)
suggest that it's comparing via the
UnderlyingSystemType
property, but I'm not sure under what circumstances two different Type objects would have the same underlying system type.
I'd be really interested to see an example where this mattered... my
guess
is that from anywhere in "user code" they'll be the same thing, but there may be some cunning BCL code where it matters.


Question:
The assembly it's trying to find isn't the root assembly - it's a referenced one, but it's in the same folder, and Directory.GetCurrentDirectory() is the folder with all of the files in.

I'm stuck - any suggestions?

Answer:
You can either:
Create a new
```
AppDomain
```
to load the assembly (and set the
```
AppDomain
```
's base directory to the directory containing all the assemblies).
Attach a handler for
```
AppDomain.AssemblyResolve
```
to help the CLR find the assembly's dependencies.
You might be able to add the directory in question to the list of paths to probe. However, it will need to reside somewhere under your application's directory. See the
probe
element for more info.


Question: I can't find a pre-built set of MSVC++ libs for Boost 1.37.0, only the source. I don't understand how their weird build system works... are there any places I can find a download of a visual studio project or something?

Answer:
Building it isn't difficult.
They have a fairly good expanaltion of the default process here:
http://www.boost.org/doc/libs/1_37_0/more/getting_started/windows.html#or-build-binaries-from-source
Download bjam (from sourceforge, there are links from the boost website), as well as the boost sources, make sure bjam is accessible from the boost dir, cd to the boost dir, and run something like the following:
bjam --build-dir= --prefix-dir= --toolset=msvc --build-type=complete install
where  is an temp dir where it can store intermediate files, and  is the final install location. There are all sorts of other options you can play around with, and not all of them are documented very well, but the basics are fairly simple.
For more help, you can run bjam --help from the boost source dir.


Question:
I always hear that using "lastInsertId" (or mysql_insert_id() if you're not using PDO) is evil. In case of triggers it obviously is, because it could return something that's totally not the last ID that your INSERT created.

$DB->exec("INSERT INTO example (column1) VALUES ('test')");
// Usually returns your newly created ID.
// However when a TRIGGER inserts into another table with auto-increment:
// -> Returns newly created ID of trigger's INSERT
$id = $DB->lastInsertId();

What's the alternative?

Answer:
It's not sophisticated and it's not efficient, but if the data you've inserted include unique fields, then a SELECT can obviously yield what you're after.
For example:
```
```
INSERT INTO example (column1) VALUES ('test');
SELECT id FROM example WHERE column1 = 'test';
```
```


Question:
I have a need to populate a Word 2007 document from code, including repeating table sections - currently I use an XML transform on the document.xml portion of the docx, but this is extremely time consuming to setup (each time you edit the template document, you have to recreate the transform.xsl file, which can take up to a day to do for complex documents).

Is there any better way, preferably one that doesn't require you to run Word 2007 during the process?

Regards
Richard

Answer:
I tried myself to write some code for that purpose, but gave up. Now I use a 3rd party product:
Aspose Words
and am quite happy with that component.
It doesn't need Microsoft Word on the machine.
"Aspose.Words enables .NET and Java applications to read, modify and write Word® documents without utilizing Microsoft Word®."
"Aspose.Words supports a wide array of features including document creation, content and formatting manipulation, powerful mail merge abilities, comprehensive support of DOC, OOXML, RTF, WordprocessingML, HTML, OpenDocument and PDF formats. Aspose.Words is truly the most affordable, fastest and feature rich Word component on the market."
DISCLAIMER
: I am not affiliated with that company.


Question:
How to get the number of years between two java.util.Date?

Note: using only java.util.Date

Answer:
How accurate do you need to be?  If approximate is good enough, then I'd do
```
```
long msDiff = date1.getTime() - date2.getTime();
int yearDiff = (int)(msDiff / 1000 / 60 / 60 / 24 / 365.25);
```
```


Question:
Can I use Xpath node set function position() in Delphi's function selectNodes() to select only a certain number of element from a node list? If I do like this:

selectNodes('Item[1]')

its all fine and I get the element with index 1, but when I try

selectNodes('Item[position()<10]')

I get exception 'unknown method', when I try

selectNodes('Item[<10]')

I get 'unexpected token <'.
Im using delphi7 and I also imported new type library into my project with newer versions of msxml.

Answer:
selectNodes requires a string, so you should try:
```
```
selectNodes('Item[position()<10]')
```
```
Or whatever xpath query.


Question:
I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.

Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.

Answer:
I use
SQL Alchemy
with cPython (I don't know if it'll work with IronPython though).  It'll be pretty familiar to you if you've used Hibernate/nHibernate.  If that's a bit too verbose for you, you can use
Elixir
, which is a thin layer on top of SQL Alchemy.  To use either one of those, you'll need
pyodbc
, but that's a pretty simple install.
Of course, if you want to write straight SQL and not use an ORM, you just need pyodbc.


Question:
I want to automate tests on my web application, and it uses postgresql. Does anyone know how define a restore point on a postgresql database and restore to an earlier state?
I heard something about point in time recovery, but i dont if this is what i need.

Thanks in advance

Answer:
I use
SQL Alchemy
with cPython (I don't know if it'll work with IronPython though).  It'll be pretty familiar to you if you've used Hibernate/nHibernate.  If that's a bit too verbose for you, you can use
Elixir
, which is a thin layer on top of SQL Alchemy.  To use either one of those, you'll need
pyodbc
, but that's a pretty simple install.
Of course, if you want to write straight SQL and not use an ORM, you just need pyodbc.


Question:
Given the following class:

class TestClass {
  public void SetValue(int value) { Value = value; }
  public int Value { get; set; }
}

I can do

TestClass tc = new TestClass();
Action<int> setAction = tc.SetValue;
setAction.Invoke(12);

which is all good. Is it possible to do the same thing using the property instead of the method? Preferably with something built in to .net.

Answer:
Properties are really wrappers around methods in .Net, so using reflection you should be able to get the delegate (set_PROPERTY and get_PROPERTY) and then execute them...
See
System.Reflection.PropertyInfo
If has two methods which you can use to get/ set the value - GetGetMethod and GetSetMethod.
So you could write:
```
```
var propertyInfo = typeof (TestClass).GetProperty ("Value");

var setMethod = property.GetSetMethod (); // This will return a MethodInfo class.
```
```


Question: What does "Overloaded"/"Overload" mean in regards to programming?

Answer:
It means that you are providing a function (method or operator) with the same name, but with a different signature.
For example:
```
```
void doSomething();
int doSomething(string x);
int doSomething(int a, int b, int c);
```
```


Question:
I distribute my application using a VS2008 install package, which normally works great.  When I create new versions of the app, I go in and increment the Version property on the install package and verify the RemovePreviousVersions property is set to True.

This works just fine most of the time - I just run the install package for the newer version and the older version is uninstalled and the newer version replaces it.

However, occasionally the install package will run successfully, but when I start the program the old version starts up.  Apparently the old version of the .exe is still present.

I end up having to completely uninstall the software and install the new version, which always works, but is a pain.

The file isn't in use as far as I can tell and the install package doesn't tell me to reboot.

Any ideas about what's going on here?

Answer:
Not a direct answer, but the key difference between an upgrade and an uninstall+ a reinstall is that any custom uninstall steps are not called in 2k8 but are in 2k5.
This is referenced in
Visual Studio 2005 -> 2008/10 Service Installer Project Upgrade issue
The other difference related to this is that in 2k8, the files get upgraded based on the version info resource - if your modules dont have newer versions, they dont get replaced.
In some cases whether you strong name also has effects, but I'm pretty confident the last paragraph covers the issue you're seeing.


Question: In C++, is the return type considered part of the function signature? and no overloading is allowed with just return type modified.

Answer:
Normal functions do not include the return type in their signature.
(
note
: i've rewritten this answer, and the comments below don't apply to this revision - see the edit-history for details).
Introduction
However, the matter about functions and function declarations in the Standard is complicated. There are two layers that have to be considered:
Declarations
Entities
The so-called
function declaration
may declare a function entity or a template entity. If a function entity is declared, then you either have to do with an explicit specialization of a function template (with all arguments specified), or a declaration of an ordinary function. If a template entity is declared, then you are declaring a primary function template, or an explicit specialization where some arguments are not specified. (This is very similar to the relation of "object declaration" and objects or references: The former may declare either an object or a reference. So an
object declaration
may not necessarily declare an object!).
The Standard defines the signature of a function to include the following at
```
1.3.10
```
:
The types of its parameters and, if the function is a class member, the cv- qualifiers (if any) on the function itself and the class in which the member function is declared. The signature of a function template specialization includes the types of its template arguments. (14.5.5.1)
It's missing the return type in this definition, which
is
part of the signature of a function template specialization (i.e a function declaration that declares a function which is a specialization of a template), as pointed out by
```
14.5.5.1
```
(recent C++0x working papers fixed that already to mention the return type in
```
1.3.10
```
too):
The signature of a function template specialization consists of the signature of the function template and of the actual template arguments (whether explicitly specified or deduced).
The signature of a function template consists of its function signature, its return type and its template parameter list.
So what exactly does a signature contain, again?
So, when we ask about the signature of a
function
, we have to give two answers:
For functions that are specializations of function templates, the signature includes the return type.
For functions that are not specializations, the return type is not part of the signature.
Notice, however, that the return type, in any case,
is
a significant part of the type of a function. That is, the following is not valid:
```
```
void f();
int (*pf)() = &f; // different types!
```
```
When is an overload invalid if only the return type differs?
Major compilers currently reject the following code:
```
```
int f();
double f(); // invalid
```
```
But accept the following code:
```
```
template<typename T> int f();
template<typename T> double f(); // invalid?
```
```
However, the
Standard does forbid a function declaration that only differs in the return type
(when defining when an overload is valid, and when not). It does not define precisely what "differs only by return type" means, though.
Standard paragraph references:
When can a function declaration be overloaded:
```
13.1
```
What is a function declaration:
```
7/2
```
and
```
7/5
```
What is the signature of a function template/specialization:
```
14.5.5.1
```
For reference, here is what the most recent C++0x draft n3000 says about "signature" in
```
1.3.11
```
, which is much more complete in its coverage of the different type of entities:
the name and the parameter type list (8.3.5) of a function, as well as the class or namespace of which it is a member. If a function or function template is a class member its signature additionally includes the cv-qualiﬁers (if any) and the ref-qualiﬁer (if any) on the function or function template itself. The signature of a function template additionally includes its return type and its template parameter list. The signature of a function template specialization includes the signature of the template of which it is a specialization and its template arguments (whether explicitly speciﬁed or deduced). [ Note: Signatures are used as a basis for name mangling and linking. — end note ]


Question: I’m trying to make the routing module works with default action or controller, but it doesn’t. I always face with 404 page not found. Did I forget to do something? I really like routing in ASP.NET MVC feature, but I’m not sure I could do the same in MR. I’m using IIS7 with the build from castle trunk for .NET 3.5.

Answer:
How are you configuring the routing? I had issues myself when trying to manage the routing-rules from web.config, but moving it to inline-code on application-start worked for me.
I tried to find an answer to why the xml-way didn't work, but never found one. They made a major rewrite of the routing-engine since RC3, that might have broken it.
Example from Application_OnStart()
```
var rule = new PatternRoute( "default", "/" )
    .DefaultForController().Is()
    .DefaultForAction().Is( "index" );

RoutingModuleEx.Engine.Add( rule );
```
Remember to load the RoutingEngineModule before the MonoRailHandler in web.config.


Question:
I have an have an ASP.Net page which contains a button. This Page contains a ServerSide Paypal button.

When pushed my server does various clever things on the back end and then rewrites the response as a form and some javascript which posts this form to paypal..

This all works great.

However, if the user then elects to click back, they will arrive at my generated self-posting form and that will forward them again to Paypal.

I thought if I could find a way to have my generated form page not exist in the history, then this will solve my problem. but I have no idea how to correct this.

How can I remove my page from the history or just have it never appear?

Update: Thanks to all... Those are some great answers. Upvoted all good ones but went with splattne on account of clever use of hidden field rather than cookies for basis of decision.

Answer:
As a web application, you'll never have full control of the user's browser.  Even if there was a way to instruct the browser to not store the page in history, which I doubt, you can't be sure it'll work.  For example, a clever user could tweak an open-source browser to store every page in history, no matter what.
I think you should try to approach the problem from another angle.  You could, for example, detect that it's the same form which is being forwarded and not send it to paypal the second time.  The important thing is to do it server-side.


Question:
I just came over this syntax in some of the questions in this forum, but Google and any other searchengine tends to block out anything but letters and number in the search so it is impossible to search out "=>".

So can anyone tell me what it is and how it is used?

Answer:
It's the lambda operator.
From C# 3 to C# 5, this was only used for
lambda expressions
. These are basically a shorter form of the
anonymous methods
introduced in C# 2, but can also be converted into
expression trees
.
As an example:
```
```
Func<Person, string> nameProjection = p => p.Name;
```
```
is equivalent to:
```
```
Func<Person, string> nameProjection = delegate (Person p) { return p.Name; };
```
```
In both cases you're creating a delegate with a
```
Person
```
parameter, returning that person's name (as a string).
In C# 6 the same syntax is used for
expression-bodied members
, e.g.
```
```
// Expression-bodied property
public int IsValid => name != null && id != -1;

// Expression-bodied method
public int GetHashCode() => id.GetHashCode();
```
```
See also:
What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)
What is a Lambda?
C# Lambda expression, why should I use this?
(And indeed many similar questions - try the
lambda
and
lambda-expressions
tags.)


Question:
I've some experiences on build application with Asp.Net, but now MVC frameworks become more popular. I would like to try building new multilingual web application using with Asp.Net MVC or Castle MonoRail but I don't know which one is good for me. I don't like the web form view engine, but I like routing feature in Asp.Net MVC.

Could anyone tells about pros and cons between those?

Which ViewEngine is the better as well for overriding the master template?

Answer:
MonoRail and ASP.NET MVC are fundamentally very similar, you should be well off using either one of them. MonoRail has existed much longer and has therefore more higher level features.
The main strength of ASP.NET MVC is it's routeing engine, to be fair MonoRail has pretty much an equivalent routing engine, and with some modification you can use the ASP.NET MVC routing engine with MonoRail as the routing engine is not really in ASP.NET MVC but in System.Web.Routing (Released in .NET 3.5 SP1). ASP.NET MVC and integration with Visual studio is also a plus, and will probably get better as we approach RTM of v1.
The MvcContrib project contains some great view engines, like Spark, NHaml and Brail. No one could be considered "Best", A personal favourite is Spark. For more on spark:
http://dev.dejardin.org/documentation/syntax
The WebForms engine has intellisense which is a great advantage that to my knowledge all alternative view engines lack.


Question:
I'm a bit new to jQuery and hope somebody can help me out.

I'm trying to change an element (li) to another element (div) after the (li) has been dropped.

Sample code:

$("#inputEl>li").draggable({
    revert: true,
    opacity: 0.4,
    helper: "clone"
});
$("#dropEl")
    .droppable({
        accept: ".drag",
        hoverClass: "dropElhover",
        drop: function(ev, ui) {
            // change the li element to div here
        }
});

The problem is, when i use

drop: function(ev, ui) {
     $(ui.draggable).replaceWith("<div>Some content</div>");
}

the original draggable elements will be disabled when the function above is triggered.

I'm using the latest jQuery and jQuery UI stable versions.

Answer:
So, what you want is to keep your original list intact and drop list items into dropEl?
How about this:
```
```
drop: function(ev,ui) {
     $(this).append("
Some content
");
}
```
```
Or, if you want to replace the list elements with a div element and also have the div element draggable, you could try this:
```
```
drop: function(ev, ui) {
        $(ui.draggable).replaceWith("
Some content
");
        $("#inputEl>div").draggable({
            revert: true,
            opacity: 0.4,
            helper: "clone"
        });
    }
```
```
The original draggable call only makes items draggable at the time it is called.  If you change or add elements and want them to be draggable, you will need to call the draggable() function again.


Question: My organization is using CppUnit and I am trying to run the same test using different parameters. Running a loop inside the test is not a good option as any failure will abort the test. I have looked at TestDecorator and TestCaller but neither seems to really fit. Code samples would be helpful.

Answer:
I'm not a C++ programmer but I can help with the unit-test concept:
Test-cases are meant to run isolated and with no dependency on external parameters. Additionally you should keep the number of test-cases down to the minimum which covers most of your code. There are cases, however (and I have already dealt with some), where some tests look the same, differing only by some minor parameters. The best bet then is to write a
fixture
which takes the parameter you're talking about, and then have one test-case for each of the parameters, calling the fixture with it. A generic example follows:
```
```
class MyTestCase

  # this is your fixture
  def check_special_condition(param)
    some
    complex
    tests
  end

  # these are your test-cases
  def test_1
    check_special_condition("value_1")
  end

  def test_2
    check_special_condition("value_2")
  end

end
```
```
Otherwise you're not writing true test-cases, because they're supposed to be reproducible without much knowledge from the one who is executing them. I imagine there are a handful of parameters which are all important as input to the tests. Then why not make each one explicit inside its own test-case? That's also the best way to document then, instead of writing a separate document to guide the programmer which will read the code years later.


Question:
I have a Panel and I am adding controls inside this panel.  But there is a specific control that I would like to float. How would I go about doing that?

pnlOverheadDetails is the panel name

pnlOverheadDetails.Controls.Add(lnkCalcOverhead);

The control named lnkCalcOverhead is the control I'd like to float.

Thanks in advance

EDIT: By float I meant the css style not anything fancy :)

Answer:
If you have a CSS class defined for the control, you could do this before calling the
```
Controls.Add
```
method:
```
```
lnkCalcOverhead.CssClass = "MyClass";
```
```
If you want to use the style attribute directly, try this:
```
```
lnkCalcOverhead.Style.Add("float", "left");
```
```


Question:
I'm trying to create number of Evenement instances and set the date for them:

   for (int i=2004; i<2009; i++){
           evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
                           (Date)formatter.parse(i+"/07/03")));

But I can't seem to get it to work,

Any ideas?

Answer:
You may want to use Calendar to create your dates.
```
```
for (int i=2004; i<2009; i++) {
    Calendar cal = Calendar.getInstance();
    cal.clear();
    // Calendar.JULY may be different depending on the JDK language
    cal.set(i, Calendar.JULY, 3); // Alternatively, cal.set(i, 6, 3);
    evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
            cal.getTime()));
}
```
```
Note that the months are zero-based, so July is 6.


Question:
My website has been giving me intermittent errors when trying to perform any Ajax activities.  The message I get is

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

Details: Error parsing near '

<!DOCTYPE html P'.

So its obviously some sort of server timeout or the server's just returning back mangled garbage.  This generally, unfortunately not always, happe

Answer:
There is an excellent blog entry by Eilon Lipton. It contains of lot of tips on how to avoid this error:
Sys.WebForms.PageRequestManagerParserErrorException - what it is and how to avoid it
Read the comments too. There is a comment of somebody with the same problem: "
I solved it changing server idle time of my app pool on IIS
. It was only 5, so I incremented it and now works."
"The UpdatePanel control uses asynchronous postbacks to control which parts of the page get rendered. It does this using a whole bunch of JavaScript on the client and a whole bunch of C# on the server.
Asynchronous postbacks are exactly the same as regular postbacks except for one important thing: the rendering. Asynchronous postbacks go through the same life cycles events as regular pages (this is a question I get asked often).
Only at the render phase do things get different. We capture the rendering of only the UpdatePanels that we care about and send it down to the client using a special format. In addition, we send out some other pieces of information, such as the page title, hidden form values, the form action URL, and lists of scripts."
Most common reasons for that error:
Calls to Response.Write():
Response filters
HttpModules
Server trace is enabled
Calls to Server.Transfer()


Question: We've all read the benchmarks and know the facts - event-based asynchronous network servers are faster than their threaded counterparts.  Think lighttpd or Zeus vs. Apache or IIS. Why is that?

Answer:
I think event based vs thread based is not the question - it is a nonblocking Multiplexed I/O, Selectable sockets, solution vs thread pool solution.
In the first case you are handling all input that comes in regardless of what is using it- so there is no blocking on the reads- a single 'listener'.  The single listener thread passes data to what can be worker threads of different types- rather than one for each connection.  Again, no blocking on writing any of the data- so the data handler can just run with it separately.  Because this solution is mostly IO reads/writes it doesn't occupy much CPU time- thus your application can take that to do whatever it wants.
In a thread pool solution you have individual threads handling each connection, so they have to share time to context switch in and out- each one 'listening'.  In this solution the CPU + IO ops are in the same thread- which gets a time slice- so you end up waiting on IO ops to complete per thread (blocking) which could traditionally be done without using CPU time.
Google for non-blocking IO for more detail- and you can prob find some comparisons vs. thread pools too.
(if anyone can clarify these points, feel free)


Question:
I am developing an application for PocketPC. When the application starts the custom function SetScreenOrientation(270) is called which rotates the screen. When the application closes the function SetScreenOrientation(0) is called which restores the screen orientation.

This way the screen orientation isn't restored if the user minimizes the application and this is not acceptable.

Does anyone know where (in which event handlers) should SetScreenOrientation(int angle) be called to set the screen orientation on application start, restore orientation on minimize, set the orientation on maximize and restore the orientation on close?

Actually I don't know which event handler handles the Minimize and Maximize event.

Answer:
I don't know what these are called in the C++ world, but in .NET Compact Framework your application form's Resize event would be called when you minimize/maximize a window, and then in the event code you would check the WindowState property of the form to see if its minimized or mazimized.
Altering the state of your PDA from within your application is risky (although there are lots of good reasons to do it), because if your app crashes it will leave the PDA in whatever state it was in.  I've done a lot of kiosk-type (full-screen) apps in Windows Mobile, and one of the tricks to doing this effectively is to hide the WM title bar (the top row with the Windows start button) to keep it from flashing up for a split second every time you open a new form.  If the app crashes, the windows bar remains invisible until you reset the device, which isn't good.  At least with screen rotation the user can restore it manually.


Question:
I would like to implement a sliding notification bar as the one in Firefox or IE for my java application. But I don't want to reinvent the wheel and I'm sure someone out there has already done it and is willing to share.
Do you know any open-source implementation of this in java/swing?

Answer:
There's an example in
Swing Hacks
called "Slide Notes Out from the Taskbar" that seems pretty close to what you want (there's a
preview
on Google's Book Search at the moment).
The code is freely available from the
official O'Reilly Swing Hacks page
, under "examples."  Not sure what the license is, but it's worth a look (Chapter 6, hack 46).  At any rate, Swing Hacks is a worthy purchase at ~$20.


Question:
Is it possible to retrieve variable set in onreadystatechange function from outside the function?

--edit--

Regarding execution of functions:

If its possible i would like to execute ajaxFunction()  with one click

 and then popup() with next click, or
somehow wait for ajax function to end and then call for alert box

In pseudocode:

function ajaxFunction(){
    //creating AJAX
    ...
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function (){
        if(ajaxRequest.readyState == 4){
            //success code
            ======>Here i want to set variable <=====
            var MyVariable='MyContent';
        }
    }
    //Retrieving page
    ....
}

function popup(){
    ajaxFunction();
    alert(MyVariable);
}

Answer:
Why not change
```
MyVariable
```
's scope to outside of the function?
```
```
var MyVariable;
function ajaxFunction(){
    //creating AJAX
     ...
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function (){
        if(ajaxRequest.readyState == 4){
            //success code
            ======>Here i want to set variable <=====
            MyVariable='MyContent';
        }
    }
    //Retrieving page
     ....
}

function popup(){
    ajaxFunction();
    alert(MyVariable);
}
```
```


Question: What is the difference between HTML <input type='button' /> and <input type='submit' />?

Answer:
```
<input type="button" />
```
buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.
```
<input type="submit">
```
buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.
The first submit button of the form is also the one being clicked for
implicit submission
, f.e. by pressing enter in a text input.


Question:
I have a query that works on Postgresql 7.4 but not on Postgresql 8.3 with same database.

Query:

SELECT * FROM login_session WHERE (now()-modified) > timeout;

Gets the following error:

ERROR:  operator does not exist: interval > integer
LINE 1: ...ELECT * FROM login_session WHERE (now()-modified) > timeout ...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Column modified is a timestamp and timeout is an integer.

Is there some settings I need to change on server?

I'm installing an application for a client on new server (ubuntu) so I can't change queries in the application.

Answer:
There are a lot of changes between 7.4 and 8.3. Some of the most drastic were the removal of some automatic casts.
I suppose the "timeout" is in seconds? If so you could change the query to:
```
```
SELECT
    *
FROM
    login_session
WHERE
    (CURRENT_TIMESTAMP - modified) > (timeout * '1 sec'::interval);
```
```


Question: What is the equivalent of Java's System.currentTimeMillis() in C#?

Answer: The framework doesn't include the old seconds (or milliseconds) since 1970. The closest you get is DateTime.Ticks which is the number of 100-nanoseconds since january 1st 0001.


Question: What do you use as a test client for your stateful web services? Is it possible to use SoapUI? Are there best practices in this area?

Answer: I don't know whether it's practical to do this with SoapUI, but I've done things like this with both iTKO LISA and Parasoft SOATest.  It wasn't for testing stateful web services, but simply executing multiple testing steps, storing results that are used in following steps.  Both LISA and SOATest have the ability to define steps in the GUI that can store pieces of responses that are used in later requests.


Question:
I'm trying to do something that gets a cs file in runtime from user make it meaningful to assembly get its properties, methods etc.

Is there a way to do this by reflection in C#?

Answer:
You can compile it reasonably easily using the
CSharpCodeProvider
. You can download the source code for my snippet compiler, Snippy, from the
C# in Depth web site
. That uses CSharpCodeProvider, so you could use it as sample code.


Question:
Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is handled by the controller.

I bind some onclick events to a button, but I find that they sometimes execute in an order I did not expect.

Is there a way to ensure order, or how have you handled this problem in the past?

Answer:
If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.
```
```
$('#mydiv').click(function(e) {
    // maniplate #mydiv ...
    $('#mydiv').trigger('mydiv-manipulated');
});

$('#mydiv').bind('mydiv-manipulated', function(e) {
    // do more stuff now that #mydiv has been manipulated
    return;
});
```
```
Something like that at least.


Question: I have a module that sends an email to a specified email address but I want to default the email recipient to the portal administrator.  How can I retrieve this information?

Answer:
```
```
' get the current portal
Dim portSettings As PortalSettings = PortalController.GetCurrentPortalSettings

' get email address
Dim email as string = portSettings.Email
```
```


Question:
I need to determine which pages of a Word document that a keyword occurs on.  I have some tools that can get me the text of the document, but nothing that tells me which pages the text occurs on.  Does anyone have a good starting place for me?  I'm using .NET

Thanks!

edit: Additional constraint: I can't use any of the Interop stuff.

edit2: If anybody knows of stable libraries that can do this, that'd also be helpful.  I use Aspose, but as far as I know that doesn't have anything.

Answer:
This is how I get the text out,  I believe you can set set the selection range to a page, then you could test that text, might be a little backwards from what you need but could be a place to start.
```
```
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
object missing = Type.Missing;
object fileName = @"c:\file.doc";
object objFalse = false;

wordApplication.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
Microsoft.Office.Interop.Word.Document doc = wordApplication.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,ref objFalse, ref missing, ref missing, ref missing, ref missing);

//I belevie you can define a SelectionRange and insert here
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();

IDataObject data = Clipboard.GetDataObject();
string text = data.GetData(DataFormats.Text).ToString();

doc.Close(ref missing, ref missing, ref missing);
doc = null;

wordApplication.Quit(ref missing, ref missing, ref missing);
wordApplication = null;
```
```


Question: I have SSRS Report being accessed from a Report Server. Is there any way I can give an error message of my own, if my report fails to open there?

Answer:
You need to assign a Country instance to the Country property of the Person instance (not just set the ID).  Something like:
```
```
Person p = new Person();
p.Country = session.Load<Country>(countryId);
session.Save(p);
```
```
Then NHibernate will know what to do.  This will also not cause a DB hit to retrieve country, since the Load method will return a Country proxy and the only thing you're accessing is the Country instance's ID.


Question:
I have a web server on port 80 and port 81. IE can connect to the server on either port. This worked fine until I installed an application with a file type (.TPJ) that had a MIME type of text/xml on the client PC. At that point IE no longer opened the web site, but offered to download a file serverName.TPJ. The file contained the correct information from the web site.

I changed the installer for the application so it didn't register the MIME type. Now IE on the client PC offers to download a file with unknown file type. Note that the application has never been installed on the server PC.

The problem occurs with IE7. It doesn't occur with Firefox, Safari, or Chrome.

Does anyone know how to work around this?

Answer:
I found the answer. There is a left-over entry in the registry for the text/xml MIME type. It can be restored to the default value by re-registering the MSXML3.DLL.
```
```
regsvr32 msxml3.dll
```
```


Question:
I'm trying to hide the "Title" field in a list.
This doesn't seem to work:

SPList myList;
...
SPField titleField = myList.Fields.GetField("Title");
//titleField.PushChangesToLists = true; <-- doesn't seem to make a difference
titleField.ShowInEditForm = false;
titleField.ShowInDisplayForm = false;
titleField.ShowInNewForm = false;
titleField.Update();
//myList.Update(); <-- make no difference

What am I doing wrong?

Answer:
Make sure you are grabbing a
new
SPWeb instance.
```
```
using (SPSite site = new SPSite(webUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        try
        {
            //... Get SPList ...
        }
    }
}
```
```


Question:
How can I go through all external links in a div with javascript, adding (or appending) a class and alt-text?

I guess I need to fetch all objects inside the div element, then check if each object is a , and check if the href attributen starts with http(s):// (should then be an external link), then add content to the alt and class attribute (if they don't exist create them, if they do exists; append the wanted values).

But, how do I do this in code?

Answer:
This can be accomplished pretty easily with
Jquery
. You would add this to the onload:
```
```
$("div a[href^='http']").each(function() {
  $(this).attr("alt",altText);
  var oldClassAttributeValue = $(this).attr("class");
  if(!oldClassAttributeValue) {
   $(this).attr("class",newClassAttributeValue);
  }
});
```
```
You could modify this to add text. Class can also be modified using the
css
function.