Question:
Okay I know I asked about this before, and the answer was basically cache data that doesn't change often.

Well what does one do when at least 99.9% of the data changes?

In my project the only tables that doesn't get updated or won't get updated frequently would be the member profile info (name/address, and settings)

So how does one still enable some kind of caching but keep and make sure the data being viewed is updated when changes are applied?

Answer:
I guess, it's not really 99.9% of all data that changes, but it's in 99.9% of all data locations that changes happen.
For example, if you are running a bulletin board, that means that there will be a steady stream of new posts, but old posts will remain the same, and even old threads will stay unchanged for a long, long time.
In that case, you'll need a way to invalidate old cached data, so that you can build a cache as soon as a thread (in the example) is viewed. If there is a change to ONE of these threads (i.e. when someone adds a new post), this one cached item is deleted/marked outdated, so the next time it is viewed, it will be rebuilt. Other items that still haven't changed will use the cache, though.


Question: How do you find out the local time of the user browsing your website in ASP.NET?

Answer: You have to use JavaScript in the client side that will get the local time and pass that value to server side. You can pass it using querystring, hidden fields or even AJAX magic.


Question: Is there a way to reformat code, i.e. force correct indentation in FlashDevelop as you can do with CTRL-SHIFT-F in Eclipse?

Answer: open netbeans 6.5, create an xml file and then paste your mxml code; right click, format code, finally copy this formatted text from netbeans and past it in flex builder. it´s all.... i hope to be usefull


Question:
I find System.Monitor very confusing, although I understand threading, locks, deadlocks, race conditions, dining philosophers and all that jazz.  Normally I use a ManualResetEvent() to do inter-thread co-ordination, but I know that that's a heavyweight kernel object, and that System.Monitor (Enter/Pulse, etc.) is much more efficient.  I've Googled and Googled but cannot find a sensible example.

I would be most grateful if the SO crew could explain this potentially wonderful construct to me :-)

Answer:
Here's a very simple example; the call to
```
Wait
```
releases the lock (allowing
```
Worker
```
to obtain it) and adds the
```
Main
```
thread to the lock-object's pending queue.
```
Worker
```
then obtains the lock, and calls
```
Pulse
```
: this moves the
```
Main
```
thread into the lock-object's ready queue. When
```
Worker
```
releases
the lock,
```
Main
```
can resume work.
Note that
```
lock(obj) {...}
```
is just compiler-candy for
```
Monitor.Enter
```
/
```
Monitor.Exit
```
in a try/finally block.
[edit: I changed the sample to move
```
lock(sync)
```
earlier, to avoid the (unlikely) risk of a missed Pulse]
```
```
static void Main()
    {
        object sync = new object();
        lock (sync)
        {
            ThreadPool.QueueUserWorkItem(Worker, sync);
            Console.WriteLine("Main sleeping");

            // wait for the worker to tell us it is ready
            Monitor.Wait(sync);
            Console.WriteLine("Main woke up!");
        }
        Console.WriteLine("Press any key...");
        Console.ReadKey();
    }
    static void Worker(object sync)
    {
        Console.WriteLine("Worker started; about to sleep");
        Thread.Sleep(5000);
        Console.WriteLine("Worker about pulse");
        lock (sync)
        { // notify Main that we did something interesting
            Monitor.Pulse(sync);
            Console.WriteLine("Worker pulsed; about to release lock");
        }
        Console.WriteLine("Worker all done");
    }
```
```


Question:
I am running the free version of Helicon ISAPI Rewrite on IIS and have several sites running through the same set of rewrite rules. Up 'til now this has been fine as all the rules have applied to all the sites. I have recently added a new site which I don't want to run through all the rules. Is there any way to make requests to this site break out of the rule set after it's executed its own rules.

I've tried the following with no luck; all requests to mysite.com result in a 404. I guess what I'm looking for is a rule that does nothing and is marked as the last rule to execute [L].

## New site rule for mysite.com only
RewriteCond  Host:  (?:www\.)?mysite\.com
RewriteRule  /content([\w/]*)   /content.aspx?page=$1 [L]

## Break out of processing for all other requests to mysite.com
RewriteCond  Host:  (?:www\.)?mysite\.com
RewriteRule (.*) - [L]

## Rules for all other sites
RewriteRule ^/([^\.\?]+)/?(\?.*)?$ /$1.aspx$2 [L]
...

Answer:
Rewrite it to itself?
```
```
RewriteCond  Host:  (?:www\.)?mysite\.com
RewriteRule ^(.*)$ $1 [QSA,L]
```
```


Question:
Is there a way I can access (for printout) a list of sub + module to arbitrary depth of sub-calls  preceding a current position in a Perl script?

I need to make changes to some Perl modules (.pm's). The workflow is initiated from a web-page thru a cgi-script, passing input through several modules/objects ending in the module where I need to use the data. Somewhere along the line the data got changed and I need to find out where.

Answer:
You can use
Devel::StackTrace
.
```
```
use Devel::StackTrace;
my $trace = Devel::StackTrace->new;
print $trace->as_string; # like carp
```
```
It behaves like Carp's trace, but you can get more control over the frames.
The one problem is that references are stringified and if a referenced value changes, you won't see it.  However, you could whip up some stuff with
PadWalker
to print out the full data (it would be huge, though).


Question:
$("#dvMyDIV").bind("resize", function(){
    alert("Resized");
});

or

$("#dvMyDIV").resize(function(){
    alert("Resized");
});

The questions

Why is this not working at FireFox, Chrome and Safari?

Can this be considered a jQuery bug since the resize is not handled for other browsers?

Could the only workaround be calling a SetTimeout function checking the clientHeight and clientWidth?

Any workarounds using jQuery?

Answer:
I believe the JavaScript resize event only applies to frames or windows, not to DIVs.
e.g. see
this page
:
The onResize even handler is use to execute specified code whenever a user or script resizes a window or frame. This allows you to query the size and position of window elements, dynamically reset SRC properties etc.
So if you want to detect when the window is resized, in jQuery you should probably use
```
$(window).resize(function() { });
```
Edit:
if you want to watch the size of a DIV, it depends on what your intention is. If you're resizing with JavaScript then you could implement a method to perform the resize and have that handle calling any other resize code.
Otherwise, if you're just watching for the DIV to resize when someone resizes the window, wouldn't it just work to attach the resize listener to the window and then check if the DIV had been resized (i.e. store the old values of width / height and check them on resize)?
Finally, you could consider using
watch
on the width / height properties, although I don't know whether this is fully browser-compatible (think this might be Mozilla-only). I did find
this jQuery plugin
which looks like it might do the same thing though (with some slight modification).


Question:
How can I convert a relative path to an absolute path in C on Unix?
Is there a convenient system function for this?

On Windows there is a GetFullPathName function that does the job, but I didn't find something similar on Unix...

Answer:
Use
realpath()
.
The
```
realpath()
```
function shall derive,
  from the pathname pointed to by
```
file_name
```
, an absolute pathname that
  names the same file, whose resolution
  does not involve '
```
.
```
', '
```
..
```
', or
  symbolic links. The generated pathname
  shall be stored as a null-terminated
  string, up to a maximum of
```
{PATH_MAX}
```
bytes, in the buffer pointed to by
```
resolved_name
```
.
If
```
resolved_name
```
is a null pointer,
  the behavior of
```
realpath()
```
is
  implementation-defined.
The following example generates an
  absolute pathname for the file
  identified by the symlinkpath
  argument. The generated pathname is
  stored in the actualpath array.
```
```
#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;

ptr = realpath(symlinkpath, actualpath);
```
```


Question: Is there any free java library which I can use to convert string in one encoding to other encoding, something like iconv? I'm using Java version 1.3.

Answer:
```
CharsetDecoder
```
should be what you are looking for, no ?
Many network protocols and files store their characters with a byte-oriented character set such as
```
ISO-8859-1
```
(
```
ISO-Latin-1
```
).
However, Java's native character encoding is
Unicode
UTF16BE (Sixteen-bit UCS Transformation Format, big-endian byte order).
See
```
Charset
```
. That doesn't mean
```
UTF16
```
is the default charset (i.e.: the default "mapping between sequences of sixteen-bit
Unicode code units
and sequences of bytes"):
Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets.
[
```
US-ASCII
```
,
```
ISO-8859-1
```
a.k.a.
```
ISO-LATIN-1
```
,
```
UTF-8
```
,
```
UTF-16BE
```
,
```
UTF-16LE
```
,
```
UTF-16
```
]
The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system.
This example demonstrates how to convert
```
ISO-8859-1
```
encoded bytes in a
```
ByteBuffer
```
to a string in a
```
CharBuffer
```
and visa versa.
```
```
// Create the encoder and decoder for ISO-8859-1
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();

try {
    // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
    // The new ByteBuffer is ready to be read.
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("a string"));

    // Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.
    // The new ByteBuffer is ready to be read.
    CharBuffer cbuf = decoder.decode(bbuf);
    String s = cbuf.toString();
} catch (CharacterCodingException e) {
}
```
```


Question:
I need to test a web form that takes a file upload.
The filesize in each upload will be about 10 MB.
I want to test if the server can handle over 100 simultaneous uploads, and still remain
responsive for the rest of the site.

Repeated form submissions from our office will be limited by our local DSL line.
The server is offsite with higher bandwidth.

Answers based on experience would be great, but any suggestions are welcome.

Answer:
I would perhaps guide you towards using cURL and submitting just random stuff (like, read 10MB out of
```
/dev/urandom
```
and encode it into base32), through a POST-request and manually fabricate the body to be a file upload (it's not rocket science).
Fork that script 100 times, perhaps over a few servers. Just make sure that sysadmins don't think you are doing a DDoS, or something :)
Unfortunately, this answer remains a bit vague, but hopefully it helps you by nudging you in the right track.
Continued as per Liam's comment:
If the server receiving the uploads is not in the same LAN as the clients connecting to it, it would be better to get as remote nodes as possible for stress testing, if only to simulate behavior as authentic as possible. But if you don't have access to computers outside the local LAN, the local LAN is always better than nothing.
Stress testing from inside the same hardware would be not a good idea, as you would do double load on the server: Figuring out the random data, packing it, sending it through the TCP/IP stack (although probably not over Ethernet), and
only then
can the server do its magic. If the sending part is outsourced, you get double (taken with an arbitrary sized grain of salt) performance by the receiving end.


Question:
When using something like object.methods.sort.to_yaml I'd like to have irb interpret the \n characters rather than print them.

I currently get the following output:

--- \n- "&"\n- "*"\n- +\n- "-"\n- "<<"\n- <=>\n ...

What I'd like is something similar to this:

---
 - "&"
 - "*"
 - +
 - "-"
 - "<<"
 - <=>

Is this possible? Is there another method I can be calling which will interpret the string perhaps?

Answer:
That's just irb -- I don't think you can control the
```
return
```
formatting.
You can still use
```
print
```
or
```
puts
```
to display it as you want.


Question: How to convey a bad news to the client?

Answer:
What type of bad news?
People in general like to break bad news by stating that the corrections / new timelines will be in place much earlier than we truely can accomplish. Be honest up front and dont give false hope. One instance of bad news is enough... no need to create new promises that you cant keep in the future.
Bottom Line: be honest to your client and yourself to control expectation management.


Question:
how to show all values of a particular field in a text box ???
ie. for eg. when u run the SP, u'll be getting 3 rows. and i want to show the (eg.empname)
in a textbox each value separated by a comma.
(ram, john, sita).

Answer:
I had this problem the other day. If you are using SQL 2005 you can use the CROSS APPLY function.
Here is a sample;
```
```
Structure;
ID TYPE TEXT
1 1 Ram
2 1 Jon
3 2 Sita
4 2 Joe

Expecteed Output;
ID TYPE TEXT
1 1 Ram, Jon
2 2 Sita, Joe

Query;
SELECT t.TYPE,LEFT(tl.txtlist,LEN(tl.txtlist)-1)
FROM(SELECT DISTINCT TYPE FROM Table)t
CROSS APPLY (SELECT TEXT + ','
             FROM Table
             WHERE TYPE=t.TYPE
             FOR XML PATH(''))tl(txtlist)
```
```
Hope this helps :)
Remember you'll need to select this as something in your sp, then bind that to the textbox on your report. Good luck!


Question:
After looking at other questions related to sharing solutions between VS 2005 and VS 2008 it seems that the way to go is to have two solution files (one for VS 2005 and one for VS 2008).

However, if the solution is under source control (VisualSVN in our case), how would we maintain two solution files and not keep overwriting one or the other with each update/commit?

Is it possible to remove just the .sln file from source control and stop the VisualSVN client from checking its status in visual studio?

Thanks

Matt

Answer:
I'm not sure I see the problem - if you've got two solution files, why would either of them be overwritten? I do really mean two files, e.g. MyApp2005.sln and MyApp2008.sln, where when you create a new project you do it in the 2005 solution and then just "add existing project" in the 2008 solution.
What would VisualSVN do to mess this up?
(I have the same setup for my
C# in Depth source code
, and I use VisualSVN - I haven't seen any problems.)


Question:
The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.

Any help would be much appreciated.

function validate_phone($phone)
{
    $phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$";

    $phonevalid = 0;

    if (ereg($phoneregexp, $phone))
    {
        $phonevalid = 1;
    }else{
        $phonevalid = 0;
    }
}

Answer:
If this is PHP, then the regex must be enclosed in quotes.
Furthermore, what's
```
preg
```
? Did you mean
```
preg_match
```
?
Another thing. PHP knows boolean values. The canonical solution would rather look like this:
```
```
return preg_match($regex, $phone) !== 0;
```
```
EDIT: Or, using
```
ereg
```
:
```
```
return ereg($regex, $phone) !== FALSE;
```
```
(Here, the explicit test against
```
FALSE
```
isn't strictly necessary but since
```
ereg
```
returns a number upon success I feel safer coercing the value into a
```
bool
```
).


Question:
I've a WEB application (with pure Java servlet) that have some heavy computational work, with database access, that can be done in asynchronous mode.
I'm planning to use a dedicated server to execute such batch jobs and I'm wondering which tools/techniques/protocols to use for communication between servlets in the WEB server and batch jobs in the new dedicated server.
I'm looking at JMS. Is it the right choice?
There are industry standard and/or widely adopted techniques?
I need also queue and priority handling for multiple simultaneous jobs.

Answer:
Messaging is one of the best options.
Make the messaging framework very generic so that it can handle any type of batch jobs.
One approach is to have an event/task manager where you put an event on the queue and the queue consumer processes the event and converts it into a set of tasks. The tasks can then be executed by separate task handlers. A task can also generate some more events that can be again put on the queues to provide a feedback loop. This way you can add work flow like features to the framework and allow your batch jobs to have dependencies on each other.


Question:
<div>
<h1>Title</h1>
<table>
...
</table>
</div>

Now, the

<h1>

has a margin: 0;
so it is at the top of the div. The height of the div is 300px.

However I'd like the table to be placed at the bottom of the div, eg. valign="bottom" but for the whole table.

Answer:
What about this:
```
```

Title

...

```
```
The only problem is that both the container div and the tableContainer divs need to be absolute positioned. Not sure if this will work for your layout.


Question: I find print_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?

Answer:
Note @tchrist recommends
Data::Dump
over
Data::Dumper
. I wasn't aware of it, but from the looks of it, seems like it's both far easier to use and producing better looking and easier to interpret results.
Data::Dumper
:
A snippet of the examples shown in the above link.
```
```
use Data::Dumper;

package Foo;
sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};

package Fuz;                       # a weird REF-REF-SCALAR object
sub new {bless \($_ = \ 'fu\'z'), $_[0]};

package main;
$foo = Foo->new;
$fuz = Fuz->new;
$boo = [ 1, [], "abcd", \*foo,
         {1 => 'a', 023 => 'b', 0x45 => 'c'},
         \\"p\q\'r", $foo, $fuz];

########
# simple usage
########

$bar = eval(Dumper($boo));
print($@) if $@;
print Dumper($boo), Dumper($bar);  # pretty print (no array indices)

$Data::Dumper::Terse = 1;          # don't output names where feasible
$Data::Dumper::Indent = 0;         # turn off all pretty print
print Dumper($boo), "\n";

$Data::Dumper::Indent = 1;         # mild pretty print
print Dumper($boo);

$Data::Dumper::Indent = 3;         # pretty print with array indices
print Dumper($boo);

$Data::Dumper::Useqq = 1;          # print strings in double quotes
print Dumper($boo);
```
```


Question:
What exactly does null do performance and storage (space) wise in MySQL?

For example:

TINYINT: 1 Byte
TINYINT w/NULL 1 byte + somehow stores NULL?

Answer:
It depends on which storage engine you use.
In MyISAM format, each row header contains a bitfield with one bit for each column to encode NULL state.  A column that is NULL still takes up space, so NULL's don't reduce storage.  See
https://dev.mysql.com/doc/internals/en/myisam-introduction.html
In InnoDB, each column has a "field start offset" in the row header, which is one or two bytes per column.  The high bit in that field start offset is on if the column is NULL.  In that case, the column doesn't need to be stored at all.  So if you have a lot of NULL's your storage should be significantly reduced.
See
https://dev.mysql.com/doc/internals/en/innodb-field-contents.html
EDIT:
The NULL bits are part of the row headers, you don't choose to add them.
The only way I can imagine NULLs improving performance is that in InnoDB, a page of data may fit more rows if the rows contain NULLs.  So your InnoDB buffers may be more effective.
But I would be very surprised if this provides a significant performance advantage in practice.  Worrying about the effect NULLs have on performance is in the realm of micro-optimization.  You should focus your attention elsewhere, in areas that give greater bang for the buck.  For example adding well-chosen indexes or increasing database cache allocation.


Question:
How do I limit os.walk to only return files in the directory I provide it?

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
            else:
                self._email_to_("ignore")
    return outputList

Answer:
You could use
```
os.listdir()
```
which returns a list of names (for both files and directories) in a given directory. If you need to distinguish between files and directories, call
```
os.stat()
```
on each name.


Question:
I would like to do remote deployment from my build machine onto a server. The remoting can be done via ssh commands from a script, but I would rather use phing and a deploy.xml file that would do the automation.

What alternatives do I have to do ssh (and also scp) tasks from within a phing build file?

Answer:
I ran into the same problem about a year ago and back then i could not find a task. I ended up doing a exec task, this way it was all in the xml file.
```
```
<exec command="scp -i keys/id_rsa myfile user@$server:myfile" dir="." />
```
```


Question: Is it quicker to make one trip to the database and bring back 3000+ plus rows, then manipulate them in .net & LINQ or quicker to make 6 calls bringing back a couple of 100 rows at a time?

Answer:
It will entirely depend on the speed of the database, the network bandwidth and latency, the speed of the .NET machine, the actual queries etc.
In other words, we can't give you a truthful general answer. I know which sounds easier to code :)
Unfortunately this is the kind of thing which you can't easily test usefully without having an
exact
replica of the production environment - most test environments are somewhat different to the production environment, which could seriously change the results.


Question: Do you always use a second-level cache in Hibernate or do you first try it without and only use it when the performance goes down?

Answer:
My usage of Hibernate has always been in the context of another framework (Spring, for example), where enabling caching is nearly trivial.  A number of these projects have made use of caching via
ehcache
for some critical domain classes.
Having said that, this is another area where we have to make trade-offs between resources - balancing retrieval performance against memory usage.  Optimization without measurement has been shown again and again to be poor practice.
Collect metrics about the performance of your application.  Then decide how to address the slow spots.  Caching may be the least of  your worries.


Question: When we add a variable to ASP.NET Session, where are those variables actually stored on the client side?

Answer:
If you are using the default session in ASP.NET then it is stored in memory inside the ASP.NET worker process. It is a server side cache, nothing at all to do with the client.
There are other session store options available such as dedicated session state machine or sql server. You can also roll your own session provider.
All explained here
http://msdn.microsoft.com/en-us/library/ms972429.aspx


Question: What would be the disadvantages (if any) of automating business process for a Enterprise/organization?

Answer:
Loosing discretionary error checking, i.e. numbers that look out of line;
Potentially, knowledge of how a process is operated could be lost if it is automated but not documented. More often than not, manual processes are passed on;
Accountability for the process becomes muddled.


Question:
Why should I choose to use one instead of the other and in which cases?

I mainly focus on desktop applications and personally speaking I do find the humble dialog box more easy and natural to use.

Answer:
In MVC, you would still use your "humble" dialog. Except all the business logic for it would be farmed off to another class somewhere else.
http://en.wikipedia.org/wiki/Model-view-controller
You need to weight up whether the investment in MVC will be worth it - especially if you're only working with a single simple dialog.


Question:
As title, I need that to run an import script generated by SQL Server DB Publishing Tool. Would that work on Sql2000 server too? Also I have seen ppl reporting missing library issues related to GAC, which libraries I precisely need to include if I am not controlling the deployment server?

To know how this thing works you can check here in MSDN Forum.
http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3947420&SiteID=1

I tested and indeed it works in my devbox with SQL2005 Express installed.

Answer:
Yes, SMO works on SQL Server 2000:
SMO and Sql Server 7.0


Question:
<div style="width: 300px">
<div id="one" style="float: left">saved</div><input type="submit" id="two" style="float: right" value="Submit" />
</div>

I would like div#one to be centred in the space between the left edge of the parent div and the left edge of the submit button.

Answer:
There are a number of techniques listed
here
However, if you simply wanted the "saved" text to be centred, I think you'll need to give a width to #one, e.g.
```
```

saved

<input type="submit" id="two" style="float: right;width:20%" value="Submit" />

```
```


Question:
I'm trying to read a file to produce a DOM Document, but the file has whitespace and newlines and I'm trying to ignore them, but I couldn't:

DocumentBuilderFactory docfactory=DocumentBuilderFactory.newInstance();
docfactory.setIgnoringElementContentWhitespace(true);

I see in Javadoc that setIgnoringElementContentWhitespace method operates only when the validating flag is enabled, but I haven't the DTD or XML Schema for the document.

What can I do?

Update

I don't like the idea of introduce mySelf < !ELEMENT... declarations and i have tried the
solution proposed in the forum pointed by Tomalak, but it doesn't work, i have used java 1.6 in an linux environment. I think if no more is proposed i will make a few methods to ignore whitespace text nodes

Answer:
‘IgnoringElementContentWhitespace’ is not about removing
all
pure-whitespace text nodes, only whitespace nodes whose parents are described in the schema as having ELEMENT content — that is to say, they only contain other elements and never text.
If you don't have a schema (DTD or XSD) in use, element content defaults to MIXED, so this parameter will never have any effect. (Unless the parser provides a non-standard DOM extension to treat all unknown elements as containing ELEMENT content, which as far as I know the ones available for Java do not.)
You could hack the document on the way into the parser to include the schema information, for example by adding an internal subset to the < !DOCTYPE ... [...] > declaration containing < !ELEMENT ... > declarations, then use the IgnoringElementContentWhitespace parameter.
Or, possibly easier, you could just strip out the whitespace nodes, either in a post-process, or as they come in using an LSParserFilter.


Question:
I m just starting using gwt and so far so good, however after reading some sample code I wonder is it necesary to have a high level of test coverage? (I can see that most code is declarative and then add some attributes I can see the sense in checking so me particular attributes are there but not all)

Also i would be interested to know anything about what are the gotchas in TDDing with GWT

I m using eclipse so also if you are really happy with some particualrs add ins for GWT I would be happy to hear about that
Thanks for the input

edit: maybe I m asking a very wide question, but even little pieces of information will help
I come from having nvelocity views with jquery/extJs/prototype/scriptaculous and this is a bit different

Answer:
I think you asked a pretty broad question, which is part of the reason why you didn't get a reply for a while.
Compared to traditional AJAX web development, one could argue a GWT application requires less testing.  Because the GWT team has worked so hard to make sure that its widgets work consistently across all web browsers, you don't have to worry about cross-browser compatibility nearly as much for your own application.
That frees you up to focus on your own application.  Create a separate test case for each of your own custom widgets and test that they behave as you expect, and then write higher-level tests for each module.  Take the extra step to make your tests fully automatable - that way every time you make a change or are about to release, it's easy to run all of your tests.
http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=DevGuideJUnitIntegration


Question:
I have a String which I would like to modify in some way. For example: reverse it or upcase it.

I have discovered that the fastest way to do this is by using a unsafe block and pointers.

For example:

        unsafe
        {
            fixed (char* str = text)
            {
                *str = 'X';
            }
        }

Are there any reasons why I should never ever do this?

Answer:
The .Net framework requires strings to be immutable. Due to this requirement it is able to optimise all sorts of operations.
String interning
is one great example of this requirement is leveraged heavily. To speed up some string comparisons (and reduce memory consumption) the .Net framework maintains a Dictionary of pointers, all pre-defined strings will live in this dictionary or any strings where you call the
```
String.intern
```
method on. When the IL instruction ldstr is called it will check the interned dictionary and avoid memory allocation if we already have the string allocated, note:
String.Concat
will not check for interned strings.
This property of the .net framework means that if you start mucking around directly with strings you can corrupt your intern table and in turn corrupt other references to the same string.
For example:
```
```
// these strings get interned
        string hello = "hello";
        string hello2 = "hello";

        string helloworld, helloworld2;

        helloworld = hello;
        helloworld += " world";

        helloworld2 = hello;
        helloworld2 += " world";

        unsafe
        {
            // very bad, this changes an interned string which affects
            // all app domains.
            fixed (char* str = hello2)
            {
                *str = 'X';
            }

            fixed (char* str = helloworld2)
            {
                *str = 'X';
            }

        }

        Console.WriteLine("hello = {0} , hello2 = {1}", hello, hello2);
        // output: hello = Xello , hello2 = Xello

        Console.WriteLine("helloworld = {0} , helloworld2 = {1}", helloworld, helloworld2);
        // output : helloworld = hello world , helloworld2 = Xello world
```
```


Question:
I am using Python to extract the filename from a link using rfind like below:

url = "http://www.google.com/test.php"

print url[url.rfind("/") +1 : ]

This works ok with links without a / at the end of them and returns "test.php".  I have encountered links with / at the end like so "http://www.google.com/test.php/".  I am have trouble getting the page name when there is a "/" at the end, can anyone help?

Cheers

Answer:
You could use
```
```
print url[url.rstrip("/").rfind("/") +1 : ]
```
```


Question:
In my main page (call it index.aspx) I call

<%Html.RenderPartial("_PowerSearch", ViewData.Model);%>

Here the viewdata.model != null
When I arrive at my partial:

<%=ViewData.Model%>

Says viewdata.model == null

What gives?!

Answer:
Have you tried just passing in ViewData instead of ViewData.Model? This is an abridged version what I use in my helpers (shamelessly stolen from the Storefront series):
```
```
/// <summary>
    /// Renders a LoggingWeb user control.
    /// </summary>
    /// <param name="helper">Helper to extend.</param>
    /// <param name="control">Type of control.</param>
    /// <param name="data">ViewData to pass in.</param>
    public static void RenderLoggingControl(this System.Web.Mvc.HtmlHelper helper, LoggingControls control, object data)
    {
        string controlName = string.Format("{0}.ascx", control);
        string controlPath = string.Format("~/Controls/{0}", controlName);
        string absControlPath = VirtualPathUtility.ToAbsolute(controlPath);
        if (data == null)
        {
            helper.RenderPartial(absControlPath, helper.ViewContext.ViewData);
        }
        else
        {
            helper.RenderPartial(absControlPath, data, helper.ViewContext.ViewData);
        }
    }
```
```
Note that I pass in the current ViewData and not the Model.


Question:
I have an Office 2007 (specifically Outlook 2007) add in created in Visual Studio 2008.

When I uncheck the "Sign the ClickOnce manifests" option, and then publish, it rechecks that option automatically.

I have a regular Windows Forms project in the same solution that allows me to publish with this unchecked.

Why isn't it allowing me to uncheck the sign option?

Answer:
You are not required to sign EXE files, but you need to sign DLL files for deployment. Your Office add-in is in the form of a DLL file, so it must be signed. Your Windows Forms project is linked into an EXE file, hence it does not need to be signed.
See the relevant MSDN page,
ClickOnce Manifest Signing and Strong-Name Assembly Signing Using Visual Studio Project Designer's Signing Page
, sub section
Signing Assemblies
.


Question:
I've made a custom DataGridViewCell that displays a custom control instead of the cell; but if the DataGridView uses shared rows, then the custom control instance is also shared, so you get strange behaviour (for example, hovering over buttons highlights all the buttons).  Also, I can't access the DataGridViewCell.Selected property, so I don't know what colour to paint the row.

How do I prevent a DataGridView from sharing rows?  I know I can add the rows using the Rows.Add(object[]) override, but then the first row is still shared (i.e. has index -1) so the problem with colours still applies.

I need to be able to tell the DataGridView not to share a row containing a custom cell.  Can that be done with attributes?  Can it be done at all?

Answer:
Try to set a Tooltip Text in one cell of the Row
A row cannot be shared in any of the following situations:
 The row contains a single selected cell that is not in a selected column.
 The row contains a cell with its ToolTipText or ContextMenuStrip properties set.
 The row contains a DataGridViewComboBoxCell with its Items property set.
or read
http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx
for more Information


Question:
I have a string in Bash:

string="My string"

How can I test if it contains another string?

if [ $string ?? 'foo' ]; then
  echo "It's there!"
fi

Where ?? is my unknown operator. Do I use echo and grep?

if echo "$string" | grep 'foo'; then
  echo "It's there!"
fi

That looks a bit clumsy.

Answer:
I am not sure about using an if statement, but you can get a similar effect with a case statement:
```
```
case "$string" in
  *foo*)
    # Do stuff
    ;;
esac
```
```


Question:
The Mutex class is very misunderstood, and Global mutexes even more so.

What is good, safe pattern to use when creating Global mutexes?

One that will work

Regardless of the locale my machine is in

Is guaranteed to release the mutex properly

Optionally does not hang forever if the mutex is not acquired

Deals with cases where other processes abandon the mutex

Answer:
I want to make sure this is out there, because it's so hard to get right:
```
```
using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid =
        ((GuidAttribute)Assembly.GetExecutingAssembly().
            GetCustomAttributes(typeof(GuidAttribute), false).
                GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    // Need a place to store a return value in Mutex() constructor call
    bool createdNew;

    // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
    // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
    var allowEveryoneRule =
        new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
                                                   , null)
                           , MutexRights.FullControl
                           , AccessControlType.Allow
                           );
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

   // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
    using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
    {
        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact that the mutex was abandoned in another process,
                // it will still get acquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statement
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}
```
```


Question:
does anybody know how to refresh the Internet Explorer (like by pressingthe F5 key) but using some "backdoor" like PostMessage or SendMessage? The internet Explorer Window is not active so I can't use the keyboard.

Thanks

(Language doesnt matter)

Answer:
If you can identify what is to be replaced through a regular expression, I recommend using the optional task
replaceregexp
. Here's the doc:
http://ant.apache.org/manual/Tasks/replaceregexp.html
You can call it twice, one for the start tag and other for the end tag.
The regexp for replacing your
can be a bit cumbersome, since you say you do not want to replace all
tags, but I think this is the easiest way.
Another option would be to create a custom ant task to do what you want.


Question:
I am working on a stored procedure with several optional parameters.  Some of these parameters are single values and it's easy enough to use a WHERE clause like:

WHERE (@parameter IS NULL OR column = @parameter)

However, in some instances, the WHERE condition is more complicated:

WHERE (@NewGroupId IS NULL OR si.SiteId IN (SELECT gs.SiteId
FROM [UtilityWeb].[dbo].[GroupSites] AS gs
WHERE gs.GroupId = @NewGroupId))

When I uncomment these complicated WHERE clauses, the query execution time doubles and the execution plan becomes remarkably more complicated. While the execution plan doesn't bother me, doubling the execution time of a query is a definite problem.

Is there a best practice or pattern that others have found for working with optional parameters in their stored procedures?

Is this one of those instances where dynamic SQL would be a better solution?

Answer:
I would create separate queries for the parameter being available or not.
This will create simpler SQL, and the optimizer will do a better job.
Like this:
```
```
if (@parameter IS NULL) then begin
   select * from foo
end
else begin
   select * from foo where value = @parameter
end
```
```
In you have to many parameters to redesign like this, and you go for the dynamic sql solution, then also always use parameters, you might get bitten by the
SQL-Injection
bug.
A combination is also possible. The most likely used query/queries you code in full, and get precompiled. All other combinations are created dynamically.


Question:
<input type="submit"/>

<style>
input {
  background: url(tick.png) bottom left no-repeat;
  padding-left: 18px;
}
</style>

But the bevel goes away, how can I add an icon to submit button and keep the bevel?

Edit: I want it to look like the browser default.

Answer:
Use border.  For example:
```
```
INPUT.button {
    BORDER-RIGHT: #999999 1px solid;
    BORDER-TOP: #999999 1px solid;
    FONT-SIZE: 11px;
    BACKGROUND: url(tick.png) bottom left no-repeat;
    BORDER-LEFT: #999999 1px solid;
    CURSOR: pointer;
    COLOR: #333333;
    BORDER-BOTTOM: #999999 1px solid
}

<input type="submit" class="button" />
```
```


Question:
In a C program (p1), how to launch a dynamically constructed command (and its arguments) that reads its standard input from p1's standard output?

Note that:

A method other than this stdout -->
stdin piping is also OK provided
it is PORTABLE across Windows and
Linux.

I cannot use C++, Java, Perl, Ruby,
Python, etc here.

Also, will this have a MinGW dependency for its Windows build?

REOPENED: The question below answers it for Linux, but this question wants a portable method.
Execute program from within a C program

Answer:
It's not 100% clear to me what you're trying to achieve exactly to be honest.
But as I understand it, you could take a look at
Boost.Process
You can do things like
```
```
bp::child cs = p.start();
 bp::postream& os = cs.get_stdin();
```
```
And then use the
os
as any stream to dump stuff in the standard input of your child process.
Anyway, an awful lot can be achieved with the library w.r.t. pipe redirecting and chaining.


Question:
Following on from a previous question, I am creating a symbolic link on a Server 2008 from a Vista machine using UNC paths. I can create the link just fine. I can go to the Server 2008 box and double click on the link in explorer to open the target file. What I cannot do though is use FileCreateW to get a handle to the UNC path link (from the Vista box). When I try it, it fails and GetLastError() returns error code 1463 (0x5B7), which is:

The symbolic link cannot be followed because its type is disabled.

How to enable its "type" in Server 2008 (assuming the error means what it says)?

Answer:
Well I found the answer, though to describe it as badly documented is an understatement!
First of all,
this TechEd article
highlights the fact that users can "enable or disable any of the four evaluations that are available in symbolic links". Those four "evaluations" include remote to local and local to remote. It doesn't give any clue as to how to do this.
However a further search revealed
this fsutil help page
, which does actually document how to "enable or disable any of the four evaluations that are available in symbolic links". So to fix the problem I was having, I need to issue the following command
on the Vista box
:
```
```
fsutil behavior set SymlinkEvaluation L2L:1 R2R:1 L2R:1 R2L:1
```
```
in order to allow full access to where symlinks are pointing on both local and remote machines.


Question:
I read the following in a review of Knuth's "The Art of Computer Programming":

"The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behavior of most other languages which implement a for loop."

(http://www.amazon.com/review/R9OVJAJQCP78N/ref=cm_cr_pr_viewpnt#R9OVJAJQCP78N)

What is this guy talking about?  How could you implement a for loop that wasn't just syntactic sugar for a while loop?

Answer:
He probably refers to for loops like
```
for i:=0 to N
```
and for-each loops that iterate over the elements of a set. I suspect all languages that have a C-style for loop actually got it from C.


Question: I'd like to create a basic "Hello World" style application for the IPhone using Java - can anyone tell me how?

Answer:
You can't code in Java for iPhone. The iPhone only supports C/C++/Objective-C - Cocoa.
However, under the current license you can use translation tools that generate such code.
There are several solutions that do exactly that:
Codename One
- focuses on building applications using Java with visual tools and simulators. Open source with a SaaS backend that removes the need for a Mac.
XMLVM
- a translator to convert Java bytecode to C/Objective-C. Open source, but requires writing iOS specific code at the moment.
There are also several proprietary solutions but I have no experience with them. E.g. Software AG has a tool called web objects.


Question:
I have a rails application that I am running with Vista,IIS7 and SQL 2005. For some reason the CSS is not being rendered. The CSS works fine when I use Webrick.

Any ideas how to get CSS working correctly with IIS7. I have uninstalled and reinstalled windows components "Common Http Features" with no luck.

Answer:
Can you use Firebug or something to check that IIS7 is sending the correct MIME type with your stylesheets? Some browsers will ignore CSS unless the server explicitly sends
```
```
Content-Type: text/css
```
```
in the HTTP response headers, and with dynamic content or non-standard file extensions you may find that IIS7 isn't configured to do this "out of the box"


Question:
I'm looking for an abstract representation of a grid in Java (grid as in that thing with columns and rows of data).  Do such things exist?  I want to be able to sort, filter, keep track of rows, set column properties etc.  I'll then be realising the grid on the web.

To be clear: I've already decided on the ultimate view technology (client side).  The thing I'm looking for will hold all the records and offer them up as the view demands.

Answer:
JTable
is what you are looking for.


Question:
How do the timeouts work in WCF? I know for example that you can configure sendTimeout and receiveTimeout for a clients binding. But how do they work?

MSDN describes sendTimeout as:

A TimeSpan value that specifies the interval of time provided for a
  send operation to complete. This value should be greater than or equal
  to Zero. The default is 00:01:00.

What are send operations/receive operations?

Answer:
Client side:
SendTimeout is used to initialize the OperationTimeout, which governs the whole interaction for sending a message (including receiving a reply message in a request-reply case).  This timeout also applies when sending reply messages from a CallbackContract method.
OpenTimeout and CloseTimeout are used when opening and closing channels (when no explicit timeout value is passed).
ReceiveTimeout is not used.
Server side:
Send, Open, and Close Timeout same as on client (for Callbacks).
ReceiveTimeout is used by ServiceFramework layer to initialize the session-idle timeout.
The source is
Brian McNamara on MSDN forums
.


Question:
In cleaning up this answer I learnt a bit about TRIGGERs and stored procedures in MySQL, but was stunned that, while BEFORE INSERT and BEFORE UPDATE triggers could modify data, they seemingly couldn't cause the insert/update to fail (ie. validation). In this particular case I was able to get this to work by manipulating the data in such a way as to cause a primary key duplicate, which in this particular case made sense, but doesn't necessarily make sense in a general sense.

Is this sort of functionality possible in MySQL? In any other RDBMS (my experience is limited to MySQL sadly)? Perhaps a THROW EXCEPTION style syntax?

Answer:
From this
blog post
MySQL Triggers: How do you abort an INSERT, UPDATE or DELETE with a
  trigger? On EfNet’s #mysql someone
  asked:
How do I make a trigger abort the operation if my business rule fails?
In MySQL 5.0 and 5.1 you need to
  resort to some trickery to make a
  trigger fail and deliver a meaningful
  error message. The MySQL Stored
  Procedure FAQ says this about error
  handling:
SP 11. Do SPs have a “raise” statement to “raise application errors”? Sorry, not at present. The SQL standard SIGNAL and RESIGNAL statements are on the TODO.
Perhaps MySQL 5.2 will include SIGNAL
  statement which will make this hack
  stolen straight from MySQL Stored
  Procedure Programming obsolete. What
  is the hack? You’re going to force
  MySQL to attempt to use a column that
  does not exist. Ugly? Yes. Does it
  work? Sure.
```
```
CREATE TRIGGER mytabletriggerexample
BEFORE INSERT
FOR EACH ROW BEGIN
IF(NEW.important_value) < (fancy * dancy * calculation) THEN
    DECLARE dummy INT;

    SELECT Your meaningful error message goes here INTO dummy
        FROM mytable
      WHERE mytable.id=new.id
END IF; END;
```
```


Question:
Ok, there are a million regexes out there for validating an email address, but how about some basic email validation that can be integrated into a TSQL query for Sql Server 2005?

I don't want to use a CLR procedure or function.  Just straight TSQL.

Has anybody tackled this already?

Answer:
Very
basic would be:
```
```
SELECT
  EmailAddress,
  CASE WHEN EmailAddress LIKE '%_@_%_.__%'
            AND EmailAddress NOT LIKE '%[any obviously invalid characters]%'
  THEN 'Could be'
  ELSE 'Nope'
  END Validates
FROM
  Table
```
```
This matches everything with an @ in the middle, preceded by at least one character, followed by at least two, a dot and at least two for the TLD.
You can write more
```
LIKE
```
patterns that do more specific things, but you will never be able to match everything that could be an e-mail address while not letting slip through things that are not. Even with regular expressions you have a hard time doing it right. Additionally, even matching according to the very letters of the RFC matches address constructs that will not be accepted/used by most emailing systems.
Doing this on the database level is maybe the wrong approach anyway, so a basic sanity check as indicated above may be the best you can get performance-wise, and doing it in an application will provide you with far greater flexibility.


Question:
I'm trying to create a form that has an expandable widget. The problem is that when the widget is open, The form extends outside the limit in the content box, and it looks bad.

I tried using overflow:scroll but it creates 2 ugly scrollbars that do not disappear even if the content is smaller then the content box. I only need one vertical scrollbar.

Visual Studio also alerted that overflow-y is not available in CSS.

Answer:
Change your overflow to
```
auto
```
and define the height and/or width of the element.


Question:
I'm using Lawrence Philips Double-Metaphone algorithm with great success, but I have found the odd "unexpected result" for some combinations.

Does anyone else have additions or changes to the algorithm for other parts of it they wouldn't mind sharing, or just the combinations that they've found that do not work as expected.

eg. I had issues between:

Peashill and Bushley. (both match with PXL)

Rockliffe and Rockcliffe (RKLF and RKKL)

Answer:
All Soundex, Metaphone and variant schemes are occasionally going to give results that aren't identical to what you expect.  This is unavoidable - they can be regarded as more or less simple hash algorithms with special information preserving properties, and will sometimes produce collisions when you'd rather they didn't, and will sometimes produce differences when you'd rather they didn't.
One possible way of improving things is using 'synonym rings'.  This basically produces lists of words that should be regarded as synonyms, independent of the spelling.  I encountered them in the context of name matching.  For example, variants on Chaudri
included:
CHAUDARY
CHAUDERI
CHAUDERY
CHAUDHARY
CHAUDHERI
CHAUDHERY
CHAUDHRI
CHAUDHRY
CHAUDHURI
CHAUDHURY
CHAUDHY
CHAUDREY
CHAUDRI
CHAUDRY
CHAUDURI
CHAWDHARY
CHAWDHRY
CHAWDHURY
CHDRY
CHODARY
CHODHARI
CHODHOURY
CHODHRY
CHODREY
CHODRY
CHODURY
CHOUDARI
CHOUDARY
CHOUDERY
CHOUDHARI
CHOUDHARY
CHOUDHERY
CHOUDHOURY
CHOUDHRI
CHOUDHRY
CHOUDHURI
CHOUDHURY
CHOUDREY
CHOUDRI
CHOUDRY
CHOUDURY
CHOUWDHRY
CHOWDARI
CHOWDARY
CHOWDHARY
CHOWDHERY
CHOWDHRI
CHOWDHRY
CHOWDHURI
CHOWDHURRYY
CHOWDHURY
CHOWDORY
CHOWDRAY
CHOWDREY
CHOWDRI
CHOWDRURY
CHOWDRY
CHOWDURI
CHOWDURY
CHUDARY
CHUDHRY
CHUDORY
COWDHURY


Question: As a developer who spent many years working within Visual C++ 6, I'm used to working with the String Table resource to store unicode strings for localization. Is there a resource within Visual Studio 2005 that provides the same? Are there any third party libraries or tools?

Answer:
ResourceManager
is your friend - and yes, Visual Studio still has support for it all in the editor. You might also want to read "
Encoding and Localization
". If you're really keen, I can thoroughly recommend
Guy Smith-Ferrier's book on .NET i18n
.


Question:
What is the best way to save enums into a database?

I know Java provides name() and valueOf() methods to convert enum values into a String and back. But are there any other (flexible) options to store these values?

Is there a smart way to make enums into unique numbers (ordinal() is not safe to use)?

Update

Thanks for all awesome and fast answers! It was as I suspected.

However, a note to toolkit: That is one way. The problem is that I would have to add the same methods to each enum type that I create. That's a lot of duplicated code and, at the moment, Java does not support any solutions for this (a Java enum cannot extend other classes).

Answer:
I would argue that the only safe mechanism here is to use the String
```
name()
```
value. When writing to the DB, you
could
use a sproc to insert the value and when reading, use a View. In this manner, if the enums change, there is a level of indirection in the sproc/view to be able to present the data as the enum value without "imposing" this on the DB.


Question:
I have some simple .doc files I made in Word 2007 where I changed the text color and used highlights to compare some similar texts. What I'd like to do is change any instances of green text or gray highlighting to different respective colors for each.

I'm sure there is a simple way to do this with VBA but any other sort of answers are also welcome.

EDIT: While I do appreciate answers, one that allows me to keep the .doc files as .docs is preferred.

Answer:
You can always save the file as HTML, and replace colors there. Color is represented with
```
```
...
```
```
and highlight is
```
```
...
```
```
Should be easy to manipulate if your document is simple enough.
Edit that answers the edit in the question: After you are done, re-open the file and save the file back as .doc.


Question: I have a gridview containing some data from db, and after a check I want to see a small cross/tick image in each row, due to the result of the check.How can I change the image url dynamically?

Answer:
```
```
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:Image ID="check" runat="server" ImageUrl='<%#If(Eval("check") = 1,"images/checked.gif","images/unchceked.gif") %>' />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>
```
```


Question:
Anyone point my at a utility for syncing sql server logins after restoring a database to a different server?

I know I can do it with scripts, but I've been using a wonderful little utility - 'Db Maint Sync SQL Logins' (http://www.dbmaint.com/SyncSqlLogins.asp) to do it on sql server 2000 which unfortunately doesn't support 2005 and I'm loath to go back to actually thinking :-)

Answer:
```
sp_change_users_login
```
with the
```
Update_One
```
action can map a login in a database to a user on a new server.


Question:
I have heard mixed opinions over the amount of memory that a byte takes up in a java program.

I am aware you can store no more than +127 in a java byte, and the documentation says that a byte is only 8 bits but here I am told that it actually takes up the same amount of memory as an int, and therefore is just a Type that helps in code comprehension and not efficiency.

Can anyone clear this up, and would this be an implementation specific issue?

Answer:
Java is never implementation or platform specific (at least as far as
primitive type sizes
are concerned).  They primitive types are always guaranteed to stay the same no matter what platform you're on.  This differs from (and was considered an improvement on) C and C++, where some of the primitive types were platform specific.
Since it's faster for the underlying operating system to address four (or eight, in a 64-bit system) bytes at a time, the JVM may allocate more bytes to store a primitive byte, but you can still only store values from -128 to 127 in it.


Question: Can a flash front end talk to a .net backend?

Answer:
Yes.
We use
Adobe Flex
to talk to .Net XML web services.
Be careful with complex serialised .Net types (for instance DataSets) - ActionScript can't handle them.
Instead produce simple XML with primitive types.
See also:
Flex and ADO.NET Data Services...anyone done it?
```
```
<mx:WebService id="myDataService" showBusyCursor="true">
    <mx:operation name="WebMethodName" resultFormat="object" result="functionFiredOnComplete();"></mx:operation>
</mx:WebService>

public function load():void
{
    myDataService.loadWSDL( "web method's wsdl" );
    myDataService.WebMethodName.send( params );
}

public function functionFiredOnComplete():void
{
    // get data
    var myData:Object = myDataService.WebMethodName.lastResult;
    ...
```
```


Question:
What are the dangerous characters that should be replaced in user input when the users' input will be inserted in a MySQL query? I know about quotes, double quotes, \r and \n. Are there others?
(I don't have the option of using a smart connector that accepts parameters so I have to build the query myself and this will be implemented in multiple programming languages, including some obscure ones so solutions such as mysql_real_escape_string in PHP are not valid)

Answer:
What languages do you need to support? It is much better to use a language's built-in sanitization than to write your own.
Edit: Looking at
```
mysql_real_escape_string
```
on php.net:
```
mysql_real_escape_string()
```
calls MySQL's library function
```
mysql_real_escape_string
```
, which prepends backslashes to the following characters:
```
\x00
```
,
```
\n
```
,
```
\r
```
,
```
\
```
,
```
'
```
,
```
"
```
and
```
\x1a
```
.


Question:
Using the following code I get a nice formatted string:

Request.QueryString.ToString

Gives me something like: &hello=world&microsoft=sucks

But when I use this code to clone the collection to another object (of the same type) I get the Type() back from the ToString() method instead.

System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
    variables.Remove("sid");
Response.Write(variables.ToString());

Is there a tidier way to output it rather than looking and building the string manually?

Answer:
Why do you want to copy the QueryString collection into a new NameValueCollection?
```
```
if (!string.IsNullOrEmpty(Request.QueryString["sid"]))
        Request.QueryString.Remove("sid");
```
```
Yes indeed, i am wrong, it is read only. So the essence is to use the Remove Method on your NameValuecollection:
```
```
System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
    variables.Remove("sid");
```
```


Question: Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?

Answer:
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as
```
<input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />
```
. This will then be available in the servlet as a request parameter.
Put it in the session (see
```
request.getSession()
```
- in a JSP this is available as simply
```
session
```
)
I recommend using the Session as it's easier to manage.


Question: How would I reset the primary key counter on a sql table and update each row with a new primary key?

Answer:
I would add another column to the table first, populate that with the new PK.
Then I'd use update statements to update the new fk fields in all related tables.
Then you can drop the old PK and old fk fields.
EDIT:
Yes, as Ian says you will have to drop and then recreate all foreign key constraints.


Question:
I am currently in the process of searching for a rules engine that works in .NET.  Our logic is pretty simple, +, -, *, /, and, or, basic order of operations stuff.  However we are going to need to store this information in the database and then generate the rules file when a new version is pulled from the database.  So the common UI editors are going to be useless to us, unless one of them has a web version UI editor.

So my question is, given what I have said, which is going to be the best rules engine for us in terms of programmatic configuration and integration with ASP.NET.

Answer:
My experience with WWF has been pretty bad.  Its great for developing a workflow that you know is going to exist (such as "this document goes to a person's manager, then to HR, if its invalid it goes back to the submitter") but a real pain if you want dynamic configuration.  As you can tell we tried to use it for a fully configurable system, something that BizTalk does really well, and it looks like MS isn't keen on letting developers replace BizTalk so cheaply.
We also looked at using the
Acumen rules engine and tools
which looked like a great fit for what we needed though we never got the time to remove WWF and replace it.
I would strongly recommend that if your rules are going to be relatively simple that you either use a rules engine you have the source code to or write it yourself.
Justin Etheredge
has a
two
part
article about performing domain validation through custom rules using the pattern identified in
Domain-Driven Designs
(Evans).
I've implemented a similar system in my current project following the same guidelines and I serialize/deserialize rules from the database.  I will have to take a look at
Drools.NET
.


Question:
On our Scrum board, tasks start at 'To Do', go to 'In Progress', and when you're done with a task, they move to 'To Verify' before ending up in 'Done'. The 'To Verify' column is when you're done with a task and someone else can have a look at it, test it, and comment on it.

This has proven helpful for errors, better code, etc.

To people who have a similar practice: after the developer has addressed the comments/errors, do you verify it again, or do you assume the issues have been addressed and move the task to 'Done'?

I hope this is clear, and would like to hear your thoughts.

Answer: In my expirence the fixing of bugs have a 50 - 75% chance of introducing new bugs, especially if the code if not covered by test cases. I would certainly verify it again.


Question: How do you find out the length/size of the data in an ntext column in SQL? - It's longer than 8000 bytes so I can't cast it to a varchar. Thanks.

Answer:
Use
DataLength()
```
```
SELECT * FROM YourTable WHERE DataLength(NTextFieldName) > 0
```
```


Question: We use Grid Control 10.2.0.4, with a catalog repository database also at 10.2.0.4. It seems that after a week or two of being up, the response time of the web interface gets very poor (20+ seconds to navigate to a new page, when normally 2-3 seconds is seen). The only thing we've found to overcome it is a restart of the catalog database and the GC/OMS. No errors reported in the alert log, just unbearable slowness. Are there any Oracle DBA's using GC out there who have seen this (and hopefully found a solution)?

Answer:
Use
DataLength()
```
```
SELECT * FROM YourTable WHERE DataLength(NTextFieldName) > 0
```
```


Question: Related to this question, how to save many different csv files into one excel workbook with one sheet per csv ? I would like to know how to do this programmatically in Java.

Answer:
You'll need some form of library for accessing Excel from Java. A Google search turned this one up:
http://j-integra.intrinsyc.com/support/com/doc/excel_example.html
An alternative is to use the XML Excel format that came into being with Office 2003. You'll end up with a XML file, but you can open it in Excel and see the different sheets.
http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-officeml.html


Question:
We are moving from regular 2.0 webforms with no testing to TDD MVC

I'm looking to find out all the requirements for making the jump from 2.0 to 3.5 MVC.

Does SQL Server 2000 work with .net 3.5?

Does the MVC Framework come with .net 3.5?

How does AJAX work with all this stuff?

Is visual studios team suite worth the time/money?

Answer:
ASP.NET MVC is an extension of ASP.NET 3.5, it is still in beta and voices says that it will be available before the end of the year.
For your other questions:
- .NET 3.5 works well on SQL Server 2000
- The MVC framework is not part of .NET 3.5
- For using AJAX with ASP.NET MVC it's better if you take a look at JQuery (or other frameworks). The support for ASP.NET Ajax is not fully available.
IMHO the real advantanges of ASP.NET MVC are:
Testability
Testability :-)
The ability to generate the HTML that you really want! No viewstate! No other noise! :-)
BTW the jump to TDD with MVC is not simple...it needs time.
HTH


Question:
I am trying to manipulate a string using Jython, I have included below an example string:

This would be a title for a website :: SiteName

This would be a title for a website :: SiteName :: SiteName

How to remove all instances of ":: Sitename" or ":: SiteName :: SiteName"?

Answer:
No different from regular Python:
```
```
>>> str="This would be a title for a website :: SiteName"
>>> str.replace(":: SiteName","")
'This would be a title for a website '
>>> str="This would be a title for a website :: SiteName :: SiteName"
>>> str.replace(":: SiteName","")
'This would be a title for a website '
```
```


Question: What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?

Answer:
From .NET 4.5 on, there is the
```
Stream.CopyToAsync
```
method
```
```
input.CopyToAsync(output);
```
```
This will return a
```
Task
```
that can be continued on when completed, like so:
```
```
await input.CopyToAsync(output)

// Code from here on will be run in a continuation.
```
```
Note that depending on where the call to
```
CopyToAsync
```
is made, the code that follows may or may not continue on the same thread that called it.
The
```
SynchronizationContext
```
that was captured when calling
```
await
```
will determine what thread the continuation will be executed on.
Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).
From .NET 4.0 on, there's is the
```
Stream.CopyTo
```
method
```
```
input.CopyTo(output);
```
```
For .NET 3.5 and before
There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:
```
```
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}
```
```
Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not
```
input.Length
```
? Because that Length may not be available! From the
docs
:
If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.


Question:
I've been experimenting with fulltext search lately and am curious about the meaning of the Score value. For example I have the following query:

SELECT table. * ,
MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
) AS Score
FROM table
WHERE MATCH (
col1, col2, col3
)
AGAINST (
'+(Term1) +(Term1)'
)

In the results for Score I've seen results, for one query, between 0.4667041301727 to 11.166275978088. I get that it's MySQLs idea of relevance (the higher the more weight).

What I don't get is how MySQL comes up with that score. Why is the number not returned as a decimal or something besides ?

How come if I run a query "IN BOOLEAN MODE" does the score always return a 1 or a 0 ? Wouldn't all the results be a 1?

Just hoping for some enlightenment. Thanks.

Answer:
Generally relevance is based on how many matches each row has to the words given to the search.  The exact value will depend on many things, but it really only matters for comparing to other relevance values in the same query.
If you really want the math behind it, you can find it at the
internals manual
.


Question: I have a table that was imported as all UPPER CASE and I would like to turn it into Proper Case. What script have any of you used to complete this?

Answer:
Here's a UDF that will do the trick...
```
```
create function ProperCase(@Text as varchar(8000))
returns varchar(8000)
as
begin
  declare @Reset bit;
  declare @Ret varchar(8000);
  declare @i int;
  declare @c char(1);

  if @Text is null
    return null;

  select @Reset = 1, @i = 1, @Ret = '';

  while (@i <= len(@Text))
    select @c = substring(@Text, @i, 1),
      @Ret = @Ret + case when @Reset = 1 then UPPER(@c) else LOWER(@c) end,
      @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end,
      @i = @i + 1
  return @Ret
end
```
```
You will still have to use it to update your data though.


Question:
I am trying to aid another programmer with a page called Default.aspx with a code-behind section, and unfortunately I am at a bit of a loss.

 Partial Class _Default
 Inherits OverheadClass
 'A bunch of global variables here'

 Private Sub page_load(ByVal sender As Object, ByVal e As System.Eventarts) Handles Me.Load
 'Function goes here'

And in the OverheadClass we have

 Public Sub Sub_OverheadClass_Load(ByVal sender As Object, ByVal e as System.EventArgs) Handles MyClass.Load

The desired effect is when the OverheadClass is inherited, we want its load to run before the load event on the page runs.  There is probably a very simple answer to this that I am missing.

Edit: I forgot to note that we write in VB, and not C# as many of you are used to for ASP.

Answer:
You should be able to override the OnLoad and call the base class's OnLoad first, then your class, for example:
C# Version
```
```
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    // Do some stuff here
}
```
```
VB Version
```
```
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)

    MyBase.OnLoad(e)

    ' Do some stuff here

End Sub
```
```


Question: I know that you can run almost all Java in Dalvik's VM that you can in Java's VM but the limitations are not very clear.  Has anyone run into any major stumbling blocks?  Any major libraries having trouble?  Any languages that compile to Java byte code (Scala, Jython etc...) not work as expected?

Answer:
There is a number of things that Dalvik will not handle or will not handle quite the same way as standard Java bytecode, though most of them are quite advanced.
The
most severe example is runtime bytecode generation
and custom class loading. Let's say you would like to create some bytecode and then use classloader to load it for you, if that trick works on your normal machine, it is guaranteed to not work on Dalvik, unless you change your bytecode generation.
That prevents you from using certain dependency injection frameworks, most known example being Google Guice (though I am sure some people work on that). On the other hand AspectJ should work as it uses bytecode instrumentation as a compilation step (though I don't know if anyone tried).
As to other jvm languages -- anything that in the end compiles to standard bytecode and does not use bytecode instrumentation at runtime can be converted to Dalvik and should work. I know people did run Jython on Android and it worked ok.
Other thing to be aware of is that there is
no just in time compilation
. This is not strictly Dalviks problem (you can always compile any bytecode on the fly if you wish) but that Android does not support that and is unlikely to do so. In the effect while microbenchmarking for standard Java was useless -- components had different runtime characterstics in tests than as parts of larger systems -- microbenchmarks for Android phones totally make sense.


Question:
I have a page that is supposed to launch the Print Preview page onload.

I found this:

var OLECMDID = 7;
/* OLECMDID values:
* 6 - print
* 7 - print preview
* 1 - open window
* 4 - Save As
*/
var PROMPT = 1; // 2 DONTPROMPTUSER
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(OLECMDID, PROMPT);
WebBrowser1.outerHTML = "";

But...

it does not work in FireFox.

it's kind of ugly.

Is there a better way for IE or a way that works for FireFox?

Answer:
You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.
That's why your example uses Active X, which bypasses the JavaScript security issues.
So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.
Read
Alist Apart: Going to Print
for a good article on the subject of print stylesheets.


Question:
near the top of the code i see things like,

btn_dropdown._visible = false;
mcMenuBkg._visible = false;

but I can't find these assets anywhere in the library or in any code, how does this make any sense?

The movie clips in the library that look the same have different names and I can delete them entirely and they still show up when I compile and run, or I can add trace statements into their code and they never get called.

where on earth are these assets defined?

Answer:
You can create movie clips with code dynamically.
This means that you may not have them in your assets if you are unable to find them.
You can create any type of symbol using a constructor out of thin air with actionscript alone.
I would search the code for one of these
```
```
var mybutton:SimpleButton=new SimpleButton();
```
```


Question: Should the "visibility" for the __destruct() function be public or something else? I'm trying to write a standards doc for my group and this question came up.

Answer:
I think it would need to be public in the case where a subclass needs to explicitly call the
__destruct
method of the parent class.
Something like this would throw an error:
```
```
<?php
class MyParent
{
    private function __destruct()
    {
        echo 'Parent::__destruct';
    }
}

class MyChild extends MyParent
{
    function __destruct()
    {
        echo 'Child::__destruct';
        parent::__destruct();
    }
}

$myChild = new MyChild();
?>
```
```


Question:
Exception is:
'Country' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

UserService.DsUserAttributes dsCountry = us_service.GetUserAttributeDropDown(systemId, "Country");
Country.DataSource = dsCountry.tblDropDownValues;
Country.DataTextField = "AttrValue";
Country.DataValueField = "Id";
Country.DataBind();

The values held within dsCountry.tblDropDownValues are:

Id                                      AttrValue       AttrName
aefa28e0-a118-11dd-ad8b-080c210c9a66    PLEASE SELECT   Country
213a743e-ea0b-419c-bd44-03b1c35241b3    USA         Country
eefa1387-8dc0-11d8-975f-13da67a41a5d    CANADA          Country

Answer:
Try binding the data on postback.  It sounds like when the event handler is accessing the DropDownList, it hasn't been repopulated with the values you are initially binding to the DropDownList.
Also, remember to bind early enough so that it is bound before the event handler starts its processing.  OnInit or OnLoad should be good enough.
Otherwise, might need some more details:
When is the exception occurring? During the rendering, or on the postback in the event handler?
Do you have a stack trace on the error that might point to the point in the code where the selected value is accessed?
When are you binding the data?


Question: Has Java 1.6 SDK been released for mac? I can't seem to find it...

Answer:
Yes, but only for 64-bit Intel-based Macs, i.e. Macs using Core 2 (duo or solo) or Xeon chips. The original Core chip is not supported, nor is any PPC chip. Also, Java 6 is currently Leopard-only. The update should appear in Software Update, if you have a compatible Mac and recent-enough OS version.
Here are the release notes for the
first update
. And here are the
second update
's release notes.


Question:
Using Vim, I'm trying to pipe text selected in visual mode to a UNIX command and have the output appended to the end of the current file. For example, say we have a SQL command such as:

SELECT * FROM mytable;

I want to do something like the following:

<ESC>
V                 " select text
:'<,'>!mysql -uuser -ppass mydb

But instead of having the output overwrite the currently selected text, I would like to have the output appended to the end of the file. You probably see where this is going. I'm working on using Vim as a simple SQL editor. That way, I don't have to leave Vim to edit, tweak, test SQL code.

Answer:
How about copying the selected text to the end of the file, select the copy and run the command? If you do not want to repeat the same commands over and over again, you can record the sequence by using
```
q
```
or add a new command. I have tried the latter as follows:
```
```
:com -range C <line1>,<line2>yank | $ | put | .,$ !rev
```
```
With it you can select some lines and then type
```
:C
```
. This will first yank the selection, then go to the end of the file, paste the yanked text and run the command (
```
rev
```
in this case) over the new text.


Question:
I am trying to get center of parent form, not center of screen behavior.
Passing in the parent form seems to only control the ownership of the window.
These classes are sealed, so I do not see how I can do any WinProc tricks.
Rewriting the classes is not an appealing option.
Any other ideas?

Answer:
I do not know much about the dialogs or message boxes but, you can position a new Form as you are looking for with its StartPosition property.
```
```
System.Windows.Forms.Form f = new Form();
f.StartPosition = FormStartPosition.CenterParent;
```
```


Question:
I'm making another app's window topmost to ensure that a click in my app brings the other's dialog into views. The problem I'm having is that I don't get focus back to my app after the call. If the other app has more windows one of them ends up with focus, and otherwise no window (looking at the taskbar only) gets focus. Where should I start investigating the issue?

My code for making the other app topmost is:

Process p = Process.GetProcessById(trackedProcessID);
IntPtr h = p.MainWindowHandle;
uint TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS;
SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

with constants as

public static readonly uint SWP_NOMOVE = 0x0002;
public static readonly uint SWP_NOSIZE = 0x0001;
public static readonly uint SWP_ASYNCWINDOWPOS = 0x4000;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);

Answer:
Related:
Unexpected behaviour of Process.MainWindowHandle
Basically MainWindowHandle gives you the current top-most window of the process despite what the documentation says.
That explains why the main window of your other process doesn't necessarily get focus.
Your other problem is because you are not returning focus to your app after giving it away.
Actually, the correct term for what you are doing is establishing
z-order
.
Instead of trying to control z-order - which cannot be guaranteed - you might be better off sending messages to the other process.


Question: When I am creating a new database table, what factors should I take into account for selecting the primary key's data type?

Answer:
If using a numeric key, make sure the datatype is giong to be large enough to hold the number of rows you might expect the table to grow to.
If using a guid, does the extra space needed to store the guid need to be considered?  Will coding against guid PKs be a pain for developers or users of the application.
If using composite keys, are you sure that the combined columns will always be unique?


Question:
The print functionality of Excel (using VBA) is extremely slow. I'm hoping someone has a way of speeding the printing up (without using the Excel 4 Macro trick).  Here's how I do it now:

Application.ScreenUpdating = False

With ActiveSheet.PageSetup

  -various setup statements which I've already minimized-

End With
ActiveSheet.PrintOut

Application.ScreenUpdating = True

Answer:
Yes, the PageSetup properties are very slow when you set them.
You have already set
```
Application.ScreenUpdating = False
```
, which is good, but an equally (or more) important step in this case is to set
```
Application.Calculation = xlCalculationManual
```
. (It is best if you save these settings and then restore them to the original at the end.)
Additionally, the property get for each PageSetup property is very fast, while it is only the property set that is so slow. Therefore, you should test the new property setting to make sure it isn't already the same as the existing property value in order to prevent an unnecessary (and expensive) call.
With all this in mind, you should be able to use code that looks something like the following:
```
```
Dim origScreenUpdating As Boolean
origScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = False

Dim origCalcMode As xlCalculation
origCalcMode =  Application.Calculation
Application.Calculation = xlCalculationManual

With ActiveSheet.PageSetup
    If .PrintHeadings <> False Then .PrintHeadings = False
    If .PrintGridlines <> False Then .PrintGridlines = False
    If .PrintComments <> xlPrintNoComments Then .PrintComments = xlPrintNoComments
    ' Etc...
End With

Application.ScreenUpdating = origScreenUpdating
Application.Calculation = origCalcMode
```
```
Edit: A couple of updates:
For Excel 2010 and above you can make use of the 'Application.PrintCommunication' property, while for Excel 2007 and below, you can make use of 'ExecuteExcel4Macro'. For more details, see
Migrating Excel 4 Macros to VBA
.
For Excel 2007 and below, another interesting trick is to temporarily assign the printer driver to the 'Microsoft XPS Document Writer' and then set it back. Printing speed can improve by 3x. See:
Slow Excel PageSetup Methods
.
Hope this helps...


Question:
I am new to jmock and trying to mock an HttpSession. I am getting:

java.lang.AssertionError: unexpected invocation: httpServletRequest.getSession()
no expectations specified: did you...
 - forget to start an expectation with a cardinality clause?
 - call a mocked method to specify the parameter of an expectation?

the test method:

@Test

public void testDoAuthorization(){

    final HttpServletRequest request = context.mock(HttpServletRequest.class);
    final HttpSession session = request.getSession();

    context.checking(new Expectations(){{
       one(request).getSession(true); will(returnValue(session));
   }});

    assertTrue(dwnLoadCel.doAuthorization(session));
}

I have done a bit of searching and it isn't clear to me still how this is done. Feels like I am missing some small piece. Anyone with experience in this can just point me in the right direction.
thanks

Answer:
I think you need to tell the JMock context how many times you expect the method to be called before you actually go ahead and call it.
```
```
final HttpServletRequest request = context.mock(HttpServletRequest.class);

context.checking(new Expectations(){{
  one(request).getSession(true); will(returnValue(session));
}});

final HttpSession session = request.getSession();
```
```
I'm not super familiar with JMock but do you actually care in your
```
dwnLoadCel
```
unit test how many times certain methods in the mocked object are called? Or are you just trying to test your class that depends on a HttpSession without an actual Session? If it's the latter than I think that JMock is overkill for you.
You might want to look into either creating a class that implements the
```
HttpSession
```
interface yourself for the purposes of unit testing only (a stub), and running your tests off of that, or you should take a look at
```
dwnLoadCel
```
and determine if it
really
needs to have a reference to the HttpSession, or if it just needs some properties within the HttpSession. Refactor
```
dwnLoadCel
```
to only depend on what it actually needs (a
```
Map
```
or a certain parameter value within the Session object) - this will make your unit test easier (the dependency on the servlet container goes bye-bye).
I think that you have some level of dependency injection in your class being tested already, but you might be dependent on too broad of an object.
The Google Test Blog
has had
a lot
of excellent
articles
on DI lately that you might find useful (I sure have).


Question: I am writing a DB upgrade script that will check to see if an index has the right two columns defined.  If it doesn't, or if it only has one of them, then I will DROP it (is there a way to ALTER an index?) and then recreate it with both.

Answer:
I don't have a database immediately on-hand to test this, but you should be able to see if a column exists in an index by using the following IF EXISTS statement.
I'm not sure whether you can alter an index on the fly.
```
```
IF EXISTS
(
   SELECT MyIndex.Name AS IndexName,
          Columns.name AS ColumnName
   FROM sys.indexes MyIndex
   INNER JOIN sys.index_columns IndexColumns
      ON  MyIndex.index_id = IndexColumns.index_id
      AND MyIndex.object_id = IndexColumns.object_id
   INNER JOIN sys.columns Columns
      ON  Columns.column_id = IndexColumns.column_id
      AND IndexColumns.object_id = Columns.object_id
   WHERE Columns.name = 'ColumnName'
   AND MyIndex.Name='IX_MyIndexName'
)
```
```


Question: I'm trying to use jQuery to get data from an ASP.NET web service (SharePoint Server 2007 lists.asmx), but any call to a web service will really help as a first step in that direction.

Answer:
Here is an example to call your webservice using jQuery.get:
```
```
$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  });
```
```
In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.


Question: I'm looking for the equivalent of right clicking on the drive in windows and seeing the disk space used and remaining info.

Answer:
Look for the commands
```
du
```
(disk usage) and
```
df
```
(disk free)


Question:
In my eternal saga to insert 1.4 million rows of data from a SQL script, I've written a basic WinForms app that takes each line of the script and executes it individually.

However, because the original script contained

SET IDENTITY_INSERT [Table] OFF

and SET is a session-wide command, this setting is getting lost on every SQL call, meaning that each line is failing.  Is there a way to set IDENTITY_INSERT off for the whole table, database-wide just so I can make these individual calls without them failing?  Or perhaps I can tell it to ignore the identity specification by appending a command to each line?

Answer:
BULK INSERT
won't work for you?  Or the SQL Server Import/Export Wizard (
here
or
here
)?  I know import/export can turn off identity insert for the whole import.  I'm reasonably certain you can do it just prior to BULK INSERT


Question:
I want yo use the EXSLT - DYN:EVALUATE in a style sheet. I have added the names pace but I don't know where the .xsl file I need to import is. I don't believe I have XALAN installed to point the import to. How would I install this? Once installed and I point it to the .xsl will it pick up the function and apply it? I am running Windows. The XSLT file is included at the top of the XML document.

Thanks

Pete

Answer:
Xalan has the EXSL dyn:evaluate function built-in, you don't need to import anything in order to use it. You just need to declare the namespace. I'll give a small example:
input.xml
:
```
```
<root>
<foo>I am foo</foo>
<bar>I am bar</bar>
</root>
```
```
dyn_evaluate.xsl
:
```
```
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:dyn="http://exslt.org/dynamic"
    extension-element-prefixes="dyn">

  <xsl:param name="path"/>

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:value-of select="dyn:evaluate($path)"/>
  </xsl:template>

</xsl:stylesheet>
```
```
Running
```
```
xalan.exe -p path '/root/foo' input.xml dyn_evaluate.xsl
```
```
gives
```
```
I am foo
```
```
Running
xalan.exe -p path '/root/bar' input.xml dyn_evaluate.xsl
gives
```
```
I am bar
```
```
Hope this helps.


Question:
Looking to hear from people who are using WCF in an enterprise environment.

What were the major hurdles with the roll out?
Performance issues?
Any and all tips appreciated!

Please provide some general statistics and server configs if you can!

Answer:
WCF can be
configuration hell
. Be sure to familiarize yourself with its
diagnostics and svcTraceViewer
, lest you get madenning cryptic, useless exceptions. And watch out for the generated client's
broken implementation of the disposable pattern
.


Question:
What would be the best way to fill an array from user input?

Would a solution be showing a prompt message and then get the values from from the user?

Answer:
```
```
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
    answer[i]= Console.ReadLine();
}
```
```


Question:
I've gone through most of the example code and I still need some help.  I want to make an uber-simple app:  show one screen at startup with a label and a button.  click the button and we slide over to another screen (I suppose these are called views) which has another label and the "back" button in the top menu bar.  I just want to click back and forth between the two screens.

How do I do this?

Answer:
You'll need to use a UINavigationController to accomplish the "slide"/"back button" behavior you're talking about. It is as simple as you might think, as long as the app is setup correctly. Essentially, UINavigationControllers allow you to push and pop instances of UIViewController or subclasses thereof, and take care of the animation and view history tracking for you.
The best way to get started, by far, is just open XCode, choose "New Project", and start with the "Navigation-Based Application." Dig around that project for a while and I think you'll start to see clearly what needs to be done.


Question:
I have a table with multiple rows. Each row is a form. I want to use JQuery to submit all the forms that have the check box checked. The form is posting to an IFrame so there is not much need for AJAX.

So far I have:

       $("form").submit();

which submits the form. but all forms. There is arbritary number of rows, could be 80-100.

Answer:
This is kinda a guess since I'm not sure of your layout, but here goes....
```
```
$("td > input:checked > form").submit();
```
```


Question: If not, is smoke testing still used?

Answer:
It's sort of a Venn Diagram.  Some Automated tests are Smoke tests, and some smoke tests are Automated (inasfar as they are ran by a computer program).  A Smoke test is a take off (if I recall correctly) on the term "Where there's smoke, there's usually fire."  It's a set of preliminary tests that the program must pass to be considered for 'real' (viz. fire) testing.
A smoke test can be manual insomuch as a tester has a list of steps he follows, but these aren't automated with a computer program.
Smoke testing is still used -- in places I've worked, it's usually automated.


Question:
Where are variables in C++ stored?

Inside the RAM or the processor's cache?

Answer:
Variables can be held in a number of different places, sometimes in more than one place.  Most variables are placed in RAM when a program is loaded; sometimes variables which are declared
```
const
```
are instead placed in ROM.  Whenever a variable is accessed, if it is not in the processor's cache, a cache miss will result, and the processor will stall while the variable is copied from RAM/ROM into the cache.
If you have any halfway decent optimizing compiler, local variables will often instead be stored in a processor's register file.  Variables will move back and forth between RAM, the cache, and the register file as they are read and written, but they will generally always have a copy in RAM/ROM, unless the compiler decides that's not necessary.


Question:
I am trying to sort a list using delegates but I am getting a signature match error. The compiler says I cannot convert from an 'anonymous method'

List<MyType> myList = GetMyList();
myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID < t2.ID); } );

What am I missing?

Here are some references I found and they do it the same way.

Developer Fusion Reference

Microsoft Reference

Answer:
The Sort doesn't take a binary predicate, it takes a
```
Comparison<T>
```
delegate which returns an
```
int
```
not a
```
bool
```
.
The return values are
```
0
```
for when the items are equal,
```
<0
```
for when the first item is less than the second, and
```
>0
```
for when the first item is greater than the second.


Question:
Assume that I set up an automatic nightly build.  What artifacts of the build should I save?

For example:

Input source code

output binaries

Also, how long should I save them, and where?

Do your answers change if I do Continuous Integration?

Answer: We save the binaries, stripped and unstripped (so we have the exactly same binary, once with and once without debug symbols). Further we build everything twice, once with debug output enabled and once without (again, stripped and unstripped, so every build result in 4 binaries). The build is stored to a directory according to SVN revision number. That way we can always retain the source from the SVN repository by simply checking out this very revision (that way the source is archived as well).


Question:
I am actually developing and application that has around 15 modules, all of them using the same database.

I am using Apache + Mongrel, I cannot use Passenger because I am working on Windows (please forgive me for this deadly sin!)

Which of the following is a better approach?

Deploy multiple small rails
applications using a virtual server
and a pair of mongrels for each
application.

Deploy only a big rails application

I am worried about the number of running mongrels and the memory/cpu load.

Answer:
It depends on hwo many simultaneous clients you expect to have.  One mongrel, one client at a time (until Rails 2.2) since Rails isn't currently threaded.
Two is enough mongrels if you don't expect more than a few simultaneous users.  You can raise that number by using page caching to bypass mongrel for pages that don't have user-specific dynamic content.
The only way to be truly sure is to test the system.
In my experience you'll need at least 4 mongrels for a moderately active site of just a few users at a time.


Question:
PHP has a very nice function, isset($variableName). It checks if $variableName is already defined in the program or not.

Can we build similar feature for C/C++ (some kind of symbol table lookup)?

Answer: Not really.  You can't dynamically create variables (though you can dynamically create storage with malloc() et al, or new et al. in C++) in C.  I suppose dynamically loaded libraries blur the picture, but even there, the way you establish whether the variable exists is by looking up its name.  If the name is not there, then, short of running a compiler to create a dynamically loaded module and then loading it, you are probably stuck.  The concept really doesn't apply to C or C++.