Question:
Just wondering if there is anything built-in to Javascript that can take a Form and return the query parameters, eg: "var1=value&var2=value2&arr[]=foo&arr[]=bar..."

I've been wondering this for years.

Answer:
I'm not entirely certain myself, I recall seeing jQuery did it to an extent, but it doesn't handle hierarchical records at all, let alone in a php friendly way.
One thing I do know for certain, is when building URLs and sticking the product into the dom, don't just use string-glue to do it, or you'll be opening yourself to a handy page breaker.
For instance, certain advertising software in-lines the version string from whatever runs your flash. This is fine when its adobes generic simple string, but however, that's very naive, and blows up in an embarrasing mess for people whom have installed Gnash, as gnash'es version string happens to contain a full blown GPL copyright licences, complete with URLs and <a href> tags. Using this in your string-glue advertiser generator, results in the page blowing open and having imbalanced HTML turning up in the dom.
The moral of the story:
```
```
var foo = document.createElement("elementnamehere");
   foo.attribute = allUserSpecifiedDataConsideredDangerousHere;
   somenode.appendChild(foo);
```
```
Not:
```
```
document.write("<elementnamehere attribute=\""
        + ilovebrokenwebsites
        + "\">"
        + stringdata
        + "</elementnamehere>");
```
```
Google need to learn this trick. I tried to report the problem, they appear not to care.


Question:
There are too many method for embedding flash in html, which way is the best?
Requirements are:

Cross-browser support

Support for alternative content (if flash is not supported by the browser)

Possibility to require a specific version of the flash player

I have been reading about SWFobject, has anyone used it/tested?

Answer:
In a project I work on we use SWFobject which works like a charm, it allows you to check for a specific version and also display alternative content if flash is not supported.
```
```
var fn = function() {
    if(swfobject.hasFlashPlayerVersion("9.0.115"))
    {
        var att = { data:"flash.swf", width:"y", height:"x" };
        var par = { menu: "false", flashvars: "" };
        signUp = swfobject.createSWF(att, par);
    }
}
swfobject.addDomLoadEvent(fn);
```
```


Question:
I need to launch a media file from a URL from within my c# .NET application. Is there any way to do this natively in .NET? I don't need an embedded player, I just need the default player to launch. I have tried

System.Diagnostics.Process.Start("File URL");

but it launches the default browser and downloads the file, instead of attempting to play it in WMP/VLC/whatever the default media player is. Any ideas?

Answer:
If you enter an URL it will be handled with the program registered to that URL format, in your case the default web browser.
What format are the media in? You can get associated program for an extension and then run that program with the url as parameter.
See:
Windows: List and Launch applications associated with an extension
So if your media is for example .MP3, then find the assoicated program for .MP3 (using the code in the link above) and pass the url as a parameter to that program.


Question:
Can we have a SQL query which will basically help in viewing table and index sizes in SQl Server.

How SQL server maintains memory usage for  tables/indexes?

Answer:
```
```
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"
```
```


Question:
I'm recoding an old site that contains a chart similar to this:

alt text http://dl.getdropbox.com/u/240752/rental-chart.gif

How would this chart be represented with pure HTML? I'm loathed to just include it as an image.

I'm thinking a table, just replaced with an image, or perhaps overlaid with absolutely positioned table rows, but I think that may be a bit fragile.

Any suggestions welcomed.

Answer:
Whats wrong with the image?
Most times when you see chart information on the Web its a generated .jpg or .png.
Have all those designers got something wrong?
Any attempt to draw the chart using tables and backgroud colours will not be intelligable to a sight impaired person, and, in all probability will not render correctly on a browser that cannot handle images.
Use the image and have an "alt" text with a real English description "A chart showing ACME product costs only $49 compared with competitors: Rental Company 4 at $51 .......


Question: How can I access the apache basic-auth username in a PHP script?

Answer:
Simply access this variable:
```
```
$_SERVER['PHP_AUTH_USER']
```
```


Question:
I have the following string:

<SEM>electric</SEM> cu <SEM>hello</SEM> rent <SEM>is<I>love</I>, <PARTITION />mind

I want to find the last "SEM" start tag before the "PARTITION" tag. not the SEM end tag but the start tag. The result should be:

<SEM>is <Im>love</Im>, <PARTITION />

I have tried this regular expression:

<SEM>[^<]*<PARTITION[ ]/>

but it only works if the final "SEM" and "PARTITION" tags do not have any other tag between them. Any ideas?

Answer:
Have you tried this:
```
```
<EM>.*<PARTITION\s*/>
```
```
Your regular expression was matching anything but "<" after the "EM" tag. Therefore it would stop matching when it hit the closing "EM" tag.


Question: How do I ping a website or IP address with Python?

Answer:
Depending on what you want to achive, you are probably easiest calling the system ping command..
Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!
```
```
import subprocess

host = "www.google.com"

ping = subprocess.Popen(
    ["ping", "-c", "4", host],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)

out, error = ping.communicate()
print out
```
```
You don't need to worry about shell-escape characters. For example..
```
```
host = "google.com; `echo test`
```
```
..will
not
execute the echo command.
Now, to actually get the ping results, you could parse the
```
out
```
variable. Example output:
```
```
round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
```
```
Example regex:
```
```
import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()

# ('248.139', '249.474', '250.530', '0.896')
```
```
Again, remember the output will vary depending on operating system (and even the version of
```
ping
```
). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)


Question:
I need to use JavaScript in a form for mobile web application.

I need some information about it, related to browser compatibility as well as way to use JavaScript in mobile web applications (syntax).

Answer:
It's a nightmare. It's like working with web-browsers in the 90's but with the manager expectations of tomorrow.
I strongly recommend you determine your target platforms in terms of regions, software, and actual hardware since the market is much more fragmented than the web and a large number of mobile devices have issues with CSS, JS and even XHTML ranging from painful to not-on-this-platform.
The good news is that android and iphone are pushing the field rapidly. The bad news is that makes a lot of the sources you'll google badly out-of-date.
Some references:
http://www.w3.org/TR/mobileOK-basic10-tests/#test_objects_or_script
http://mobiforge.com/developing/story/getting-started-with-mobile-ajax
http://mobiforge.com/
Especially that last one :)


Question:
I can't seem to retrieve an ID I'm sending in a html.ActionLink in my controller, here is what I'm trying to do

<li>
    <%= Html.ActionLink("Modify Villa", "Modify", "Villa", new { @id = "1" })%></li>

    public ActionResult Modify(string ID)
    {

        ViewData["Title"] =ID;
        return View();
    }

That's what a tutorial I followed recommended, but it's not working, it's also putting ?Length=5 at the end of the URL!

Here is the route I'm using, it's default

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

Answer:
Don't put the @ before the id
```
```
new { id = "1" }
```
```
The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route


Question:
I've got a dump of a .Net process that has hung due to a deadlock (the gui thread is no longer responding, and my logs show that some threads have stopped responding). I have taken a snapshot and am now looking through it in windbg, and all threads bar one are waiting for the last one. Looking at that one thread's stacktrace with !clrstack -p I can see that it is trying to aquire a write on a ReaderWriterLock

How do I tell which other thread holds that lock so I can start figuring out how the deadlock happened?

thanks

[edit] apparently there was a command !rwlocks in the .Net1.1 sos.dll to help with this, but it isn't there in the .Net2.0 version. The hunt continues

Answer:
I'm not absolutely sure but you might be able to use !SyncBlk to look at the sync block objects, if you invoke it without any arguments I think you should see the sync blocks that are owned by a thread.
If you have a sync block deadlock, the extension
SOSEX
might be what you need. This extension offers the command !dlk that shows which threads are waiting for which locks. This only works for sync blocks though, deadlocks on other sync objects will not be detected, if you are using lock() (Monitor.Enter) this should not be a problem for you.


Question:
I've been playing with ADO.NET Entity Framework lately, and I find that it suits my needs for a project I'm developing. I also find cool its non-invasive nature.

After generating a data model from an existing database you are faced with the task of integrating the generated model and your business logic. More specifically, I'm used to integration-test my classes that interact with the data store via mocks/stubs of the DAL interfaces. The problem is that you cannot do this using the ADO.NET Entity Framework because the entities it generates are simple classes with no interface.

The question is: how do I apply a TDD approach to the development of an application that uses ADO.NET Entity Framework? Is this even possible or should I migrate to another DAL-generation toolset?

Answer:
"The tight coupling of the persistence
  infrastructure to the entity classes
  largely eliminates the ability to
  efficiently use very tight feedback
  cycles on the business logic with
  automated testing. In its current
  state, EF entity classes cannot be
  effectively unit tested independently
  of the database.
The efficiency of automated unit
  testing of behavioral objects is
  largely a matter of how easy the
  mechanics of test data setup are and
  how quickly the tests can be executed.
  Using the actual database will make
  test data setup more laborious,
  introduce data to satisfy relational
  constraints that are not germane to
  the test, and make test execution an
  order of magnitude slower.
A team’s ability to do evolutionary
  design and incremental delivery is
  damaged by the Entity Framework’s
  inattention to fundamental software
  design principles like Separation of
  Concerns."
Blatantly stolen from here:
http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/


Question:
I need to know if I can create a file in a specific folder, but there are too many things to check such as permissions, duplicate files, etc.
I'm looking for something like File.CanCreate(@"C:\myfolder\myfile.aaa"), but haven't found such a method.
The only thing I thought is to try to create a dummy file and check for exceptions but this is an ungly solution that also affects performance.
Do you know a better solution?

Answer:
In reality, creating a dummy file isn't going to have a huge performance impact in most applications. Of course, if you have advanced permissions with create but not destroy it might get a bit hairy...
Guids are always handy for random names (to avoid conflicts) - something like:
```
```
string file = Path.Combine(dir, Guid.NewGuid().ToString() + ".tmp");
// perhaps check File.Exists(file), but it would be a long-shot...
bool canCreate;
try
{
    using (File.Create(file)) { }
    File.Delete(file);
    canCreate = true;
}
catch
{
    canCreate = false;
}
```
```


Question:
Aloha

I have a method with (pseudo) signature:

public static T Parse<T>(string datadictionary) where T : List<U>

This doesn't build. How can I restrict the  in the method to accept only generic List<> objects (which should of cource not contain T's but something else :)

I need to restrict the type of T because I need to call a method on it in this code. The type passed in is a custom collection (based on List).

public class MyCollection<T> : List<T> where T: MyClass, new()
{
    public void Foo();
}

public static T Parse<T>(string datadictionary) where T : MyCollection<U>
{
    T.Foo();
}

-Edoode

Answer:
Well, you can have two type parameters:
```
```
public static T Parse<T, U>(string datadictionary) where T : List<U>
```
```
That way you'll also actually know what U is (in a compile-time manner)...
EDIT: Alternatively (and better), just specify the element type and change the return type:
```
```
public static List<T> Parse<T>(string datadictionary)
```
```
e.g.
```
```
List<int> data = Parse<int>(whatever);
```
```
Note that you may wish to change from
```
List<T>
```
to
```
IList<T>
```
or even a broader interface.


Question:
If you have a route:

routes.MapRoute("search", "{controller}/{action}/{filter1}/{filter2}/{filter3}", _
  New With {.filter1 = "", .filter2 = "", .filter3 = ""})

then in a view satisfied by the route pattern with a url of /member/search/dev/phil/hoy, when you attempt to create another route url with only filter1 present i.e.

<%=Url.RouteUrl(New RouteValueDictionary(
  New With {.controller="member",.action="search", .filter1="dev"}))%>

the result is the current route /member/search/dev/phil/hoy, not the expected trimmed route /member/search/dev

I have managed to work round the issue by using RouteTable.Routes.GetVirtualPath method directly, but does anyone know why it works this way or is it perhaps a bug?

Answer:
Some people use nested
```
StackPanel
```
s to "solve" this problem, but IMHO that just introduces another problem (code bloat). I think the best way to solve this is to write your own panel that lays out children consecutively in columns. I did this on a previous project and it has a number of advantages:
More readable and terse XAML
Easier to maintain XAML
Faster performance
The usage looked something like this:
```
```
<local:FieldPanel>
    Field 1:
    <TextBox/>

    Field 2:
    <TextBox/>

    Field 3:
    <TextBox/>
</local:FieldPanel>
```
```


Question:
I autoformat a GridView in ASP.NET.

It looks nice but the headers all run together like this:

idfirstNamelastNameage

I set CellPadding="5" but it does nothing.

How can I set the cell padding of the headers and all cells?

A D D E N D U M :

Thanks Andrew, I fixed it with this. Works in Firefox and Explorer 7:

.gridview2 tr td
{
    padding: 5px;
    border: 1px solid #ddd;
}
.gridview2 tr th
{
    padding: 5px;
}

Answer:
You should set a cssclass and use css to control it. The only property of a table you cant fully control cross browser with css is cellspacing.
```
```
.myTableClass tr th {
    padding: 5px;
}
```
```


Question:
i've got a site with a lot of referenced .js-Files; those are rather small files, but I want to keep my methods separated by topic/functionality.

Is it better to keep all the methods in one .js-File or is it no problem to have many (~ 20 - 30) small files all including only some lines?

Answer:
By all means keep them separate for development, but you should consider bundling them together into one file for production.
There is a nice discussion at
sitepoint.com
For each of these files, an HTTP
  request is sent to the server, and
  then the browser awaits a response
  before requesting the next file.
  Limits (or limitations) of the browser
  generally prevent parallel downloads.
  This means that for each file, you
  wait for the request to reach the
  server, the server to process the
  request, and the reply (including the
  file content itself) to reach you. Put
  end to end, a few of these can make a
  big difference to page load times.


Question: I have a bunch of rows in Excel that I want to paste into a new table in MS SQL. Is there a simple way ?

Answer:
The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement.
Then copy these insert into a text file and then execute on the SQL.
The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.


Question:
What's better for DSL: TCL or Lisp?
What can you say about Java(C#)-TCL binding versus Lisp(Scheme)?
What DSL tool is applicable for .Net development? (excepting Microsoft DSL tools)

Answer:
It really depends on who will use the DSL.
If you are expecting non-IT domain experts then something simple and straightforward like TCL would be recommended. Explaining the joys of LISP to a non IT graduate would be a serious problem as would debugging a large LISP program written by someone who hasnt grokked LISP.
Equally expaining to someone that b = a + 1 is written B = INCR(A) isnt such a good idea either.
I would recommend Python, you can embed the domain specific code in one or two specialist classes. You have a language where non-IT users can code simple readable programs, and, where there are no limits on what an IT specialist can code.


Question:
I am developing an application and want to display a form that will be filled in if editing the form, but will not be if the form will be a new entry.  I believe the least verbose way of doing this is to have just one form and to suppress any errors for echoing my variables so that nothing will be printed if it is a new form (since the variables will not exist if it is a new form).  For example:

<?php
if ( ! $new_item) {
    $variable = 'Example';
}
?>
<form>
    <input type="text" name="inputbox" value="<?php echo @$variable; ?>" />
</form>

Is this a good practice, or is there a better way of doing it?  Should I make separate views for the new items and for the items to be edited?  What are the performance repercussions of doing this?

Answer:
I think the best way is to always set the variable
```
```
if ( ! $new_item) {
    $variable = 'Example';
} else {
    $variable = 'Default value';
    //or
    $variable = '';
}
```
```
Using the
```
@
```
error suppression is slow.
edit
Note that when you print the variable into the input value attribute, you should first call
```
htmlentities()
```
or
```
htmlspecialchars()
```
on it.
2nd edit
You say in your comment you are fetching the data as on object, in that case you could also do:
```
```
class example {
    public $somefield = 'default value';
}
```
```
Then if it is an existing record you are editing do something like this, which will cause the returned object to be an instance of 'example':
```
```
$record = mysql_fetch_object($result, 'example');
```
```
or if it is a new record instanciate it yourself:
```
```
$record = new example();
```
```
Then you always know
```
$record->somefield
```
will be set and you can do :
```
```
<form>
    <input type="text" name="somefield" value="<?php echo htmlspecialchars($record->somefield); ?>" />
</form>
```
```


Question: What are the other ways of achieving auto-increment in oracle other than use of triggers?

Answer:
You can create and use oracle sequences. The syntax and details are at
http://www.techonthenet.com/oracle/sequences.php
Also read the article
http://rnyb2.blogspot.com/2006/02/potential-pitfall-with-oracle-sequence.html
to understand the limitations with respect to AUTONUMBER in other RDBMS


Question: How can I validate a SOAP response against an XSD file that defines the response schema. the web service I'm calling has an XMLDocument as input and output, so can't use WSDL for response schema validation.

Answer:
I case you still need this (valid for SOAP UI version 2.5.1):
File, Preferences, Editor Setting, Validate Response.


Question:
Does anybody know why

  vector<int> test(10);
  int a=0;

  for_each(test.begin(),test.end(),(_1+=var(a),++var(a)));

  for_each(test.begin(),test.end(),(cout << _1 << " "));
  cout << "\n"

Gives :  "0 1 2 3 4 5 6 7 8 9"

but

  transform(test.begin(),test.end(),test.begin(), (_1+=var(a),++var(a)));
  ...(as before)

Gives : "1 2 3 4 5 6 7 8 9 10"

?

Answer:
Comma operator evaluates left to right, so the result of the
```
```
_1+=var(a), ++var(a)
```
```
is ++var(a), which you'll store using the transform version.
for_each:
_1 += var(a) is evaluated, updating your sequence (via the lambda _1), then ++var(a) is evaluated, but this has no effect on your sequence.
transform:
_1+=var(a) is evaluated, updating your sequence (just like before), then ++var(a) is evaluated, this also gives the result of the whole expression, then that is used to update your sequence again (via the transform)


Question:
As the question says, how do I add a new option to a DropDownList using jQuery?

Thanks

Answer:
With the plugin:
jQuery Selection Box
. You can do this:
```
```
var myOptions = {
        "Value 1" : "Text 1",
        "Value 2" : "Text 2",
        "Value 3" : "Text 3"
    }
    $("#myselect2").addOption(myOptions, false);
```
```


Question: Does the opening Window enhance an application's attractiveness? Should it be a picture or bland Blue and White?

Answer:
Use the default OS theme colors.  Anything else will be attractive to certain groups of people, and ugly to others (who will complain
very loudly
about how ugly they find it).  If you stick with the OS theme colors, then at least your application's appearance will not be something you'll be criticized over.


Question: There seem to be many options to create an XML document in .NET. What's the best approach?

Answer:
I would personally use LINQ to XML if I possibly could. It's
much
nicer than the DOM API. Of course, it does rely on you using .NET 3.5...
Note that your String.Format solution breaks down if you have any text which would need escaping. Admittedly I can't think of any car makes and models including
```
&
```
or
```
<
```
etc, but in a more general case it's a real issue.


Question:
For our school project, we are tasked to define a design document describing the architecture of a PHP application.

We are free te decide what to include in the document.

Our professor suggested, lots of (UML) diagrams.

He also asked us to consider class diagrams, but with care, as PHP is not fully object oriented.

My question: Is a Domain Driven Object Oriented Design feasible for a PHP application? What to consider when doing OO in PHP? What are the pro's and con's? Any helpful resources on OO in PHP and PHP best-practices?

Answer:
IMHO it's pretty difficult to describe the architecture of any application without knowing what the application is supposed to do. All applications (PHP or otherwise) of any complexity look different.
Secondly, PHP5 gives you classes/objects and the usual plethora of OO gubbings - so to describe it as 'not fully object orientated' is misleading I think. If you mean you can take a procedural approach with out being restricted to objects then yes, but if you wanted everything to be an object then that's your choice.
Is DDD feasible for PHP? Yes, of course. A particular approach to architecture is not usually dependent on technology. Best practices, pros/cons of OO design apply to most languages - PHP leaves you pretty free to decide how to structure your code.
You may find this
Best Practices
talk from the PHP site useful ;)


Question:
I would like to change all the names of the attributes where class="testingCase" throughout all my whole html document.

e.g. Change:

<a class="testingCase" href="#" title="name of testing case">Blabla</a>
<a class="testingCase" href="#" title="name of another testing case">Bloo</a>

To this:

<a class="testingCase" href="#" newTitleName="name of testing case">Blabla</a>`
<a class="testingCase" href="#" newTitleName="name of another testing case">Bloo</a>`

I was thinking of a find and replace but that seems a lot of code for something so easy. Is there a jQuery function for this or a simple method?

Answer:
There is no built-in method/function to "rename" an attribute in javascript, but you can create new attributes and remove other ones...
```
```
$('a.testingCase[title]').each(function() {
  var $t = $(this);
  $t.attr({
      newTitleName: $t.attr('title')
    })
    .removeAttr('title');
});
```
```
```
```

Blabla
Bloo
```
```
Edit: added in the bit that makes it only select
```
a
```
elements with class="testingCase"


Question:
On Apache/PHP sites if I want to put a senstive file within my website folders, I put a .htaccess file in that folder so users can't download the sensitive file.

Is there a similar practice for IIS/ASP.NET sites, i.e. if I have a shared hosting account and don't have access to IIS server. Can I do this in web.config for instance?

e.g. the ASPNETDB.MDF file that ASP.NET Configuration put in the App_Data directory. I would assume this is protected by default but where can I change the settings for this folder as I could with a .htaccess file?

Answer:
There are some things you can do with web.config like defining security settings etc...
Other times you have to use HttpModules or HttpHandlers, look here:
http://msdn.microsoft.com/en-us/library/aa719858(VS.71).aspx
If not, you can find different ISAPI, but in this case you need access to IIS.
For example, the ISAPI for emulating rewrite mod apache:
> http://www.codeplex.com/IIRF
The other question, yes ASPNETDB.MDF in APP_Data is protected normally (it depends on your administrator). To change the path, change the connectionstring.


Question: I am looking for any tool which will allow the performance testing/tuning of Sybase nested stored procedures. There are many tools around and of course Sybase's own for performance tuning and testing SQL but none of these can handle nested stored procedures (i.e. a stored proc calling another stored proc). Does anyone have/know of such a tool?

Answer:
There are some things you can do with web.config like defining security settings etc...
Other times you have to use HttpModules or HttpHandlers, look here:
http://msdn.microsoft.com/en-us/library/aa719858(VS.71).aspx
If not, you can find different ISAPI, but in this case you need access to IIS.
For example, the ISAPI for emulating rewrite mod apache:
> http://www.codeplex.com/IIRF
The other question, yes ASPNETDB.MDF in APP_Data is protected normally (it depends on your administrator). To change the path, change the connectionstring.


Question:
I'd like to know when i should and shouldn't be wrapping things in a USING block.

From what I understand, the compiler translates it into a try/finally, where the finally calls Dispose() on the object.

I always use a USING around database connections and file access, but its more out of habit rather than a 100% understanding. I know you should explicity (or with a using) Dispose() objects which control resources, to ensure they are released instantly rather than whenever the CLR feels like it, but thats where my understanding breaks down.

Are IDisposables not disposed of when they go out of scope?

Do I only need to use a USING when my object makes use of Dispose to tidy itself up?

Thanks

Edit: I know there are a couple of other posts on the USING keyword, but I'm more interested in answers relating the the CLR and exactly whats going on internally

Andrew

Answer:
No,
```
IDisposable
```
items are not disposed when they go out of scope. It is for precisely this reason that we need
```
IDisposable
```
- for deterministic cleanup.
They will
eventually
get garbage collected, and if there is a finalizer it will (maybe) be called - but that could be a long time in the future (not good for connection pools etc). Garbage collection is dependent on memory pressure - if nothing wants extra memory, there is no need to run a GC cycle.
Interestingly (perhaps) there are some cases where "using" is a pain - when the offending class throws an exception on
```
Dispose()
```
sometimes. WCF is an offender of this. I have discussed this topic (with a simple workaround)
here
.
Basically - if the class implements
```
IDisposable
```
, and you
own
an instance (i.e. you created it or whatever), it is your job to ensure that it gets disposed. That might mean via "using", or it might mean passing it to another piece of code that assumes responsibility.
I've actually seen debug code of the type:
```
```
#if DEBUG
    ~Foo() {
        // complain loudly that smoebody forgot to dispose...
    }
#endif
```
```
(where the
```
Dispose
```
calls
```
GC.SuppressFinalize
```
)


Question:
I mainly use the MySQL GUI tools. This allows me to easily see the results in a table as well as to quick edits and bookmark frequently run queries. This suits my needs far better than the command line.

I remember when I used to do this on Oracle DBs years ago I could put variables in the query itself, so that when running the query I got prompted for the variable.

e.g.

select email from users where login = [VAR]

And when you run the query the system prompts you for VAR and you can type in john_smith14 and it executes the query. This is really useful for adhoc queries which you run a lot.

Yes I know using shell scripts and the command line this could be done more easily, but for several reasons aside from this, shell scripts are not a good solution for me.

Answer:
I'm not sure if there's a way to get the GUI tools to prompt you for a value, but you can certainly use variables in MySQL.
```
```
SET @myVar='john_smith14';
SELECT email FROM users WHERE login = @myVar;
```
```
That might even suit you better, since you don't have to keep typing in the variable value each time..?


Question: I want to develop a mobile web application using asp.net 3.5 that can be viewed on an iPhone but there is no longer a template in VS2008 to enable mobile development. Can this be done ?

Answer:
the iphone uses the "regular" version of your website so developing a "mobile" version would nto accomplish what you're looking for. You should check the browser headers and redirect people to the iPhone version of your site if you detect mobile safari.
http://iphone.facebook.com/
Another option (if you're using MVC) is to have your controller detect the browser and show a different view if it catches mobile safari. This way you wouldn't need a duplicate site, just two sets of views.


Question:
Why not use partial class to build the ViewModel?

Since the definition of viewmodel classes have some definition of the data classes of datamodel, why not try to reduce some work, extending or making partial classes of the datamodel, completing them with command and etc.

Answer:
In some cases this may be useful, but generally the ViewModel (or PresentationModel) has a different set of concerns that would muddle the rest of the model.
For example, imagine that you have an object model that represents an order processing workflow (everybody's favorite example.) This same model might be underlying a WPF, a web site, and perhaps even other services.
Within the WPF application there will be WPF-specific concerns for presentation. Adding these concerns to primary model (even as partial classes) results in a violation of SRP. Ultimately, it would obscure the intent of model and make it difficult for consumers of the model to know which parts of it where essential and which were incidental.


Question:
I am using NetBeans for PHP 6.5.

In my code I frequently use the following type of command:

if (($row = $db->get_row($sql))) {
        return $row->folder;
    } else {
        return FALSE;
    }

Netbeans tells me that I should not be using assignments in the IF statement.

Why ?

Answer:
It's probably trying to help you avoid the dreaded typo:
```
```
if(a = b)
   //logic error
```
```
Although I would expect an enviroment smart enough to warn you about that, to also be smart enough to have "oh, don't worry about that case" conditions.


Question:
I'm currently having a problem with a ShoppingCart for my customer.

He wants to be able to add Text between the CartItems so I was wondering if there is some way to still only have one List.

My solution would be to have two lists, one of type IList that gets iterated over when calculating Weight and overall Price of the Cart while having another IList that only exposes the necessary fields for displaying it in the ListView and that is a SuperType of CartItem. (But how do I then access additional fields for the listView, defaulting weight and price to 0 in the Description-Text-Class would break LSP).

But having two lists somehow feels a bit odd (and still gives me problems), so I was wondering if I could do some sort of a TypedList where I specify the Type of each item.

Any suggestions are welcome, I'm not really happy with both options.

Answer:
Use an interface:
```
```
ICartListItem
```
```
And make your list be:
```
```
List<ICartListItem>
```
```
Now, create several types, have all of them implement this interface, and you can store them all safely in your list.
Alternatively, if you want there to be some default logic in a CartItem, use a base class instead of an interface.


Question:
I am trying to build a server control that, depending on a "QuestionTypeId" display either a text box, date picker or Yes-No radio buttons.

I have my control displaying how I want it to, but when the submit button is pressed on the form, the text box, date picker or radio buttons that were generated in the RenderContents method are all null.

I have attempted to store the generated controls in view state, that stopped them being null, but the user inputs were not being stored.

I will post code if it is needed. Just ask.

Answer:
When you add controls dynamically, you need to make sure they are recreated before the viewstate is restored.
I haven't done this in a while, but from memory I think you should recreate your controls in the OnInit method. This happens before postback data has been loaded and before the controls have their values set from viewstate.
It may be worth doing some reading on the asp.net page lifecycle:
http://msdn.microsoft.com/en-us/library/ms178472.aspx


Question: Is there any setting using which the iPhone keyboard won't appear for a particular textbox in web page? May be some css kind of setting?

Answer:
Do you want the text box to be editable for any other browser other than the iPhone?  If not, have you attempted to disable the text box?  I haven't tried this, nor can I recall seeing a disabled text box on a site with my iPhone; however, it may do it.
If disabling the text box works
, but you still only want to restrict it to the iPhone, you'll need to look at the User Agent for the iPhone.  You can determine this through server side code or through JavaScript's
```
navigator.userAgent
```
.
To save a bit more time for you as well, the iPhone's user agent is as follows:
```
```
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3
```
```


Question: Which ftp client or which syntax allows easy chmod for sub-directories?

Answer:
To chmod all subdirs from where you are (recursive):
```
```
chmod -R *
```
```


Question:
How would you get tree-structured data from a database with the best performance? For example, say you have a folder-hierarchy in a database. Where the folder-database-row has ID, Name and ParentID columns.

Would you use a special algorithm to get all the data at once, minimizing the amount of database-calls and process it in code?

Or would you use do many calls to the database and sort of get the structure done from the database directly?

Maybe there are different answers based on x amount of database-rows, hierarchy-depth or whatever?

Edit: I use Microsoft SQL Server, but answers out of other perspectives are interesting too.

Answer:
If you have many trees in the database, and you will only ever get the whole tree out, I would store a tree ID (or root node ID) and a parent node ID for each node in the database, get all the nodes for a particular tree ID, and process in memory.
However if you will be getting subtrees out, you can only get a subtree of a particular parent node ID, so you either need to store all parent nodes of each node to use the above method, or perform multiple SQL queries as you descend into the tree (hope there are no cycles in your tree!), although you can reuse the same Prepared Statement (assuming that nodes are of the same type and are all stored in a single table) to prevent re-compiling the SQL, so it might not be slower, indeed with database optimisations applied to the query it could be preferable. Might want to run some tests to find out.
If you are only storing one tree, your question becomes one of querying subtrees only, and the second answer applied.


Question:
I understand that, if S is a child class of T, then a List<S> is not a child of List<T>. Fine. But interfaces have a different paradigm: if Foo implements IFoo, then why is a List<Foo> not (an example of) a List<IFoo>?

As there can be no actual class IFoo, does this mean that I would always have to cast each element of the list when exposing a List<IFoo>? Or is this simply bad design and I have to define my own collection class ListOfIFoos to be able to work with them? Neither seem reasonable to me...

What would be the best way of exposing such a list, given that I am trying to program to interfaces? I am currently tending towards actually storing my List<Foo> internally as a List<IFoo>.

Answer:
MASSIVE EDIT
You'll be able to do it with C# 4.0, but
[thanks Jon]
You can get around it using
```
ConvertAll
```
:
```
```
public List<IFoo> IFoos()
{
    var x = new List<Foo>(); //Foo implements IFoo
    /* .. */
    return x.ConvertAll<IFoo>(f => f); //thanks Marc
}
```
```


Question:
I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.

Is there a function that can do this easily?

For example:

$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";
$string2 = 100charfunction($string1);
print $string2

To get:

I am looking for a way to pull the first 100 characters from a string vari

Answer:
```
```
$small = substr($big, 0, 100);
```
```
For
String Manipulation
here is a page with a lot of function that might help you in your future work.


Question:
When the page is done loading I call a function which puts the hover event on $('a.tooltip'). When I want to unbind this event I do the following:

   $('a.tooltip').unbind('mouseover mouseout');

That works! However when I want rebind the hover event and I call the function that was first loaded at document ready again, it doesn't rebind the hover helper. How can I rebind it?

Thank you,

Ice

Answer:
Are you sure the unbinding is working correctly? In my experience, .hover() does rebind properly, but I have had to use this unbind syntax:
```
```
$(this).unbind('mouseenter').unbind('mouseleave');
```
```
When I tried putting both events into one unbind(), it only unbound one of them.
I wonder if that's happening for you? (Or if the choice of
```
mouseover
```
vs
```
mouseenter
```
, etc, matters?)
Update
According to
quirksmode.org
,
```
mouseenter
```
and
```
mouseleave
```
are IE-specific events, but as Jimmy pointed out in the comments, jQuery implements them for other browsers as well.


Question:
I'm testing the basics for exchanging rest messages between a asp.net mvc site and a WCF 3.5 service.
The service is built using the template found in the WCF REST Starter Kit found on codeplex.
I would like to exchange json messages using jquery.
The REST Singleton service is working properly and it also provide examples of all the possible calling adding the help parameter ad the end of the uri.
I arrive to perform GET requests with the built in jquery $.getJSON.
I have problems doing the PUT (for updating values) and POST.

$.ajax({
     type: "PUT",
     dataType: "json",
     url: "http://localhost:1045/Service.svc/?format=json",
     data: '{"Value":testvalue}'
 });

What is the best approach for this? Is it possible not to use Ms. Ajax at all and is it correct to bypass it?

Answer:
"PUT" and "DELETE" are not supported by all browsers according to jQuery
The type of request to make ("POST" or
  "GET"), default is "GET". Note: Other
  HTTP request methods, such as PUT and
  DELETE, can also be used here, but
  they are not supported by all
  browsers.
http://docs.jquery.com/Ajax/jQuery.ajax#options
I didn't really understand your question though.  Are you having a problem doing a PUT and a POST or just a POST?  Does the GET work fine?
One error that I noticed was your data, notice I added it without quotes.
```
```
$.ajax({
     type: "PUT",
     dataType: "json",
     url: "http://localhost:1045/Service.svc/?format=json",
     data: { Value: "testvalue" }
});
```
```


Question:
I am creating a GUI frontend for the Eve Online API in Python.

I have successfully pulled the XML data from their server.

I am trying to grab the value from a node called "name":

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name

This seems to find the node, but the output is below:

[<DOM Element: name at 0x11e6d28>]

How could I get it to print the value of the node?

Answer:
It should just be
```
```
name[0].firstChild.nodeValue
```
```


Question: I'm interested in hearing people's thoughts about the pros and cons of database mirroring vs. log shipping in this scenario: we need to setup a database backup situation wherein there is exactly one secondary server that need not automatically pick up when the primary fails.  Recovering and starting with the secondary should not have to take too long though.

Answer: Switching to the secondary database does take longer with log shipping, but it's not too bad.  You'll have to manually copy any uncopied backup files, apply the transaction log backups to the secondary database, recover the secondary database, and change its role to primary.  If the old primary databases accessible, you should back up its transaction log before beginning.  Failing over with mirroring is somewhat simpler, and can be done automatically if you are using High Availability mode.  Even when using High Performance mode, it's still a one statement operation.


Question:
In the Boost Signals library, they are overloading the () operator.

Is this a convention in C++? For callbacks, etc.?

I have seen this in code of a co-worker (who happens to be a big Boost fan). Of all the Boost goodness out there, this has only led to confusion for me.

Any insight as to the reason for this overload?

Answer:
Another co-worker pointed out that it could be a way to disguise functor objects as functions. For example, this:
```
```
my_functor();
```
```
Is really:
```
```
my_functor.operator()();
```
```
So does that mean this:
```
```
my_functor(int n, float f){ ... };
```
```
Can be used to overload this as well?
```
```
my_functor.operator()(int n, float f){ ... };
```
```


Question:
I have a table, users, in an Oracle 9.2.0.6 database.  Two of the fields are varchar - last_name and first_name.

When rows are inserted into this table, the first name and last name fields are supposed to be in all upper case, but somehow some values in these two fields are mixed case.

I want to run a query that will show me all of the rows in the table that have first or last names with lowercase characters in it.

I searched the net and found REGEXP_LIKE, but that must be for newer versions of oracle - it doesn't seem to work for me.

Another thing I tried was to translate "abcde...z" to "$$$$$...$" and then search for a '$' in my field, but there has to be a better way?

Thanks in advance!

Answer:
How about this:
```
```
select id, first, last from mytable
where first != upper(first) or last != upper(last);
```
```


Question:
I'm looking for the best way to interpret the standard (well, standardish) Ethernet PHY registers, to determine the speed that an Ethernet link is actually running at.  (e.g. 10/100/1000 and full/half-duplex)

I daresay that this is to be found in the source of things like Linux, and I'm just off to look there now, but if anyone has a good reference I'd be interested.

What I'm interested in is if it actually linked and what it linked at, rather than the vast sea of possibilities that each end has advertised at the outset.

Answer:
How about this:
```
```
select id, first, last from mytable
where first != upper(first) or last != upper(last);
```
```


Question:
The navigation on the left menu in the below site uses CSS for mouseover links.
PVH

When I take the code of the navigation and make it separate page. Then the mouseover links are not working. What could be the reason?

Test

Answer:
Probably...
```
```
<script src="menu_1b.js" type="text/javascript">
</script>
<script src="menu_com.js" type="text/javascript">
```
```
have something to say on the matter. EDIT: A function called function CreateMenuStructureAgain() kind of gives it away.


Question: Is it possible to get access to the spell checker that is incorporated in browsers for text areas from Javascript? I would like to be able to control spell checking from withing my code. Most browsers (apart from IE) seem to have some kind of a spell checker built in to them nowadays.

Answer:
The most access that I know of is disabling or enabling spellchecking on a field:
Inline Disabling of Firefox Spellcheck?
I don't know of a way that you can directly access the spellchecker of a browser via javascript.  If you aren't particular to the spell checker of the browser, there are many open source spell checkers for javascript. Just try googling javascript spell checker.
If you really want to use the browsers spellcheck you might want to create a textbox and set the display to none.  You could then put each word in the textbox and then check to see if it's underlined or not.  I'm not sure of the feasability of this, just a thought.  My suggestion would be to use a javascript spellchecker instead of trying to hack up a way of using the browser's spellchecker.


Question:
How can I select multiple elements using a WHERE...IN... type of clause as in

select * from orders where orderid in (1, 4, 5)

in LinqToSql? I'd prefer not to have a lambda expression since they scare me.

Answer:
LINQ has "Contains" which is like "IN" but expressed the other way round - an element isn't "in" a set, a set "contains" an element.
```
```
int[] validIds = { 1, 4, 5 };
var query = from order in db.Orders
            where validIds.Contains(order.Id)
            select order
```
```
This is more simply expressed (IMO) with a lambda though:
```
```
int[] validIds = { 1, 4, 5 };
var query = db.Orders.Where(order => validIds.Contains(order.Id));
```
```
I realise lambdas are "new" and therefore scary to some extent, but it's really well worth grabbing hold of them with both hands. They're lovely.


Question:
I have a view which contains a form, the form posts and the data gets processed etc, then I want to return the view Index, so return view("Index");

however this will then complain about my ViewData not existing, I get the feeling that the controller code under Index() isn't being processed which adds the list it requires to the ViewData, anyone know what's wrong?

Thanks

edit: Apparently it's done to prevent recursion.. in which case, I'm lost as to what to do without repeating all my ViewData stuff both Controllers

Answer:
I think you should have two actions: one that processes the form submission, and another one that collects data for the view.
Once the form has been processed, you call
```
return RedirectToAction("Index")
```
and you are done.
I hope I understood what you meant by this.


Question:
I would like to write a utility that will provide me with a relatively unique ID in Java.  Something pretty simple, like x bits from timestamp + y bits from random number.

So, how would I implement the following method:

long getUniqueID()
{
    long timestamp = System.currentTimeMillis();
    long random = some random long

    ...

    return id;
}

BONUS

Any suggestions for other easily obtainable information I could use to form my ID?

note: I am aware of GUIDs and I know Java has a UUID class, but I don't want something that is 128 bits long.

Answer:
What you are trying to do is create a
hash function
that combines two long values into a single long value. In this case, the
uniformity
of the hash function will be of utmost importance since collisions in created unique ID values are unacceptable. However, if you can compare hash values to previously created identifiers, then collisions can be resolved by modifying the hash until no collision occurs.
For example, you could take the time stamp and perform an
exclusive-or
(using the caret ^ operator in Java) with the random value. If a collision is detected, then add one to the result.


Question:
Up to now in my application, I've been supporting all flavors of Windows from Windows 98 to Windows NT/2000 to XP to Vista.

But because of adding Unicode in my next version, support of Windows 98 would still be possible, but very difficult.

I know there are still some of my users running Windows 98.

What are the pros and cons of me no longer supporting Windows 98?

Answer:
If you still have users running Windows 98, then one obvious drawback to dropping support is that some of those will inevitably refuse to upgrade. They'll either stick with the version of your software they already have, or switch to something else.
On the other hand, the cost of developing for and supporting those users probably outweighs the additional revenue gained from it. So even though in principle you don't want any unhappy customers, in practice it may be more cost-effective to keep 99% of them happy.


Question:
When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding because I feel the overhead of maintaining the state of the yeilding method doesn't buy me much. In almost all cases where I am returning a collection I feel that 90% of the time, the calling method will be iterating over all elements in the collection, or will be seeking a series of elements throughout the entire collection.

I do understand its usefulness in linq, but I feel that only the linq team is writing such complex queriable objects that yield is useful.

Has anyone written anything like or not like linq where yield was useful?

Answer:
Note that with yield, you are iterating over the collection once, but when you build a list, you'll be iterating over it twice.
Take, for example, a filter iterator:
```
```
IEnumerator<T>  Filter(this IEnumerator<T> coll, Func<T, bool> func)
{
     foreach(T t in coll)
        if (func(t))  yield return t;
}
```
```
Now, you can chain this:
```
```
MyColl.Filter(x=> x.id > 100).Filter(x => x.val < 200).Filter (etc)
```
```
You method would be creating (and tossing) three lists.  My method iterates over it just once.
Also, when you return a collection, you are forcing a particular implementation on you users. An iterator is more generic.


Question:
I have a ComboBox inside of a cell of a DataGridView Row on a Windows form.  I need the following to happen:

click on the ComboBox

pick a value

recalculate a total & display inside of a lable that is sitting
    outside of the DataGridView.

Currently, the following is happening:

Click on the ComboBox

Click it again to open the CB's Drop-down list

select a value

click outside of the cell to force a recalculation of the
    external label.

I want to avoid, first, having to click the combo twice (once to set focus, and again to select the value).  Second, I'd like for a live recalculation to happen after selecting a value.

Does anyone have a trick or two to solve any of these?

I've tried most of the events on the DGV without much luck.

Answer:
Add a handler to the CellClick event of the DataGridView that looks a bit like:
```
```
private void vehicleTypeGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if ( e.RowIndex == - 1 ) return; //Header Cell clicked -> ignore it.
    vehicleTypeGridView.BeginEdit ( true );
    var control = vehicleTypeGridView.EditingControl as DataGridViewComboBoxEditingControl;
    if ( control != null ) control.DroppedDown = true;
}
```
```


Question:
when i point my browser to http://localhost/phpmyadmin, instead of showing me its front page, it comes up with save as dialog.

I'm running:
Apache/2.2.3 (Debian) PHP/5.2.0-8+etch13 Server

I've reinstalled both apache2 and php5.
After re-install i don't have httpd.conf file, how can i get it back? Is there a standard file which i can just copy into /etc/apache2?

I did a locate httpd.conf and the only file i got was the empty file i have under /etc/apache2/ which i made.

Answer:
Did you configure the php extension to send an http header?
In httpd.conf:
AddType application/x-httpd-php .php
EDIT
The file is not necessarily named
```
httpd.conf
```
, that's just the default name.  Try searching for other configuration files in the Apache directory -- the extension probably is
```
.conf
```
but it might be something else...
If you used apt-get on debian to install apache2, try
```
/etc/apache2/apche2.conf
```
/EDIT


Question:
What is the best way to centralize and secure the connections strings used by applications?  In my environment we have many internal applications.  Each application requires one or more connection strings in order to access the database.  We have a goal of centralizing all these connection strings (particularly SQL logins and passwords) so we could change passwords in one place instead of in 35 different .config files, registry entries etc.

Currently we are using a home grown component which pulls the connection string information from an access database, this covers the centralization requirement but isn't particularly secure.  In addition we have applications written in languages from classic asp, vb6, delphi, c++, .net so the solution would need to be usable by all those applications.

Does anyone have an idea of how to do this better, or do we need to rework our whole approach to the way our applications access the database.

Answer:
The company I work for has used a similar situation through a SQL Server database instead.  We ended up creating a COM-compliant .net dll to simplify and secure the API into the database and to ensure that the same logic is used between classic asp, .Net, and DTS packages.  It has worked out great for us for year and while there are some refactoring items a lot of us would like to do with it, it's been great to address issues like server migrations or renamings.
I think you are on the right path; however, I would recommend the following changes:
Try to move to a true database server.  Access is great for MS Office but not for something of this scale.
Build an administrative console that allows for auditing of who is adding and editing information (secure who has access to what settings too).
Build a COM-compliant DLL so that it can be consumed by other systems in a secure and consistent manner.
EDIT:
Something that I have noticed after working years in a system like this is that it ties your hands slightly on some solutions.  Many tools out there (i.e. nHibernate, Elmah, etc. in the .Net world) really are limited when the connection string is no longer in the config files.  Many can be easily modified to use your API; however, it is something that takes more time to investigate if you want to use it.  Just a FYI on that.


Question:
I'd like to allow a user to open files in their own client applications via Silverlight. I'd like this to work similarly to WebDAV, in the sense that they could read/write the file back into Silverlight's isolated storage...

Is it possible to construct a file:// link to an isolated storage file?
Is there a uri scheme that is defined for silverlight in a browser that has the silverlight plugin?

Am I totally nuts?

Answer:
The company I work for has used a similar situation through a SQL Server database instead.  We ended up creating a COM-compliant .net dll to simplify and secure the API into the database and to ensure that the same logic is used between classic asp, .Net, and DTS packages.  It has worked out great for us for year and while there are some refactoring items a lot of us would like to do with it, it's been great to address issues like server migrations or renamings.
I think you are on the right path; however, I would recommend the following changes:
Try to move to a true database server.  Access is great for MS Office but not for something of this scale.
Build an administrative console that allows for auditing of who is adding and editing information (secure who has access to what settings too).
Build a COM-compliant DLL so that it can be consumed by other systems in a secure and consistent manner.
EDIT:
Something that I have noticed after working years in a system like this is that it ties your hands slightly on some solutions.  Many tools out there (i.e. nHibernate, Elmah, etc. in the .Net world) really are limited when the connection string is no longer in the config files.  Many can be easily modified to use your API; however, it is something that takes more time to investigate if you want to use it.  Just a FYI on that.


Question:
The scenario is:

svn cp or mv some file

modify that file

svn diff > mypatch

On other machine (same working copy, but no changes):

Try to apply mypatch.

Fail -> tries to modify unexistant file.

How can I make svn diff produce patch-appliable patch, or cleanly apply patch produced by svn diff in this case? I can't commit. I would like to preserve mergeinfo (because the obvious workaround is to add the file as totally new, without connection to the previous one).

Answer:
With subversion, you can specify which diff binary to use, and parameters to pass to it.  See
the manual
on svn diff.
You'd want to produce a regular patch file from a svn diff, so you'd want the svn diff to look like a normal diff.  Try this:
```
```
svn diff --diff-cmd /usr/bin/diff -x "-i -b" > mypatch
...
patch -p0 < mypatch
```
```
Proof of concept:
```
```
echo "newline" >> README.txt
svn diff --diff-cmd /usr/bin/diff -x "-i -b" > mypatch
cp README.txt README.txt.patched
svn revert README.txt
patch -p0 < mypatch
diff README.txt README.txt.patched
```
```
No difference in the two files after patching.


Question: I have a table with almost 800,000 records and I am currently using dynamic sql to generate the query on the back end.  The front end is a search page which takes about 20 parameters and depending on if a parameter was chosen, it adds an " AND ..." to the base query.  I'm curious as to if dynamic sql is the right way to go ( doesn't seem like it because it runs slow).  I am contemplating on just creating a denormalized table with all my data.  Is this a good idea or should I just build the query all together instead of building it piece by piece using the dynamic sql. Last thing, is there a way to speed up dynamic sql?

Answer:
It is more likely that your indexing (or lack thereof) is causing the slowness than the dynamic SQL.
What does the execution plan look like?  Is the same query slow when executed in SSMS?  What about when it's in a stored procedure?
If your table is an unindexed heap, it will perform poorly as the number of records grows - this is regardless of the query, and a dynamic query can actually perform better as the table nature changes because a dynamic query is more likely to have its query plan re-evaluated when it's not in the cache.  This is not normally an issue (and I would not classify it as a design advantage of dynamic queries) except in the early stages of a system when SPs have not been recompiled, but statistics and query plans are out of date, but the volume of data has just drastically changed.
Not the static one yet. I have with the dynamic query, but it does not give any optimizations. If I ran it with the static query and it gave suggestions, would applying them affect the dynamic query? – Xaisoft (41 mins ago)
Yes, the dynamic query (EXEC (@sql)) is probably not going to be analyzed unless you analyzed a workload file. – Cade Roux (33 mins ago)
When you have a search query across multiple tables that are joined, the columns with indexes need to be the search columns as well as the primary key/foreign key columns - but it depends on the cardinality of the various tables. The tuning analyzer should show this. – Cade Roux (22 mins ago)


Question:
I am developing a product with heavy 3D graphics computations, to a large extent closest point and range searches. Some hardware optimization would be useful. While I know little about this, my boss (who has no software experience) advocates FPGA (because it can be tailored), while our junior developer advocates GPGPU with CUDA, because its cheap, hot and open. While I feel I lack judgement in this question, I believe CUDA is the way to go also because I am worried about flexibility, our product is still under strong development.

So, rephrasing the question, are there any reasons to go for FPGA at all? Or is there a third option?

Answer:
I investigated the same question a while back. After chatting to people who have worked on FPGAs, this is what I get:
FPGAs are great for realtime systems, where even 1ms of delay might be too long. This does not apply in your case;
FPGAs can be very fast, espeically for well-defined digital signal processing usages (e.g. radar data) but the good ones are much more expensive and specialised than even professional GPGPUs;
FPGAs are quite cumbersome to programme. Since there is a hardware configuration component to compiling, it could take hours. It seems to be more suited to electronic engineers (who are generally the ones who work on FPGAs) than software developers.
If you can make CUDA work for you, it's probably the best option at the moment. It will certainly be more flexible than a FPGA.
Other options include Brook from ATI, but until something big happens, it is simply not as well adopted as CUDA. After that, there's still all the traditional HPC options (clusters of x86/PowerPC/Cell), but they are all quite expensive.
Hope that helps.


Question:
I'm trying to redirect the java compiler output to a file.
I thought it's supposed to be:

javac file.java > log.txt

or something. Instead, I see all the output on the terminal and nothing in log.txt!

Also, if I want to log errors too, do I do

javac file.java 2>&1 > log.txt

?

Answer:
```
```
javac file.java 2> log.txt
```
```
The reason is that you have
two
output file descriptors instead of one. The usual one is stdout, which you can redirect with > and it's supposed to be used for resulting output. The second one, stderr, is meant for human readable output like warnings, errors, current status etc., this one is redirected with 2>.
Your second line, using 2>&1, redirects stderr to stdout and finally stdout into log.txt.


Question: What is the best way to make the SSRS reporr fit in to PDF page.

Answer:
Next time please indicate what version of SSRS you are working with...
If you are careful to design your canvas to certain constraints your should be fine. Typically the PDF is going to emulate a 8.5" by 11" piece of paper - considering margins you should keep the width of your report to less than 7" but I think 6.5" is best.
You can do this by selecting the report itself, the menu in BIDS (VS) should now have a report item which you can select to reveal Report Properties. In the report properties you can select the orientation as well as standard paper sizes and margins. Based on your paper size and your left and right margins you should be able to calculate the maximum width for the body of your report. Back in the report designer select the report body and look at the properties. The object drop down list should specifically say BODY, in this you want to ensure the size of your body (width) is not greater than the Report width minus the margins.


Question:
I get this error during checkout:

cvs checkout: warning: new-born file.java has disappeared
cvs [checkout aborted]: cannot make directory : No such file or directory
cvs status: cannot rewrite CVS/Entries.Backup: Permission denied

I'm sure I have the proper permissions to this folder and it happens even when I try to check out to a new one. I'm also sure that these files exist in cvs..

my checkout command is:

cvs co -d dir -N -r(num) -r(num)... file file... and so on

What does this new-born thing mean?

Answer:
```
new-born
```
refers to a file that has been
```
add
```
-ed but not
```
commit
```
-ted yet, or that
```
CVS
```
is having trouble getting the file written locally.
My guess would be that there is a
```
.cvs
```
directory present that records an
```
add
```
but the file has since been deleted.
The additional errors you're seeing relate to permissions in the checkout directory - maybe you don't have write access to the checkout directory,
```
umask
```
is set incorrectly or there is a directory permission inheritance problem.


Question:
I am iterating though a TreeSet and printing it out:

while (it.hasNext()) {
  System.out.println(it.next());
}

output:

after
explorers
giant
hoping
internet
into
.
.
.
virtual
world

However, I would like to only print out those strings who's first character is within the range m-z. I have been playing around with java.util.regex, with no success:

String pattern = "[^m-z]";

Do I have the right idea here? Or is there a simpler way of doing this? All I want to do is make sure I only print out those Strings in the TreeSet who's first character is within the range m-z.

Answer:
seems like an homework but anyhow,
the "[^m-z]" means NOT m-z
try putting the "^" outside the "[]"
Have a look at the
Pattern
class
and BTW, try
```
String.matches()
```


Question:
How can we write an update sql statement that would update records and the 'set' value changes every time?

For example:
If we have records like this

SomeNumber SomeV CurCode WhatCodeShouldBe
200802754 432 B08 B09
200802754 432 B08 B09
200802754 432 B08 B09
200808388 714 64B C00
200804119 270 64B C00

I wish to update each 'SomeNumber' record so that 'CurCode' will be same as 'WhatCodeShouldBe'

Thanks for any help!

Answer:
```
UPDATE yourtable SET CurCode = WhatCodeShouldBe
```


Question:
Each of these variables has an integer value.  But this syntax is not valid for some reason:

<xsl:when test="$nextAnswerListItemPos < $nextQuestionStemPos" >

Answer:
You have to use
```
<
```
instead of
```
<
```
and
```
>
```
instead of
```
>
```
, because those are reserved characters.


Question:
Is there some equivalent of "friend" or "internal" in php? If not, is there any pattern to follow to achieve this behavior?

Edit:
Sorry, but standard Php isn't what I'm looking for. I'm looking for something along the lines of what ringmaster did.

I have classes which are doing C-style system calls on the back end and the juggling has started to become cumbersome. I have functions in object A which take in object B as a parameter and have to call a method in object B passing in itself as an argument. The end user could call the method in B and the system would fall apart.

Answer:
I'm pretty sure what you're looking for is "protected" or "private", depending on your use case.
If you're defining an function in a class, and you only want it available to itself, you'll define it this way:
```
```
private function foo($arg1, $arg2) { /*function stuff goes here */ }
```
```
If you're defining a function in a class that you want to be available to classes which inherit from this class, but not available publicly, definite it this way:
```
```
protected function foo($arg1, $arg2)
```
```
I'm pretty sure that by default in PHP5, functions are public, meaning you don't have to use the following syntax, but it's optional:
```
```
public function foo($arg1, $arg2) { /*function stuff goes here */ }
```
```
You'll still have to instantiate the object before using a public function.  So I'll just be thorough and let you know that in order to use a function in a class without instantiating an object, be sure to use the following syntax:
```
```
static function foo($arg1, $arg2) { /*function stuff goes here */ }
```
```
That will allow you to use the function by only referencing the class, as follows:
```
```
MyClass::foo($a1, $a2);
```
```
Otherwise, you'll need to do the following:
```
```
$myObject = new MyClass();
$myObject->foo($a1, $a2);
```
```


Question:
I've got a few dozen Linux machines running cron and I'd like to put the crontabs in some sort of revision control system.  For source control I use Mercurial (hg), so that'd be ideal, but if there's some other system that is better suited to this task I'd consider it.

One aspect which is specific to my situation is that all the crontabs belong to a common user (not a real person, but a placeholder "services" login).  I'd like the revision history to include the actual author of each change, rather than the special account where the cron jobs actually run.

Answer:
http://joey.kitenet.net/code/etckeeper/
?
From that site:
etckeeper is a collection of tools to let /etc be stored in a git, mercurial, darcs, or bzr repository. It hooks into apt (and other package managers including yum and pacman-g2) to automatically commit changes made to /etc during package upgrades. It tracks file metadata that revison control systems do not normally support, but that is important for /etc, such as the permissions of
```
/etc/shadow
```
. It's quite modular and configurable, while also being simple to use if you understand the basics of working with revision control.


Question:
For some reason my code won't work.

    from tan in TANS
    where tan.ID.ToString().Count() != 1
    select tan

I want to select all IDs that are duplicates in a table so I am using the count != 1 and I get this error.

NotSupportedException: Sequence operators not supported for type 'System.String'

Help please?

Answer:
```
tan.ID.ToString()
```
is a string, not a collection so you can't apply Count().
I believe you want something like:  (This syntax is wrong, but close)
```
```
from tan in TANS
group tan by tan.ID into dups
where dups.Count() > 1
select dups.Key;
```
```
Update (after 5 years minus 5 days): (It's a bit weird to Google a problem and find an answer YOU wrote ..) At the core of this problem is the the LINQ statement is trying to build an SQL statement, and the database doesn't know how to apply Count() to a string.  However, if you use LINQ against a collection in memory, then it would treat the string as an IEnumerable and the Count() would work just fine.


Question:
I am developing on a LAMP(erl) stack and know of several ways to store obscured passwords.  I'd like to hear from those who feel they have a best practice, given MySQL 4.1.1 and Perl 5.8, and the reasons why it's the best.

One option I have read about, using the MySQL ENCODE() and DECODE() functions, sounds pretty good to me... your thoughts?

Answer:
Well, since there's a
```
DECODE()
```
function, I'd say no, for the simple fact that you probably want to store the password in hashed form, to prevent anyone obtaining your database/password file from casually reading passwords.
I'd recommend going with the classic salted hash method.


Question:
I have just realized I've been coercing binding/dependency properties and not really fundamentally understanding the concept.

Heres the dependency property:

public string Problem
{
    get { return (string)GetValue(ProblemProperty); }
    set { SetValue(ProblemProperty, value); }
}

public static readonly DependencyProperty ProblemProperty =
    DependencyProperty.Register(
    "Problem",
    typeof(string),
    typeof(TextBox));

The XAML is as so:

<TextBlock Text="{Binding Path=Problem}"/>

I'm manually setting the Problem property to a value in the constructor of the object but it doesn't update the TextBlock accordingly . . . any ideas? I've tried Mode="OneWay" and Mode="TwoWay" on the binding and it still doesn't work.

I thought this was supposed to work automatically? Or am i fundamentally getting something wrong?

Thanks

Answer:
The problem your having is definitely related to your DataContext. The {Binding} extension needs to know where the property lives that you are binding to. The default location it looks at is the elements DataContext which by default is always set to the DataContext of it's parent element. If you walk the DataContext up the logical tree to the parent window, The DataContext would be null (because the DataContext of your window is null). Therefore your {Binding} on your textblock is saying "Bind my Text property to the Problem roperty of my DataContext...which is null.
There are a couple of ways to solve this. One would be to do just like Jobi mentioned and set the Element property of you binding to point to the Window where the DependencyProperty is defined like this:
```
```
<TextBlock Text="{Binding Path=Problem,ElementName=_window}" />
```
```
Another option would be to set the DataContext of your Window to point to itself. That way all the elements contained in it's content will all have the DataContext of the window.
```
```
<Window ....
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
```
```
Now anytime you need to binding to properties defined in the window (like your Problem dependency property), then you can just do this:
```
```
<TextBlock Text="{Binding Problem}" />
```
```


Question:
In the admin section of a website i am building i would like to put together a dashboard page, or 'quick look' type page where the most recent changes/additions/etc in several different areas can be viewed.

I was thinking the best way to do this would be to use partials and have each partial contain the markup for the data i need to display.

My question is, is this the best approach? and if so, how do i separate the logic and presentation of these partials? For instance how do i put the logic in the dashboard controller, but keep the presentation in the partial rhtml?

Answer:
Partials are definitely the way to go, especially when you can pass in arbitrary data into them to make them do stuff. To answer your logic separation issue specifically, you would use:
```
```
<%= render :partial => "name_of_partial", :locals => { :some_var => @data_from_model } %>
```
```
Then, inside your partial, you'd have access to @data_from_model via the some_var variable.


Question:
Not sure what's going on here.

I have a DateTime object, and when I try:

String.Format( "{0:dd/MM/yyyy}", _date)

the value returned is:

"24-05-1967"

What I want is

"24/05/1967"

Can anyone explain why my format string is being ignored?

A bit more background:
This is a web app which started out life as .net 1.1, and I'm in the process of moving it up to 2.0/3.5.

Update:

If I change the format to {0:dd:MM:yyyy}, it returns 24:05:1967 - it's only the / in the format string that gets changed to the - char.

Resolution:

When updating the app to run under 2.0, the asp.net globalization settings were messed up.

From the web site properties, ASP.NET tab, Edit Configuration, Application Tab - the culture and UI Culture were both set to the first item in the list (af-ZA) for some bizarre reason.

Answer:
You likely want to use the
ToString()
method of your DateTime object to get the string representation you are after. A format string of
"dd'/'MM'/'yyyy"
will give you the format you described. Note that you need to escape literal characters in the format string using single quotes.
Example:
```
DateTime.Now.ToString("dd'/'MM'/'yyyy");
```


Question: How do I setup a class that represents an interface?  Is this just an abstract base class?

Answer:
Make a class with pure virtual methods. Use the interface by creating another class that overrides those virtual methods.
A pure virtual method is a class method that is defined as virtual and assigned to 0.
```
```
class IDemo
{
    public:
        virtual ~IDemo() {}
        virtual void OverrideMe() = 0;
};

class Child : public IDemo
{
    public:
        virtual void OverrideMe()
        {
            // do stuff
        }
};
```
```


Question:
Let's say we're tracking the end-user IP for a web service:

ip = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If ip = "" Then
    ip = Request.ServerVariables("REMOTE_ADDR")
End If

I've read that this is the best method of retrieving end-user IP because it works even for users on a transparent proxy.

If we're using the end-user IP address to filter malicious users, are there are any security implications with the above method instead of, say, just using Request.ServerVariables("REMOTE_ADDR")?

For example, if we banned a malicious user by end-user IP, could they easily change their IP via a proxy and continue using our web service?

Thanks in advance for your help.

Answer:
```
REMOTE_ADDR
```
is generated by the web server based on the connection from the client.
```
HTTP_X_FORWARDED_FOR
```
is based on a HTTP header sent by the client.
You can't trust input from the client, particularly input that is easily faked, such as HTTP headers.  Clients can stick
anything
into that
```
HTTP_X_FORWARDED_FOR
```
header.


Question:
Simple question:

How do I do this on one line:

my $foo = $bar->{baz};
fizz(\$foo);

I've tried \$bar->{baz}, \${$bar->{baz}}, and numerous others.  Is this even possible?

-fREW

Update: Ok, the hashref is coming from DBI and I am passing the scalar ref into template toolkit.  I guess now that I look more closely the issue is something to do with how TT does all of this.  Effectively I want to say:

$template->process(\$row->{body}, $data);

But TT doesn't work that way, TT takes a scalar ref and puts the data there, so I'd have to do this:

$template->process(\$row->{body}, $shopdata, \$row->{data});

Anyway, thanks for the help.  I'll at least only have one reference instead of two.

Answer:
I am not even sure what you are doing.
You also should put quotes around baz.
Now let's consider that you assign a scalar to the scalar in the first line then the second line should work.
However I don't really know if this is what you are trying here and it does not really make sense in Perl.
Using references is often used in other languages to
speed up a function call
allow multiple values to be returned.
Now the first is usually not needed with scalars and anyway Perl is a script language so if you are really concerned about speed write C.
The second is not needed in Perl as you can return lists and references to anonymous hashes quite easy.
Have you looked at "man perlref"?


Question:
I have a generic list of objects in C#, for example sake, here's what the object might be.

public class Thing {
    public string Name { get; set; }
    public DateTime EditDate { get; set; }
}

var things = new List<Thing>();

Now I want to call:

thing.Sort((t1, t2) => t1.EditDate.CompareTo(t2.EditDate));

However, some of my EditDate properties are null.  I want these objects with a null EditDate property to show up at the top of my list (i.e. closer to the zero index).  How can I do this?

Answer:
List has a
sort function
that takes a delegate.
Now that I've read the question
```
```
TheList.Sort(int delegate(Type a, Type b)
{
    if (a.memeber == null) return -1;
    if (b.memeber == null) return 1;
    if (a.memeber<b.memeber) return -1;
    if (b.memeber<a.memeber) return 1;
    return 0;
}
```
```


Question:
I have to do some work for college and my professor likes to torture us with Nassi-Shneiderman diagrams.

Has anyone a good editor/graphcial tool to draw these? Requirements:

cross platform (or able to run within wine)

open source (or a least free to for private use)

--

After considering some editors, I ended up by using Strutorizer from http://structorizer.fisch.lu/

It hasn't the best usability but it's good enough. And it's written in Java.

Answer:
You can download a free trial copy of
SmartDraw
, which can edit Nassi-Schneiderman diagrams, or there's the free
Nassi-Shneiderman Diagram-Editor
.
EDIT:
How to draw Nassi-Shneiderman diagrams with SmartDraw


Question:
I have developed a web application using internationalization best practices such as putting all my displayable strings in property files, etc, etc.

I would like to have the strings in the property files translated into 5 different languages.

Does anyone have any experience using Mechanical Turk or another crowd sourcing service for language translation?

The reason I don't want to just hire a translation company or service is because I want to eventually have ongoing content fed into the translation service via an API.

My Google results for more information on this topic were surprisingly dismal.  Any links or pointers are appreciated.

Answer:
I don't have any experience crowd-sourcing translations, but my advice would be to find some dependable freelance translators in your target languages (check out Proz.com), and keep going back to them every time you have new content. Application UIs are notoriously difficult to localize because of lack of context in the resource files, and so you want someone who understands the application and is able/willing to test the localized version. Each of the localizations will undoubtedly reveal i18n bugs as well, so there is likely to be a bit of back and forth the first time around. I guess my point is that you don't want arms-length relationships with your translators; they should feel like an extension of your team.
Anyway, bravo for internationalizing your application. Good luck!


Question:
I have a list control in Flex that has been data bound to an e4x xml object from an HTTPService.

I would now like to have a button that clears the list, how can I do this?

I have tried:

list.dataProvider = null;

which does not seem to work, I have also tried:

list.dataProvider = {};

which clears the items but leaves [object,object] as the first item in the list...

Answer:
I don't have any experience crowd-sourcing translations, but my advice would be to find some dependable freelance translators in your target languages (check out Proz.com), and keep going back to them every time you have new content. Application UIs are notoriously difficult to localize because of lack of context in the resource files, and so you want someone who understands the application and is able/willing to test the localized version. Each of the localizations will undoubtedly reveal i18n bugs as well, so there is likely to be a bit of back and forth the first time around. I guess my point is that you don't want arms-length relationships with your translators; they should feel like an extension of your team.
Anyway, bravo for internationalizing your application. Good luck!


Question:
As I continue my quest of learning functional programming, I've come
to wonder if there may be alternatives to my default "procedural" way
of thinking. To be more specific, I'm looking at a function I
wrote. Here is what it does:

Swap two elements of an unordered list of numbers, such that one of the elements
 is now in the right place
Add the sum of the swapped values to an accumulated total
Repeat until list is sorted

So, right now I'm using a standard loop* with an accum variable to do
the above. It works fine and all, and there's certainly nothing wrong
with iteration in real life, but as the point of this exercise is to
expand my way of thinking, I'm curious if there is a more functional
approach to the above algorithm.

Thanks!

*(Actually recursion, but whatever)

Answer:
I don't have any experience crowd-sourcing translations, but my advice would be to find some dependable freelance translators in your target languages (check out Proz.com), and keep going back to them every time you have new content. Application UIs are notoriously difficult to localize because of lack of context in the resource files, and so you want someone who understands the application and is able/willing to test the localized version. Each of the localizations will undoubtedly reveal i18n bugs as well, so there is likely to be a bit of back and forth the first time around. I guess my point is that you don't want arms-length relationships with your translators; they should feel like an extension of your team.
Anyway, bravo for internationalizing your application. Good luck!


Question: Sometimes software installers force you to scroll to the end of the EULA before the “I agree” box is enabled.  How can I produce the same effect on a web page?

Answer:
```
```

        <form>
            <textarea id="agreetext" rows="8" cols="40">Long agreement</textarea>

            <input type="checkbox" id="agreebox" value="true"/> I agree

            <input type="submit" value="Continue"/>
        </form>

```
```


Question:
My question is similar to "What is the difference between include and extend in Ruby?".

What's the difference between require and include in Ruby?  If I just want to use the methods from a module in my class, should I require it or include it?

Answer:
What's the difference between
  "include" and "require" in Ruby?
Answer:
The include and require methods do
  very different things.
The require method does what include
  does in most other programming
  languages: run another file. It also
  tracks what you've required in the
  past and won't require the same file
  twice. To run another file without
  this added functionality, you can use
  the load method.
The include method takes all the
  methods from another module and
  includes them into the current module.
  This is a language-level thing as
  opposed to a file-level thing as with
  require. The include method is the
  primary way to "extend" classes with
  other modules (usually referred to as
  mix-ins). For example, if your class
  defines the method "each", you can
  include the mixin module Enumerable
  and it can act as a collection. This
  can be confusing as the include verb
  is used very differently in other
  languages.
Source
So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use
```
require
```
.
Oddly enough, Ruby's
```
require
```
is analogous to C's
```
include
```
, while Ruby's
```
include
```
is almost nothing like C's
```
include
```
.


Question:
How do I setup an Ant task to generate a Findbugs report when the source folder has many jars in it?

I'm looking for a worked example of the ant task required to output the fancy HTML from a folder containing multiple jars

Answer:
What's the difference between
  "include" and "require" in Ruby?
Answer:
The include and require methods do
  very different things.
The require method does what include
  does in most other programming
  languages: run another file. It also
  tracks what you've required in the
  past and won't require the same file
  twice. To run another file without
  this added functionality, you can use
  the load method.
The include method takes all the
  methods from another module and
  includes them into the current module.
  This is a language-level thing as
  opposed to a file-level thing as with
  require. The include method is the
  primary way to "extend" classes with
  other modules (usually referred to as
  mix-ins). For example, if your class
  defines the method "each", you can
  include the mixin module Enumerable
  and it can act as a collection. This
  can be confusing as the include verb
  is used very differently in other
  languages.
Source
So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use
```
require
```
.
Oddly enough, Ruby's
```
require
```
is analogous to C's
```
include
```
, while Ruby's
```
include
```
is almost nothing like C's
```
include
```
.


Question: what is the best way to track and lower GDI windows handles . .

Answer:
Personally I use
IARSN TaskInfo
to see the number of handles my program uses, GDI included. As for lowering the number of active handles, then I would look at what in your application is using handles.
Things like (but not limited to):
Pens
Bitmaps
Controls (I don't think all of them uses handles)
Do you have a specific problem with too many handles, or perhaps even a handle leak?


Question:
I'm trying to get distinct results using the Criteria API in NHibernate. I know this is possible using HQL, but I would prefer to do this using the Criteria API, because the rest of my app is written using only this method. I found this forum post, but haven't been able to get it to work. Is there a way with the criteria API to get distinct result sets?

Edit: In doing this, I also wanted to exclude the Primary Key column, which is also an identity, and get the remaining distinct records. Is there a way to do this? As it is, the distinct records are returning duplicates because the primary key is unique for each row, but all other fields are the same.

Answer:
Cannot see the forum post at this moment (broken link?), so maybe this is not the answer, but you can add a DistinctRootEntityResultTransformer:
```
```
session.CreateCriteria(typeof(Product)
    .Add(...)
    .SetResultTransformer(new DistinctEntityRootTransformer())
```
```


Question:
I am trying to set the margin of an object from JavaScript. I am able to do it in Opera & Firefox, but the code doesn't work in Internet Explorer.

Here is the JavaScript I have:

function SetTopMargin (ObjectID, Value)
{
    document.getElementById(ObjectID).style.marginTop =  Value.toString() + "px";
}

And it is called like this:

SetTopMargin("test_div_id", 100);

So does anyone know some code that will work in Internet Explorer?

Answer:
[Updated in 2016] On all current browsers (including IE8+), your code
```
```
document.getElementById(ObjectId).style.marginTop = Value.ToString() + 'px';
```
```
works fine.
On
very old
IE (< 8) versions, you must use this non-standard contraption instead:
```
```
document.getElementById(ObjectId).style.setAttribute(
   'marginTop', Value.ToString() + 'px');
```
```
EDIT
- From deleted comment by OP:
Note that while you can use style.setAttribute('margin-top', ..) in current IEs, 8 and older require style.setAttribute('marginTop', ..)


Question:
The two key event argument classes KeyEventArgs and PreviewKeyDownEventArgs each have two properties, KeyCode and KeyData, which are both of the enumeration type Keys.

What is the difference between these two properties? Do the values in them ever differ from each other?  If so, when and why?

Answer:
```
KeyCode
```
is an enumeration that represents all the possible keys on the keyboard.
```
KeyData
```
is the
```
KeyCode
```
combined with the modifiers (Ctrl, Alt and/or Shift).
Use
```
KeyCode
```
when you don't care about the modifiers,
```
KeyData
```
when you do.


Question: Server 2008 machine with SP1, Visual Studio 2008 with SP1. My user; Developer, is in the local Administrators group. That said, some actions I perform in Visual Studio (use the properties window of a web application to invoke the creation of a virtual directory in local IIS) tell me that Admin privileges are required. It is an annoyance more than anything, I can just launch VS with right click (Run As Administrator) to perform the action -  but I was curious if anyone knows why this happens?

Answer:
Because that's how it works, I guess... It doesn't matter the group your user is in, what matters is if the application is running with admin privileges or not. If it is, than you will be able to perform admin actions, otherwise you won't.
All applications that use UAC to perform admin actions (when you see the security badge) they will either a) restart the application with admin privileges or b) launch a process with admin privileges to perform the respective action. They will never be able to grant you admin privileges without launching a process with them.
That's just the way it works really. As far as I know, this is how it works...


Question:
I need to display 2d images in opengl using textures.

The image dimensions are not necessarily powers of 2.

I thought of creating a larger texture and restricting the display to the part I was using but the image data will be shared with openCV so I don't want to copy data a pixel at a time into a larger texture.

EDIT - it turns out that even the simplest Intel on board graphics under Windows supports none-power-of-2 textures.

EDIT2 - and even if you don't have arb texture size, then making your image smaller and rescaling to the window size it is very fast even on low end hardware

Answer:
First of all, most modern videocards actually support texture dimensions that are both non-square and non-power-of-two sized. But for maximum compatibility, using only power of two textures is probably recommended.
Start off by determining the closest power of two that is larger for each of the image dimensions (width and height) and creating a texture of that size.
Then you have two options. The first one is to do a software resize of the pixel data to fit the image, and then size your quad according to the original aspect ration when you need to display it. Or, you can just fill part of the texture with your image data and put transparent pixels in the rest.


Question:
I'm generating titles out of a few other fields, and want the "right" way to do:

Me.Title.Value = Join(Array([Conference], [Speaker], partstr), " - ")

Except any of [conference], [speaker] or partstr might be null, and I don't want the extra "-"'s.  Are there any functions that'll make this job straightforward?

Answer:
Nope - you'll have to check each one and then cleanup at the end
```
```
Dim Temp As String

If Not IsNull([Conference]) Then
  Temp = Temp & [Conference] & " - "
End If

If Not IsNull([Speaker]) Then
  Temp = Temp & [Speaker] & " - "
End If

If Not IsNull(partstr) Then
  Temp = Temp & partstr & " - "
End If

If Temp > "" then
  Me.Title.Value = Left(Temp, Len(Temp) - 3)
Else
  Me.Title.Value = Null
End If
```
```
Revised with generic function:
```
```
Public Function JoinEx(ByVal pArray As Variant, ByVal pDelimiter As String) As String

  Dim sTemp As String
  Dim iCtr As Integer

  For iCtr = 0 To UBound(pArray)
    If Not IsNull(pArray(iCtr)) Then
      sTemp = sTemp & pArray(iCtr) & pDelimiter
    End If
  Next

  If sTemp > "" Then
   JoinEx = Left(sTemp, Len(sTemp) - Len(pDelimiter))
  End If

End Function
```
```
Calling Example:
```
```
JoinEx(Array("one","two","three"), " - ")  'Returns "One - Two - Three"
 JoinEx(Array(null,"two","three"), " - ")  'Returns "Two - Three"
```
```


Question:
Is it possible to cast an object in Java to a combined generic type?

I have a method like:

public static <T extends Foo & Bar> void doSomething(T object) {
    //do stuff
}

Calling this method is no problem if I have a class that implements both interfaces (Foo & Bar).

The problem is when I need to call this method the object I need to pass to it is received as java.lang.Object and I need to cast it to make the compiler happy. But I can't figure out how to make this cast.

edit:

The problem lies in a function like this:

public void problemFunction (Object o) {
  if ( o instanceof Foo && o instanceof Bar) {
      doSomething((Problematic cast) o);
  }
}

}

Answer:
Unfortunately, there is no legal cast that you can make to satisfy this situation. There must be a single type known to implement all of the interfaces that you need as bounds, so that you can cast to it. The might be a type you create for the purpose, or some existing type.
```
```
interface Baz extends Foo, Bar { }

public void caller(Object w) {
  doSomething((Baz) w);
}
```
```
If other types are known, like
```
Baz
```
, to meet the bounds, you could test for those types, and have a branch in your caller that calls
```
doSomething
```
with a cast to those types. It's not pretty.
You could also use delegation, creating your own class
```
Baz
```
that meets the bounds required by
```
doSomething
```
. Then wrap the object you are passed in an instance of your
```
Baz
```
class, and pass that wrapper to
```
doSomething
```
.
```
```
private static class FooBarAdapter implements Foo, Bar {
  private final Object adaptee;
  FooBarAdapter(Object o) {
    adaptee = (Foo) (Bar) o;
  }
  public int flip() { return ((Foo) adaptee).flip(); }
  public void flop(int x) { ((Foo) adaptee).flop(x); }
  public void blort() { ((Bar) adaptee).blort(); }
}

public void problemFunction (Object o) {
  doSomething(new FooBarAdapter(o));
}
```
```


Question:
I'm trying to assert that one object is "equal" to another object.

The objects are just instances of a class with a bunch of public properties. Is there an easy way to have NUnit assert equality based on the properties?

This is my current solution but I think there may be something better:

Assert.AreEqual(LeftObject.Property1, RightObject.Property1)
Assert.AreEqual(LeftObject.Property2, RightObject.Property2)
Assert.AreEqual(LeftObject.Property3, RightObject.Property3)
...
Assert.AreEqual(LeftObject.PropertyN, RightObject.PropertyN)

What I'm going for would be in the same spirit as the CollectionEquivalentConstraint wherein NUnit verifies that the contents of two collections are identical.

Answer:
Override .Equals for your object and in the unit test you can then simply do this:
```
```
Assert.AreEqual(LeftObject, RightObject);
```
```
Of course, this might mean you just move all the individual comparisons to the .Equals method, but it would allow you to reuse that implementation for multiple tests, and probably makes sense to have if objects should be able to compare themselves with siblings anyway.