Question:
I realize you can script Microsoft Office apps, but I'm looking for something more general that I can apply to other apps, such as Adobe Acrobat, web browsers and other apps with no scripting ability.

I've used AutoIt but it's a bit clunky, especially when trying to debug why a script fails or stalls. Also, getting the timing of actions, such as clicking a button, or selecting a menu item correctly can be a pain.

Are there build tools that could be used for this purpose?

Answer:
I recommend
AutoHotKey
. Its syntax is not pretty, but most of the times you don't have to concoct your own scripts, because its community is so large and well organized. Even if you do, the documentation is extensive and good and the forums will answer your questions quickly. The developer is active and responsive, which means that bugs get fixed quickly, and new features are being considered and added.
Since I began using AHK I don't imagine doing without it - it allows to make life on Windows simpler in so many ways.
You can also employ the COM interface from Python and other scripting languages. It is more complex, but you get to use a more powerful language.


Question:
How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this almost works for me:

proc1 = subprocess.Popen(['python','mytest.py'])
proc2 = subprocess.Popen(['python','mytest.py'])
proc1.wait()
print "1 finished"
proc2.wait()
print "2 finished"

The problem is that when proc2 finishes before proc1, the parent process will still wait for proc1. On Unix one would use waitpid(0) in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows?

Answer:
It might seem overkill, but, here it goes:
```
```
import Queue, thread, subprocess

results= Queue.Queue()
def process_waiter(popen, description, que):
    try: popen.wait()
    finally: que.put( (description, popen.returncode) )
process_count= 0

proc1= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
    (proc1, "1 finished", results))
process_count+= 1

proc2= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
    (proc2, "2 finished", results))
process_count+= 1

# etc

while process_count > 0:
    description, rc= results.get()
    print "job", description, "ended with rc =", rc
    process_count-= 1
```
```


Question:
Are there any tools available for calculating Cyclomatic Complexity in Javascript?

I've found it a very helpful metric in the past while working on server side code, and would like to be able to use it for the client side Javascript I write.

Answer:
Since cyclomatic complexity is evaluated counting the number of keyword
"if, switch, while for break" etc.. every tools that works with C will do the job, like
sourcemonitor:
http://www.campwoodsw.com/sourcemonitor.html
Actually, on javascript the more you try to modulize your code, the more you will slow it down, so take it with a grain of salt ;)
EDIT:
I
Really
can't understand what's going on on this answer, I get another downvote, when in my answer I tell a good tool for calculating cyclomatic complexity in javascript,
and this in particular works very well.
For the second assertion, mine is a comment that comes from experience, I never tell
don't modulize your js code
, I only tell to
make attention in doing it
, because often there is a tradeoff with speed, and when I talk of speed I mean that 2 different slowdown can happen: at
download time
and at
execution time
(and in slow device like pda/smartphone this is important).
Since tools like this often drive developer into writing more code trying to chase the smaller index possible,
but in js more code unfortunately means that slowdowns can happen, and the
overuse
of these tools is bad.
Surelly these tools can give you hints of
where
your code can be improved, but you've to master how to use the tool and not blindy rely on it.
So if you downvote me again, please write a comment in which you explain why you do so, the discussion can only benefit from this, thank you and sorry for the vent.


Question:
Are there any tools available for calculating the average number of lines of code per method?

I want to know the average size of each method, not just the total number of lines in the project. The per method count will allow me to measure how simple each method is.

This will be calculated as part of the build process, and displayed on a dashboard. The idea being that we can see if the average size of each method is increasing. And this will flag the possibility that code complexity is increasing and we may need to think about refactoring.

Answer:
I am not sure if it does that, but searching, after your previous post, what is cyclomatic complexity, I went to the related Wikipedia page which pointed to
Code Analyzer
.
There they say:
When counting for HTML or JSP files, it will count LoC correctly for
  javascript and vbscript code embedded within the <script> tag.
I don't know if this count is dispatched per method, but it might be worth taking a look (it is a free tool).


Question: I have a problem that confuses my users, being that although an item is highlighted (by the hover style) when the user mouses over it, they have to mouse over the actual item text, sometimes quite small compared to the item.  Is there a way to make the whole item clickable?

Answer:
Add some padding to the A element? Or if it's in a menu contained within a block-level element, make the A display as block too:
```
```
a {
  display: block;
  width: 100%;
}
```
```


Question:
I'm wondering, how expensive it is to have many threads in waiting state in java 1.6 x64.

To be more specific, I'm writing application which runs across many computers and sends/receives data from one to another. I feel more comfortable to have separate thread for each connected machine and task, like 1) sending data, 2) receiving data, 3) reestablishing connection when it is dropped. So, given that there are N nodes in cluster, each machine is going to have 3 threads for each of N-1 neighbours. Typically there will be 12 machines, which comes to 33 communication threads.

Most of those threads will be sleeping most of the time, so for optimization purposes I could reduce number of threads and give more job to each of them. Like, for example. reestablishing connection is responsibility of receiving thread. Or sending to all connected machines is done by single thread.

So is there any significant perfomance impact on having many sleeping threads?

Answer:
For most cases, the resources consumed by a sleeping thread will be its stack space. Using a 2-threads-per-connection-model, which I think is similar to what you're describing, is known to cause great scalability issues for this very reason when the number of connections grow large.
I've been in this situation myself, and when the number of connections grew above 500 connections (about a thousand threads), you tend to get into lots of cases where you get OutOfMemoryError, since the threads stack space usage exceeds the maximum amount of memory for a single process. At least in our case, which was in a Java on 32 bit Windows world. You can tune things and get a bit further, I guess, but in the end it's just not very scalable since you waste lots of memory.
If you need a large number of connections, Java NIO (new IO or whatever) is the way to go, making it possible to handle lots of connections in the same thread.
Having said that, you shouldn't encounter much of a problem with under a 100 threads on a reasonably modern server, even if it's probably still a waste of resources.


Question:
I've seen several examples of code like this:

if not someobj:
    #do something

But I'm wondering why not doing:

if someobj == None:
    #do something

Is there any difference? Does one have an advantage over the other?

Answer:
In the first test, Python try to convert the object to a
```
bool
```
value if it is not already one. Roughly,
we are asking the object : are you meaningful or not ?
This is done using the following algorithm :
If the object has a
```
__nonzero__
```
special method (as do numeric built-ins,
```
int
```
and
```
float
```
), it calls this method. It must either return a
```
bool
```
value which is then directly used, or an
```
int
```
value that is considered
```
False
```
if equal to zero.
Otherwise, if the object has a
```
__len__
```
special method (as do container built-ins,
```
list
```
,
```
dict
```
,
```
set
```
,
```
tuple
```
, ...), it calls this method, considering a container
```
False
```
if it is empty (length is zero).
Otherwise, the object is considered
```
True
```
unless it is
```
None
```
in which case, it is considered
```
False
```
.
In the second test, the object is compared for equality to
```
None
```
. Here,
we are asking the object, "Are you equal to this other value?"
This is done using the following algorithm :
If the object has a
```
__eq__
```
method, it is called, and the return value is then converted to a
```
bool
```
value and used to determine the outcome of the
```
if
```
.
Otherwise, if the object has a
```
__cmp__
```
method, it is called. This function must return an
```
int
```
indicating the order of the two object (
```
-1
```
if
```
self < other
```
,
```
0
```
if
```
self == other
```
,
```
+1
```
if
```
self > other
```
).
Otherwise, the object are compared for identity (ie. they are reference to the same object, as can be tested by the
```
is
```
operator).
There is another test possible using the
```
is
```
operator.
We would be asking the object, "Are you this particular object?"
Generally, I would recommend to use the first test with non-numerical values, to use the test for equality when you want to compare objects of the same nature (two strings, two numbers, ...) and to check for identity only when using sentinel values (
```
None
```
meaning not initialized for a member field for exemple, or when using the
```
getattr
```
or the
```
__getitem__
```
methods).
To summarize, we have :
```
```
>>> class A(object):
...    def __repr__(self):
...        return 'A()'
...    def __nonzero__(self):
...        return False

>>> class B(object):
...    def __repr__(self):
...        return 'B()'
...    def __len__(self):
...        return 0

>>> class C(object):
...    def __repr__(self):
...        return 'C()'
...    def __cmp__(self, other):
...        return 0

>>> class D(object):
...    def __repr__(self):
...        return 'D()'
...    def __eq__(self, other):
...        return True

>>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:
...     print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \
...         (repr(obj), bool(obj), obj == None, obj is None)
  '': bool(obj) -> False, obj == None -> False, obj is None -> False
  (): bool(obj) -> False, obj == None -> False, obj is None -> False
  []: bool(obj) -> False, obj == None -> False, obj is None -> False
  {}: bool(obj) -> False, obj == None -> False, obj is None -> False
   0: bool(obj) -> False, obj == None -> False, obj is None -> False
 0.0: bool(obj) -> False, obj == None -> False, obj is None -> False
 A(): bool(obj) -> False, obj == None -> False, obj is None -> False
 B(): bool(obj) -> False, obj == None -> False, obj is None -> False
 C(): bool(obj) ->  True, obj == None ->  True, obj is None -> False
 D(): bool(obj) ->  True, obj == None ->  True, obj is None -> False
None: bool(obj) -> False, obj == None ->  True, obj is None ->  True
```
```


Question:
I'm looking for a good way to represent organic growth - especially trees and flowers - using code.

I've found Lindenmayer Systems as a reasonable way to portray this, but need a good place to start programming this.

Any good suggestions?

Answer:
I am not sure how much you already know on the topic, but I believe Wikipedia's article on
L-system
should be a good start.
"using code" is a bit fuzzy, so I can hardly answer. You might find some freeware to experiment with L-systems, you can play with some graphical language like Processing, do that in GDI or Java2D (or 3D), etc.
There are other methods too, my own
Ferns - Static view
was made with Processing, drawing short lines, using a hierarchical class system to represent trunk, branches and leaves.


Question: Hi were can I find training videos for MySQL ?

Answer:
In youtube you find somethings like
mysql install:
http://www.youtube.com/watch?v=KQcFP3GcQ0s
mysql trainning:
http://www.youtube.com/watch?v=BHq-bORKncA
Google presentation about mysql tunning (hot)
http://www.youtube.com/watch?v=u70mkgDnDdU
You have anothers google presentations about mysql, just search in youtube and googlevideos :-)


Question: While editing an aspx file I found both these opening tags used for seemingly the same thing. Is there a difference and if yes, what is it?

Answer:
The difference is that the # symbol specifies a data binding directive, that is resolved at data binding time (for example, when you call Page.DataBind ) and the = sign specifies an evaluation expression just evaluates and prints to the HTML output when that line is processed.
Edit: Just adding that only inside <%# %> you have acces to databinding functions like Eval.


Question:
I have C++ project (VS2005) which includes header file with version number in #define directive. Now I need to include exactly the same number in twin C# project. What is the best way to do it?

I'm thinking about including this file as a resource, then parse it at a runtime with regex to recover version number, but maybe there's a better way, what do you think?

I cannot move version outside .h file, also build system depends on it and the C# project is one which should be adapted.

Answer:
MSDN tells us:
The #define directive cannot be used
  to declare constant values as is
  typically done in C and C++. Constants
  in C# are best defined as static
  members of a class or struct. If you
  have several such constants, consider
  creating a separate "Constants" class
  to hold them.
You can create library using managed C++ that includes class - wrapper around your constants. Then you can reference this class from C# project. Just don't forget to use
readonly < type >
instead of
const < type >
for your constants declaration :)


Question:
As most of you would know, if I drop a file named app_offline.htm in the root of an asp.net application, it takes the application offline as detailed here.

You would also know, that while this is great, IIS actually returns a 404 code when this is in process and Microsoft is not going to do anything about it as mentioned here.

Now, since Asp.Net in general is so extensible, I am thinking that shouldn't there be a way to over ride this status code to return a 503 instead? The problem is, I don't know where to start looking to make this change.

HELP!

Answer:
You can try turning it off in the web.config.
```
```
<httpRuntime enable = "False"/>
```
```


Question:
What's the best / simplest / most accurate way to detect the browser of a user?

Ease of extendability and implementation is a plus.

The less technologies used, the better.

The solution can be server side, client side, or both. The results should eventually end up at the server, though.

The solution can be framework agnostic.

The solution will only be used for reporting purposes.

Answer:
The
JQuery Browser Plugin
will do it client-side for you.
What is the jQuery Browser Plugin?
The jQuery Browser Plugin is an addon for jQuery that makes it easy to uniquely identify your visitors' browsers.
What does it do?
It gives you an object in javascript that contains all of the information about the browser being used. It also adds CSS browser selectors, which means you can style elements or write functions for specific browsers, browser versions, layouts, layout versions, and even operating systems. Image of the jQuery Browser Plugin in action.
The plug-in makes
```
$.browser
```
available, which you can re-submit to your server via an AJAX call, if you really need it server-side.
```
```
alert($.browser.name);  // Alerts Firefox for me
```
```
The plug-in will only be as effective as the browsers it's been tested against, however. The plugin listed above has a list of
browsers recognised in it's tests
, but there's always the risk that a new browser will come sneaking out (
Google Chrome..
) that will require a re-write of the recognition rules. That said, this plug-in seems to be regularly updated.


Question:
Per man pages, snprintf is returning number of bytes written from glibc version 2.2 onwards. But on lower versions of libc2.2 and HP-UX, it returns a positive integer, which could lead to a buffer overflow.

How can one overcome this and write portable code?

Edit : For want of more clarity

This code is working perfectly in lib 2.3

    if ( snprintf( cmd, cmdLen + 1, ". %s%s", myVar1, myVar2 )  != cmdLen )
    {
        fprintf( stderr, "\nError: Unable to  copy bmake command!!!");
        returnCode = ERR_COPY_FILENAME_FAILED;
    }

It returns the length of the string (10) on Linux. But the same code is returning a positive number that is greater than the number of characters printed on HP-UX machine. Hope this explanation is fine.

Answer:
I have found one portable way to predict and/or limit the number of characters returned by sprintf and related functions, but it's inefficient and many consider it inelegant.
What you do is create a temporary file with tmpfile(), fprintf() to that (which reliably returns the number of bytes written), then rewind and read all or part of the text into a buffer.
Example:
```
```
int my_snprintf(char *buf, size_t n, const char *fmt, ...)
{
    va_list va;
    int nchars;
    FILE *tf = tmpfile();

    va_start(va, n);
    nchars = vfprintf(tf, fmt, va);
    if (nchars >= (int) n)
        nchars = (int) n - 1;
    va_end(va);
    memset(buf, 0, 1 + (size_t) nchars);

    if (nchars > 0)
    {
        rewind(tf);
        fread(buf, 1, (size_t) nchars, tf);
    }

    fclose(tf);

    return nchars;
}
```
```


Question: I'm trying to read data from a Delphi DBIV database, every time I access the database it creates a Paradox.lck and a Pdoxusrs.lck file.  I'm using only a TQuery Object to do this (nothing else). can I access a  Delphi DBIV database without it creating these lock files?

Answer:
I have found one portable way to predict and/or limit the number of characters returned by sprintf and related functions, but it's inefficient and many consider it inelegant.
What you do is create a temporary file with tmpfile(), fprintf() to that (which reliably returns the number of bytes written), then rewind and read all or part of the text into a buffer.
Example:
```
```
int my_snprintf(char *buf, size_t n, const char *fmt, ...)
{
    va_list va;
    int nchars;
    FILE *tf = tmpfile();

    va_start(va, n);
    nchars = vfprintf(tf, fmt, va);
    if (nchars >= (int) n)
        nchars = (int) n - 1;
    va_end(va);
    memset(buf, 0, 1 + (size_t) nchars);

    if (nchars > 0)
    {
        rewind(tf);
        fread(buf, 1, (size_t) nchars, tf);
    }

    fclose(tf);

    return nchars;
}
```
```


Question:
Can someone explain to me the advantages of using an IOC container over simply hardcoding the default implementation into a default constructor?

In other words, what is wrong about this code?

public class MyClass
{
    private IMyInterface _myInterface;

    public MyClass()
    {
        _myInterface = new DefaultMyInterface();
    }

    public MyClass(IMyInterface myInterface)
    {
        _myInterface = myInterface;
    }
}

As far as I can tell, this class supports constructor injection enough so unit testing and mocking is easily done.  In addition to which, the default constructor removes the computational overhead of the IOC container (not to mention the whole process is a lot more transparent).

The only benefits i can see to using an IOC container is if you need to switch out the implementation of your interfaces frequently.  Am I missing something?

Answer:
The idea of IoC is to delegate part of your component's functionality to another part of the system. In IoC world, you have components that don't know about each other. Your example violates this, as you're creating tight coupling between MyClass and some implementation of IMyInterface.
The main idea
is that your component
has no knowledge
about how it will be used. In your example, your component
makes some assumptions
about its use.
Actually this approach can work, but mixing IoC and explicit object initialization is not a good practice IMO.
IoC gives you loose coupling by performing late binding for the price of code clarity. When you add additional behavior to this process, it makes things even more complicated and can lead to bugs when some components can potentially receive object with unwanted or unpredicted behavior.


Question: I installed MySQL via MacPorts. What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)?

Answer:
Apparently you want:
```
```
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
```
```
Have a further read in
Jeez People, Stop Fretting Over Installing RMagic
.


Question:
We have a graphics intensive application that seems to be experiencing problems on AMD 64 bit Dual Core platforms that are not apparent on Intel platforms.

Running the application causes the CPU to run at 100%, in particular when using code for shadows and lighting (Open GL).

Does anyone know of specific issues with AMD processors that could cause this or know where to track down the problem, and/or ways to optimize the code base to avoid these issues?

note, the application generally works well on mid range hardware, my dev machine has an nvidia gtx260 card in, so lack of power should not be an issue

Answer:
I would invest in profiling software to trace down the actual cause of the problem.
On linux, Valgrind ( which contains Cachegrind &  Callgrind ) + KCacheGrind can make working out where all the heavy function calls are going on.
Also, compile with full debug symbols and it can even show the assembley code at the slow function calls.
If you're using an Intel Specific compiler, this may be part of your problem ( not definate tho ), and try the GCC family.
Also, you may want to dive into OpenMP and Threads if you haven't already.


Question:
I'm new to both Web Services and RMI and I wonder which is the better way to do remoting between different web applications, when these applications are all written in Java, that is when different programming languages don't matter (which would be the advantage of WS).

While on the one hand I would guess that there's a performance overhead when using web services (does anyone have some numbers to prove that?), on the other hand it seems to me that web services are much more loosely coupled and can be used to implement a more service-oriented architecture (SOA) (which isn't possible with RMI, right?).

Although this is quite a general question, what's your opinion?

Thanks

Answer:
My experience with RMI and Web Services mirrors your guesses above.  In general, RMI's performance exceeds web services, if the communication requirement is for complex objects. The JEE interface specification needs to be explicitly specified for Web Services.
Note that Web Services are interoperable whereas RMI is not (in terms of the technologies of Client and Server).  I tend to use Web Services when I had one or more external partners who were implementing the interface, but RMI if I was in control of both ends of the connection.


Question:
So I got this question from one of the developers in my team: What is domain driven design? I could of course point to the book from Evans but is that actually an answer?

How would you explain DDD in a few sentences to junior software engineers in your team?

Answer: I would say this practice promotes concentrating your efforts on the 'problem space' rather than the 'solution space'. Driving an emergent solution (the design) by studying and really getting to know and understand the domain. One of the practices (taken from XP) would be the writing of stories that occur in the problem domain. From these you can identify your use cases and objects for your design. They 'emerge' and tell you what needs to be in the solution, and how they will need to interact with each other.


Question:
Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to.

We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client.

Can anyone recommend an approach that would allow us to do this.

Thanks

DOm

Answer:
For catching exceptions in Rails 2,
```
rescue_from
```
controller method is a great way to specify actions which handle various cases.
```
```
class ApplicationController < ActionController::Base
  rescue_from MyAppError, :with => :show_errors

  def show_errors
    render :action => "..."
  end
end
```
```
This way you can make dynamic error pages to replace the static "public/500.html" page.


Question: I want to create a stored procedure with one argument which will return different sets of records depending on the argument. What is the way to do this? Can I call it from plain SQL?

Answer:
I think you want to return a REFCURSOR:
```
```
create function test_cursor
            return sys_refcursor
            is
                    c_result sys_refcursor;
            begin
                    open c_result for
                    select * from dual;
                    return c_result;
            end;
```
```
Update
: If you need to call this from SQL, use a table function like @Tony Andrews suggested.


Question:
I have a Win32 TreeCtrl where the user can rename the tree labels. I process the TVN_ENDLABELEDIT message to do this.

In certain cases I need to change the text that the user entered. Basically the user can enter a short name during edit and I want to replace it with a longer text.

To do this I change the pszText member of the TVITEM struct I received during TVN_ENDLABELEDIT. I do a pointer replace here, as the original memory may be too small to do a simple strcpy like operation.

However I do not know how to deallocate the original pszText member. Basically because it's unknown if that was created with malloc() or new ... therefore I cannot call the appropriate deallocator. Obviously Win32 won't call the deallocator for the old pszText because the pointer has been replaced. So if I don't deallocate, there will be a memory leak.

Any idea how Win32 allocate these structs and what is the proper way to handle the above situation?

Answer:
Unless you're using
```
LPSTR_TEXTCALLBACK
```
, the tree-view control is responsible for allocating the memory, not your code, so you shouldn't change the value of the
```
pszText
```
pointer.
To change the item's text in your
```
TVN_ENDLABELEDIT
```
handler, you can use
```
TreeView_SetItem
```
, then return 0 from the handler.


Question:
I cannot understand the Oracle documentation. :-(

Does anybody know how to fetch multiple rows of simple data from Oracle via OCI?

I currently use OCIDefineByPos to define single variables (I only need to do this for simple integers -- SQLT_INT/4-byte ints) and then fetch a single row at a time with OCIStmtExecute/OCIStmtFetch2.

This is OK for small amounts of data but it takes around .5ms per row, so when reading a few ten thousand rows this is too slow.

I just don't understand the documentation for OCIBindArrayOfStruct. How can I fetch a few thousand rows at a time?

Answer:
Unless you're using
```
LPSTR_TEXTCALLBACK
```
, the tree-view control is responsible for allocating the memory, not your code, so you shouldn't change the value of the
```
pszText
```
pointer.
To change the item's text in your
```
TVN_ENDLABELEDIT
```
handler, you can use
```
TreeView_SetItem
```
, then return 0 from the handler.


Question:
If you are writing a simple little loop, what should you name the counter?

Provide example loops!

Answer:
My experience is that most people use single letters, e.g.:
```
i
```
,
```
j
```
,
```
k
```
,
...
or
```
x
```
,
```
y
```
,
or
```
r
```
,
```
c
```
(for row/column)
or
```
w
```
,
```
h
```
(for width/height)
, etc.
But I learned a great alternative a long time ago, and have used it ever since: double letter variables.
```
```
// recommended style              ●    // "typical" single-letter style
                                  ●
for (ii=0; ii<10; ++ii) {         ●    for (i=0; i<10; ++i) {
    for (jj=0; jj<10; ++jj) {     ●        for (j=0; j<10; ++j) {
        mm[ii][jj] = ii * jj;     ●             m[i][j] = i * j;
    }                             ●        }
}                                 ●    }
```
```
In case the benefit isn't immediately obvious: searching through code for any single letter will find many things that
aren't
what you're looking for.  The letter
```
i
```
occurs quite often in code where it isn't the variable you're looking for.


Question: Was this an oversight?  Or is it to do with the JVM?

Answer: I guess it has to do with the fact that the JVM is coded in C++. Apart from that, pointers and references are nearly similar. You could say that the reference mechanism in Java is implemented using C++ pointers and the name 'NullPointerException' allows that implementation detail to shine through.


Question:
I have an Exchange mailbox linked as a table in an MS Access app. This is primarily used for reading, but I would also like to be able to "move" messages to another folder.

Unfortunately this is not as simple as writing in a second linked mailbox, because   apparently I can not edit some fields. Some critical fields like the To: field are unavailable, as I get the following error

"Field 'To' is based on an expression and cannot be edited".

Using CreateObject("Outlook.Application") instead is not an option here, because as far as I know, this gives a security dialog when called from Access.

Any solutions?*

Answer:
Is this two problems? Mail can be moved using the Move method. Here is a snippet:
```
```
Set oApp = CreateObject("Outlook.Application")

Set oNS = oApp.GetNamespace("MAPI")

Set oMailItems = oNS.GetDefaultFolder(olFolderInbox)
Set itm = oMailItems.Items(6)
itm.Move oNS.GetDefaultFolder(olFolderDeletedItems)
```
```
However, Recipients (To) is read only, even, I believe, with Outlook Redemtion.


Question: Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version?

Answer:
You should possibly just share a common ancestor class, then you can flick it with a single js command if need be.
```
```
<body class="style2">

<body class="style1">
```
```
etc.


Question: How do I read text from the (windows) clipboard with python?

Answer:
Try win32clipboard from the win32all package (that's probably installed if you're on ActiveState Python).
See sample here:
http://code.activestate.com/recipes/474121/


Question: How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it.

Answer:
```
```
if(doc.SelectSingleNode("//mynode")==null)....
```
```
Should do it (where doc is your XmlDocument object, obviously)
Alternatively you could use an XSD and validate against that


Question:
I need to count and check how much of some images is placed in folder od web server.
Example- images get names from user_id, and on example I have user_id 27, and my images are:

27_1.jpg, 27_2.jpg, 27_3.jpg, ...

How to check and write to database this thing?

Thanks

Answer:
Once you know your path you can use IO.Directory.GetFiles() method.
```
```
IO.Directory.GetFiles("\translated\path","27_*.jpg").Count()
```
```
will give you what you're looking for.


Question: How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?

Answer:
From the controller you can just return a JsonResult:
```
```
public ActionResult MyAction()
{
    ... // Populate myObject
    return new JsonResult{ Data = myObject };
}
```
```
The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like:
```
```
$.getJSON("/controllerName/MyAction", callbackFunction);
```
```
where the
```
callbackFunction
```
takes a parameter which is the data from the XHR request.


Question:
In Python there is a really neat function called zip which can be used to iterate through two lists at the same time:

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for v1, v2 in zip(list1, list2):
    print v1 + " " + v2

The above code should produce the following:

1 a
2 b
3 c

I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.

Answer:
Nope, there is no such function in .NET. You have roll out your own. Note that C# doesn't support tuples, so python-like syntax sugar is missing too.
You can use something like this:
```
```
class Pair<T1, T2>
{
    public T1 First { get; set;}
    public T2 Second { get; set;}
}

static IEnumerable<Pair<T1, T2>> Zip<T1, T2>(IEnumerable<T1> first, IEnumerable<T2> second)
{
    if (first.Count() != second.Count())
        throw new ArgumentException("Blah blah");

    using (IEnumerator<T1> e1 = first.GetEnumerator())
    using (IEnumerator<T2> e2 = second.GetEnumerator())
    {
        while (e1.MoveNext() && e2.MoveNext())
        {
            yield return new Pair<T1, T2>() {First = e1.Current, Second = e2.Current};
        }
    }
}

...

var ints = new int[] {1, 2, 3};
var strings = new string[] {"A", "B", "C"};

foreach (var pair in Zip(ints, strings))
{
    Console.WriteLine(pair.First + ":" + pair.Second);
}
```
```


Question: I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is.  I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource.

Answer:
Run this SQL:
```
```
select * from v$version;
```
```
And you'll get a result like:
```
```
BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE    10.2.0.3.0      Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
```
```


Question:
I'm playing with the wonderful FindBugs plugin for Hudson. Ideally, I'd like to have the build fail if FindBugs finds any problems. Is this possible?

Please, don't try and tell me that "0 warnings" is unrealistic with FindBugs. We've been using FindBugs from Ant for a while and we usually do maintain 0 warnings. We achieve this through the use of general exclude filters and specific/targeted annotations.

Answer:
You can not rely on find bugs so much , it is just an expert system that tells you that something
may
be wrong with your program during runtime. Personally I have seen a lot of warning generated by findbugs because it was not able to figure out the correctness of code (in fact).
One example when you open a stream or jdbc connection in one method and close it in other, in this case findbugs expecting to see close() call in same method which sometimes is impossible to do.


Question: I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is.  I want to confirm that the database type is indeed Postgres, and if possible, what version of Postgres they are running by sending a SQL statement to the datasource.

Answer:
```
```
SELECT version();
```
```


Question: Net::HTTP can be rather cumbersome for the standard use case!

Answer:
This is what I use:
http://rubyforge.org/projects/restful-rails/
.


Question:
I have a pivot table on an olap cube. I can go into a page field and manually deselect multiple items. How can I do this in VBA based on a list of items I need excluded? (n.b. I do not have a corrresponding list of items I need included)

I know how to exclude these items in other ways, by altering the underlying query for example. I specifically want to replicate the user action of deselecting items in the pivot.

Answer:
I apologize for this example being in C#, but I really don't know enough VBA to translate it (perhaps someone can edit this entry and add it below).
Are you refering to something like this?
```
```
((MOE.PivotField)pivotTableObject.PivotFields("[NAME]")).Delete();
```
```
Where MOE is the Microsoft.Office.Interop.Excel namespace and [NAME] is the name of the field you want to remove


Question:
/etc/init.d/*

/etc/rc{1-5}.d/*

Answer:
```
/sbin/chkconfig
```
— The
```
/sbin/chkconfig
```
utility is a simple command line tool for maintaining the
```
/etc/rc.d/init.d/
```
directory hierarchy.


Question:
I want to search for $maximumTotalAllowedAfterFinish and replace it with $minimumTotalAllowedAfterFinish. Instead of typing the long text:

:%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g

Is there a way to COPY these long variable names down into the search line, since, on the command line I can't type "p" to paste?

Answer:
Type
```
q:
```
to get into history editing mode in a new buffer. Then edit the last line of the buffer and press
```
Enter
```
to execute it.


Question: As the title says: What is the difference between a non-secure random number generator and a secure random number generator?

Answer:
No computationally feasible algorithm should:
recover the seed, or
predict the "next bit"
for a secure random number generator.
Example: a linear feedback shift register produces lots of random numbers out there, but given enough output, the seed can be discovered and all subsequent numbers predicted.


Question: Our application is written in ActionScript2 and has about 50.000+ lines of code. We want to port it to ActionScript3 and we're trying to find out what our options are. Do we have to do it manually or can we use a converter, and what problems can we expect?

Answer:
I don't think you can ever use an automatic converter for this task.
A converter may be able to save you some steps or point out places where change must take place, but you'll have to go over the code manually.
For example, referring to a _level0.variableName in AS2 can point to a movieClip on the _root level, to a FlashVar sent from the HTML container or to an object created by the code itself. There's no real way of knowing. (You can't look for the varname in the code since that too can be calculated or read externally.
You need to have a very good reason to do such conversion. If AS2 is not suitable anymore for some reason, maybe you should try to solve the problem instead of converting to AS3 just because it has a nice little function that you need.


Question:
I was wondering are there any security concerns with adding crossdomain.xml to the root of an application server? Can it be added to any other parts of the server and are you aware of any work arounds that dont require the server to have this file in place?

Thanks
Damien

Answer:
By adding the crossdomain.xml, the main security concern is that flash applications can now connect to your server.  So if someone logs into your site, and then browses over to another website with a malicious flash app, that flash app can connect back to your site.  Since it's in a browser, cookies are shared to the flash app.  This allows the flash app to hijack the user's session to do whatever it is your website does without the user knowing about it.
If your flex app is served from the same server, you don't need a crossdomain.xml
You can put it in a sub directory of your site and use System.security.loadSecurityPolicy()
http://livedocs.adobe.com/flex/2/langref/flash/system/Security.html
Applications would then be limited to that tree of your directory structure.


Question:
What is the most efficient way given to raise an integer to the power of another integer in C?

// 2^3
pow(2,3) == 8

// 5^5
pow(5,5) == 3125

Answer:
An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large to do shifting on an int. You can still do 2^x in constant time by screwing with a float.
```
```
struct IeeeFloat
{

    unsigned int base : 23;
    unsigned int exponent : 8;
    unsigned int signBit : 1;
};

union IeeeFloatUnion
{
    IeeeFloat brokenOut;
    float f;
};

inline float twoToThe(char exponent)
{
    // notice how the range checking is already done on the exponent var
    static IeeeFloatUnion u;
    u.f = 2.0;
    // Change the exponent part of the float
    u.brokenOut.exponent += (exponent - 1);
    return (u.f);
}
```
```
You can get more powers of 2 by using a double as the base type.
(Thanks a lot to commenters for helping to square this post away).
There's also the possibility that learning more about
IEEE floats
, other special cases of exponentiation might present themselves.


Question:
I'm guessing I need to implement an NVelocityViewEngine and NVelocityView - but before I do I wanted to check to see if anyone has already done this.

I can't see anything in the trunk for MVCContrib.

I've already seen the post below - I'm looking specifically for something which works with Preview 5:

Testing ScottGu: Alternate View Engines with ASP.NET MVC (NVelocity)

Otherwise I'll start writing one :)

Answer:
An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large to do shifting on an int. You can still do 2^x in constant time by screwing with a float.
```
```
struct IeeeFloat
{

    unsigned int base : 23;
    unsigned int exponent : 8;
    unsigned int signBit : 1;
};

union IeeeFloatUnion
{
    IeeeFloat brokenOut;
    float f;
};

inline float twoToThe(char exponent)
{
    // notice how the range checking is already done on the exponent var
    static IeeeFloatUnion u;
    u.f = 2.0;
    // Change the exponent part of the float
    u.brokenOut.exponent += (exponent - 1);
    return (u.f);
}
```
```
You can get more powers of 2 by using a double as the base type.
(Thanks a lot to commenters for helping to square this post away).
There's also the possibility that learning more about
IEEE floats
, other special cases of exponentiation might present themselves.


Question:
Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as 96. Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as 0140. Hexadecimal based numbers are usually prefixed by 0x: 96 would be written as 0x60.

The question is: can I write numbers as binary literals in Ruby? How?

Answer:
From
this manual
```
```
0b01011
```
```
binary integer


Question:
I know how to change the schema of a table in SQL server 2005:

ALTER SCHEMA NewSchama TRANSFER dbo.Table1

But how can i check and/or alter stored procedures that use the old schema name?

Sorry: I mean:
There are stored procedures that have the old schema name of the table in the sql of the stored procedure... How can i edit all the stored procedures that have the dbo.Table1 in the body of the procedure...

Answer:
Get a list of dependent objects by right-clicking on the table before you change the schema and then look at what is dependent on the table, make a list and then change those. There is, however, always a possibility that you'll miss something because it is possible to break the dependencies SQL server tracks.
But the best way would be to script the database out into a file and then do a search for the table name, make a list of all of the sprocs where it needs to be changed and then add those to the script to change the schema of the table.


Question:
Does anybody know if there is a feasible way on Windows XP to programmatically create and configure a user account so that after logging in from the console (no terminal services) a specific app is launched and the user is "locked" to that app ?

The user should be prevented from doing anything else with the system (e.g.: no ctrl+alt+canc, no ctrl+shift+esc, no win+e, no nothing).

As an added optional bonus the user should be logged off when the launched app is closed and/or crashes.

Any existing free tool, language or any mixture of them that gets the job done would be fine (batch, VB-script, C, C++, whatever)

Answer:
I guess you're building a windows kiosk?
Here's some background in replacing the windows login shell -
http://blogs.msdn.com/embedded/archive/2005/03/30/403999.aspx
The above link talks about using IE as the replacement, but any program can be used.
Also check out Windows Steady State -
http://www.microsoft.com/windows/products/winfamily/sharedaccess/default.mspx


Question:
I have some code which collects points (consed integers) from a loop which looks something like this:

(loop
    for x from 1   to     100
    for y from 100 downto 1
        collect `(,x . ,y))

My question is, is it correct to use `(,x . ,y) in this situation?

Edit: This sample is not about generating a table of 100x100 items, the code here just illustrate the use of two loop variables and the consing of their values. I have edited the loop to make this clear. The actual loop I use depends on several other functions (and is part of one itself) so it made more sense to replace the calls with literal integers and to pull the loop out of the function.

Answer:
Why not just
```
```
(cons x y)
```
```
By the way, I tried to run your code in CLISP and it didn't work as expected. Since I'm not a big fan of the loop macro here's how you might accomplish the same thing recursively:
```
```
(defun genint (stop)
  (if (= stop 1) '(1)
      (append (genint (- stop 1)) (list stop))))

(defun genpairs (x y)
  (let ((row (mapcar #'(lambda (y)
                        (cons x y))
                        (genint y))))
    (if (= x 0) row
        (append (genpairs (- x 1) y)
                row))))

(genpairs 100 100)
```
```


Question: I have Flex Builder 3 installed on two Windows machines and the same project on both of them. On one computer, the CSS styles I defined are shown in design view; on the other computer they are not applied. Is there any reason why it might not work on one?

Answer:
Why not just
```
```
(cons x y)
```
```
By the way, I tried to run your code in CLISP and it didn't work as expected. Since I'm not a big fan of the loop macro here's how you might accomplish the same thing recursively:
```
```
(defun genint (stop)
  (if (= stop 1) '(1)
      (append (genint (- stop 1)) (list stop))))

(defun genpairs (x y)
  (let ((row (mapcar #'(lambda (y)
                        (cons x y))
                        (genint y))))
    (if (= x 0) row
        (append (genpairs (- x 1) y)
                row))))

(genpairs 100 100)
```
```


Question:
When I run a Flex application in the debug flash player I get an exception pop up as soon as something unexpected happened. However when a customer uses the application he does not use the debug flash player. In this case he does not get an exception pop up, but he UI is not working.

So for supportability reasons, I would like to catch any exception that can happen anywhere in the Flex UI and present an error message in a Flex internal popup. By using Java I would just encapsulate the whole UI code in a try/catch block, but with MXML applications in Flex I do not know, where I could perform such a general try/catch.

Answer:
There is no way to be notified on uncaught exceptions in Flex 3. Adobe are aware of the problem but I don't know if they plan on creating a workaround.
The only solution as it stands is to put try/catch in logical places and make sure you are listening to the ERROR (or FAULT for webservices) event for anything that dispatches them.
Edit:
Furthermore, it's actually impossible to catch an error thrown from an event handler. I have logged a
bug
on the Adobe Bug System.
Update 2010-01-12:
Global error handling is now supported in
Flash 10.1
and
AIR 2.0
(both in beta), and is achieved by subscribing the
UNCAUGHT_ERROR
event of
LoaderInfo.uncaughtErrorEvents
. The following code is taken from the
code sample on livedocs
:
```
```
public class UncaughtErrorEventExample extends Sprite
{
    public function UncaughtErrorEventExample()
    {
        loaderInfo.uncaughtErrorEvents.addEventListener(
            UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
    }

    private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
    {
        if (event.error is Error)
        {
            var error:Error = event.error as Error;
            // do something with the error
        }
        else if (event.error is ErrorEvent)
        {
            var errorEvent:ErrorEvent = event.error as ErrorEvent;
            // do something with the error
        }
        else
        {
            // a non-Error, non-ErrorEvent type was thrown and uncaught
        }
    }
```
```


Question:
The above error message comes up just before SQL Server marks the database as "Suspect" and refuses to open it. Does anyone know what the message means and how to fix it? I think it's a matter of grabbing the backup, but would be nice if it was possible to recover the data.

I've had a look at the kb article but there are no transactions to resolve.

Answer:
It appears that it means your distributed transaction coordinator failed to start correctly when bringing the SQL Server online.
please refer to this
ASP.NET forum post
and
knowledge base article
Depending on the level of logging, you should be able to take the last known backup and slowly recover the logs using point in time recovery techniques to slowly bring the database up to the point right before failure began.


Question: How do I get an element or element list by it's tag name. Take for example that I want all elements from <h1></h1>.

Answer:
document.getElementsByTagName('a') returns an array. Look here for more information:
http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName
Amendment: If you want a real array, you should use something like
```
Array.from(document.getElementsByTagName('a'))
```
, or these days you'd probably want
```
Array.from(document.querySelectorAll('a'))
```
. Maybe polyfill
```
Array.from()
```
if your browser does not support it yet. I can recommend
https://polyfill.io/v2/docs/
very much (not affiliated in any way)


Question:
I've got an application that uses a hibernate(annotations)/mysql combination for ORM. In that application, I got an entity with a Date field. I'm looking for a way to select on that date within a time range (so hh:mm:ss without the date part).

In MySQL there's a function TIME(expression) that can extract the time part and use that in the where clause, but that does not seem to be available in Hibernate without switching to native queries. Is there an option in hibernate to do this, or should I loop through the results in java and do the comparison there? Would this be much slower as the MySQL solution, since that would not use indexes anyway?

Answer:
The following functions are available in HQL, maybe you could use them:
```
second(...), minute(...), hour(...), day(...), month(...), year(...)
```


Question: I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?

Answer:
You can use or at last study
difflib
from Python's stdlib to write your code.
It is very flexible, and has algorithms to find differences between lists of strings, and to point these differences. Then you can use the
```
get_close_matches()
```
to find similar words:
```
```
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
```
```
It is not the solution but maybe it is a start.


Question: Is there a setting in ReSharper 4 (or even Visual Studio itself...) that forces a warning if I forget to wrap code in a using block, or omit the proper Dispose call in a finally block?

Answer:
Correct automatic Dispose analysis requires DFA (Data Flow Analysis) in a global way. It is unlikely that you create an IDisposable object and doesn't call any method on it and do not pass it around as an argument. If disposable object is passed to other methods (including calling its members, when "this" is implicitly passed), the tool should analyse if Dispose is not called within, or that object is not stored somewhere for later disposal.
That said, naive implementation of checking if disposable object is in fact disposed with "using" construct or in any other way would yield too much false positives, and render analysis useless.


Question:
Let's say I have this code:

if (md5($_POST[$foo['bar']]) == $somemd5) {
  doSomethingWith(md5($_POST[$foo['bar']]);
}

I could shorten that down by doing:

$value = md5($_POST[$foo['bar']];
if ($value == $somemd5) {
  doSomethingWith($value);
}

But is there any pre-set variable that contains the first or second condition of the current if? Like for instance:

if (md5($_POST[$foo['bar']]) == $somemd5) {
  doSomethingWith($if1);
}

May be a unnecessary way of doing it, but I'm just wondering.

Answer:
No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement.
```
if (($value = md5(..)) == $somemd5) { ... }
```
In general, though, you'll want to avoid embedding assignments into conditional expressions:
The code is denser and therefore harder to read, with more nested parentheses.
Mixing = and == in the same expression is just asking for them to get mixed up.


Question: What are the best continuous integration frameworks/projects for Perl and why?

Answer:
The only one I've seen in action is
Smolder
(it is used for
parrot
). It is TAP based and therefore integrates well with standard perl testing structures. See also this
presentation
.


Question:
When I run indent with various options I want against my source, it does what I want but also messes with the placement of *s in pointer types:

  -int send_pkt(tpkt_t* pkt, void* opt_data);
  -void dump(tpkt_t* bp);
  +int send_pkt(tpkt_t * pkt, void *opt_data);
  +void dump(tpkt * bp);

I know my placement of *s next to the type not the variable is unconventional but how can I get indent to just leave them alone? Or is there another tool that will do what I want?  I've looked in the man page, the info page, and visited a half a dozen pages that Google suggested and I can't find an option to do this.

I tried Artistic Style (a.k.a. AStyle) but can't seem to figure out how to make it indent in multiples of 4 but make every 8 a tab.  That is:

if ( ... ) {
<4spaces>if ( ... ) {
<tab>...some code here...
<4spaces>}
}

Answer:
Uncrustify
Uncrustify has several options on how to indent your files.
From the config file:
```
indent_with_tabs
  How to use tabs when indenting code
  0=spaces only
  1=indent with tabs, align with spaces
  2=indent and align with tabs
```
You can find it
here
.
BCPP
From the website:
"bcpp indents C/C++ source programs, replacing tabs with spaces or the reverse. Unlike indent, it does (by design) not attempt to wrap long statements."
Find it
here
.
UniversalIndentGUI
It's a tool which supports several beautifiers / formatters. It could lead you to even more alternatives.
Find it
here
.
Artistic Style
You could try
Artistic Style aka AStyle
instead (even though it doesn't do what you need it to do, I'll leave it here in case someone else finds it useful).


Question:
Take this code:

<?php
if (isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
}

if ($action) {
    echo $action;
}
else {
    echo 'No variable';
}
?>

And then access the file with ?action=test
Is there any way of preventing $action from automatically being declared by the GET? Other than of course adding

&& !isset($_GET['action'])

Why would I want the variable to be declared for me?

Answer:
Check your php.ini for the
```
register_globals
```
setting. It is probably on, you want it off.
Why would I want the variable to be declared for me?
You don't.
It's a horrible security risk. It makes the Environment, GET, POST, Cookie and Server variables global
(PHP manual)
. These are a handful of
reserved variables
in PHP.


Question: Is there any easy to install/use (on unix) database migration tools like Rails Migrations? I really like the idea, but installing ruby/rails purely to manage my database migrations seems overkill.

Answer:
I haven't personally done it, but it should be possible to use ActiveRecord::Migration without any of the other Rails stuff.  Setting up the load path correctly would be the hard part, but really all you need is the
```
rake
```
tasks and the
```
db/migrate
```
directory plus whatever Rails gems they depend on, probably
```
activerecord
```
,
```
actviesupport
```
and maybe a couple others like
```
railties
```
.  I'd try it and just see what classes are missing and add those in.
At a previous company we built a tool that did essentially what ActiveRecord::Migration does, except it was written in Java as a Maven plugin.  All it did was assemble text blobs of SQL scripts.  It just needs to be smart about the filenames going in order and know how to update a versioning table.


Question: How can I add Page transitions effects like IE in Safari for web pages?

Answer:
You could check out this example:
http://sachiniscool.blogspot.com/2006/01/implementing-page-transitions-in.html
. It describes how to emulate page transitions in Firefox using AJAX and CSS. The same method works for Safari as well. The code below is taken from that page and slightly formatted:
```
```
var xmlhttp;
var timerId = 0;
var op = 1;

function getPageFx() {
  url = "/transpage2.html";
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest()
    xmlhttp.onreadystatechange=xmlhttpChange
    xmlhttp.open("GET",url,true)
    xmlhttp.send(null)
  } else getPageIE();
}

function xmlhttpChange() {
// if xmlhttp shows "loaded"
  if (xmlhttp.readyState == 4) {
  // if "OK"
    if (xmlhttp.status == 200) {
      if (timerId != 0)
        window.clearTimeout(timerId);
        timerId = window.setTimeout("trans();",100);
    } else {
       alert(xmlhttp.status)
    }
  }
}

function trans() {
  op -= .1;
  document.body.style.opacity = op;
  if(op < .4) {
    window.clearTimeout(timerId);
    timerId = 0; document.body.style.opacity = 1;
    document.open();
    document.write(xmlhttp.responseText);
    document.close();
    return;
  }
  timerId = window.setTimeout("trans();",100);
}

function getPageIE() {
  window.location.href = "transpage2.html";
}
```
```


Question:
I've just created my first Preview 5 error and it doesn't seem to place nice with Resharper.  All the C# in the Views are coming up with errors, things like <%= Html.Password("currentPassword") %> has the "currentPassword" highlighted with the following error: Argument type "System.String" is not assignable parameter type "string".

IList errors = ViewData["errors"] as IList; has the IList highlighted as "Can not resole symbol 'string'"

Has anyone seen this?

Answer:
Did you try
latest nightly build
of ReSharper 4.1? In some cases the bug in 4.1 manifests itself with numerous ambiguity errors, and it has been fixed within the follow up build.


Question:
What tools are there for me to build a real, honest to goodness external DSL. And no, I'm not talking about abusing Ruby, Boo, XML or another existing language or syntax, I mean a REAL external DSL -- my own language for my own purposes.

I know that there are a few language workbenches being developed and I've heard about things like "Irony" for .NET.  And, of course, there's ANTLR, Lex/Yaac, etc but I'm afraid those are too complicated for what I'm trying to do.

Please talk about a DSL builder tool you may have used or heard about and your impressions on how it helps and what its downsides are.

Answer:
You should really check out
Ragel
. It's a framework to embed state machines in your regular source code. Ragel supports C, C++, Objective-C, D, Java and Ruby.
Ragel's great for writing file and protocol parsers as well as stepping through external DSL stuff. Chiefly because it allows you to execute any kind of code on state transitions and such.
A couple of notable projects that use Ragel are,
Mongrel
, a great ruby web server. And
Hpricot
, a ruby based html-parser, sort of inspired by jQuery.
Another great feature of Ragel is how it can generate
graphviz
-based charts that visualize your state machines. Below is an example taken from
Zed Shaw's
article on ragel state charts
.


Question: Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?

Answer:
Take a look at
PHP's DOM
, especially
DOMDocument::schemaValidate
and
DOMDocument::validate
.
The example for DOMDocument::validate is fairly simple:
```
```
<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
    echo "This document is valid!\n";
}
?>
```
```


Question:
I am trying to develop a .NET Web Project using NHibernate and Spring.NET, but I'm stuck. Spring.NET seems to depend on different versions of the NHibernate assemblies (maybe it needs 1.2.1.4000 and my NHibernate version is 1.2.0.4000).

I had originally solved similar problems using the "bindingRedirect" tag, but now even that stopped working.

Is there any simple solution to resolve these inter-library relations?

Answer:
I too ran into this, frustrated I just grabbed the Spring source and compiled it against the latest NHibernate to make it go away forever.  Not sure if that's an option for you but the 10 minutes that took seems to have saved me a lot of time overall.
Here's the SourceForge link for the Spring Source for all versions:
Spring Source


Question:
The default 64 MB max heap memory can be small for a large Java application. Are there any applet parameter to increment this for a signed applet?

For a Java program this is a simple command line parameter but how this work for an applet in the browser.

Answer:
Not that I know for certain, it's been a long time since I wrote applets, but I don't think you can set this from the applet.
Apparently, you can set the JVM's heap size for the browser's JVM from the Java plug-in control panel, but that's something the user has to do before starting your applet.
You can always check
http://forums.sun.com/thread.jspa?threadID=523105&messageID=3033288
for more discussion on the topic.


Question: In C++, when is it best to use the stack? When is it best to use the heap?

Answer:
Use the heap for only allocating space for objects at runtime. If you know the size at compile time, use the stack. Instead of returning heap-allocated objects from a function, pass a buffer into the function for it to write to. That way the buffer can be allocated where the function is called as an array or other stack-based structure.
The fewer malloc() statements you have, the fewer chances for memory leaks.


Question:
With previous versions of flash, entering the full screen mode increased the height and width of the stage to the dimensions of the screen.  Now that hardware scaling has arrived, the height and width are set to the dimensions of the video (plus borders if the aspect ratio is different).

That's fine, unless you have controls placed over the video.  Before, you could control their size; but now they're blown up by the same scale as the video, and pixellated horribly.  Controls are ugly and subtitles are unreadable.

It's possible for the user to turn off hardware scaling, but all that achieves is to turn off anti-aliasing.  The controls are still blown up to ugliness.

Is there a way to get the old scaling behaviour back?

Answer:
```
```
stage.align     = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, onStageResize);

function onStageResize(event:Event):void {
    //do whatever you want to re-position your controls and scale the video
    // here's an example
    myFLVPlayback.width = stage.stageWidth;
    myFLVPlayback.height = stage.stageHeight - controls.height;
    controls.y = stage.stageHeight - controls.height;
}
```
```
Or, and I'm not entirely sure about this, you might try to do some 9 slice scaling on the FLVPlayback, but I don't know if that'll work.
9-slice scaling tutorial:
http://www.sephiroth.it/tutorials/flashPHP/scale9/


Question: Is there a tutotial or help file, suitable for a beginner c# programmer to use.

Answer:
Andy Beaulieu has beein doing a lot of work to make Farseer easier to use in Silverlight, you can read about it here:
http://www.andybeaulieu.com/Home/tabid/67/EntryID/115/Default.aspx


Question: How to add child rows in datagrid c#.net windows forms?

Answer:
I'm not sure if this is what you're asking, but if you want to append rows you're easiest way is to append them to whatever DataSource you're using before you DataBind()
If this wasn't what you're after, please provide more detail.


Question: Sorry, I'm new to SVN and I looked around a little for this. How do you mark a major version in SVN, kind of like set up a restore point. Right now I just setup my server and added all my files- I've been intermittently committing different changes. When I have something in a stable state is there a way to mark this so I can easily revert back to it if necessary?

Answer:
Sounds like you're looking for tags.
Tags in the Subversion book
"A tag is just a “snapshot” of a project in time"


Question:
I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled.

Example:

This a very very very very very very very very very very very very very very very very very very very very very very long line.

  This is another very very very very very very very very very very very very very very very very very very very very very very long line.|

The cursor is on line number four, not two.

Can someone provide me with the implementation of the method:

int getLineNumber(JTextPane pane, int pos)
{
     return ???
}

Answer:
Try this
```
```
/**
   * Return an int containing the wrapped line index at the given position
   * @param component JTextPane
   * @param int pos
   * @return int
   */
  public int getLineNumber(JTextPane component, int pos)
  {
    int posLine;
    int y = 0;

    try
    {
      Rectangle caretCoords = component.modelToView(pos);
      y = (int) caretCoords.getY();
    }
    catch (BadLocationException ex)
    {
    }

    int lineHeight = component.getFontMetrics(component.getFont()).getHeight();
    posLine = (y / lineHeight) + 1;
    return posLine;
  }
```
```


Question:
Is there a way to "align" columns in a data repeater control?

I.E currently it looks like this:

user1 - colA colB colC colD colE
user2 - colD colE

I want it to look like:

  user1
   -colA
   -colB
   -colC
   -colD
   -colE

   user1

   -colD
   -colE

I need to columns for each record to align properly when additional
records might not have data for a given column.

The requirements call for a repeater and not a grid control.

Any ideas?

Answer:
If you have access to how many columns are mising in the repeat, then just the following as the table tag.  I you don't have access to this, can you post the source for your data repeater and what DataSource you're going against?
```
```
<td colspan='<%# MissingCount(Contatiner.DataItem) %>'>
```
```


Question: Can I determine from an ASP.NET application the transfer rate, i.e. how many KB per second are transferd?

Answer:
There are a number of debugging tools you can use to check this at the browser.  It will of course vary by page, cache settings, server load, network connection speed, etc.
Check out
http://www.fiddlertool.com/fiddler/
Or if you are using Firefox, the FireBug add-in
http://addons.mozilla.org/en-US/firefox/addon/1843


Question:
What is the best way to add "Expires" in http header for static content? eg. images, css, js

The web server is IIS 6.0; the language is classical ASP

Answer:
I don't know if this is what you are looking for, but it does keep my pages from being cached.
```
```
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-store">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
<META HTTP-EQUIV="Cache-Control" CONTENT="max-age=0">
```
```
I got these from an article on line that I no longer have a reference for.


Question:
I'd like to add a drop-down list to a Windows application.  It will have two choices, neither of which are editable.  What's the best control to use?  Is it a combo box with the editing property set to No?

I'm using Visual Studio 2008.

Answer:
```
yourComboBox.DropDownStyle = ComboBoxStyle.DropDownList
```


Question:
I have a strange problem on a PeopleSoft application.   It appears that integration broker messages are being processed out of order.   There is another possibility, and that is that the commit is being fired asynchronously, allowing the transactions to complete out of order.

There are many inserts of detail records, followed by a trailer record which performs an update on the rows just inserted.   Some of the rows are not receiving the update.  This problem is sporadic, about once every 6 months, but it causes statistically significant financial reporting errors.

I am hoping that someone has had enough dealings with the internals of PeopleTools to know what it is up to, so that perhaps I can find a work around to the problem.

Answer:
You don't mentioned whether you've set this or not, but you have a choice with Integration Broker.  All messages flow through message channels, and a channel can either be ordered or unordered.  If a channel is ordered then - if a message errors - all subsequent messages queue up behind it and will not be processed until it succeeds.
Whether a channel is ordered or not depends upon the checkbox on the message channel properties in Application Designer.  From memory channels are ordered by default, but you can uncheck the box to increase throughput.
Hope this helps.
PS. As of Tools 8.49 the setup changed slightly, Channels became Queues, Messages Service Operations etc.


Question:
Does full trust mean the same as Run As Administrator?  I have read things stating that "for this to work, the application must be a full-trust application."  Is that the same as you must have administrator privileges to run the application?  If not, what's the difference?  How can you tell if an app is "full-trust"?

I am told that "Administrator or not, .Net apps won't do certain things if they aren't running from a 'trusted' location."  What is a "trusted location"?  If you run an app from a "trusted location", can you do things that "require full-trust" without being an administrator?

Answer:
No.  As of version 2.0, the .Net framework has it's own little filesystem setup for security.  Administrator or not, .Net apps won't do certain things if they aren't running from a 'trusted' location.
Just about anything on your local hard drive is trusted, but (and supposedly they fixed this for 3.5sp1) even the local intranet is
not
trusted, so most .Net desktop apps will fail to even start if they're sitting on a network drive or share.
You can change the configuration on a machine so it will allow apps from that zone, but it has to be done for
every
machine that's going to run the application, which breaks a common corporate deployment scenario.
From an ASP.Net standpoint, it also means that certain activities require more 'trust' than others.  Sending e-mail, for example, can cause exceptions if not set up correctly.


Question: What would be the best WPF control in C# (VS 2008) that you can place on a form that would allow you to do drawing similar to the "Paint" function for the CWnd class in C++?  Also, that could display bitmaps, have a scroll bar, and the ability to accept user inputs (ie. MouseMove, Button Clicks, etc...).  Basically all the functionality of a CWnd in a control on a WPF form?

Answer:
No.  As of version 2.0, the .Net framework has it's own little filesystem setup for security.  Administrator or not, .Net apps won't do certain things if they aren't running from a 'trusted' location.
Just about anything on your local hard drive is trusted, but (and supposedly they fixed this for 3.5sp1) even the local intranet is
not
trusted, so most .Net desktop apps will fail to even start if they're sitting on a network drive or share.
You can change the configuration on a machine so it will allow apps from that zone, but it has to be done for
every
machine that's going to run the application, which breaks a common corporate deployment scenario.
From an ASP.Net standpoint, it also means that certain activities require more 'trust' than others.  Sending e-mail, for example, can cause exceptions if not set up correctly.


Question:
I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want:

Org_ID      Org_Address    Org_OtherDetails    Employess

1           132A B Road    List of details     Emp1, Emp2, Emp3.....

Answer:
If you use Oracle you can create a PL/SQL function you can use in your query that accepts an organization_id as input, and returns the first name of all employees belonging to that org as a string. For example:-
```
```
select
   o.org_id,
   o.org_address,
   o.org_otherdetails,
   org_employees( o.org_id ) as org_employees
from
   organization o
```
```


Question:
I have a need to open a popup detail window from a gridview (VS 2005 / 2008).  What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:

<asp:Button ID="btnShowDetails" runat="server" CausesValidation="false"
   CommandName="Details" Text="Order Details"
   onClientClick="window.open('PubsOrderDetails.aspx?OrderId=<%# Eval("order_id") %>',
   '','scrollbars=yes,resizable=yes, width=350, height=550');"

Of course, what isn't working is the appending of the <%# Eval...%> section to set the query string variable.

Any suggestions?  Or is there a far better way of achieving the same result?

Answer:
I believe the way to do it is
```
```
onClientClick=<%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %>
```
```


Question:
I'm building an install using VS 2003. The install has an Excel workbook and two Access databases. I need to force the Access files to load regardless of the create/mod date of the existing databases on the user's computer. I currently use ORCA to force in a Version number on the two files, but would like to find a simpler, more elegant solution (hand editing a .msi file is not something I see as "best practice".

Is there a way to add a version number to the databases using Access that would then be used in the install?

Is there a better way for me to do this?

Answer:
Since it sounds like you don't have properly versioned resources, have you tried changing the REINSTALLMODE property?
IIRC, in the default value of 'omus', it's the 'o' flag that's only allowing you to install if you have an older version.  You may try changing this from 'o' to 'e'.  Be warned that this will overwrite missing, older AND equally versioned files.
Manually adding in versions was the wrong way to start, but this should ensure that you don't have to manually bump up the version numbers to get them to install.


Question:
I have just installed a build server with a 64 bit windows server 2008 for continuous integration.

The reason I choose a 64 bit server was to have more than ~3Gb of RAM. I had hopes that this machine would provide blazing fast builds.

Unfortunately, the result are lacking greatly to say the least. My desktop provides faster builds than this server equipped with a Xeon quad core, 15k RPM SAS and 8 Gigs of RAM.

We use Visual C++ 2005 to compile our 32 bit application with Cygwin.

Could the WOW64 emulator be the bottleneck that is slowing down the build process?

Any pointers, comments would be greatly appreciated.

Regards,

Answer:
Since it sounds like you don't have properly versioned resources, have you tried changing the REINSTALLMODE property?
IIRC, in the default value of 'omus', it's the 'o' flag that's only allowing you to install if you have an older version.  You may try changing this from 'o' to 'e'.  Be warned that this will overwrite missing, older AND equally versioned files.
Manually adding in versions was the wrong way to start, but this should ensure that you don't have to manually bump up the version numbers to get them to install.


Question: I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?

Answer:
By far the easiest approach, and almost certainly the fastest, is something along the lines of:
```
```
def sorted_dict(d):
    keys = d.keys()
    keys.sort()
    for key in keys:
        yield d[key]
```
```
You can't sort without fetching all keys. Fetching all keys into a list and then sorting that list is the most efficient way to do that; list sorting is very fast, and fetching the keys list like that is as fast as it can be. You can then either create a new list of values or yield the values as the example does. Keep in mind that you can't modify the dict if you are iterating over it (the next iteration would fail) so if you want to modify the dict before you're done with the result of sorted_dict(), make it return a list.


Question:
I am looking for a .NET implementation of a priority queue or heap data structure

Priority queues are data structures that provide more flexibility than simple sorting, because they allow new elements to enter a system at arbitrary intervals. It is much more cost-effective to insert a new job into a priority queue than to re-sort everything on each such arrival.

The basic priority queue supports three primary operations:

Insert(Q,x). Given an item x with key k, insert it into the priority queue Q.

Find-Minimum(Q). Return a pointer to the item
  whose key value is smaller than any other key in the priority queue
  Q.

Delete-Minimum(Q). Remove the item from the priority queue Q whose key is minimum

Unless I am looking in the wrong place, there isn't one in the framework. Is anyone aware of a good one, or should I roll my own?

Answer:
I like using the
```
OrderedBag
```
and
```
OrderedSet
```
classes in
PowerCollections
as priority queues.


Question:
Given an existing valid SVG document, what's the best way to create "informational popups", so that when you hover or click on certain elements (let's say ) you popup a box with an arbitrary amount (i.e. not just a single line tooltip) of extra information?

This should display correctly at least in Firefox and be invisible if the image was rasterized to a bitmap format.

Answer:
```
```
<svg>
  <text id="thingyouhoverover" x="50" y="35" font-size="14">Mouse over me!</text>
  <text id="thepopup" x="250" y="100" font-size="30" fill="black" visibility="hidden">Change me
    <set attributeName="visibility" from="hidden" to="visible" begin="thingyouhoverover.mouseover" end="thingyouhoverover.mouseout"/>
  </text>
</svg>
```
```
Further explanation can be found
here
.


Question:
When commiting to SVN I can add a top level commit message to detail what is being committed, but I would ideally like  a means to comment on the individual files and what has changed within them. I have seen something similar in previous employment, but this was using CVS (and I can't recall whether this was achieved with a home brew script to produce the skeleton file)

I have had a look at changelists but again I don't think (although i am willing to be proved wrong) that this gives the kind of granularity as outlined below.

Ideally I am looking for something along the lines of:

Foo.vb

Added new function bar

Bar.vb

Removed function foo

Added functionality in xyz to do abc
  +/- Modified function to log error

Answer:
I would just do this in the individual commit message.
TortoiseSVN
has filename autocompletion so that greatly aids in this.
Another thing you could do is svn st before you commit and copy/paste the filenames into your commit message.
Oh, and be sure to strongly question the value of this. I know some OSS projects (linux?) require this sort of fidelity, but for many projects this is just noise. Diff can tell you much more than this, and more accurately.
One other thing you may want to consider is using
Git
. Git allows you to commit locally, in smaller steps. You then push to the master server all of your commits individually or squashed into a single commit w/ all the commit messages in a single message. That was a way simplified explanation, but it probably is worth checking out.


Question:
I am a big fan of the light colors on a dark background color scheme for programming - which is unfortunately  not what Quest's Toad comes with by default.

I notice that it is possible to export and import settings under the language management window, and I know that Toad has a large level of community involvement.  So I assume there must be some location where people are posting their custom coloring schemes.  However, in part because I don't know what the Toad guys call them (skins? colorization? themes?) and in part because its so hard to Google Toad +skins I cannot for the life of me find them.

Does anyone know if there is such a place so I don't have to set the colors by hand?

Answer:
UPDATED ENTIRELY:
What's the official name?
The file extension (
```
.dvtcolortheme
```
) suggests
```
"Color Theme"
```
or
```
"DWT Color Theme"
```
are the official names. Most users on Toad forums seem to use the same terminology.
Where are they shared?
There does not seem to be a dedicated site for sharing color themes. However, there were a couple forums on
ToadWorld
, and
ToadForOracle
where folks were talking about swapping these color theme files. I would suggest hopping on the forum and asking if others have files to share or know of any repository sites.
Available Color Themes
* Nocturnal theme on GitHub:
https://github.com/grng/Nocturnal-Toad-Color-Scheme
* A nice dark-background theme:
http://toadfororacle.com/thread.jspa?messageID=93203
Rolling-your-own
I know you did not want to create your own, but it looks a lot easier than either of us expected. The
```
.dwtcolortheme
```
settings file is just XML.
I suggest visiting
http://studiostyl.es/
- as it's a large repository of Visual Studio themes. Find a thumbnail you like, take a screen shot, and use a color picker to capture the values. Plop them in your XML settings file and you are ready to go.


Question:
Within an XSLT document, is it possible to loop over a set of files in the current directory?

I have a situation where I have a directory full of xml files that need some analysis done to generate a report.  I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents.

I was thinking along these lines:

<xsl:for-each select="{IO Selector Here}">
    <xsl:variable select="document(@url)" name="contents" />
    <!--More stuff here-->
</xsl:for-each>

Answer:
I don't think XSL is set up to work that way: it's designed to be used by something else on one or more documents, and the something else would be responsible for finding files to which the XSLT should be applied.
If you had one main document and a fixed set of supporting documents, you could possibly use the
```
document()
```
function
to return specific nodes and/or values, but I suspect your case is different.


Question: What are some of the advantages of using one over the other?

Answer: Biggest single advantage for me would be the clear-cut separation between your Model, View, and Controller layers. It helps promote good design from the start.


Question:
What's the best way to shut down the computer from a C# program?

I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.

Answer:
You can launch the shutdown process:
```
shutdown -s -t 0
```
- Shutdown
```
shutdown -r -t 0
```
- Restart


Question: I'm working on a drop in assembly that has predefined pages and usable controls.  I am having no difficulties with creating server controls, but I'm wondering what the "best practices" are with dealing with pages in an assembly.  Can you compile a page into an assembly and release it as just a dll?  How would this be accessed from the client browser's perspective as far as the address they would type or be directed to with a link?  As an example, I have a simple login page with the standard username and password text boxes, and the log in button and a "remember me" checkbox, with a "I can't remember my username and/or password" hyperlink. Can I access that page as like a webresource?  such as "http://www.site.name/webresource.axd?related_resource_id_codes"

Answer:
You can add an httpHandler element to web.config pointing to your page. Something like:
```
```
<httpHandlers>
   <add verb="*" path="login.aspx" type="MyPages.LoginPage, MyPages" />
</httpHandlers>
```
```


Question:
In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int:

activation successful of id 1010101

The line above is the exact structure of the data in the db field.

And no I don't want to do this in the code of the application, I actually don't want to touch it, just in case you were wondering ;-)

Answer:
```
```
-- Test table, you will probably use some query
DECLARE @testTable TABLE(comment VARCHAR(255))
INSERT INTO @testTable(comment)
    VALUES ('activation successful of id 1010101')

-- Use Charindex to find "id " then isolate the numeric part
-- Finally check to make sure the number is numeric before converting
SELECT CASE WHEN ISNUMERIC(JUSTNUMBER)=1 THEN CAST(JUSTNUMBER AS INTEGER) ELSE -1 END
FROM (
       select right(comment, len(comment) - charindex('id ', comment)-2) as justnumber
       from @testtable) TT
```
```
I would also add that this approach is more set based and hence more efficient for a bunch of data values.  But it is super easy to do it just for one value as a variable.  Instead of using the column comment you can use a variable like
```
@chvComment
```
.


Question:
Below is part of the XML which I am processing with PHP's XSLTProcessor:

<result>
    <uf x="20" y="0"/>
    <uf x="22" y="22"/>
    <uf x="4" y="3"/>
    <uf x="15" y="15"/>
</result>

I need to know how many "uf" nodes exist where x == y.

In the above example, that would be 2.

I've tried looping and incrementing a counter variable, but I can't redefine variables.

I've tried lots of combinations of xsl:number, with count/from, but couldn't get the XPath expression right.

Thanks!

Answer:
```
```
count('/result/uf[@x = @y]')
```
```


Question: I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum width of the dialog without resorting to creating my own custom form?

Answer:
You can embed newlines in the text to force it to wrap at a certain point. e.g.
```
```
"message text...\nmore text..."
```
```
update: I posted that thinking it was a win32 API question, but I think the principle should still apply. I assume WinForms eventually calls MessageBox().


Question: So essentially does margin collapsing occur when you don't set any margin or padding or border to a given div element?

Answer:
"the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin."
Source:
Box Model - 8.3.1 Collapsing margins


Question:
I'm looking to run a Jabber server on a Windows 2003 server(web farm) and like some practical advice from anyone who has run a live environment with ~500 concurrent users.

Criteria for comment:

Performance

Capacity (ie ~number of concurrent users)

Stability

Answer:
I think you're going to need to be a bit more explicit - you looking for server configurations, or software e.g. Jabber Server?
If you're thinking Jabber server,
EJabberD
is probably the most stable, flexible, capable of being clustered etc.
Really useful comparison of Open Source servers here...
http://www.saint-andre.com/jabber/jsc/


Question:
I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout.  This obviously isn't great for maintainability.  Generally, when I design a site I pick 3-5 main colours for a theme.  I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted.  How do you avoid this?  I was thinking of creating separate rules for each colour and just use those when I need to restyle.

i.e.

.color1 {
    color: #3d444d;
}

Answer:
You could have a colours.css file with just the colours/images for each tag in.
Then you can change the colours just by replacing the file, or having a dynamically generated CSS file, or having different CSS files available and selecting based upon website URL/subfolder/property/etc.
Or you can have colour tags as you write, but then your HTML turns into:

Blah

CSS should have a feature where you can define values for things like colours that you wish to be consistent through a style but are defined in one place only. Still, there's search and replace.


Question: I haven't used Visual Studio since VB 3 and am trying to give it a shot with ASP.NET. It seems that it should be able to connect to a website (via some sort of ftp like protocol I figure) and allow to edit without having to manually upload/download the files. Is this the way it is supposed to work or am I mis-understanding? I have tried using 'create new website' and 'open website' using my testing domain (hosted by godaddy, wondering if that may be the issue as well), each time it gives me errors. I'm not sure if I'm doing something wrong or trying to do something it wasn't meant to.

Answer:
You really don't want to be working directly on a live web site, do you?  That's just crazy.  One little mistake and you've hosed the site.
Visual Studio now has it's own built in web server.  You use that for testing.  If you really don't want to use that you can put IIS on your local machine or set up a Dev/QA server somewhere.  In that case, you'd edit it via a file share.
You should be using some kind of source control.  Even for a single developer it's very important.  When finished with a programming session, you check your updates back into source control.
Finally, only after the site's gone through a suitable QA process, the production server is updated from source control, not from within visual studio.


Question:
I need to create a PRIVATE message queue on a remote machine and I have resolved to fact that I can't do this with the .NET Framework in a straight forward manner.  I can create a public message queue on a remote machine, but not a PRIVATE one. I can create a message queue (public or private) locally.

I am wondering if anyone knows how to access MSMQ through WMI.

Edit: I don't see anything to do it with using the MSMQ Provider. May have to get tricky and use PSExec to log onto a remote server and execute some code.

Answer:
A blog post about MSMQ and WMI is here:
http://msmq.spaces.live.com/blog/cns!393534E869CE55B7!210.entry
It says there is a provider here:
http://www.msmq.biz/Blog/MSMQWmiSetup.msi
It also says there is a reference here:
http://www.msmq.biz/Blog/MSMQ%20WMI%20Provider%20Objects.doc
Hope this helps.


Question:
I need to retrieve a record from a database, display it on a web page (I'm using ASP.NET) but store the ID (primary key) from that record somewhere so I can go back to the database later with that ID (perhaps to do an update).

I know there are probably a few ways to do this, such as storing the ID in ViewState or a hidden field, but what is the best method and what are the reasons I might choose this method over any others?

Answer:
```
```
Session["MyId"]=myval;
```
```
It would be a little safer and essentially offers the same mechanics as putting it in the viewstate


Question:
I am trying to execute some stored procedures in groovy way.  I am able to do it quite easily by using straight JDBC but this does not seem in the spirit of Grails.

I am trying to call the stored procedure as:

sql.query( "{call web_GetCityStateByZip(?,?,?,?,?)}",[params.postalcode,
sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.VARCHAR),
sql.out(java.sql.Types.INTEGER), sql.out(java.sql.Types.VARCHAR)]) { rs ->
   params.city = rs.getString(2)
   params.state = rs.getString(3)
}

I tried various ways like sql.call. I was trying to get output variable value after this.

Everytime error:

Message: Cannot register out parameter.
Caused by: java.sql.SQLException: Cannot register out parameter.
Class: SessionExpirationFilter

but this does not seem to work.

Can anyone point me in the right direction?

Answer:
This is still unanswered, so I did a bit of digging although I don't fully understand the problem. The following turned up from the Groovy source, perhaps it's of some help:
This line seems to be the origin of the exception:
http://groovy.codehaus.org/xref/groovy/sql/Sql.html#1173
This would seem to indicate that you have a Statement object implementing PreparedStatement, when you need the subinterface CallableStatement, which has the registerOutParameter() method which should be ultimately invoked.


Question:
Can someone please remind me how to create a .Net class from an XML file?

I would prefer the batch commands, or a way to integrate it into the shell.

Thanks!

Answer:
You might be able to use the xsd.exe tool to generate a class, otherwise you probably have to implement a custom solution against your XML
XML Schema Definition Tool
XML Serialization


Question:
I was reading a MS Excel help article about pivotcache and wonder what they mean by OLE DB and ODBC sources

...You should use the CommandText
  property instead of the SQL property,
  which now exists primarily for
  compatibility with earlier versions of
  Microsoft Excel. If you use both
  properties, the CommandText property’s
  value takes precedence.

For OLE DB sources, the CommandType
  property describes the value of the
  CommandText property.

For ODBC sources, the CommandText
  property functions exactly like the
  SQL property, and setting the property
  causes the data to be refreshed...

I really appreciate your short answers.

Answer:
On a very basic level those are just different APIs for the different data sources (i.e. databases). OLE DB is newer and arguably better.
You can read more on both in Wikipedia:
OLE DB
ODBC
I.e. you could connect to the same database using an ODBC driver or OLE DB driver. The difference in the database behaviour in those cases is what your book refers to.


Question: How do you enumerate the fields of a certificate help in a store. Specifically, I am trying to enumerate the fields of personal certificates issued to the logged on user.

Answer:
See
http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx
```
```
using System.Security.Cryptography.X509Certificates;
...
var store = new X509Store(StoreName.My);
foreach(var cert in store.Certificates)
...
```
```


Question:
Is there a good Eclipse plugin for recording and playing back macros?

I've tried this one, but it didn't do me any good- it seemed like it wasn't ready for prime time.

I know about editor templates, but I'm looking for something that I can use to record my keystrokes and then apply multiple times against a wad of text.

This seems like a strange hole in an IDE. Am I missing some built-in facility for this?

Answer:
This seems like a strange hole in an IDE, am I missing some builtin facility for this?
This is a common problem. There are around four bugs opened in Eclipse tracker for this. Unfortunately you would probably see macros in Eclipse in v4.0 or later.


Question: Speaking entirely in technology-free terms, what is the best way to make a mobile friendly site?  That is, I want to make a site that will work on a regular computer but also have mobile versions of the pages.  Should I rewrite each page?  The pages will probably have different functionality, so should I rewrite the backend code?  Should it be an effectively different site with the same database?

Answer:
I added a mobile presentation layer to an operational site about a year ago. Based on the architecture of the site (hopefully this isn't too technology dependent for you) I added a new set of JSPs to accommodate mobile browsers (sidenote: see
http://wurfl.sourceforge.net/
for a great way to build mobile pages independent of browser type). Additionally some of the back-end functionality was changed due to the limited functionality of most mobile browsers. So, in short, the integration wasn't as painful as one would expect.
Good luck!


Question: From managed C++, I am calling an unmanaged C++ method which returns a double. How can I convert this double into a managed string?

Answer:
C++ is definitely not my strongest skillset.  Misread the question, but this should convert to a std::string, not exactly what you are looking for though, but leaving it since it was the original post....
```
```
double d = 123.45;
std::ostringstream oss;
oss << d;
std::string s = oss.str();
```
```
This should convert to a managed string however..
```
```
double d = 123.45
String^ s = System::Convert::ToString(d);
```
```