Question:
Is it possible to create an integer (or DataTime, etc) column in ListView? It is quite important, because I would like to properly sort the list according to this column.

The only way to add subItems to a ListViewItem I found are:

listviewitem.SubItems.Add("1");

I would like to avoid parsing these strings to get the int representation for every sort!

Answer:
Rather than that you just add strings to the list and receive strings by using
```
.Text
```
property.
Example:
```
```
int a = 0;
listView1.Items.Add(a.ToString());
```
```
or
```
```
int a = Convert.ToInt32(listView1.Items[0].SubItems[0].Text);
```
```
You can do this same with
```
DataTime
```
and other datatypes, just by converting them to
```
String
```
type.
How you interpret the column containing i.e dates it fully depends of you.
Just implement your algorithm of sorting particular
```
ListView
```
column.


Question:
I can query the AD and find all the IIS sites and their virtual directories, now I need to be able to update those home directories and save the changes.

After I fetch the directory entry I can display the site path using $site.Path, however setting it doesn't seem to have any effect.  It never changes the actual stored path.

I have tried $site.Path = <new path> and $site.Put( "Path", <new path> ) but neither have these seem to be affecting the stored path.

    $site = $iis.psbase.children |
        where {$_.keyType -eq "iiswebserver"} |
        where {$_.psbase.properties.servercomment -eq $siteConfig.name };

    $s = [ADSI]($site.psbase.path + "/ROOT");
    $s.Path
    # $s.Path = $siteConfig.path
    # $s.Put("Path", $siteConfig.path )
    $s.psbase.CommitChanges()

Answer:
Ok, I tried this and it seems to work:
```
```
$s.psbase.properties.path[0] = $siteConfig.path
    $s.psbase.CommitChanges()
```
```
Is there a better cleaner way of handling this?


Question:
I don't understand why one method would work and the other would throw a NoMethodError if they come from the same lib file.

# app/views/bunnies/show.html.erb
<% if logged_in? %>
  <%= current_user.login %> |
  <%= link_to 'Logout', logout_path %> |
  <% if authorized? %>
    <%= link_to 'Edit Details', edit_bunny_path(@broker) %> |
  <% end %>
  <%= link_to 'Back', bunnies_path %>
<% end %>

... throws a NoMethodError for authorized?.  If I comment that if block out, the page works fine (with logged_in?).

# lib/authenticated_system.rb
def logged_in?
  !!current_user
end

def authorized?
  current_user.login == "admin"
end

# app/controllers/application.rb
class ApplicationController < ActionController::Base
  include AuthenticatedSystem
end

What gives?

Answer:
Right, so I still  don't understand why that wasn't working, but I have found an alternative solution.
(1) Leave authenticated_system.rb as is.
(2) Add a helper method to controllers/application.rb:
```
```
helper_method :is_admin?
def is_admin?
  if logged_in? && current_user.login == "admin"
    true
  else
    false
  end
end
```
```
(3) Use the helper method instead of
```
authorized?
```
.  If anyone would like to explain why the original code wasn't working, I'm all ears!
(Thanks to
this post
)


Question:
I am compiling a legacy C code here and there is a lot of variables and struct members named "interface", but VC2008 express is complaining about these, do you know how to disable this?

I already changed settings to compile the code only as a C code, but no effect on this.

Answer:
Do a
```
```
#define interface QQInterface
```
```
before your code (eg. in the header file), this way everywhere where the keyword interface is used, the compilers sees "QQInterface", which is not a keyword. If all code includes this define, you will not get compiler or linker errors.


Question:
If I have the following setting in my app.config file.  It is a setting I need to make sure my WCF client can negotiate the default proxy server.

<system.net>
    <defaultProxy enabled="true" useDefaultCredentials="true"></defaultProxy>
</system.net>

Unfortunately, I can't add to the app.config file in my environment.  How do I ensure these settings by setting them at runtime?

Answer:
Whatever the defined name of your executable (not a library dll) assembly is,  add a ".config" at the end...
so if your executable is to be
AcmeWidgets.EastCoast.MyApplicationName.exe
Then the app.config will get renamed to
AcmeWidgets.EastCoast.MyApplicationName.exe.config
However, I wouldn't recommend you attempt to dynamically change these settings (in the config file on disk)  at runtime...
instead, can you code your app so that it instead populates and uses static variables from these config settings... and then implement the dynamic "change the value" functionality so that it changes these static variables...
This way you can still "affect" the runtime behavior dynamically, but avoid the hassle of writing to the config file, and Ops management can manage the "default" values in the config file by editing it...


Question:
I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema.  How do I do this in Python?

I'd prefer something using the standard library, but I can install a third-party package if necessary.

Answer:
lxml provides etree.DTD
from the tests on
http://lxml.de/api/lxml.tests.test_dtd-pysrc.html
```
```
...
root = etree.XML(_bytes("<b/>"))
dtd = etree.DTD(BytesIO("<!ELEMENT b EMPTY>"))
self.assert_(dtd.validate(root))
```
```


Question:
To implement data access code in our application we need some framework to wrap around jdbc (ORM is not our choice, because of scalability).

The coolest framework I used to work with is Spring-Jdbc. However, the policy of my company is to avoid external dependencies, especially spring, J2EE, etc.
So we are thinking about writing own handy-made jdbc framework, with functionality similar Spring-jdbc: row mapping, error handling, supporting features of java5, but without transaction support.

Does anyone have experience of writing such jdbc wrapper framework?
If anyone has experience of using other jdbc wrapper frameworks, please share your experience.

Thanks in advance.

Answer: Spring-JDBC is fantastic.  Consider that for an open source project like Spring the down side of external dependency is minimized.  You can adopt the most stable version of Spring that satisfies your JDBC abstraction requirements and you know that you'll always be able to modify the source code yourselves if you ever run into an issue -- without depending on an external party.  You can also examine the implementation for any security concerns that your organization might have with code written by an external party.


Question:
We're trying to send an image of a large SWF file to a server to have it mailed out and we're having a bit of trouble with transmission time.

The SWF is about 900px x 600px and restricted to AS2 so we've been using this Bitmap Exporter class. We've tried using several different ways to transmit the data; base10, base36 and base128 but none of them will send the file in any kind of timely manner.

Right now we're dealing with 60-120 seconds per image which isn't acceptable.

Has anyone any advice for dealing with either this class or another for sending large bitmap data to a server with flash?

Thank you for your time.

Answer:
The reason you get such long upload times is that the image is barely compressed (or not at all depending on how the class is implemented). 900 by 600 pixels at 16 bpp (or whatever it now is flash uses) amounts to something like 1.5mb of raw data.
I'm doubtful that there are any useful compression libraries for AS2, but that
may
be a possible path.
The easiest way to make the image smaller on the client side would be lowering the resolution. Are you using the full resolution once it reaches the server? If not that might be a possible way.
(I guess you're aware that this would be way easier using AS3, then you could compress the whole image as a jpeg clientside without very much effort, but I guess the rest of your application is AS2 making that a somewhat moot point)


Question:
My current project involves deploying an upgraded .exe file that runs as a Windows Service.  In order to overwrite the existing .exe with the new version, I currently need to:

Stop the service

Uninstall the service

Reboot the system (so Windows releases it's hold on the file)

Deploy the new .exe

Reinstall the service

Start the upgraded service.

I'd like to avoid the reboot, so that this can be a fully scripted/automated upgrade.

Is there any way to avoid rebooting?  Maybe a command-line tool that will force Windows to give up it's death grip on the old .exe?

Answer:
Are you not able to stop the service before the update (and restart after the update) using the commands below?
```
```
net stop <service name>
net start <service name>
```
```
Whenever I'm testing/deploying a service I'm able to upload files without reinstalling as long as the service is stopped.  I'm not sure if the issue you are having is different.


Question: What is the most direct and/or efficient way to convert a char[] into a CharSequence?

Answer:
A
```
String
```
is a
```
CharSequence
```
.  So you can just create a new
```
String
```
given your
```
char[]
```
.
```
```
CharSequence seq = new String(arr);
```
```


Question: I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?

Answer:
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript.  JSON is not only lighterweight but easier to make in javascript.  Check out
JSON-PHP
for parsing JSON.
You might want to take a look at
Creating JSON Data in PHP


Question:
I'd like to write a plugin that does something with the currently edited file in Eclipse. But I'm not sure how to properly get the file's full path.

This is what I do now:

IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput().
    getAdapter(IFile.class);

Now I have an IFile object, and I can retrieve it's path:

file.getFullPath().toOSString();

However this still only gives me the path relative to the workspace. How can I get the absolute path from that?

Answer:
Looks like you want
```
IResource.getRawLocation()
```
.  That returns an
```
IPath
```
, which also has a
```
makeAbsolute()
```
method if you want to be doubly sure you've got an absolute path.


Question: When issuing an HTTP DELETE request, the request URI should completely identify the resource to delete. However, is it allowable to add extra meta-data as part of the entity body of the request?

Answer:
The spec
does not explicitly forbid or discourage it, so I would tend to say it is allowed.
Microsoft sees it the same way (I can hear murmuring in the audience), they state in the MSDN article about the
DELETE Method of ADO.NET Data Services Framework
:
If a DELETE request includes an entity body, the body is ignored [...]
Additionally here is what
RFC2616
(HTTP 1.1) has to say in regard to requests:
an
entity-body
is only present when a
message-body
is present (section 7.2)
the presence of a
message-body
is signaled by the inclusion of a
```
Content-Length
```
or
```
Transfer-Encoding
```
header (section 4.3)
a
message-body
must not be included when the specification of the request method does not allow sending an
entity-body
(section 4.3)
an
entity-body
is explicitly forbidden in TRACE requests only, all other request types are unrestricted (section 9, and 9.8 specifically)
For responses, this has been defined:
whether a
message-body
is included depends on both request method
and
response status (section 4.3)
a
message-body
is explicitly forbidden in responses to HEAD requests (section 9, and 9.4 specifically)
a
message-body
is explicitly forbidden in 1xx (informational), 204 (no content), and 304 (not modified) responses  (section 4.3)
all other responses include a message-body, though it may be of zero length  (section 4.3)


Question:
Does anyone know a good tool that can be run on a page (for asp.net, for example) to help to minimize the footprint size of the page?

The page will have typical items: HTML, Javascript, etc.

I've heard of Javascript crunchers in the past, that will make the size of the code as compact as possible (and obfuscate it, I suppose).

The goal is to help optimize the page size (make it as small as possible for speed, without changing anything).

Is this possible?

Answer:
Well, its not a automatic cleaner-upper, but I like
YSlow
for optimizing pages.  And the
YUI Compressor
can minify your javascript.
If you're really interested in javascript, the keyword is "minify".
Also, look at this question just posted:
HTML and stuff
Hope that helps!


Question: What's the difference between java.lang.ref.WeakReference and java.lang.ref.SoftReference ?

Answer:
Weak references are collected eagerly. If GC finds that an object is
weakly reachable (reachable only through weak references), it'll clear the
weak references to that object immediately. As such, they're good for
keeping a reference to an object for which your program also keeps
(strongly referenced) "associated information" somewere, like cached
reflection information about a class, or a wrapper for an object, etc.
Anything that makes no sense to keep after the object it is associated
with is GC-ed. When the weak reference gets cleared, it gets enqueued in a
reference queue that your code polls somewhere, and it discards the
associated objects as well. That is, you keep extra information about an
object, but that information is not needed once the object it refers to
goes away. Actually, in certain situations you can even subclass
WeakReference and keep the associated extra information about the object
in the fields of the WeakReference subclass. Another typical use of
WeakReference is in conjunction with Maps for keeping canonical instances.
SoftReferences on the other hand are good for caching external, recreatable resources
as the GC typically delays clearing them. It is guaranteed though that all
SoftReferences will get cleared before OutOfMemoryError is thrown, so they
theoretically can't cause an OOME[*].
Typical use case example is keeping a parsed form of a contents from a
file. You'd implement a system where you'd load a file, parse it, and keep
a SoftReference to the root object of the parsed representation. Next time
you need the file, you'll try to retrieve it through the SoftReference. If
you can retrieve it, you spared yourself another load/parse, and if the GC
cleared it in the meantime, you reload it. That way, you utilize free
memory for performance optimization, but don't risk an OOME.
Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If
on the other hand you mistakenly use SoftReference for a task a WeakReference is meant
to be used (namely, you keep information associated with an Object somehow
strongly referenced, and discard it when the Reference object gets
cleared), you can run into OOME as your code that polls the ReferenceQueue
and discards the associated objects might happen to not run in a timely
fashion.
So, the decision depends on usage
- if you're caching information that is expensive to construct, but
nonetheless reconstructible from other data, use soft references
- if you're keeping a reference to a canonical instance of some data, or
you want to have a reference to an object without "owning" it (thus
preventing it from being GC'd), use a weak reference.


Question:
This is a design question and good practice question.  How do you structure your Java web development such that a lot of logic is not in the JSP file.  Should you use any of the JSP tags for if structures or loops.  I see a lot of code where the logic is hard to follow because of poorly designed JSP files.  And then when you want to output to a different format like a PDF or XML document, you can't do it because all the logic is in the JSP file.

Are there any tips or practices that you follow for Java Web development.

I am currently using a combination of Spring, Hibernate, Struts...and work with some Servlet code.

There are good practices associated with Java development.  Many of us that have worked a while know them.  What are some good practices for JSP development.

Answer:
The easiest way to avoid placing logic in JSPs is simply to perform all that logic
before
forwarding a request to a JSP. The only logic you should need to do in a JSP is some basic looping (e.g. for creating HTML table rows), evaluating conditional statements, and data formatting.
All of this can be done without using scriptlet code (Java code) in the JSPs by using JSP tag libraries and EL. The most important tag library is
JSTL
. The JSTL tag library provides most of the logic you should ever need to perform in a view, though you may occasionally also use niche 3rd party tag libraries like
displaytag
which can reduce the amount of JSP code you need to write for specific tasks.


Question:
I'm trying to put in an exception in my web.config so that one page does not require authentication.  However, it still redirects to the login page.

The question isn't how to setup the web.config.  Why?  Our system (for better or worse) has a bunch of instrumentation besides the web.config.  We have global.asax and custom HttpHandlers.  The code base isn't huge, but there's a lot of potential causes for the redirect.

What I do want to know is how to best determine the cause of the redirect.  Is there some way to find out what code triggered the redirect?

Answer:
Have you tried turning on Tracing?  That may help.
How are you specifying the page doesn't require authentication, like:
```
```
<system.web>
...
</system.web>

<location path="NoAuthNeeded.aspx">
    <system.web>
        <authorization>
        <allow roles="*" />
        <allow roles="?" />
        </authorization>
    </system.web>
</location>
```
```


Question:
Once it is compiled, is there a difference between:

delegate { x = 0; }

and

() => { x = 0 }

?

Answer:
Short answer : no.
Longer answer that may not be relevant:
If you assign the lambda to a delegate type (such as
```
Func
```
or
```
Action
```
) you'll get an anonymous delegate.
If you assign the lambda to an Expression type, you'll get an expression tree instead of a anonymous delegate.  The expression tree can then be compiled to an anonymous delegate.
Edit:
Here's some links for Expressions.
System.Linq.Expression.Expression(TDelegate)
(start here).
Linq in-memory with delegates (such as System.Func) uses
System.Linq.Enumerable
.  Linq to SQL (and anything else) with expressions uses
System.Linq.Queryable
.  Check out the parameters on those methods.
An
Explanation from ScottGu
.  In a nutshell, Linq in-memory will produce some anonymous methods to resolve your query.  Linq to SQL will produce an expression tree that represents the query and then translate that tree into T-SQL.  Linq to Entities will produce an expression tree that represents the query and then translate that tree into platform appropriate SQL.


Question: I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?

Answer:
Python provides a debugger which allows you to step through your code, inspect variables and manipulate them. Refer to
http://pythonconquerstheuniverse.wordpress.com/category/python-debugger/
which can take you over the steps...
Also check the python standard library reference for pdb
http://www.python.org/doc/2.5.2/lib/module-pdb.html


Question:
In the Linux kernel, given the task_struct's mm I can access the process's list of vm_area_structs. Given these vm_area_structs, how do I get the struct pages which actually correspond to this vma?

I tried looking for functions in mm/memory.c and the like, but I was at a loss.

Edit: the idea is to find which pages in the vma are currently in memory and which are not. But I don't want someone telling me how to do this bit, as that's a small part of a homework assignment that I need to figure out on my own. But I can't seem to figure out how to find the pages that correspond to this vma. If I can find the pages, I figure I can check to see if they have a valid pfn or not.

Answer:
From your comment to another answer (edit: the other answer seems to have been deleted), it seems you want to read from user space. The function to get the user space pages would be
```
get_user_pages()
```
, but that is most probably not what you want; you probably want
```
copy_from_user
```
/
```
copy_to_user
```
.


Question: I've been given the task of working with SAML to implement an SSO solution between my company and a third party provider.  My only issue is that I can't seem to find how to implement SAML in C# 2.0.  I've been able to find a few examples for .Net 3.0 and 3.5, but none for 2.0 (and the classes they use don't appear to be available in 2.0).  Does anyone know of any oline examples using SAML and C# 2.0?

Answer: Unless you can find a third party implementation, you are going to have to upgrade beyond v2.0. Probobly not what you want to hear, sorry...


Question:
I need to do transactions (begin, commit or rollback), locks (select for update).
How can I do it in a document model db?

Edit:

The case is this:

I want to run an auctions site.

And I think how to direct purchase as well.

In a direct purchase I have to decrement the quantity field in the item record, but only if the quantity is greater than zero. That is why I need locks and transactions.

I don't know how to address that without locks and/or transactions.

Can I solve this with CouchDB?

Answer:
No.  CouchDB uses an "optimistic concurrency" model.  In the simplest terms, this just means that you send a document version along with your update, and CouchDB rejects the change if the current document version doesn't match what you've sent.
It's deceptively simple, really.  You can reframe many normal transaction based scenarios for CouchDB. You do need to sort of throw out your RDBMS domain knowledge when learning CouchDB, though.  It's helpful to approach problems from a higher level, rather than attempting to mold Couch to a SQL based world.
Keeping track of inventory
The problem you outlined is primarily an inventory issue.  If you have a document describing an item, and it includes a field for "quantity available", you can handle concurrency issues like this:
Retrieve the document, take note of the
```
_rev
```
property that CouchDB sends along
Decrement the quantity field, if it's greater than zero
Send the updated document back, using the
```
_rev
```
property
If the
```
_rev
```
matches the currently stored number, be done!
If there's a conflict (when
```
_rev
```
doesn't match), retrieve the newest document version
In this instance, there are two possible failure scenarios to think about.  If the most recent document version has a quantity of 0, you handle it just like you would in a RDBMS and alert the user that they can't actually buy what they wanted to purchase.  If the most recent document version has a quantity greater than 0, you simply repeat the operation with the updated data, and start back at the beginning.  This forces you to do a bit more work than an RDBMS would, and could get a little annoying if there are frequent, conflicting updates.
Now, the answer I just gave presupposes that you're going to do things in CouchDB in much the same way that you would in an RDBMS.  I might approach this problem a bit differently:
I'd start with a "master product" document that includes all the descriptor data (name, picture, description, price, etc).  Then I'd add an "inventory ticket" document for each specific instance, with fields for
```
product_key
```
and
```
claimed_by
```
.  If you're selling a model of hammer, and have 20 of them to sell, you might have documents with keys like
```
hammer-1
```
,
```
hammer-2
```
, etc, to represent each available hammer.
Then, I'd create a view that gives me a list of available hammers, with a reduce function that lets me see a "total".  These are completely off the cuff, but should give you an idea of what a working view would look like.
Map
```
```
function(doc)
{
    if (doc.type == 'inventory_ticket' && doc.claimed_by == null ) {
        emit(doc.product_key, { 'inventory_ticket' :doc.id, '_rev' : doc._rev });
    }
}
```
```
This gives me a list of available "tickets", by product key.  I could grab a group of these when someone wants to buy a hammer, then iterate through sending updates (using the
```
id
```
and
```
_rev
```
) until I successfully claim one (previously claimed tickets will result in an update error).
Reduce
```
```
function (keys, values, combine) {
    return values.length;
}
```
```
This reduce function simply returns the total number of unclaimed
```
inventory_ticket
```
items, so you can tell how many "hammers" are available for purchase.
Caveats
This solution represents roughly 3.5 minutes of total thinking for the particular problem you've presented.  There may be better ways of doing this!  That said, it does substantially reduce conflicting updates, and cuts down on the need to respond to a conflict with a new update.  Under this model, you won't have multiple users attempting to change data in primary product entry.  At the very worst, you'll have multiple users attempting to claim a single ticket, and if you've grabbed several of those from your view, you simply move on to the next ticket and try again.
Reference:
https://wiki.apache.org/couchdb/Frequently_asked_questions#How_do_I_use_transactions_with_CouchDB.3F


Question:
I am trying to call a Actionscript function from javascript but I am having problems in Internet Explorer.
I am using Swiff.remote in mootools 1.2.1 to call the actionscript function ie:

Swiff.remote(playSwf.toElement(), 'sendResult', result, plays, name);

This all works fine in FireFox, Safari and Opera but I'm getting an "unspecified" error in Internet Explorer 6 and 7.
I have tried using the bog standard:

window['flash'].sendResult(result, plays, name);

To no avail.

Thanks for any help.
Mark

Answer:
I'm not familiar with the Swiff plugin, but you don't need a plugin to call flash functions from Javascript. It's even easier to do it natively.
From AS:
```
```
//1. calling javascript function from Flash.
ExternalInterface.call("sendData",tempStr);
// argument 1: javascript function, argument 2: data/variables to pass out.
//2. calling javascript function from Flash with recursion.
var returnValue:String = ExternalInterface.call("sendReturn",tempStr).toString();
//3. setting up a callback function for javascript
ExternalInterface.addCallback("callFlash",flashResponse);
// argument 1: function name called by javascript, argument 2: function on the Flash side.
// AS2 version looks like this : ExternalInterface.addCallback("callFlash",null,flashResponse);
```
```
From JS:
```
```
//1. javascript function as called from Flash.
function sendData(val){
    alert(val);
    document.flashForm.flashOutput.value = val;
}

//2. javascript function with recursion.
function sendReturn(val){
    var tempData = "Hello from JS";
    return tempData + ' :return';
}

//3. calling Flash function with javascript.
function sendToFlash(val){
    window['flash'].callFlash(val);
}
```
```


Question:
I searched and found this question but did not like the answer.

Is there another way to get SVN to ignore config files that are checked in in-place (that you cannot check-in changed), but must be modified on your system.

This is a pretty severe failure of SVN, my first disappointment with the system actually.  What I'm hoping for is that someone out there figured out a trick, perhaps with branching just the config files onto a new branch while leaving everything else pointing at the original branch.  Perhaps modifying the .svn directory?

There must be a better solution then template/copy, that seems so unmaintainable.

Answer:
After messing around for a few hours I think I have an answer.  Since it's my own question, I guess I'll make it community wiki...
I created a branch of the entire repository and pointed the "Config" type files at the new branch, then checked them in.
I'm not sure how this will play out, but it made the "Check everything in" stuff work correctly.  I think if I change one of those files it'll work fine, checking it into my local repository.
The only thing that could be annoying is if someone else changes a file that I have branched, I'm not sure how I'll identify the fact that I'm supposed to merge.


Question:
I recently started facelets development, and a couple of days ago made my first useful custom tag. Now I would like to have auto-completion support in eclipse, like I have for standard taglibs like h, c and ui.

Is there any easy way (less than 30 min work) to enable tool support for custom tags?

I'm using eclipse 3.4 with jboss tools.

Answer:
What version of Eclipse are you using?
My current version (Version: 3.4.0, Build id: I20080617-2000, with WTP)has autocompletion for any taglib added as a directive on my JSP page (even if the current JSP file does a
```
<%@ include file="..." %>
```
to the actual file with the taglib declarations in it), even the non-standard ones.
For example, Eclipse will autocomplete any
```
<form:blah>
```
tags for me if I have the following declaration:
```
```
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
```
```


Question:
I have an existing application written in Perl. Now I need to integrate this application with OBI. The plan is having a button the user can click on to open OBI in an iframe. OBI resides on a different server from the running application.

Has anyone done this before, know what is the best practice for doing this, and what is the effort of doing this?

Another question is is it possible to add customizations to the OBI displayed in the iframe.?

Answer:
There are two ways to address the problem that I know of and tried out.  According to your needs, one or the other might be more appropriate (or both, they're not mutually exclusive).  In both cases, the documentation is good and readily available.
The "Go URL"
The Go URL is documented more thoroughly in the Oracle Business Intelligence Presentation Services Administration Guide. It provides a quick and easy interface to the reports you've already defined, in the form of a URL.  All that's needed to get it running is to fill in a few query parameters to direct to the report you want.  You might need to include authentication tokens too.
Pros: very easy to try out.
Cons: harder to get security right.
The web services
The presentation server comes with a series of web services that enable a more programmatic way of querying your repository.  The functionality offered through this channel goes further: for example most catalog management, including report creation and editing is possible.  The full list fills a guide of its own: the Oracle Business Intelligence Web Services Guide.
Pros: better integration (i.e., no need for an IFRAME); easier to get the security right.
Cons: harder to setup; lots of XML; more advanced features (e.g. in-place drilldown) need an HTTP bridge that was a bitch to get right in my case.  The generated HTML might clash a bit with yours and require cleaning up, notably in the CSS.


Question:
I'm executing several discrete queries in a single batch against SQL Server. For example:

update tableX set colA = 'freedom';

select lastName from customers;

insert into tableY (a,b,c) values (x,y,z);

Now, I want to capture the result in a DataSet (from select statement) which is easy enough to do...but how do I also capture the "meta" response from that command similar to the way Query Analyzer/SQL Mgt Studio does when it displays the "Messages" tab and diplays something similar to:

(1 Row affected)
(2 Rows Updated)

Answer:
My suggestion would be to use the @@rowcount variable for this.  Usually, when I'm doing these kind of commands, if I want to trap both the potential error and the rows affected, I do
```
```
declare @rowsAffected int, @error int

select * from sometable
     select @rowsAffected = @@rowcount, @error = @@error

if @@error <> 0 goto errorCleanup
```
```


Question: In Mootools, I'd just run if ($('target')) { ... }.  Does if ($('#target')) { ... } in jQuery work the same way?

Answer:
no, jquery always returns a jquery object regardless if a selector was matched or not.
You need to use .length
```
```
if ( $('#someDiv').length ){

}
```
```


Question:
I'd like to have my Eclipse plugin cause a URL to be opened by the users' default browser. This seems like pretty standard behavior, but I haven't been able to find any docs on how to do this.

Can anyone help?

Answer:
Do you mean launch an external windows (IE, FireFox, ...) outside eclipse, or opening an internal "
Browser
" composite ?
Because on the internal side, the
org.eclipse.help.ui.internal.browser.embedded.EmbeddedBrowser
seems to be able to define any kind of major browser.
To open the default user's browser (as an internal or external window) is a preference defined in General/Web browser.


Question:
I'm reloading a web page that has the following code:

<label for="showimage">Show Image</label>
<input id="showimage" name="showimage" type="checkbox" value="1" />

Even though the HTML stays sent to the browser is the same for each reload of the page, the checkbox always takes on the checked value when a reload was performed.  In other words, if the user checks the checkbox and reloads, the checkbox is still checked.

Is there some caching going on here?

Edit: I tried Gordon Bell's solution below and find that this is still happening even after removing the value="1".  Anything else I might be missing?

<label for="showimage">Show Image</label>
<input id="showimage" name="showimage" type="checkbox" />

Answer:
Yes, I believe it is caching. I see this behaviour on Firefox for example (not Safari, for what that's worth :) ).
you can reload the page and bypass the cache (on Firefox) using
CTRL
-
SHIFT
-
R
and you'll see the check value doesn't carry (a normal
CTRL
-
R
will grab the info from the cache however)
edit
: I was able to disable this server side on Firefox, setting a cache control header:
```
```
Cache-Control: no-store
```
```
this seems to disable the "remember form values" feature of Firefox


Question:
I'm trying to setup an alert to let me know via email (SMTP) when free disk space on one of my servers is less than a specified value. To do this I'm using PerfMon alerts, as described at MSFT Technet. I have the alert working and writing to the system log, but when I try to set it to 'Run Program' it fails. The log alert fires but the program fails.

The program I'm using is a small C# app I wrote to send an smtp email. I have tested the app independently from this server, running it manually and it works fine, without any user interaction (console app). But when I have it set to run via the alert trigger it fails.

Answer:
Yes, I believe it is caching. I see this behaviour on Firefox for example (not Safari, for what that's worth :) ).
you can reload the page and bypass the cache (on Firefox) using
CTRL
-
SHIFT
-
R
and you'll see the check value doesn't carry (a normal
CTRL
-
R
will grab the info from the cache however)
edit
: I was able to disable this server side on Firefox, setting a cache control header:
```
```
Cache-Control: no-store
```
```
this seems to disable the "remember form values" feature of Firefox


Question:
In linux, if I have a file I'm sharing with a group, and I put the file on a USB memory stick, for example, and copy it to a computer that doesn't have the same group or users, does the file have no permissions for anyone on that new computer?  What if I bring a linux file that only lets user X to read it to a windows machine?  Who gets to read it on the windows machine? since user X (and group) doesn't exist on that machine.

What kind of security do I get copying a linux file to another linux machine? how about to a windows machine?

What kind of security do I get copying a windows file to another windows machine?  how about to a linux machine?

Please let me know.

jbu

Answer:
Regarding the USB key: generally, USB keys use one of the FAT family of filesystems; FAT doesn't support security at all, so as soon as you copy the file to it the security information is lost. So for your first question, anyone who has the USB key can read it on any computer from any user account. It is possible to format USB keys using another filesystem (for example, NTFS, which does support security); in that case, if the accounts (in Windows, at least, it must be a domain account or similar, just naming two accounts the same will not do it) do not exist on the target computer, only a user who can ignore filesystem permissions (such as root on *nix or Administrator on Windows) will be able to access the file.
For the second, I'm not 100% sure but I believe it depends on how you copy it; things like FTP and rcp generally don't copy permissions over, so I would assume that the file gets some kind of default permissions for the target directory, or a default built into the copy program, depending on what the copy program does.
For windows, to the best of my knowledge the security descriptor is initially inherited from the target folder; permissions are, again, not persisted across machines. It can be modified after the copy.
In general, except in specific environments that are designed to transfer permissions, I would assume that transferring any file from one computer to another resets the security permissions to a default (generally whatever a
new
file in that location would receive).


Question:
I'm writing an HTTP Cache library for Java, and I'm trying to use that library in the same application which is started twice. I want to be able to share the cache between those instances.

What is the best solution for this? I also want to be able to write to that same storage, and it should be available for both instances.

Now I have a memory-based index of the files available to the cache, and this is not shareable over multiple VMs. It is serialized between startups, but this won't work for a shared cache.

According to the HTTP Spec, I can't just map files to URIs as there might be a variation of the same payload based on the request. I might, for instance, have a request that varies on the 'accept-language' header: In that case I would have a different file for each subsequent request which specifies a different language.

Any Ideas?

Answer:
I think you should have a look at the
WebDav-Specifications
. It's an HTTP extension for sharing/editing/storing/versioning resources on a server. There exists an implementation as an
Apache module
, wich allows you a swift start using them.
So instead of implementing your own cache server implementation, you might be better off with a local Apache + mod-dav instance that is available to both of your applications.
Extra bonus: Since WebDav is a specified protocoll you get the interoperability with lots of tools for free.


Question:
CodeIgniter allows access to POSTed data via:

$this->input->post('input_name');

where 'input_name' is the name of a form field. This works well for a static form where each input name in known ahead of time.

In my case, I am loading a collection of key/value pairs from the database. The form contains a text input for each key/value pair.

I am wondering, is there a way to get an array of posted data via the CodeIgniter api?

Thanks!

Answer:
According to the documentation, no. I would suggest just using
```
array_keys($_POST)
```
to get the keys.


Question: I am using a ResourceDictionary, but I would like to be able to look up the value or the key with the other item.  Each is always unique, so that is not a problem.  Is there a type that has this double sided lookup feature?

Answer:
Not built in, but this is pretty easy to write.  I would probably implement IDictionary for this though...  You would then dump the ResourceDictionary into your custom type.
```
```
public class DoubleLookup<TKey, TValue>
{
  private IDictionary<TKey, TValue> keys;
  private IDictionary<TValue, TKey> values;

  //stuff...

  public void Add(TKey key, TValue value)
  {
    this.keys.Add(key, value);
    this.values.Add(value, key);
  }

  public TKey GetKeyFromValue(TValue value)
  {
    return this.values[value];
  }

  public TValue GetValueFromKey(TKey key)
  {
    return this.keys[key];
  }

}
```
```


Question:
How can I center an image horizontally and aligned to the bottom of the container at the same time?

I have been able to center the image horizontally by its self. I have also been able to align the bottom of the container by its self. But I have not been able to do both at the same time.

Here is what I have:

.image_block {
    width: 175px;
    height: 175px;
    position: relative;
    margin: 0 auto;
}
.image_block a img {
position: absolute;
bottom: 0;
}

<div class="image_block">
    <a href="..."><img src="..." border="0"></a>
</div>

That code aligns the image to the bottom of the div. What do I need to add/change to make it also center the image horizontally inside the div? The image size is not known before hand but it will be 175x175 or less.

Answer:
Remove the
```
position: relative;
```
line. I'm not sure why exactly but it fixes it for me.


Question:
The following code works for me:

var webProxy = WebProxy.GetDefaultProxy();
webProxy.UseDefaultCredentials = true;
WebRequest.DefaultWebProxy = webProxy;

Unfortunately, WebProxy.GetDefaultProxy() is deprecated.  What else should I be doing?

(using app.config to set the defaultProxy settings is not allowed in my deployment)

Answer:
From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.
The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.
If you wanted to use
different proxy settings
to the current user then you would need to code
```
```
WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);
```
```
or
```
```
WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);
```
```
You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call
```
webRequest.Proxy.GetProxy(new Uri("http://google.com.au"))
```
to see the actual details of the proxy server that would be used.
There seems to be some debate about whether you can set
```
webRequest.Proxy
```
or
```
WebRequest.DefaultWebProxy = null
```
to prevent the use of any proxy. This seems to work OK for me but you could set it to
```
new DefaultProxy()
```
with no parameters to get the required behaviour. Another thing to check is that if a
proxy element
exists in your applications config file, the .NET Framework will
NOT
use the proxy settings in Internet Explorer.
The MSDN Magazine article
Take the Burden Off Users with Automatic Configuration in .NET
gives further details of what is happening under the hood.


Question:
I have a string of test like this:

<customtag>hey</customtag>

I want to use a RegEx to modify the text between the "customtag" tags so that it might look like this:

<customtag>hey, this is changed!</customtag>

I know that I can use a MatchEvaluator to modify the text, but I'm unsure of the proper RegEx syntax to use. Any help would be much appreciated.

Answer:
I'd chew my own leg off before using a regular expression to parse and alter HTML.
Use
XSL
or
DOM
.
Two comments have asked me to clarify.  The regular expression substitution works in the specific case in the OP's question, but in general regular expressions are not a good solution.  Regular expressions can match
regular languages
, i.e. a sequence of input which can be accepted by a finite state machine.  HTML can contain nested tags to any arbitrary depth, so it's not a regular language.
What does this have to do with the question?  Using a regular expression for the OP's question as it is written works, but what if the content between the
```
<customtag>
```
tags contains other tags?  What if a literal
```
<
```
character occurs in the text?  It has been 11 months since Jon Tackabury asked the question, and I'd guess that in that time, the complexity of his problem may have increased.
Regular expressions are great tools and I do use them all the time.  But using them in lieu of a real parser for input that needs one is going to work in only very simple cases.  It's practically inevitable that these cases grow beyond what regular expressions can handle.  When that happens, you'll be tempted to write a more complex regular expression, but these quickly become very laborious to develop and debug.  Be ready to scrap the regular expression solution when the parsing requirements expand.
XSL and DOM are two standard technologies designed to work with XML or XHTML markup.  Both technologies know how to parse structured markup files, keep track of nested tags, and allow you to transform tags attributes or content.
Here are a couple of articles on how to use XSL with C#:
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
http://www.csharphelp.com/archives/archive78.html
Here are a couple of articles on how to use DOM with C#:
http://msdn.microsoft.com/en-us/library/aa290341%28VS.71%29.aspx
http://blogs.msdn.com/tims/archive/2007/06/13/programming-html-with-c.aspx
Here's a .NET library that assists DOM and XSL operations on HTML:
http://www.codeplex.com/Wiki/View.aspx?ProjectName=htmlagilitypack


Question:
Are there any issues with changing elements which will appear on a web page within a thread. I am from a windows programming background and obviously if a thread needs to change the GUI in some way you have to delegate it to the GUI thread.

Basically my page uses 3 sql queries which can be run concurrently to obtain the page data. So I setup 3 threads and have them run, if one fails or has no records it makes an error message visible about it, this is currently done within the thread and seems to work.

Note: The 3 sql queries are for very different data it is definitely fastest to run 3 separate queries and running them at the same time makes it even faster (In terms of how long it takes the page to display).

Edit: The threads are joined in the page load event

Answer: You're going to have to join all 3 threads before rendering the page.  Once it's rendered out, there's no updating it.


Question:
I'm working on some Silverlight controls and I would like to explicitly handle the way they appear in Blend.
Specifically, these controls have dependencies that are initialized at runtime, and thus throw exceptions in the designer. But even in the absence of the exception, I would like to make them appear a certain way in Blend.

I know that this is possible with WPF (using myassembly.VisualStudio.Design.dll), but I haven't been able to find info on doing this with Silverlight.

I have seen the hack described here that checks does this:

bool designTime = (System.Windows.Browser.HtmlPage.IsEnabled == false);

I would prefer a more explicit solution though.

Answer:
There is an extremely detailed post on
how to deal with design time extensibility here
. There you will find out how to do the Visual Studio and Blend design time stuff for Silverlight.
Control vendors and people who author custom controls often find themselves wishing they could give a better experience for their custom controls.
  However, there’s a huge lack of public information on this topic. And I’ve decided to correct this situation with this short 50+ pages article.
Like I said, it's long. :)


Question:
I have got a template class as follows:

class MyClass<T>
{
    T field;
    public void myMethod()
    {
       field = new T(); // gives compiler error
    }
}

How do I create a new instance of T in my class?

Answer:
After type erasure, all that is known about
```
T
```
is that it is some subclass of
```
Object
```
. You need to specify some factory to create instances of
```
T
```
.
One approach could use a
```
Supplier<T>
```
:
```
```
class MyClass<T> {

  private final Supplier<? extends T> ctor;

  private T field;

  MyClass(Supplier<? extends T> ctor) {
    this.ctor = Objects.requireNonNull(ctor);
  }

  public void myMethod() {
    field = ctor.get();
  }

}
```
```
Usage might look like this:
```
```
MyClass<StringBuilder> it = new MyClass<>(StringBuilder::new);
```
```
Alternatively, you can provide a
```
Class<T>
```
object, and then use reflection.
```
```
class MyClass<T> {

  private final Constructor<? extends T> ctor;

  private T field;

  MyClass(Class<? extends T> impl) throws NoSuchMethodException {
    this.ctor = impl.getConstructor();
  }

  public void myMethod() throws Exception {
    field = ctor.newInstance();
  }

}
```
```


Question:
In C# if I want to convert a double (1.71472) to an int then I get the answer 2.  If I do this in Java using intValue() method, I get 1 as the answer.

Does Java round down on conversions?

Why do the Java API docs have such scant information about their classes i.e.

Returns the value of the specified
  number as an int. This may involve
  rounding or truncation.

A bit more info about the rounding would have been helpful!

Answer:
Java rounds toward zero when narrowing from a floating point to an integer type.
There's more documentation about the general rules in the
Java Language Specification
. Note that while the documentation in
```
Number
```
leaves options open for subclasses, the documentation on the concrete boxing types is more explicit:
Returns the value of this Double as an
  int (by casting to type int).
When using
BigDecimal
, you can specify one of eight different rounding policies.


Question: I am writing a text editor for Mac OS X.  I need to display hidden characters in an NSTextView (such as spaces, tabs, and special characters).  I have spent a lot of time searching for how to do this but so far I have not found an answer.  If anyone could point me in the right direction I would be grateful.

Answer:
Have a look at the NSLayoutManager class. Your NSTextView will have a layout manager associated with it, and the layout manager is responsible for associating a character (space, tab, etc.) with a glyph (the image of that character drawn on the screen).
In your case, you would probably be most interested in the
```
replaceGlyphAtIndex:withGlyph:
```
method, which would allow you to replace individual glyphs.


Question:
Where is the best documentation of ffmpeg and libavcodec?

It appears that ffmpeg supports many undocumented options that it is very hard to find a good reference.

Answer:
One of the things that can be quite useful:
```
```
ffmpeg -formats
```
```
lists all the codecs and containers that can be used...I haven't found any other good place where these can be found, probably because they depend on what libraries your ffmpeg copy was built with.  This page (
http://ffmpeg.mplayerhq.hu/general.html
) has some of them, but don't tell you what to enter at the command line.
Also, howto-pages.org has a decent tutorial here:
http://howto-pages.org/ffmpeg/


Question:
I have 2 tables, an active table and an inactive table. I want to move rows from the active to the inactive table. My first thought was

insert into inactive select * from active where ...
delete from active active where ...

However about .42 seconds later I noticed this will drop/duplicate rows if updates alter what the where clause selects.

In this case, I can easily prevent that but what should I do in cases where I can't?

edit: From the answers it look like there isn't an easy/trivial way to do this. I'm really surprised by this. I would think that there would be some substantial benefits to having it.

Answer:
Status flags are your friend.
```
```
UPDATE old_data SET move="MARKED";
INSERT INTO somewhere... SELECT where move="MARKED";
DELETE FROM old_data WHERE move="MARKED";
```
```
If you do this with Autocommit off, it will seize locks all over the place.
You can COMMIT after each step, if you want to do a little less locking.


Question:
I'm trying to develop some SharePoint workflows for the company I work for, and I'm not too familiar with the ins and outs of the technology.  Normally when I want to familiarize myself with something, I just play with it, look at the properties, find all the methods, etc.

When I fire up Visual Studio and try to create a SharePoint workflow, it gives me an error indicating I don't have a reference to "Microsoft.SharePoint.dll". Someone told me that it was normal to see that because you have to do all your development on the SharePoint Server itself if you want to do workflows.  Is this true?

If so, is there anyone out there that has successfully developed SharePoint workflows in a multi-developer environment without resorting to any "hacks"??  Thank you for reading and your responses...

Answer:
Yes, you have to do all your development on a the SharePoint server itself.  Consider using a virtual machine and package up features that you can deploy to your staging and production environments.
http://weblogs.asp.net/erobillard/archive/2007/02/23/build-a-sharepoint-development-machine.aspx
http://www.wssdemo.com/Pages/EntDev.aspx


Question: We were working on a design, and for that we created the skeleton of the classes in our main branch.  Now, we are starting to code, and for that we got a new branch.  So, it would be nice if I can move all the new files in the main branch into the new branch.  However, I cannot check them in yet.  So, is it possible to integrate the checked out changelist?  Thanks.

Answer:
I never found a way to do that within perforce, but you can at least partially automate it.
Usually when I had to do something like that I'd check out the files in the branch I want to move things to, then use
WinMerge
to diff the branches and copy the changes over.  Once that's done you can revert the changes in the original branch and check them in in the new branch.
It's not the best solution (no automatic checkout/add/delete of files on the new branch), but was the fastest method I came up with.


Question: Recently there has been quite some hype around all the different mocking frameworks in the .NET world. I still haven't quite grasped what is so great about them. It doesn't seem to be to hard to write the mocking objects I need myself. Especially with the help of Visual Studio I quickly can write a class that implements the interface I want to mock (it auto-generates almost everything for me) and then write an implementation for the method(s) I need for my test. Done! Why going through the hassle of understanding a mocking framework for the sole purpose of saving a few lines of code. Or is a mocking framework not only about saving lines of code?

Answer:
Well I certainly don't think that you NEED a mocking framework. It's a framework like any other, and it's ultimately designed to save you some time and effort. You can also do things like roll your own common data structures like stacks and queues, but isn't it generally easier to just use the ones built into the class libraries that ship with the compiler/IDE of your language of choice?
I'm sure there are other compelling reasons for using mocking frameworks, though I'd leave it to the TDD and unit testing gurus to answer.


Question: Which version of JavaScript does Google Chrome support in relation to Mozilla Firefox?  In other words, does Chrome support JavaScript 1.6, 1.7, or 1.8 which Firefox also supports or some combination of them?

Answer:
Google Chrome supports up to Javascript 1.7:
```
```
<script language="javascript1.7">alert(1.7);</script> - Alerts
<script language="javascript1.8">alert(1.8);</script> - Doesn't alert
```
```


Question: We have 2 flowdocuments that we'd like to compare similar to when using a diff viewer (winmerge, beyond compare, etc).  Has anybody done this or know how to get the text out of a flowdocument to do a compare?

Answer:
Google Chrome supports up to Javascript 1.7:
```
```
<script language="javascript1.7">alert(1.7);</script> - Alerts
<script language="javascript1.8">alert(1.8);</script> - Doesn't alert
```
```


Question:
I want to embed a swf over a html page, like a floating video watching panel. I already have a swf file which will automatically adjust its size according to the browser size, and the swf file is partially transparent. I thought I can just add a div tag, make the position absolute and change z-index bigger, but that doesn't work because the swf just replaced everything that's on the page.

Here's what I did

<script>
      swfobject.embedSWF("swf/float.swf", "header", "100%", "100%", "9.0.0");
</script>

<body bgcolor="#000000">
      <div id="header"></div>
      <div id="shell">
          things in my html
      </div>
</body>

#header {
    position:absolute;
    z-index:100;

}

Any idea? Thanks.

Answer:
I believe the problem with this is that the CSS doesn't work well with
```
<object />
```
tags.  The
```
swfobject.embedSWF
```
turns the
```
<div id="header"></div>
```
into an
```
<object />
```
tag with a bunch of attributes that might be effecting the CSS.  If you create a wrapper DIV around the header DIV and apply the CSS to the wrapper DIV, everything works better.  You also need to add 100% width and height in the CSS.  Here's the revised source:
```
```

        things in my html

#wrapper {
    position:absolute;
    z-index:100;
    width:100%;
    height:100%;
}
```
```


Question:
for the following:

( a != b ) ? cout<<"not equal" : cout<<"equal";

suppose I don't care if it's equal, how can I use the above statement by substituting cout<<"equal" with a no-op.

Answer:
This is very confusing code. You
could
just write
```
```
cond ? cout << "equal" : cout;
```
```
but you won't (will you?) because you've got conventional
```
if
```
for that.


Question:
I am designing a web app and I intent to embed data on an xml island so that I can dynamically render it on an HTML table on the client-side based on options the users will select.

I have the broad concepts, but I need pointers on how to use DOM in navigating my xml. And how to update my xml island possibly for posting back to the server?

Please any links to online resources or a quick advice will be very appreciated.

NB: I understand most of the dynamic HTML concepts and server and client side stuff, so don't shy being very technical in your response:)

Answer:
In
W3C
HTML there are no XML data islands (unless you're referring to external XML file linked via frames loaded using Javascript), but you can re-use HTML elements and insert metadata in
```
class
```
,
```
title
```
(if you care about HTML4 validity),
```
data-*
```
(HTML5) or your custom attributes.
For DOM navigation you've got
DOM Core
, like
```
element.childNodes
```
,
```
.nextSibling
```
,
```
.getAttribute()
```
, etc.
DOM can be verbose and tedious to use (e.g. when looking for elements in DOM you have to be careful to skip text nodes), so there are JS libraries like jQuery and Prototype built on top of it that offer more convenient API.
If you intend to a lot of DOM transformations, then Javascript API for
XPath
and
XSLT processor
will be handy.


Question:
In javascript how do I get a handle on the frame that I'm in based on an element in that frame?

function myFunction(elementInFrame){
   // here I want to get a handle on the frame that elementInFrame lives in
}

Answer:
In IE you can do
```
elementInFrame.document.parentWindow
```
Doesn't work in Firefox unfortunately.
Edit: If you're using frames then in FF you could do it the long way... loop through all the frames until you find the element you're looking for.


Question:
I need to be able to display some data in Eclipse in a grid/table control... I need things like paging, multiple column sorting, column choosing, etc. There is an SWT Table and the Nebula project has a grid in alpha.

Does what I need exist? 3rd party maybe? Doesn't have to be free, we can pay for the functionality.

Answer:
You could use the facilities of table presentation offered by the
BIRT plugin
, that is if you are really advance
table layout needs
.
(source:
theserverside.com
)
(otherwise the classic SWT
TableViewer
offers already some of the feature you are after
(source:
richclient2.eu
)
)


Question:
I've saved an entire webpage's html to a string, and now I want to grab the "href" values from the links, preferably with the ability to save them to different strings later. What's the best way to do this?

I've tried saving the string as an .xml doc and parsing it using an XPathDocument navigator, but (surprise surprise) it doesn't navigate a not-really-an-xml-document too well.

Are regular expressions the best way to achieve what I'm trying to accomplish?

Answer:
Regular expressions are one way to do it, but it can be problematic.
Most HTML pages can't be parsed using standard html techniques because, as you've found out, most don't validate.
You could spend the time trying to integrate
HTML Tidy
or a similar tool, but it would be much faster to just build the regex you need.
UPDATE
At the time of this update I've received 15 up and 9 downvotes.  I think that maybe people aren't reading the question nor the comments on this answer.  All the OP wanted to do was grab the href values.
That's it.
From that perspective, a simple regex is just fine.  If the author had wanted to parse other items then there is no way I would recommend regex as I stated at the beginning, it's problematic at best.


Question: If I have an embedded browser in a windows form, is it possible to initiate a javascript method from the container application?

Answer:
You can use Document.InvokeScript, as outlined in this excellent MSDN article:
How to: Implement Two-Way Communication Between DHTML Code and Client Application Code


Question:
I have an html like this:

<div id="container1">
    <div class="dragme">drag me</div>
</div>
<div id="container2">
    <div class="dragme">drag me</div>
</div>
<div id="droponme"></div>

$(".dragme").draggable();
$("#droponme").droppable({
    accept: ".dragme",
    drop: function(e, u) { alert( /* find id of the container here*/ ); };
});

I want to find the container of the draggable object on drop event handler. How can I do this?

Answer:
```
```
$(".dragme").draggable();
$("#droponme").droppable({
    accept: ".dragme",
    drop: function(e, u) {
        alert(u.draggable.parent().attr('id') );
        // in your example: container1 or container2
    }
});
```
```


Question: What is the differences between those 2 assuming I'm using SQL Server as my database? Are they the same?

Answer:
Long answer: google.
Short answer: using entity framework, you will be able to create something based on classes (partial, that you can "extend") resembling domain objects (not true DDD though, that's why NHibernate still exists and linq to nhibernate is being developed), using sql you will be just thinking database and tables.


Question:
I have a third-party library in my SVN repository and I'd like to associate source/javadoc with it locally in Eclipse. I.e., there should be some local setting (for example, an entry in the local.properties file) that associates the source/javadoc with the JAR file, but which doesn't introduce local dependencies into the repository via .classpath. Ideally I'd have

lib_src_dir = /my/path/to/lib/src

in local.properties and then

<classpathentry kind="lib" path="lib.jar" sourcepath="${lib_src_dir}">

in .classpath. Can this be done?

[EDIT] @VonC's answer is helpful... Is there a way to load Path Variables from a text file (e.g., local.properties) instead of going through Window -> Preferences -> General -> Workspace -> Linked Resources?

Answer:
I believe this would be better achieved through:
the creation of a linked folder combined with
the declaration of a linked resource
The linked resource defines a path variable which would be equals to
```
/my/path/to/lib/src
```
The linked folder would refers to your linked resource
(you can use a variable and not a fixed path, with the "Variable" button)
The variable is actually always local (to one's workspace), and will be modified through the
```
Linked Resources
```
preference screen.
The linked folder can also be... a linked
file
, thus allowing the reference of an archive through a relative path (relative to the variable).
Then this linked file (here a linked archive) can be associated to your
```
classpathentry
```
in the "
```
source
```
" attribute.
The problem with Linked Resources is they are local to the workspace, in the preferences.
You can
export the preferences in a
```
[myPrefs.epf]
```
file
, and then trim the exported file in order to leave only the lines containing
```
pathvariable
```
:
```
```
/instance/org.eclipse.core.resources/pathvariable.MY_DIRECTORY=/my/path/to/lib/src
```
```
Anyone can then import this special preference file, which will only affect the "
```
Linked Resources
```
" part.
That solution is not very satisfying, since the
```
.epf
```
preference file can not be loaded automatically in the project
.
When I setup a project with a linked resources defining a path, I always leave a big
```
README.txt
```
at the root of my project, in order to incite the user of said project to define that same linked resources with his/her own fixed local path.
Several bugs
are in progress to enhance this situation or around the
Linked Resources topic
.
Especially:
Exporting a project with linked resources
Relative paths without variables
Have linked resources relative to workspace paths
Would like to use path relative to workspace root
DevByStarlight
mentions in
the comments
the project (not very active since Oct. 2011)
workspacemechanic
.
The Workspace Mechanic automates maintenance of your Eclipse environment by tweaking preferences, adding extension locations, and so on. You can use it to:
Create a consistent environment among groups as large as the entire company, your local team, or even among your own many workspaces
Save time setting up new workspaces
Create tasks that ensure your favorite new preferences are applied to all your current and future workspaces. (This is one of our favorite features!)
The key to the Workspace Mechanic's behavior is the
```
Task
```
.
A task describes a simple test and an action that, when run, changes the environment so the test will subsequently pass.
```
Tasks
```
can come in many forms: preference files, Java classes, Groovy scripts and Eclipse extensions. You can easily define your own Tasks.
It comes with a collection of scripts:
workspace-mechanic
workspacemechanic-settings


Question: Can anyone tell me how to display all the selected value of my multi value parameter in SSRS report. When giving parameter.value option it gives error.

Answer:
You can use the "Join" function to create a single string out of the array of labels, like this:
```
```
=Join(Parameters!Product.Label, ",")
```
```


Question:
I have a class which has a private member $content. This is wrapped by a get-method:

class ContentHolder
{
    private $content;
    public function __construct()
    {
        $this->content = "";
    }

    public function getContent()
    {
        return $this->content;
    }
}
$c = new ContentHolder();
$foo = array();
$foo['c'] = $c->getContent();

Now $foo['c'] is a reference to content, which is what I don't understand. How can I get the value? Thank You in advance.

Answer:
In PHP, you don't say: "
```
$foo = new array();
```
"
Instead, you simply say: "
```
$foo = array();
```
"
I ran your code (PHP 5.2.6) and it seems to work fine.  I tested it by dumping the array:
```
```
var_dump($foo);
```
```
This outputs:
```
```
array(1) {
  ["c"]=>
  string(0) ""
}
```
```
I can also simple use
```
echo
```
:
```
```
echo "foo[c] = '" . $foo['c'] . "'\n";
```
```
This outputs:
```
```
foo[c] = ''
```
```


Question:
I want to create buttons with icons in Flex dynamically using Actionscript.

I tried this, with no success:

var closeButton = new Button();
closeButton.setStyle("icon", "@Embed(source='images/closeWindowUp.png");

Answer:
I'm assuming you're adding it to the stage?
Also, I think your Embed is missing a close quote / paren.
```
```
closeButton.setStyle("icon", "@Embed(source='images/closeWindowUp.png");
```
```
should be:
```
```
closeButton.setStyle("icon", "@Embed(source='images/closeWindowUp.png')");
```
```


Question:
I'm trying to select the "name" field from the author node in an ATOM feed using LINQ. I can get all the fields I need like so:

XDocument stories = XDocument.Parse(xmlContent);
XNamespace xmlns = "http://www.w3.org/2005/Atom";
var story = from entry in stories.Descendants(xmlns + "entry")
            select new Story
            {
                Title = entry.Element(xmlns + "title").Value,
                Content = entry.Element(xmlns + "content").Value
            };

How would I go about selecting the author -> name field in this scenario?

Answer:
You basically want:
```
```
entry.Element(xmlns + "author").Element(xmlns + "name").Value
```
```
But you might want to wrap that in an extra method so you can easily take appropriate action if either the author or name elements are missing. You might also want to think about what you want to happen if there's more than one author.
The feed might also have an author element... just another thing to bear in mind.


Question:
I have some Jasper reports which are displayed in HTML format. I would like the width of the columns in the HTML tables to automatically resize to fit the content of the widest cell (in that column), such that all the data is displayed.

Currently this does not happen because the HTML generated by Jasper specifies fixed widths for the <table> and some <td> elements, e.g.

<td style="width: 20px; height: 17px;">
  <span style="font-family: Arial; font-size: 11px;">foo-bar-baz@examp</span>
</td>

I can't simply remove all these width properties (using JavaScript), because (as shown in the HTML above) any data that would be hidden when using these widths is not even returned to the client-side

Cheers,
Don

Answer:
While not perfect, you could flag the field to stretch with overflow. This would at least give you all the data. In your jrxml file it would be similar to:
```
```
<textField isStretchWithOverflow="true" hyperlinkType="None">
    <reportElement style="Report Sub-Title" x="0" y="84" width="802" height="20"/>
    <textElement/>
    <textFieldExpression class="java.lang.String">
        <![CDATA["For the period ...]]>
    </textFieldExpression>
</textField>
```
```
I'm afraid I don't know of any feature of Jasper reports that would allow the dynamic resizing of column widths - It is probably one of those things that makes sense for HTML but little sense for other output formats such as PDF.


Question:
i am programatically adding Webcontrols in to a User Control i am also adding a javascript event passing the controlID as a parameter but the clientID is the one i assigned a it does not contain the one that asp.net generates

   var txt = new TextBox();
   txt.ID = "MyID"+Number;

   chkBox.Attributes.Add("onClick", "EnableTxtBox('" +txt.ClientID + "');");

i can workAround this by adding the parent control ID

   chkBox.Attributes.Add("onClick", "EnableTxtBox('" + this.ClientID+"_"+txt.ClientID + "');");

On which Page life cycle are the Client IDs generated?

Answer:
You need to add the control to the control hierarchy before you add the attribute.
```
```
var txt = new TextBox();
   txt.ID = "MyID"+Number;
   Controls.Add ( txt );
   chkBox.Attributes.Add("onClick", "EnableTxtBox('" +txt.ClientID + "');");
```
```
ControlCollection is no ordinary collection; it notifies the owner control when controls are added, and the control can take appropriate actions.


Question:
When I make the same query twice, the second time it does not return new rows form the database (I guess it just uses the cache).

This is a Windows Form application, where I create the dataContext when the application starts.

How can I force Linq to SQL not to use the cache?

Here is a sample function where I have the problem:

public IEnumerable<Orders> NewOrders()
{
    return from order in dataContext.Orders
           where order.Status == 1
           select order;
}

Answer:
The simplest way would be to use a new DataContext - given that most of what the context gives you is caching and identity management, it really sounds like you just want a new context. Why did you want to create just the one and then hold onto it?
By the way, for simple queries like yours it's more readable (IMO) to use "normal" C# with extension methods rather than query expressions:
```
```
public IEnumerable<Orders> NewOrders()
{
    return dataContext.Orders.Where(order => order.Status == 1);
}
```
```
EDIT: If you
never
want it to track changes, then set
ObjectTrackingEnabled
to false before you do anything. However, this will severely limit it's usefulness. You can't just flip the switch back and forward (having made queries between). Changing your design to avoid the singleton context would be much better, IMO.


Question:
I have HTML code edited by FCKEditor stored in a database and would like to display (well render) it onto a view. So, for instance, something stored as:

&lt;&gt;pre&lt;&gt;This is some sample text&lt;&gt;pre&lt;/&gt

Will be displayed to the user as:

This is some sample text

(With the appropriate style for pre-formatted-text)

The view already has the required string to display from ViewData, I'm just not sure what the best way to show it to the user is.

Answer:
Try this:
```
```
<%= System.Web.HttpUtility.HtmlDecode(yourEncodedHtmlFromYouDatabase) %>
```
```
More info
here
.


Question:
I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode.
Apparently urllib.unquote does not support unicode.

Answer:
```
```
def unquote(text):
    def unicode_unquoter(match):
        return unichr(int(match.group(1),16))
    return re.sub(r'%u([0-9a-fA-F]{4})',unicode_unquoter,text)
```
```


Question: I have an application which is fully unicode compatible in Delphi 2006. I had replaced all AnsiStrings with WideStrings, replaced all VCL controls with TNT controls, and changed all string functions from AnsiStrings to WideStrings. It looks like all that work was for nothing, because I'm going to have to reverse it all. Is there anyway to Trick Delphi 2009 into thinking Widestrings are in fact UnicodeStrings?

Answer:
No, there really isn't. But you won't regret the work to truly Unicode enable your application.
The TNT controls can easily be replaced with the regular VCL controls.  You can do that pretty simply using the wizard from GExperts (
http://www.gexperts.org
) that replaces one control type with another automatically.
Then, you can change all your WideString declarations to regular strings.  String is now an alias for UnicodeString, and so all your strings can hold Unicode data just fine.
BTW, the author of the TNT controls, Troy Wolbrink, now vastly prefers Delphi 2009 over his own controls.


Question:
Looking in the gnuwin32/bin directory, there is an odd-looking program file named [.exe

I couldn't find it in the documentation, gnuwin32.sourceforge.net or in a google search, so I ran it and got:

$ [
[: missing `]'
$

so I gave it ] as a parameter and got

$ [ ]

$

It didn't complain, so I assumed it was on the right track. I tried:

$ [ hello ]

again, no complaints. so I tried an arithmetic expression:

$ [ 1 + 1 ]
[: +: binary operator expected
$

I tried a bunch of different combinations, including prefix & postfix notation but nothing seemed to work. What does this thing do?

Answer:
```
```
test a
```
```
==
```
```
[ a ]
```
```
It's just sugar
Edit: To clarify, that's the conditional syntax, e.g. [ "a" = "a" ]


Question:
Observing one year of estimations during a project I found out some strange things that make me wonder if evidence based scheduling would work right here?

individual programmers seem to have favorite numbers (e.g. 2,4,8,16,30 hours)

the big tasks seem to be underestimated by a fix value (about 2) but the standard deviation is low here

the small tasks (1 or 2 hours) are absolutely wide distributed. In average they have the same average underestimation factor of 2, but the standard deviation is high:

some 5 minute spelling issues are estimated with 1 hour

other bugfixes are estimated with 1 hour too, but take a day

So, is it really a good idea to let the programmers break down the 30 hours task down to 4 or 2 hours steps during estimations? Won't this raise the standard deviation? (Ok, let them break it down - but perhaps after the estimations?!)

Answer:
I think it is a good idea. When people break tasks down - they figure out the specifics of the task, You may get small deviations here and there, this way or the other, they may compensate or not...but you get a feeling of what is happening.
If you have a huge task of 30 hours - can take all 100. This is the worst that could happen.
Manage the risk - split down. You already figured out these small deviation - you know what to do with them.
So make sure developers also know what they do and say :)


Question: Why is it bad to check in lines with trailing whitespace to your source control?  What kinds of problems could that cause?

Answer:
False differences, basically. It's helpful if diffs only show "real" changes. Some diff programs will ignore whitespace, but it would be better just to avoid the dummy change in the first place.
Of course, it also doesn't help if it makes the line wrap on a colleague's machine.


Question:
I'm trying to implement paging using row-based limiting (for example: setFirstResult(5) and setMaxResults(10)) on a Hibernate Criteria query that has joins to other tables.

Understandably, data is getting cut off randomly; and the reason for that is explained here.

As a solution, the page suggests using a "second sql select" instead of a join.

How can I convert my existing criteria query (which has joins using createAlias()) to use a nested select instead?

Answer:
You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects.
Simply add this to your criteria:
```
```
criteria.setProjection(Projections.distinct(Projections.property("id")));
```
```
Now you'll get the correct number of results according to your row-based limiting. The reason this works is because the projection will perform the distinctness check
as part of
the sql query, instead of what a ResultTransformer does which is to filter the results for distinctness
after
the sql query has been performed.
Worth noting is that instead of getting a list of objects, you will now get a list of ids, which you can use to hydrate objects from hibernate later.


Question:
I am developing a .NET application which uses a few projects that I've pieced together from other internal projects.  I was thinking about merging the .exe and the DLLS into a single executable file with a tool called ILMerge.

I may be sending the executable outside the company, so merging everything into a single file would be easier to pass out.  But, I was wondering if there are any downsides to merging DLLs with the executable?

Answer:
As long as they're your libraries, I don't think there's any big problem with it. Unless it makes the image absolutely and monstrously huge, I think it's better if the executable relies on itself as much as it can (exceptions being, of course, when you're replicating system functionality... no point in that).
On the other hand, if the libraries don't actually belong to you, you had better make sure that their terms of use allow for this. You may not be allowed to package them up into your executable and distribute them as your own code (even if you give your product away and the library was "free", you may still have to acknowledge that you use it some how so make sure to check the terms of use for
all
the libraries you include).


Question:
From a Java program, I need to launch the default browser on a local HTML file, pointed to an anchor inside the file.  In Java SE 6, the java.awt.Desktop.browse method will open the file, but will not honor the anchor, so something like the following opens the file at the top, but does not page the browser to the anchor:

Desktop.getDesktop("file:///C:/foo/bar.html#anchor");

Sun says here http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6477862 that anchors are not supported in the file URI protocol.

Does anyone have a better answer?

I can use Java SE 6.  I would be OK with a Windows only solution.

Answer:
For Windows only, you could try
```
```
System.exec("cmd.exe start file:///C:/foo/bar.html#anchor")
```
```


Question: Is there really that much of a difference between the performance of Vector and ArrayList?  Is it good practice to use ArrayLists at all times when thread safety isn't an issue?

Answer:
If thread safety is not an issue,
```
ArrayList
```
will be faster as it does not have to synchronize.  Although, you should always declare your variable as a
```
List
```
so that the implementation can be changed later as needed.
I prefer to handle my synchronization explicitly because a lot of operations require multiple calls.  For example:
```
```
if (!myList.isEmpty()) {
    myList.get(0);
}
```
```
should be:
```
```
synchronized (myList) {
   if (!myList.isEmpty()) {
       myList.get(0);
   }
}
```
```


Question:
Is it possible to do a cross table join in mysql spaning different tables? in different databases.

This seem to be easily possible in MSSQL, and greatly speeds up data transfer?

How about mysql, do you need to use a powerful IDE to achieve this? or do you have to write a program to do something like this?

UPDATE tblUser
SET tblUser.ReceiveInfo=old_database.dbo.contact.third_party_info_yn
FROM tblUser inner join old_database.dbo.contact
ON old_database.dbo.contact.id=tblUser.oldid

Answer:
Sure, very easy.  Prefix the table name with the database name, like you show.  We do cross-database joins on a regular basis.  For example:
SELECT COUNT(*) FROM newusers1.users
  JOIN newusers2.users
It certainly won't speed up data transfer compared to having both tables in the same database, though.
Now, if your tables are sitting on different database servers, the answer is no.  An example of this is if your database is too big and you need to shard your tables.  Things get more than a little messy.  But given that you seem to be happy with the MS SQL solution, that does not seem to apply here.


Question: Is there a standard Java library that handles common file operations such as moving/copying files/folders?

Answer:
Not yet, but the
New NIO (JSR 203)
will have support for these common operations.
In the meantime, there are a few things to keep in mind.
File.renameTo
generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.
When a rename doesn't work you will need to actually copy the file (deleting the original with
File.delete
if it's a "move" operation). To do this with the greatest efficiency, use the
FileChannel.transferTo
or
FileChannel.transferFrom
methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.


Question:
I am developing a map control in WPF with C#. I am using a canvas control e.g. 400 x 200 which is assigned a map area of e.g. 2,000m x 1,000m.

The scale of the map would be:  canvas_size_in_meters / real_size_in_meters.

I want to find the canvas_size_in_meters.

The canvas.ActualWidth gives the Width in DIU's (Device Independant Units). So, 400 DIU's is 400/96 = 4,17 inches, PROVIDED that the physical resolution of my monitor is 96 dpi.

However, using a ruler, I found that the physical resolution of my monitor is 87 dpi. (There are only few monitors that ACTUALLY have 96 physical dpi)

That DPI difference (10%) translates to a +10% difference in the actual map control width on screen.

How do I measure the size of a WPF control in inches EXACTLY and regardless of screen resolution and DPI setting ?

Answer:
How do I measure the size of a WPF control in inches EXACTLY and regardless of screen resolution and DPI setting ?
This isn't actually possible, because for it to work, WPF would have to know the resolution (in terms of DPI) of your monitor. Sounds nice in theory, but in practice windows doesn't know this information. This is why windows itself always assumes 96dpi blindly instead of being smarter about it.
Even if there were some way to manually tell it, or if your particular monitor has a custom driver that does pass the correct information to windows, this isn't going to work on anyone else's computer, so windows doesn't pass this information on to any applications.
The best you can do is draw a scale like google maps does. You know that 1
pixel
== 1 mile, so you can draw a 50 pixel line on your map, with a label saying "this line equals 50 miles"


Question: How do get the startup path ( system.windows.forms.application.StartupPath ) of my exe without adding a reference to system.windows.forms?

Answer:
EDIT: @KiwiBastard's answer is the correct method:
```
```
System.AppDomain.CurrentDomain.BaseDirectory
```
```
Add a reference to
```
System.Reflection
```
and use
```
```
Assembly.GetExecutingAssembly().Location
```
```
EDIT: Depending where you intend getting the startup path, this might be more appropriate:
```
```
Assembly.GetEntryAssembly().Location
```
```


Question:
What would be a clever way to make a 'please wait' control for a Flex application for long running operations like calling a webservice.

I am not asking about the graphical portion of it - just the 'controller' part. How should I trigger it and hide it. I am planning to make just a simple canvas with text in.

For instance :

can I somehow intercept all web service calls - and not have to activate it for every web service

how should i add it to my canvas. should it be added to 'stage' as a top level component?

should it have a 'cancel' button to cancel the web service request if it takes too long. that sounds kind of complicated because I'm not even sure if I can terminate a running async web request?

FYI: This is for a reporting application so long running queries are to be expected

Answer:
One way I have done it in the past is to have a global integer and increment / decrement the value based on the web services running. When the counter was 0, I would hide the loading text, when it was greater than 0, I would display the loading text. Here is a simplified version of it:
```
```
<mx:Application>
    <mx:Script>
        [Bindable]public var ws_count:int = 0;
    </mx:Script>
    <mx:Label text = "loading..." visible="{ws_count > 0}" />
</mx:Application>
```
```
I then had a little helper class to control the global counter:
```
```
package ws {
    import mx.core.Application;
    public class WSCounter {
        public static function sent():void {
            Application.application.ws_count += 1;
        }
        public static function receive():void {
            Application.application.ws_count -= 1;
        }
    }
}
```
```
Then all that needs to be done is to call the helper function when a web service is called...e.g:
```
```
import ws.WSCounter;
import mx.rpc.http.HTTPService;

var srv:HTTPService = new HTTPService();
srv.url = "http://localhost/service.py";
srv.addEventListener(ResultEvent.RESULT,function(event:ResultEvent):void {
    WSCounter.receive();
});
srv.send();
WSCounter.sent();
```
```
I always have thought there was a better way to do this, like you said have some type of hook to detect if a service is running...I'm looking forward to other responses in this post...


Question:
I'm writing a direct3d application and after noticing strange bugs such as anti-aliasing occurring even when it was turned off and the mouse pointer not lining up to things with the same coordinates as itself I discovered that when creating a window the width and height parameters include the border.  The program was rendering a 800x600 graphics output to a window of the same size, but because of the borders it was squished into 792x566 rectangle.  I've increased the size of the window to compensate, but this does not work if the system uses a border style other the standard XP style.  (Classic style, for example)

Is there a way to tell what the border width and heights will be before I create the window?

Answer:
It sounds like you are looking for the GetSystemMetrics function.  For example, the border width in pixels is returned by
```
```
GetSystemMetrics(SM_CXBORDER)
```
```
ADDED:
For the total size you will need to add together the various "pieces" of the non-client area: border, frame sizes, title bars, etc.


Question:
I have seen many apps that take instrument classes and take -javaagent as a param when loading also put a -noverify to the command line.

The Java doc says that -noverify turns off class verification.

However why would anyone want to turn off verification even if they are instrumenting classes?

Answer:
Start-up time, I'd say. Verification that classes are correct takes some time when the class is loaded. Since classes might be loaded in a lazy fashion (not on app start, but when being used for the first time), this might cause unexpected and undesired runtime delays.
Actually the class does not need to be checked in general. The compiler will not emit any invalid bytecode or class construct. The reason for verification is that the class may be build on one system, get hosted online and is transmitted to you through the unprotected internet. On this path, a malicious attacker might modify the bytecode and create something the compiler might never create; something that can crash the JVM or possibly circumvents security restrictions. Thus the class is verified before it is used. If this is a local application, there is usually no need to check the bytecode again.


Question:
I'm using a WPF RichTextBox control to input some text with user formatting capability, including font size adjustment.  The built-in commands for IncreaseFontSize and DecreaseFontSize will adjust the font size by 0.75pt each time the command is executed.  I would like to increase the granularity to 2pt.

Can this be done without implementing my own custom commands?

Answer:
Unfortunately the value is hard-coded and you cannot change it. The fastest way to implement this is to use the TextRange class. Something like this:
```
```
var range = new TextRange( rtb.Document.ContentStart, rtb.Document.ContentEnd );
range.ApplyPropertyValue( TextElement.FontSizeProperty, 30.0 );
```
```


Question: How would you use set! in a simple procedure f such that evaluating (+ (f 0) (f 1)) will return 0 if the arguments to + are evaluated from left to right but will return 1 if the arguments are evaluated from right to left?

Answer:
Easiest approach is probably to store some external state and have the implementation of f affect it's contents.
```
```
(define x 0)
(define (f n) (let ((tmp x)) (set! x n) tmp))
```
```
Thus, x is initially 0 and each call to f will return the current value of x and save the argument as the new value of x. Thus (f 0) followed by (f 1) will both return 0, leaving the final x value of 1. While evaluating (f 1) followed by (f 0) will yield 0 then 1, with a final x of 0.


Question:
I know I can loop over the string or build a regex or invert the set (ASCII isn't that big after all) and search for the first instance of that, but Yuck.

What I'm looking for is a nice one liner.

fewer features is better, LINQ is out (for me, don't ask, it's a long story)

The solution I'm going with (unless I see something better)

static int FirstNotMeta(int i, string str)
{
    for(; i < str.Length; i++)
        switch(str[i])
        {
            case '\\':
            case '/':
            case '.':
                continue;
            default:
                return i;
        }
    return -1;
}

OK, I cheated, I know in advance what char's I care about.

Answer:
Not all that efficient, but:
```
```
char f(string str, IEnumerable<char> list)
{
  return str.ToCharArray().First(c => !list.Contains(c))
}
```
```


Question:
I want to insert something into a STL list in C++, but I only have a reverse iterator. What is the usual way to accomplish this?

This works: (of course it does)

std::list<int> l;
std::list<int>::iterator forward = l.begin();
l.insert(forward, 5);

This doesn't work: (what should I do instead?)

std::list<int> l;
std::list<int>::reverse_iterator reverse = l.rbegin();
l.insert(reverse, 10);

Answer:
```
l.insert(reverse.base(), 10);
```
will insert '10' at the end, given your definition of the 'reverse' iterator. Actually,
```
l.rbegin().base() == l.end()
```
.


Question:
How do I launch an app and capture the output via stdout and maybe stderr?

I am writing an automated build system and I need to capture the output to analyze. I'd like to update the svn repo and grab the revision number so I can move the files in autobuild/revNumber/ if successful. I also would like to build using make and upload the compile text to my server for everyone to see the warnings and errors on a failed build.

I can't find the system() function, but I found the CreateProcess() function on MSDN. I am able to launch what I need but I have no idea how to capture the stderr and stdout.  I notice the process launches separately unless I set a breakpoint and keep my app exiting which it then will keep all the text in my app console window. I would also want to wait until all processes are finished and then scan the data it produced to do any additional operations I need. How do I do any of this?

Answer:
In real shells (meaning, not sea shells - I mean, not in C Shell or its derivatives), then:
```
```
program arg1 arg2 >/tmp/log.file 2>&1
```
```
This runs program with the given arguments, and redirects the stdout to /tmp/log.file; the notation (
hieroglyph
) '
```
2>&1
```
' at the end sends stderr (file descriptor 2) to the same place that stdout (file descriptor 1) is going.  Note that the sequence of operations is important; if you reverse them, then standard error will go to where standard output was going, and then standard output (but not standard error) will be redirected to the file.
The choice of file name shown is abysmal for numerous reasons - you should allow the user to choose the directory, and probably should include the process ID or time stamp in the file name.
```
```
LOG=${TMPDIR:-/tmp}/log.$$.$(date +%Y%m%d-%H%M%S)
program arg1 arg2 >$LOG 2>&1
```
```
In C++, you can use the
```
system()
```
function (inherited from C) to run processes.  If you need to know the file name in the C++ program (plausible), then generate the name in the program (
```
strftime()
```
is your friend) and create the command string with that file name.
(Strictly, you also need
```
getenv()
```
to get $TMPDIR, and the POSIX function
```
getpid()
```
to get the process ID, and then you can simulate the two-line shell script (though the PID used would be of the C++ program, not the launched shell).
You could instead use the POSIX
```
popen()
```
function; you'd have to include the '
```
2>&1
```
' notation in the command string that you create to send the standard error of the command to the same place as standard output goes, but you would not need a temporary file:
```
```
FILE *pp = popen("program arg1 arg2 2>&1", "r");
```
```
You can then read off the file stream.  I'm not sure whether there's a clean way to map a C file stream into a C++ istream; there probably is.


Question: I would like to generate documentation for a RESTful web service API that is written in Python. Ideally it would look like Yahoo's RESTful web service docs. Does anyone have any ideas or references?

Answer:
Unfortunately I don't know anything specific that will help you in Python specifically -- However just as points of reference, you might take a peak at the WADL specification that the JAX-RS java spec is using --
https://wadl.dev.java.net/
-- Additionally, there is a xslt that will transform the wadl into html --
http://www.mnot.net/webdesc/
They use the yahoo REST API's as examples.


Question:
I'd like to know how to convert Perforce depot locations to client view locations for the purpose of script writing.

I have a script that first checks out a file for edit in perforce and then interacts with the file.   I need to have the depot location (i.e. \Projects\Project6) converted to the client view location.  (i.e. d:\Projects\Project6).

Is this possible?

Answer:
Check out the
```
p4 have
```
command. You give it
either
a depot location
or
a client filename and it gives you the depot location, client filename,
and
what version of that file you have.


Question:
I have the following code:

for attribute in site.device_attributes
  device.attribute
end

where I would like the code to substitute the value of "attribute" for the method name.

I have tried device."#{attribute}" and various permutations.

Is this completely impossible? Am I missing something?

I have considered overriding method_missing, but I can't figure out how that would actually help me when my problem is that I need to call an "unknown" method.

Answer:
The "send" method should do what you're looking for:
```
```
object = "upcase me!"
method = "upcase"
object.send(method.to_sym) # => "UPCASE ME!"
```
```