Question:
In a silverlight application, I want to access the page the silverlight .xap file from an HTTP subdomain, but have the web services access a different subdomain for sensitive information over HTTPS.

I set up clientaccesspolicy.xml at the root of the subdomain and it lets the silverlight app access its services over http, but not over https.  It gives the cross domain access error that it would give normally without a clientaccesspolicy in place.

I know that browsers themselves have a lot of restrictions about mixing http and https.  Am I trying to do something that is not allowed?

Answer:
Check out:
http://silverlight.net/forums/t/12741.aspx
You can either make https calls to the
  same domain or http cross-domain
  calls, but not https cross-domain
  calls.
This is described in
http://msdn2.microsoft.com/en-us/library/cc189008(VS.95).aspx
(see "If not HTTPS" in the matrix)
  By JohnSpurlock


Question: I'm developing a client/server app that will communicate via rest. Some custom request data will be stored in the header of the request. Both the server sending the request and the receiving server have an SSL certificate - will the headers be encrypted, or just the content?

Answer:
SSL encrypts the entire communications path from the client to the server and back, so yes - the headers will be encrypted.
By the way, if you develop networked applications and care about data security, the least you should do is read a book like Practical Cryptography, by Niels Ferguson and Bruce Schneier, and probably further reading that's more focused on web application security would be a good idea. If I may make an observation - and please, I don't mean that as a personal criticism - your question indicates a fundamental lack of understanding of very basic web security technologies, and that's never a good sign.
Also, it's never a bad idea to confirm that data which is assumed to be encrypted is indeed encrypted. You can use a network analyzer to monitor traffic on the wire and watch out for anything sensitive being sent in the clear. I've used Wireshark to do this before - the results can be surprising, sometimes.


Question:
I have an List and I'd like to wrap it into an IQueryable.

Is this possible?

Answer:
```
```
List<int> list = new List<int>() { 1, 2, 3, 4, };
IQueryable<int> query = list.AsQueryable();
```
```
If you don't see the
```
AsQueryable()
```
method, add a using statement for
```
System.Linq
```
.


Question: If you have a JSF <h:commandLink> (which uses the onclick event of an <a> to submit the current form), how do you execute JavaScript (such as asking for delete confirmation) prior to the action being performed?

Answer:
```
```
<h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}">
    <h:outputText value="#{msgs.deleteText}" />
</h:commandLink>
<script type="text/javascript">
if (document.getElementById) {
    var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />');
    if (commandLink && commandLink.onclick) {
        var commandLinkOnclick = commandLink.onclick;
        commandLink.onclick = function() {
            var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?');
            if (result) {
                return commandLinkOnclick();
            }
            return false;
        }
    }
}
</script>
```
```
Other Javascript actions (like validating form input etc) could be performed by replacing the call to
```
confirm()
```
with a call to another function.


Question:
I have a string that is like below.

,liger, unicorn, snipe

in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?

Thanks.

There's been a lot of back and forth about the StartTrim function.  As several have pointed out, the StartTrim doesn't affect the primary variable.  However, given the construction of the data vs the question, I'm torn as to which answer to accept.  True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data.  So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.

Answer:
```
```
if (s.StartsWith(",")) {
    s = s.Substring(1, s.Length - 1);
}
```
```


Question: How can I start an interactive console for Perl, similar to the irb command for Ruby or python for Python?

Answer:
```
perl -d
```
is your friend:
```
```
% perl -de 0
```
```


Question:
The following will cause infinite recursion on the == operator overload method

    Foo foo1 = null;
    Foo foo2 = new Foo();
    Assert.IsFalse(foo1 == foo2);

    public static bool operator ==(Foo foo1, Foo foo2) {
        if (foo1 == null) return foo2 == null;
        return foo1.Equals(foo2);
    }

How do I check for nulls?

Answer:
Cast to object in the overload method:
```
```
public static bool operator ==(Foo foo1, Foo foo2) {
    if ((object) foo1 == null) return (object) foo2 == null;
    return foo1.Equals(foo2);
}
```
```


Question:
I have a dropdownlist with the autopostback set to true. I want the
user to confirm if they really want to change the value,
which on post back fires a server side event (selectedindexchanged).

I have tried adding an onchange attribute "return confirm('Please click OK to change. Otherwise click CANCEL?';") but it will not postback regardless of the confirm
result and the value in the list does not revert back if cancel
selected.

When I remove the onchange attribute from the DropdownList tag, the page does postback. It does not when the onchange attribute is added. Do I still need to wire the event handler (I'm on C# .Net 2.0 ).

Any leads will be helpful.

Thanks!

Answer:
Make sure your event is wired:
```
```
dropDown.SelectedIndexChanged += new EventHandler(dropDown_SelectedIndexChanged);
```
```
You can also apply a client-side attribute to return the confirmation. Set the index accordingly if cancelled.
```
```
dropDown.Attributes.Add("onchange", "javascript: return confirm('confirmation msg')");
```
```


Question: I've heard people referring to this table and was not sure what it was about.

Answer:
I think this wikipedia article may help clarify.
http://en.wikipedia.org/wiki/DUAL_table
The DUAL table is a special one-row
  table present by default in all Oracle
  database installations. It is suitable
  for use in selecting a pseudocolumn
  such as SYSDATE or USER The table has
  a single VARCHAR2(1) column called
  DUMMY that has a value of "X"


Question:
I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells.  The cells may contain text, numbers or be blank.  I am not very familiar / comfortable working with the concept of 'Range'.  Therefore, any sample codes would be greatly appreciated.  (I did try to google it, but the code snippets I found didn't quite do what I needed)

Thank you.

Answer:
In Excel VBA, this function will give you the content of any cell in any worksheet.
```
```
Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
    getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function
```
```
So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.


Question: How do I tell Subversion (svn) to treat a file as a binary file?

Answer:
For example:
```
```
svn propset svn:mime-type image/png foo.png
```
```


Question: Has anyone run into issues serializing components into a file and reading them back, specifically in the area where the component vendor upgrades the VCL components.  For example a file serialized with DelphiX and then years later read back with delphiY.  Do the serialization formats change and if so what can be done to prevent errors reading in the componets when upgrading.

Answer:
Formats will defintely change, as vendors will add features to their components. Serialization simply loops over all published properties and saves them to a stream. When they are read back, each of the properties that is read from the stream will be set back to the component. If the property does not exist anymore, you have a problem. I don't think you can do anything about that besides some basic exception handling.
Best way to guarantee compatibility is to do your own serialization.


Question: I would like to write small console based applications on Windows Mobile.  What console applications might I use?

Answer:
There is no command prompt style console on Windows Mobile.  If you're really after a command prompt, check out www.pocketdos.com for a high level of dos application compatibility.
If you're more interested in writing small applications for Windows Mobile, C# or VB.Net are your best choices.
On small mobile devices like this, command prompts are significantly harder for users to interact with compared to GUI based applications.


Question:
I'm looking into clustering points on a map (latitude/longitude). Are there any recommendations as to a suitable algorithm that is fast and scalable?

More specifically, I have a series of latitude/longitude coordinates and a map viewport. I'm trying to cluster the points that are close together in order to remove clutter.

I already have a solution to the problem (see here), only I am wondering if there is any formal algorithm that solves the problem efficiently.

Answer:
Google Maps Hacks
has a hack,
"Hack 69. Cluster Markers at High Zoom Levels"
, on that.
Also, see
Wikipedia on clustering algorithms
.


Question: How can I combine multiple PDFs into one PDF without a 3rd party component?

Answer:
AFAIK C# has no built-in support for handling PDF so what you are asking can not be done without using a 3rd party component or a COTS library.
Regarding libraries there is a myriad of possibilities. Just to point a few:
http://csharp-source.net/open-source/pdf-libraries
http://www.codeproject.com/KB/graphics/giospdfnetlibrary.aspx
http://www.pdftron.com/net/index.html


Question:
In a shellscript, I'd like to set the IP of my box, run a command, then move to the next IP. The IPs are an entire C block.

The question is how do I set the IP of the box without editing a file? What command sets the IP on Slackware?

Thanks

Answer:
It should be something like:
```
ifconfig eth0 192.168.0.42 up
```
Replace eth0 by the network interface of your network card, obviously adapt the ip address to your needs and the up is only necessary once, but doesn't hurt if you run it each time.


Question:
In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content.

This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :(

Is there any workaround for this problem?
How can I use CSS to set different widths for dropbox and the dropdownlist?

Answer:
You can add a style directly to the select element:
```
<select name="foo" style="width: 200px">
```
So this select item will be 200 pixels wide.
Alternatively you can apply a class or id to the element and reference it in a stylesheet


Question:
In JavaScript, what is the best way to determine if a date provided falls within a valid range?

An example of this might be checking to see if the user input requestedDate is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.

Answer:
So if i understand currenctly, you need to look if one date is bigger than the other.
```
```
function ValidRange(date1,date2)
{
   return date2.getTime() > date1.getTime();
}
```
```
You then need to parse the strings you are getting from the UI, with Date.parse, like this:
```
```
ValidRange(Date.parse('10-10-2008'),Date.parse('11-11-2008'));
```
```
Does that help?


Question: I am a bit rusty on my cursor lingo in PL/SQL. Anyone know this?

Answer:
An explicit cursor is one you declare, like:
```
```
CURSOR my_cursor IS
  SELECT table_name FROM USER_TABLES
```
```
An implicit cursor is one created to support any in-line SQL you write (either static or dynamic).


Question:
How can I specify the filename when dumping data into the response stream?

Right now I'm doing the following:

byte[] data= GetFoo();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();

With the code above, I get "foo.aspx.pdf" as the filename to save.  I seem to remember being able to add a header to the response to specify the filename to save.

Answer:
```
```
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
```
```


Question: I'm looking for real world best practices, how other people might have implemented solutions with complex domains.

Answer:
This is what
MSDN
has to say about IEqualityComparer (non-generic):
This interface allows the implementation of customized equality comparison for collections. That is, you can create your own definition of equality, and specify that this definition be used with a collection type that accepts the
```
IEqualityComparer
```
interface. In the .NET Framework, constructors of the
```
Hashtable
```
,
```
NameValueCollection
```
, and
```
OrderedDictionary
```
collection types accept this interface.
This interface supports only equality comparisons. Customization of comparisons for sorting and ordering is provided by the
```
IComparer
```
interface.
It looks like the generic version of this interface performs the same function but is used for
```
Dictionary<(Of <(TKey, TValue>)>)
```
collections.
As far as best practices around using this interface for your own purposes.  I would say that the best practice would be to use it when you are deriving or implementing a class that has similar functionality to the above mentioned .NET framework collections and where you want to add the same capability to your own collections.  This will ensure that you are consistent with how the .NET framework uses the interface.
In other words support the use of this interface if you are developing a custom collection and you want to allow your consumers to control equality which is used in a number of LINQ and collection related methods (eg. Sort).


Question:
Is there a way to use sql-server like analytic functions in Hibernate?

Something like

select foo from Foo foo where f.x = max(f.x) over (partition by f.y)

Answer:
You are after a native SQL query.
If you are using JPA the syntax is:
```
```
Query q = em.createNativeQuery("select foo.* from Foo foo " +
                               "where f.x = max(f.x) over " +
                               "(partition by f.y)", Foo.class);
```
```
If you need to return multiple types, take a look at the
SQLResultSetMapping
annotation.
If you're using the the Hibernate API directly:
```
```
Query q = session.createSQLQuery("select {foo.*} from Foo foo " +
                                 "where f.x = max(f.x) over "+
                                 "(partition by f.y)");
q.addEntity("foo", Foo.class);
```
```
See
10.4.4. Queries in native SQL
in the Hibernate documentation for more details.
In both APIs you can pass in parameters as normal using setParameter.


Question:
When using Business Objects' CrystalReportViewer control, how can you detect and manually print the report the user has currently drilled into? You can print this automatically using the Print() method of the CrystalReportViewer, but I want to be able to do a manual printing of this report.

It is possible to print the main ReportSource of the CrystalReportViewer, but I need to know what report the user has drilled into and then do a manual printing of that particular drill down. Any ideas?

Answer:
You are after a native SQL query.
If you are using JPA the syntax is:
```
```
Query q = em.createNativeQuery("select foo.* from Foo foo " +
                               "where f.x = max(f.x) over " +
                               "(partition by f.y)", Foo.class);
```
```
If you need to return multiple types, take a look at the
SQLResultSetMapping
annotation.
If you're using the the Hibernate API directly:
```
```
Query q = session.createSQLQuery("select {foo.*} from Foo foo " +
                                 "where f.x = max(f.x) over "+
                                 "(partition by f.y)");
q.addEntity("foo", Foo.class);
```
```
See
10.4.4. Queries in native SQL
in the Hibernate documentation for more details.
In both APIs you can pass in parameters as normal using setParameter.


Question:
I have a function in Python which is iterating over the attributes returned from dir(obj), and I want to check to see if any of the objects contained within is a function, method, built-in function, etc.  Normally you could use callable() for this, but I don't want to include classes.  The best I've come up with so far is:

isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))

Is there a more future-proof way to do this check?

Edit: I misspoke before when I said: "Normally you could use callable() for this, but I don't want to disqualify classes."  I actually do want to disqualify classes.  I want to match only functions, not classes.

Answer:
```
```
if hasattr(obj, '__call__'): pass
```
```
This also fits in better with Python's "duck typing" philosophy, because you don't really care
what
it is, so long as you can call it.
It's worth noting that
```
callable()
```
is being removed from Python and is not present in 3.0.


Question: It seems obvious that some people have been able to figure out how to access the iPhone camera through the SDK (Spore Origins, for example). How can this be done?

Answer:
You need to use the
```
UIImagePickerController
```
class, basically:
```
```
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = pickerDelegate
picker.sourceType = UIImagePickerControllerSourceTypeCamera
```
```
The
```
pickerDelegate
```
object above needs to implement the following method:
```
```
- (void)imagePickerController:(UIImagePickerController *)picker
           didFinishPickingMediaWithInfo:(NSDictionary *)info
```
```
The dictionary
```
info
```
will contain entries for the original, and the edited image, keyed with
```
UIImagePickerControllerOriginalImage
```
and
```
UIImagePickerControllerEditedImage
```
respectively. (see
https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate
and
https://developer.apple.com/documentation/uikit/uiimagepickercontrollerinfokey
for more details)


Question:
I have a Windows XP SP2 virtual machine which can be accessed via VNC. It's also running Deep Freeze so there should be no problem in forcing it to reboot. I am looking for a way to force the operating system to reboot instead of shutting down or completely remove the ability to shut down the machine using software applications (such as the usual way from the start menu, the shutdown program or other custom programs).

Thank you,
Tom

Answer:
Try this:
```
shutdown /r /t 1 /f
```
Alex


Question: How do you convert between hexadecimal numbers and decimal numbers in C#?

Answer:
```
```
String stringrep = myintvar.ToString("X");

int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
```
```


Question:
I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:

INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
  (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);

I tried but get a syntax error message.

What would you do if you want to do this?

Answer:
Remove
```
VALUES
```
from your SQL.


Question:
I have been playing with this for a while, but the closest I have gotten is a button that opens the Paste Special dialog box and requires another couple of mouse clicks to paste the contents of the clipboard as unformatted text.

So often I am doing a copy-paste from a web site into a document where I don't want the additional baggage of the HTML formatting, it would be nice to be able to do this with a shortcut key or a toolbar button.

Answer:
Make the button call the macro:
```
```
public sub PasteSpecialUnformatted()
  selection.pastespecial datatype:=wdpastetext
end sub
```
```


Question:
Is there a way to restart the Rails app (e.g. when you've changed a plugin/config file) while Mongrel is running. Or alternatively quickly restart Mongrel. Mongrel gives these hints that you can but how do you do it?

** Signals ready.  TERM => stop.  USR2 => restart.  INT => stop (no restart).

** Rails signals registered.  HUP => reload (without restart).  It might not work well.

Answer:
For example,
```
```
killall -USR2 mongrel_rails
```
```


Question:
On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day after the day specified by that object. I can use <jsp:scriptlet> to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me.

Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?

Answer:
While this does not answer your initial question, you could perhaps eliminate the hassle of going through java.util.Calendar by doing this:
```
```
// Date d given
d.setTime(d.getTime()+86400000);
```
```


Question:
I have an ext combobox which uses a store to suggest values to a user as they type.

An example of which can be found here: combobox example

Is there a way of making it so the suggested text list is rendered to an element in the DOM. Please note I do not mean the "applyTo" config option, as this would render the whole control, including the textbox to the DOM element.

Answer:
So clarify, you want the selected text to render somewhere besides directly below the text input. Correct?
ComboBox is just a composite of
Ext.DataView
, a text input, and an optional trigger button. There isn't an official option for what you want and hacking it to make it do what you want would be really painful. So, the easiest course of action (other than finding and using some other library with a component that does exactly what you want) is to build your own with the components above:
Create a text box. You can use an
Ext.form.TextField
if you want, and observe the keyup event.
Create a DataView bound to your store, rendering to whatever DOM element you want. Depending on what you want, listen to the 'selectionchange' event and take whatever action you need to in response to the selection. e.g., setValue on an Ext.form.Hidden (or plain HTML input type="hidden" element).
In your keyup event listener, call the store's filter method (see
doc
), passing the field name and the value from the text field. e.g., store.filter('name',new RegEx(value+'.*'))
It's a little more work, but it's a lot shorter than writing your own component from scratch or hacking the ComboBox to behave like you want.


Question: I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary #include directives. Sometimes the #includes are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the .cpp file.  Are there any good tools for detecting both of these cases?

Answer:
While it won't reveal unneeded include files, Visual studio has a setting
```
/showIncludes
```
(right click on a
```
.cpp
```
file,
```
Properties->C/C++->Advanced
```
) that will output a tree of all included files at compile time.  This can help in identifying files that shouldn't need to be included.
You can also take a look at the pimpl idiom to let you get away with fewer header file dependencies to make it easier to see the cruft that you can remove.


Question:
I need to convert a value which is in a DateTime variable into a varchar variable formatted as yyyy-mm-dd format (without time part).

How do I do that?

Answer:
Try the following:
```
```
CONVERT(varchar(10), [MyDateTimecolumn], 20)
```
```
For a full date time and not just date do:
```
```
CONVERT(varchar(23), [MyDateTimecolumn], 121)
```
```
See this page for convert styles:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
OR
SQL Server CONVERT() Function


Question:
I am trying to use the import random statement in python, but it doesn't appear to have any methods in it to use.

Am I missing something?

Answer:
I think you need to give some more information.  It's not really possible to answer why it's not working based on the information in the question.  The basic documentation for random is at:
https://docs.python.org/library/random.html
You might check there.


Question:
What is the easiest way to manage the authorized_keys file for openssh across a large number of hosts? If I need to add or revoke a new key to an account on 10 hosts say, I must login and add the public key manually, or through a clumsy shell script, which is time consuming.

Ideally there would be a central database linking keys to accounts@machines with some sort of grouping support (IE, add this key to username X on all servers in the web category). There's fork of SSH with ldap support, but I'd rather use the mainline SSH packages.

Answer:
I've always done this by maintaining a "master" tree of the different servers' keys, and using rsync to update the remote machines. This lets you edit things in one location, push the changes out efficiently, and keeps things "up to date" -- everyone edits the master files, no one edits the files on random hosts.
You may want to look at projects which are made for running commands across groups of machines, such as Func at
https://fedorahosted.org/func
or other server configuration management packages.


Question:
I have a .ico file that is embedded as a resource (build action set to resource).  I am trying to create a NotifyIcon.  How can I reference my icon?

notifyIcon = new NotifyIcon();
notifyIcon.Icon = ??     // my icon file is called MyIcon.ico and is embedded

Answer:
Your icon file should be added to one of your project assemblies and its Build Action should be set to Resource. After adding a reference to the assembly, you can create a NotifyIcon like this:
```
```
System.Windows.Forms.NotifyIcon icon = new System.Windows.Forms.NotifyIcon();
Stream iconStream = Application.GetResourceStream( new Uri( "pack://application:,,,/YourReferencedAssembly;component/YourPossibleSubFolder/YourResourceFile.ico" )).Stream;
icon.Icon = new System.Drawing.Icon( iconStream );
```
```


Question:
I have a function that takes, amongst others, a parameter declared as int privateCount.  When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call.  So, curious as I am, I remove the ToString(), and the code still builds!

How can a C# compiler allow this, where str is a string?

str += privateCount + ...

Answer:
The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus:
```
```
string x = "123" + 45;
```
```
Gets compiled to:
```
```
String.Concat("123", 45);
```
```
Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it.
Note that this "overloading" is not via operator overloading in the language (aka it's not a method named op_Addition) but is handled by the compiler.


Question:
I'm developing a website on an XP virtual machine and have an SMTP virtual server set up in IIS -- it delivers mail just fine. What I would like is to confirm that any emails the site sends are only going to a specific domain.

The XP firewall seems to only involve incoming connections, I can't block outgoing TCP on port 25. And I haven't been able to configure the SMTP server to filter by delivery address.

With this setup, is there any easy way to filter outgoing email by destination address?

Answer:
I think the easiest way would be to add a check to your mail sending code on the website (there's got to be some class which is in charge of sending the mails out).
You could include a check which is only active when the code is compiled in debug mode (using compiler directives). Thus, when you are developing and building the site in debug mode, this code checks if the outgoing messages are valid (specific domain) or not. If they are it lets them go, else it doesn't send the mail.


Question: I would like to use the 7-Zip DLLs from Delphi but have not been able to find decent documentation or examples.  Does anyone know how to use the 7-Zip DLLs from Delphi?

Answer:
As of release 1.102 the
JEDI Code Library
has support for
7-Zip
built into the
JclCompression
unit. Haven't used it myself yet, though.


Question:
Does anyone have details in setting up Qt4 in Visual Studio 2008? Links to other resources would be appreciated as well.

I already know that the commercial version of Qt has applications to this end. I also realize that I'll probably need to compile from source as the installer for the open source does not support Visual Studio and installs Cygwin.

Answer:
As of release 1.102 the
JEDI Code Library
has support for
7-Zip
built into the
JclCompression
unit. Haven't used it myself yet, though.


Question:
In Team Foundation Server, I know that you can use the Annotate feature to see who last edited each line in a particular file (equivalent to "Blame" in CVS). What I'd like to do is akin to running Annotate on every file in a project, and get a summary report of all the developers who have edited a file in the project, and how many lines of code they currently "own" in that project.

Aside from systematically running Annotate of each file, I can't see a way to do this. Any ideas that would make this process faster?

PS - I'm doing to this to see how much of a consultant's code still remains in a particular (rather large) project, not to keep tabs on my developers, in case you're worried about my motivation :)

Answer:
It's easy enough to use the "tf.exe history" command recursively across a directory of files in TFS. This will tell you who changed what files.
However what you're after is a little bit more than this - you want to know if the latest versions of any files have lines written by a particular user.
The Team Foundation Power Tools ship with a command-line version of annotate called "tfpt.exe annotate". This has a /noprompt option to direct the output to the console, but it only outputs the changeset id - not the user name.
You could also use the TFS VersionControl object model to write a tool that does exactly what you need.


Question: I am interested in writing static code analyzer for vb.net to see if it conforms to my company standard coding guidelines. Please advise from where i have to start.

Answer:
Rather than write your own static code analyzer, I recommend you use
FxCop
: and instead, write custom FxCop rules for your needs. It'll save you a lot of time.
http://www.binarycoder.net/fxcop/


Question:
I'm maintaining the Perl Beginners' Site and used a modified template from Open Source Web Designs. Now, the problem is that I still have an undesired artifact: a gray line on the left side of the main frame, to the left of the navigation menu. Here's an image highlighting the undesired effect.

How can I fix the CSS to remedy this problem?

Answer:
It's the
```
background-image
```
on the body showing through. Quick fix (edit style.css or add elsewhere):
```
```
#page-container
{
   background-color: white;
}
```
```


Question:
I have a table inside a div. I want the table to occupy the entire width of the div tag.

In the CSS, I've set the width of the table to 100%.  Unfortunately, when the div has some margin on it, the table ends up wider than the div it's in.

I need to support IE6 and IE7 (as this is an internal app), although I'd obviously like a fully cross-browser solution if possible!

I'm using the following DOCTYPE...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Edit: Unfortunately I can't hard-code the width as I'm dynamically generating the HTML and it includes nesting the divs recursively inside each other (with left margin on each div, this creates a nice 'nested' effect).

Answer:
The following works for me in Firefox and IE7... a guideline, though is: if you set width on an element, don't set margin or padding on the same element. This holds true
especially
if you're mixing units -- say, mixing percents and pixels.
```
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Test</title>

      This is the outer div

        This is the inner div

            Here is my td

```
```
See
here
for an example.


Question:
Every project I compile with Delphi 7, in which I do not compile with run-time packages, gives a linker error: "Too many resources". Even a blank application gives this error.

In other words: Delphi died on me.

Answer:
What happens when you try to build it from the command line?
(i.e., \Program Files\Borland\Delphi7\Bin\dcc32.exe)
Also, have you build any custom .RES files for this project?  If not, try deleting the default .RES that Delphi created for you, and let it get re-created by the project.
You can also force an update to the .RES file by changing something trivial, like the version #, saving your project, then changing it back again.
Sorry these are not answers... but hopefully we will find the issue with a little poking around.


Question:
example:

public static void DoSomething<K,V>(IDictionary<K,V> items) {
   items.Keys.Each(key => {
      if (items[key] **is IEnumerable<?>**) { /* do something */ }
      else { /* do something else */ }
}

Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable<> implements IEnumerable?

Answer:
```
```
if (typeof(IEnumerable).IsAssignableFrom(typeof(V))) {
```
```


Question:
Can't understand why the following takes place:

String date = "06-04-2007 07:05";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm");
Date myDate = fmt.parse(date);

System.out.println(myDate);  //Mon Jun 04 07:05:00 EDT 2007
long timestamp = myDate.getTime();
System.out.println(timestamp); //1180955100000 -- where are the milliseconds?

// on the other hand...

myDate = new Date();
System.out.println(myDate);  //Tue Sep 16 13:02:44 EDT 2008
timestamp = myDate.getTime();
System.out.println(timestamp); //1221584564703 -- why, oh, why?

Answer:
What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for?
```
```
String date = "06-04-2007 07:05:00.999";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S");
Date myDate = fmt.parse(date);

System.out.println(myDate);
long timestamp = myDate.getTime();
System.out.println(timestamp);
```
```


Question: I need to check CPU and memory usage for the server in java, anyone know how it could be done?

Answer:
If you are using Tomcat, check out
Psi Probe
, which lets you monitor internal and external memory consumption as well as a host of other areas.


Question: I have a QMainWindow in a Qt application. When I close it I want it to store its current restore size (the size of the window when it is not maximized). This works well when I close the window in restore mode (that is, not maximized). But if I close the window if it is maximized, then next time i start the application and restore the application (because it starts in maximized mode), then it does not remember the size it should restore to. Is there a way to do this?

Answer:
I've encountered this problem as well.
What you can do: in addition to the window's size, save whether it's maximized or not (
```
QWidget::isMaximized()
```
).
Then next time you start the application, first set the size (
```
QWidget::resize()
```
) and then maximize it if appropriate (
```
QWidget::showMaximized()
```
). When it's restored, it should return to the correct size.


Question:
Is it possible to listen for a certain hotkey (e.g:Ctrl-I) and then perform a specific action? My application is written in C, will only run on Linux, and it doesn't have a GUI. Are there any libraries that help with this kind of task?

EDIT: as an example, amarok has global shortcuts, so for example if you map a combination of keys to an action (let's say Ctrl-+, Ctrl and +) you could execute that action when you press the keys. If I would map Ctrl-+ to the volume increase action, each time I press ctrl-+ the volume should increase by a certain amount.

Thanks

Answer:
How global do your hotkeys need to be?  Is it enough for them to be global for a X session?  In that case you should be able to open an Xlib connection and listen for the events you need.
Ordinarily keyboard events in X are delivered to the window that currently has the focus, and propagated up the hierarchy until they are handled.  Clearly this is not what we want.  We need to process the event before any other window can get to it.  We need to call
XGrabKey
on the root window with the keycode and  modifiers of our hotkey to accomplish this.
I found a good example
here
.


Question:
I am looking for a tool which will take an XML instance document and output a corresponding XSD schema.

I certainly recognize that the generated XSD schema will be limited when compared to creating a schema by hand (it probably won't handle optional or repeating elements, or data constraints), but it could at least serve as a quick starting point.

Answer:
the
Microsoft XSD inference tool
is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.
edit: I just discovered the .net
XmlSchemaInference
class, so if you're using .net you should consider that


Question:
I need to rearrange some content in various directories but it's a bit of a pain. In order to debug the application I'm working on (a ruby app) I need to move my gems into my gem folder one at a time (long story; nutshell: one is broken and I can't figure out which one).

So I need to do something like:

sudo mv backup/gem/foo gem/
sudo mv backup/doc/foo doc/
sudo mv backup/specification/foo.gemspec specification/

replacing "foo" each time. How can I author a simple shell script to let me do something like: gemMove("foo") and it fill in the blanks for me?

Answer:
Put the following into a file named
```
gemmove
```
:
```
```
#!/bin/bash

if [ "x$1" == x ]; then
  echo "Must have an arg"
  exit 1
fi

for d in gem doc specification ; do
  mv "backup/$d/$1" "$d"
done
```
```
then do
```
```
chmod a+x gemmove
```
```
and then call
```
sudo /path/to/gemmove foo
```
to move the foo gem from the backup dirs into the real ones


Question:
Flex has built in drag-n-drop for list controls, and allows you to override this. But they don't cover this in examples. The built-in functionality automatically drags the list-item, if you want to override this you find the handlers are being set up on the list itself.
What I specifically want to do, is my TileList shows small thumbnails of items I can drag onto a large Canvas. As I drag an item from the list, the drag proxy should be a different image.

So, I followed the technique suggested and it only works if I explicitly set the width/height on the proxy Image. Why?

Answer:
It's not obvious until you've tried it =) I struggled with the same thing just a few weeks ago. This was my solution:
The list:
```
```
<List>
  <mouseDown>onListMouseDown(event)</mouseDown>
</Tree>
```
```
The mouse down handler:
```
```
private function onMouseDown( event : MouseEvent ) : void {
  var list : List = List(event.currentTarget);

  // the data of the clicked row, change the name of the class to your own
  var item : MyDataType = MyDataType(list.selectedItem);

  var source : DragSource = new DragSource();

  // MyAwsomeDragFormat is the key that you will retrieve the data by in the
  // component that handles the drop
  source.addData(item, "MyAwsomeDragFormat");

  // this is the component that will be shown as the drag proxy image
  var dragView : UIComponent = new Image();

  // set the source of the image to a bigger version here
  dragView.source = getABiggerImage(item);

  // get hold of the renderer of the clicked row, to use as the drag initiator
  var rowRenderer : UIComponent = UIComponent(list.indexToItemRenderer(list.selectedIndex));

  DragManager.doDrag(
    rowRenderer,
    source,
    event,
    dragView
  );
}
```
```
That will start the drag when the user clicks an item in the list. Notice that I don't set
```
dragEnabled
```
and the other drag-related properties on the list since I handle all that myself.
It can be useful to add this to the beginning of the event handler:
```
```
if ( event.target is ScrollThumb || event.target is Button ) {
  return;
}
```
```
Just to short circuit if the user clicks somewhere in the scrollbar. It's not very elegant but it does the job.


Question: I'm developing a .NET 3.5 XBAP application that runs perfectly fine in FF3 and IE6/7 etc. I'm just wondering if its possible to get these to run under other browsers, specifically (as its in the limelight at the moment) Google Chrome.

Answer:
At the moment, XBAPs do not work in Google Chrome.  I've gotten it to run once, somehow, but every time there after I've received an error that the browser cannot locate xpcom.dll.  Apparently this error occurs for more than just XBAP applications.  From what I've read users will have to wait for a fix seeing as Chrome is still in beta.
Update:
Looks like it's not going to be fixed:
http://code.google.com/p/chromium/issues/detail?id=4051


Question:
In a VB6 application, I have a Dictionary whose keys are Strings and values are instances of a custom class.  If I call RemoveAll() on the Dictionary, will it first free the custom objects?  Or do I explicitly need to do this myself?

Dim d as Scripting.Dictionary

d("a") = New clsCustom
d("b") = New clsCustom

' Are these two lines necessary?
Set d("a") = Nothing
Set d("b") = Nothing

d.RemoveAll

Answer:
Yes, all objects in the
```
Dictionary
```
will be released after a call to
```
RemoveAll()
```
.  From a performance (as in speed) standpoint I would say those lines setting the variables to
```
Nothing
```
are unnecessary, because the code has to first look them up based on the key names whereas
```
RemoveAll()
```
will enumerate and release everything in one loop.


Question:
I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.

Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.

I need to write the values out to a fixed length data file.

Answer:
Aside from limiting the columns selected to reduce bandwidth and memory:
```
```
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
```
```


Question: Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element).

Answer:
You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat="server") form tags.
You can implement two form tags (or more) as long as only one has the runat="server" attribute and one is not contained in the other. Example:
```
```
<body>
<form action="http://www.google.com/cse" id="cse-search-box"> ... </form>
<form runat="server" id="aspNetform"> ... </form>
<body>
```
```


Question:
How to you find the URL that represents the documentation of a .NET framework method on the MSDN website?

For example, I want to embed the URL for the .NET framework method into some comments in some code.  The normal "mangled" URL that one gets searching MSDN isn't very friendly looking: http://msdn.microsoft.com/library/xd12z8ts.aspx.  Using a Google search URL isn't all that pretty looking either.

What I really want a URL that can be embedded in comments that is plain and easy to read.  For example,

// blah blah blah.  See http://<....>/System.Byte.ToString for more information

Answer:
A lot of the time you can merely append the lowercase namespace reference to the domain:
```
```
http://msdn.microsoft.com/en-us/library/system.windows.application_events.aspx
```
```
Moreover, for say the .Net 2.0 version (or any specific version) you can add "(VS.80)":
```
```
http://msdn.microsoft.com/en-us/library/system.windows.forms.button(VS.80).aspx
```
```
Other versions:
.Net 1.1 -> (VS.71)
.Net 2.0 -> (VS.80)
.Net 3.0 -> (VS.85)
.Net 3.5 -> (VS.90)
Try it for a method (Control.IsInputChar) like so:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isinputchar.aspx


Question: If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements.  However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it.  Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?

Answer:
Yes, simple.
say you have
```
```
char *a = new char[10];
```
```
writing in the debugger:
```
```
a,10
```
```
would show you the content as if it were an array.


Question:
Is it possible to reach the individual columns of table2 using HQL with a configuration like this?

<hibernate-mapping>
  <class table="table1">
    <set name="table2" table="table2" lazy="true" cascade="all">
      <key column="result_id"/>
      <many-to-many column="group_id"/>
    </set>
  </class>
</hibernate-mapping>

Answer:
They're just properties of table1's table2 property.
```
```
select t1.table2.property1, t1.table2.property2, ... from table1 as t1
```
```
You might have to join, like so
```
```
select t2.property1, t2.property2, ...
    from table1 as t1
    inner join t1.table2 as t2
```
```
Here's the relevant part of the
hibernate doc
.


Question:
When you're doing a usual gdb session on an executable file on the same computer, you can give the run command and it will start the program over again.

When you're running gdb on an embedded system, as with the command target localhost:3210, how do you start the program over again without quitting and restarting your gdb session?

Answer:
Unfortunately, I don't know of a way to restart the application and still maintain your session.  A workaround is to set the PC back to the entry point of your program.  You can do this by either calling:
```
jump
function
```
or
```
set $pc=
address
```
.
If you munged the arguments to
```
main
```
you may need set them up again.
Edit:
There are a couple of caveats with the above method that could cause problems.
If you are in a multi-threaded program jumping to main will jump the current thread to main, all other threads remain.  If the current thread held a lock...then you have some problems.
Memory leaks, if you program flow allocates some stuff during initialization then you just leaked a bunch of memory with the jump.
Open files will still remain open.  If you mmap some files or an address, the call will most likely fail.
So, using jump isn't the same thing as restarting the program.


Question: In how many languages is Null not equal to anything not even Null?

Answer:
Oracle is this way.
```
```
SELECT * FROM dual WHERE NULL=null;  --no rows returned
```
```


Question:
Does anyone know of a good open source plugin for database querying and exploring within Eclipse?

The active Database Exploring plugin within Eclipse is really geared around being associated with a Java project. While I am just trying to run ad-hoc queries and explore the schema. I am effectively looking for a just a common, quick querying tool without the overhead of having to create a code project. I have found a couple open source database plugins for Eclipse but these have not seen active development in over a year.

Any suggestions?

Answer:
Oracle is this way.
```
```
SELECT * FROM dual WHERE NULL=null;  --no rows returned
```
```


Question:
The problem is simple, but I'm struggling a bit already.

Server server = new Server(8080);
Context context = new Context(server, "/", Context.NO_SESSIONS);
context.addServlet(MainPageView.class, "/");
context.addServlet(UserView.class, "/signup");
server.start();

That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets.

Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?

Answer:
Use the
```
Context.addServlet
```
overload that takes a
```
ServletHolder
```
.
```
ServletHolder
```
is a class that accepts either a Class or a Servlet instance.
```
```
Servlet myServlet = new MyServlet();
ServletHolder holder = new ServletHolder(myServlet);
context.addServlet(holder, "/");
```
```
This assumes Jetty 6.  I think it will work for Jetty 7 as well.


Question: What method do I call to get the name of a class?

Answer:
It's not a method, it's a field.  The field is called
```
__name__
```
.
```
class.__name__
```
will give the name of the class as a string.
```
object.__class__.__name__
```
will give the name of the class of an object.


Question: As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?

Answer:
Use the <
attrib
> task. For example, to make the file "test.txt" read/write, you would use
```
```
<attrib file="test.txt" readonly="false"/>
```
```


Question: I have just started reading DDD. I am unable to completely grasp the concept of Entity vs Value objects.. Can someone please explain the problems (maintainability, performance.. etc) a system could face when a Value object is designed as a Entity object? Example would be great...

Answer:
Reduced to the essential distinction, identity matters for entities, but does not matter for value objects. For example, someone's Name is a value object. A Customer entity might be composed of a customer Name (value object), List<Order> OrderHistory (List of entities), and perhaps a default Address (typically a value object). The Customer Entity would have an ID, and each order would have an ID, but a Name should not; generally, within the object model anyway, the identity of an Address probably does not matter.
Value objects can typically be represented as immutable objects; changing one property of a value object essentially destroys the old object and creates a new one, because you're not as concerned with identity as with content. Properly, the Equals instance method on Name would return "true" as long as the object's properties are identical to the properties of another instance.
However, changing some attribute of an entity like Customer doesn't destroy the customer; a Customer entity is typically mutable. The identity remains the same (at least once the object has been persisted).
You probably create value objects without realizing it; anytime you are representing some aspect of an Entity by creating a fine-grained class, you've got a value object. For example, a class IPAddress, which has some constraints on valid values but is composed of simpler datatypes, would be a value object. An EmailAddress could be a string, or it could be a value object with its own set of behaviors.
It's quite possible that even items that have an identity in your database don't have an identity in your object model. But the simplest case is a composite of some attributes that make sense together. You probably don't want to have Customer.FirstName, Customer.LastName, Customer.MiddleInitial and Customer.Title when you can compose those together as Customer.Name; they'll probably be multiple fields in your database by the time you think about persistence, but your object model doesn't care.


Question:
Does anyone know of some good resources related to setting up heirarchical user account systems? I'm currently setting one up and am struggling with some of the more complex logic (especially with determining permissions). I was hoping I might be able to find some resources to help me along.

Some Background:
I'm building a user account system for a web CMS that allows for a nested group hierarchy. Each group can be allowed/denied access to read, write, add, and delete (either explicitly for that group, or implicitly by one of its parents). As if that weren't complicated enough, the system also allows for users to be members of multiple groups. -- This is where I'm stuck. I've got everything set up, but I'm struggling with the actual logic for determining pemissions for a  given user.

Answer:
Look at the permissions in the
Andrew File System
.  It allows users to create and administer groups of their own, while selectively assigning admin rights and ACLs.  You might find that many of the pesky details are already worked out for you in their model.
Edit:
here's a better link to AFS documentation:
http://www.cs.cmu.edu/~help/afs/index.html
Here's the section on groups:
http://www.cs.cmu.edu/~help/afs/afs_groups.html


Question:
I am serving all content through apache with Content-Encoding: zip but that compresses on the fly.  A good amount of my content is static files on the disk.  I want to gzip the files beforehand rather than compressing them every time they are requested.

This is something that, I believe, mod_gzip did in Apache 1.x automatically, but just having the file with .gz next to it.  That's no longer the case with mod_deflate.

Answer:
This functionality was misplaced in mod_gzip anyway. In Apache 2.x,
you do that with content negotiation
. Specifically, you need to enable
```
MultiViews
```
with the
```
Options
```
directive
and you need to specify your encoding types with the
```
AddEncoding
```
directive
.


Question:
I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP.

 I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work.

Any advice?

Thanks.

Answer:
The parseDate and formatDate tags work, but they work with Date objects.
You can call new java.util.Date(longvalue) to get a date object, then pass that to the standard tag.
somewhere other than the jsp create your date object.
```
```
long longvalue = ...;//from database.
java.util.Date dateValue = new java.util.Date(longvalue);
request.setAttribute("dateValue", dateValue);
```
```
put it on the request and then you can access it in your tag like this.
```
```
<fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>
```
```


Question:
I'm trying to have the same KDE Konsole experience within Mac OS X.

Here's my (overly complicated?) setup:

I have Control and Command swapped at the System Preferences level.  (Can't live without this)

Parallels lets you, at the Parallels application level, also reverse Control and Command.  So I can undo the System Preferences setting (and get the setup I want within virtual Linux)

I want this same per-application-opt-out for the Mac OS X Terminal app.  Is it possible?

Answer:
You can
simply ssh into the Linux/Unix system
and run X11 programs direct to your Mac screen:
```
ssh -X user@host_or_ipaddress
```
, login, and just run the X11 programs you want (e.g.
```
emacs&
```
) and the X11 apps will appear on the Mac display.
Pros:
X11 windows work just like any other window, including Exposé goodness, etc...
No need to work only inside the Parallels console window
Same solution works with any Linux/Unix system, remote or virtual
ssh connection is secure even over the internet
Tech info:
"ssh -X" turns on X11 forwarding for the ssh connection, i.e. the X11 display connection is tunneled through ssh securely
"ssh -X" also handles X11 authentication tunneling
```
X11.app
```
is automagically started on OSX by
```
launchd
```
when needed
X11 can connect to displays over the network, which is one of the few cool things about it ;-)


Question:
I have a JSP page that contains a scriplet where I instantiate an object.  I would like to pass that object to the JSP tag without using any cache.

For example I would like to accomplish this:

<%@ taglib prefix="wf" uri="JspCustomTag" %>

<%
 Object myObject = new Object();
%>

<wf:my-tag obj=myObject />

I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.

Answer:
Use expression language:
```
<wf:my-tag obj="${myObject}" />
```


Question: or "How do I answer questions on SO in Firefox using gVim inside the textboxes?"

Answer:
One way to do this is to use the
vimperator
extension - of course, that does a
lot
more than what you're looking for.


Question:
I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application.

I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback.

A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit.
Anyone ever see an issue?

In your config, would you have two transaction managers?
Would you have txManager1 and txManager2?

That's what I have with JPA, two different Spring beans that are transaction managers.

Answer:
I guess you have 2 choices
If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I'm not sure you will be able to use the @Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple
TransactionProxyFactoryBean
to define transaction boundaries, eg:
```
```
<bean id="firstRealService" class="com.acme.FirstServiceImpl"/>
<bean id="firstService"
    class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager" ref="firstJpaTm"/>
    <property name="target" ref="firstRealService"/>
    <property name="transactionAttributes">
        <props>
           <prop key="insert*">PROPAGATION_REQUIRED</prop>
           <prop key="update*">PROPAGATION_REQUIRED</prop>
           <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
        </props>
    </property>
</bean>
<!-- similar for your second service -->
```
```
If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The
API
states:
This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.
What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following:
```
```
<tx:annotation-driven transaction-manager="txManager"/>

<bean id="txManager"
    class="org.springframework.transaction.jta.JtaTransactionManager">
    <property name="transactionManagerName" value="appserver/jndi/path" />
</bean>
```
```
If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven't tried this myself yet)
As for configuring the Jpa persistence provider, I'm not that familiar. What JPA persistence provider are you using?
The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate's JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element.
Hope this helps


Question: Let's say I write a DLL in C++, and declare a global object of a class with a non-trivial destructor.  Will the destructor be called when the DLL is unloaded?

Answer:
It should be called when either the application ends or the DLL is unloaded, whichever comes first.  Note that this is somewhat dependent on the actual runtime you're compiling against.
Also, beware non-trivial destructors as there are both timing and ordering issues. Your DLL may be unloaded
after
a DLL your destructor relies on, which would obviously cause issues.


Question:
I have searched for various techniques on how to read/write dBase III (dbf) files using OLEDB or ODBC with C#/.NET.  I have tried almost all of the tecniques posted, but without success.  Can someone point me in the right direction?

Thanks for your time.

Answer:
FoxPro 2.0 files were exactly the same as dBase III files with an extra bit for any field that was of type "memo" (not sure the exact name, it's been a while). That means that if you just use a
FoxPro 2.x method
for accessing the files, it should work.


Question:
In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword.  But for multiple dependent objects, this ends up nesting further and further:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
    using (BufferedStream bs = new BufferedStream(fs))
    {
        using (StreamReader sr = new StreamReader(bs))
        {
            // use sr, and have everything cleaned up when done.
        }
    }
}

In C++, I'm used to being able to use destructors to do it like this:

{
    FileStream fs("c:\file.txt", FileMode.Open);
    BufferedStream bs(fs);
    StreamReader sr(bs);
    // use sr, and have everything cleaned up when done.
}

Is there a better way in C# to do this?  Or am I stuck with the multiple levels of nesting?

Answer:
The using statement is syntactic sugar that converts to:
```
```
try
   {
      obj declaration
      ...
   }
   finally
   {
      obj.Dispose();
   }
```
```
You can explicitly call Dispose on your objects, but it won't be as safe, since if one of them throws an exception, the resources won't be freed properly.


Question: I've seen numerous people mentions that you shouldn't use widths and padding or margins on the same element with CSS. Why is that?

Answer:
Because some browsers treat the width as the total width of the element including the padding and the margins, and others treat the width as the base width to which the padding and margins are added.  As a result your design will look different in different browsers.
For more information, see the
W3C page on Box Model
and
quirksmode's take
.


Question: What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.

Answer:
Most people use symbols (that's the
```
:foo_bar
```
syntax). They're sort of unique opaque values. Symbols don't belong to any enum-style type so they're not really a faithful representation of C's enum type but this is pretty much as good as it gets.


Question: 1.exe doesn't give enough time for me to launch the IDE and attach 1.exe to the debugger to break into.

Answer:
I assume you have the source to 1.exe (if you're debugging it), then just insert a statement near the beginning that will cause it to hang around long enough to attach a debugger.  ( getch() if you're desperate and it's not interactive. )
After the attach, just skip to the next statement and let it go.


Question:
I assumed that the C# margin property had a meaning like in CSS - the spacing around the outside of the control. But Margin values seem to be ignored to matter what values I enter.

Then I read on the SDK:

Setting the Margin property on a
  docked control has no effect on the
  distance of the control from the the
  edges of its container.

Given that I'm placing controls on forms, and perhaps docking them, what does the Margin property get me?

Answer:
The margin property is used by whatever layout engine your control host (Panel, for example) is using, in whatever way that layout engine sees fit.   However, it is best used for spacing just as you assume.   Just read the documentation for that specific layout engine.
It can be very handy when using a FlowLayoutPanel or TableLayoutPanel, for example - to either reduce the default padding or space things out a bit.   Obviously, if you write a  custom layout provider, you can use Margin however you see fit.


Question:
Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed.

Related resources:

http://www.codeproject.com/KB/dotnet/AppBar.aspx

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/

Answer:
Please Note:
This question gathered a good amount of feedback, and some people below have made great points or fixes.  Therefore, while I'll keep the code here (and possibly update it), I've also
created a
WpfAppBar project on github
.  Feel free to send pull requests.
That same project also builds to a
WpfAppBar nuget package
I took the code from the first link provided in the question (
http://www.codeproject.com/KB/dotnet/AppBar.aspx
) and modified it to do two things:
Work with WPF
Be "standalone" - if you put this single file in your project, you can call AppBarFunctions.SetAppBar(...) without any further modification to the window.
This approach doesn't create a base class.
To use, just call this code from anywhere within a normal wpf window (say a button click or the initialize).   Note that you can not call this until AFTER the window is initialized, if the HWND hasn't been created yet (like in the constructor), an error will occur.
Make the window an appbar:
```
```
AppBarFunctions.SetAppBar( this, ABEdge.Right );
```
```
Restore the window to a normal window:
```
```
AppBarFunctions.SetAppBar( this, ABEdge.None );
```
```
Here's the full code to the file -
note
you'll want to change the namespace on line 7 to something apropriate.
```
```
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;

namespace AppBarApplication
{
    public enum ABEdge : int
    {
        Left = 0,
        Top,
        Right,
        Bottom,
        None
    }

    internal static class AppBarFunctions
    {
        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct APPBARDATA
        {
            public int cbSize;
            public IntPtr hWnd;
            public int uCallbackMessage;
            public int uEdge;
            public RECT rc;
            public IntPtr lParam;
        }

        private enum ABMsg : int
        {
            ABM_NEW = 0,
            ABM_REMOVE,
            ABM_QUERYPOS,
            ABM_SETPOS,
            ABM_GETSTATE,
            ABM_GETTASKBARPOS,
            ABM_ACTIVATE,
            ABM_GETAUTOHIDEBAR,
            ABM_SETAUTOHIDEBAR,
            ABM_WINDOWPOSCHANGED,
            ABM_SETSTATE
        }
        private enum ABNotify : int
        {
            ABN_STATECHANGE = 0,
            ABN_POSCHANGED,
            ABN_FULLSCREENAPP,
            ABN_WINDOWARRANGE
        }

        [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
        private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern int RegisterWindowMessage(string msg);

        private class RegisterInfo
        {
            public int CallbackId { get; set; }
            public bool IsRegistered { get; set; }
            public Window Window { get; set; }
            public ABEdge Edge { get; set; }
            public WindowStyle OriginalStyle { get; set; }
            public Point OriginalPosition { get; set; }
            public Size OriginalSize { get; set; }
            public ResizeMode OriginalResizeMode { get; set; }

            public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,
                                    IntPtr lParam, ref bool handled)
            {
                if (msg == CallbackId)
                {
                    if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)
                    {
                        ABSetPos(Edge, Window);
                        handled = true;
                    }
                }
                return IntPtr.Zero;
            }

        }
        private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo
            = new Dictionary<Window, RegisterInfo>();
        private static RegisterInfo GetRegisterInfo(Window appbarWindow)
        {
            RegisterInfo reg;
            if( s_RegisteredWindowInfo.ContainsKey(appbarWindow))
            {
                reg = s_RegisteredWindowInfo[appbarWindow];
            }
            else
            {
                reg = new RegisterInfo()
                    {
                        CallbackId = 0,
                        Window = appbarWindow,
                        IsRegistered = false,
                        Edge = ABEdge.Top,
                        OriginalStyle = appbarWindow.WindowStyle,
                        OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top),
                        OriginalSize =
                            new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight),
                        OriginalResizeMode = appbarWindow.ResizeMode,
                    };
                s_RegisteredWindowInfo.Add(appbarWindow, reg);
            }
            return reg;
        }

        private static void RestoreWindow(Window appbarWindow)
        {
            RegisterInfo info = GetRegisterInfo(appbarWindow);

            appbarWindow.WindowStyle = info.OriginalStyle;
            appbarWindow.ResizeMode = info.OriginalResizeMode;
            appbarWindow.Topmost = false;

            Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y,
                info.OriginalSize.Width, info.OriginalSize.Height);
            appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
                    new ResizeDelegate(DoResize), appbarWindow, rect);

        }

        public static void SetAppBar(Window appbarWindow, ABEdge edge)
        {
            RegisterInfo info = GetRegisterInfo(appbarWindow);
            info.Edge = edge;

            APPBARDATA abd = new APPBARDATA();
            abd.cbSize = Marshal.SizeOf(abd);
            abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;

            if( edge == ABEdge.None)
            {
                if( info.IsRegistered)
                {
                    SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
                    info.IsRegistered = false;
                }
                RestoreWindow(appbarWindow);
                return;
            }

            if (!info.IsRegistered)
            {
                info.IsRegistered = true;
                info.CallbackId = RegisterWindowMessage("AppBarMessage");
                abd.uCallbackMessage = info.CallbackId;

                uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);

                HwndSource source = HwndSource.FromHwnd(abd.hWnd);
                source.AddHook(new HwndSourceHook(info.WndProc));
            }

            appbarWindow.WindowStyle = WindowStyle.None;
            appbarWindow.ResizeMode = ResizeMode.NoResize;
            appbarWindow.Topmost = true;

            ABSetPos(info.Edge, appbarWindow);
        }

        private delegate void ResizeDelegate(Window appbarWindow, Rect rect);
        private static void DoResize(Window appbarWindow, Rect rect)
        {
            appbarWindow.Width = rect.Width;
            appbarWindow.Height = rect.Height;
            appbarWindow.Top = rect.Top;
            appbarWindow.Left = rect.Left;
        }

        private static void ABSetPos(ABEdge edge, Window appbarWindow)
        {
            APPBARDATA barData = new APPBARDATA();
            barData.cbSize = Marshal.SizeOf(barData);
            barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;
            barData.uEdge = (int)edge;

            if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right)
            {
                barData.rc.top = 0;
                barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;
                if (barData.uEdge == (int)ABEdge.Left)
                {
                    barData.rc.left = 0;
                    barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth);
                }
                else
                {
                    barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;
                    barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth);
                }
            }
            else
            {
                barData.rc.left = 0;
                barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;
                if (barData.uEdge == (int)ABEdge.Top)
                {
                    barData.rc.top = 0;
                    barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight);
                }
                else
                {
                    barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;
                    barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);
                }
            }

            SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);
            SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);

            Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top,
                (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top));
            //This is done async, because WPF will send a resize after a new appbar is added.
            //if we size right away, WPFs resize comes last and overrides us.
            appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
                new ResizeDelegate(DoResize), appbarWindow, rect);
        }
    }
}
```
```


Question:
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools?

Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier.

Ruby has similar issues and although I do like Ruby much better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app.

Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?

Answer:
cakephp.org
Cakephp is really good, really close to ruby on rails (1.2).  It is in php, works very well on shared hosts and is easy to implement.
The only downside is that the documentation is somewhat lacking, but you quickly get it and quickly start doing cool stuff.
I totally recommend cakephp.


Question:
All the docs for SQLAlchemy give INSERT and UPDATE examples using the local table instance (e.g. tablename.update()... )

Doing this seems difficult with the declarative syntax, I need to reference Base.metadata.tables["tablename"] to get the table reference.

Am I supposed to do this another way?   Is there a different syntax for INSERT and UPDATE recommended when using the declarative syntax?  Should I just switch to the old way?

Answer:
via the
```
__table__
```
attribute on your declarative class


Question:
I'm trying to insert a Spry accordion into an already existing JSF page using Dreamweaver. Is this possible?

I've already tried several things, and only the labels show up.

Answer:
I'm not a Dreamweaver expert, but all Spry Accordian requires is the correct HTML structure. E.g.:
```
```

Panel 1

                    Panel 1 Content

                    Panel 1 Content

                    Panel 1 Content

```
```
Provided you have the
JavaScript
library loaded correctly, that should pretty much be all you need to do.


Question: As a part of database maintenance we are thinking of taking daily backups onto an external/firewire drives. Are there any specific recommended drives for the frequent read/write operations from sql server 2000 to take backups?

Answer: Whatever you do, just don't use USB 1.1.


Question: This may be a no-brainer for the WPF cognoscenti, but I'd like to know if there's a simple way to put text on the WPF ProgressBar. To me, an empty progress bar looks naked. That's screen real estate that could carry a message about what is in progress, or even just add numbers to the representation. Now, WPF is all about containers and extensions and I'm slowly wrapping my mind around that, but since I don't see a "Text" or "Content" property, I'm thinking I'm going to have to add something to the container that is my progress bar. Is there a technique or two out there that is more natural than my original WinForms impulses will be? What's the best, most WPF-natural way to add text to that progress bar?

Answer:
If you are needing to have a reusable method for adding text, you can create a new Style/ControlTemplate that has an additional TextBlock to display the text.  You can hijack the TextSearch.Text attached property to set the text on a progress bar.
If it doesn't need to be reusable, simply put the progress bar in a Grid and add a TextBlock to the grid.  Since WPF can compose elements together, this will work nicely.
If you want, you can create a UserControl that exposes the ProgressBar and TextBlock as public properties, so it would be less work than creating a custom ControlTemplate.


Question:
I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like:

<div>
  <!-- some html -->
  <script type="text/javascript">
    /** some javascript */
  </script>
</div>

I'm inserting the whole thing into the DOM, but the JavaScript isn't being run.  Is there a way to run it?

Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed.  I can't call eval on the response because the JavaScript is within a larger block of HTML.  I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky.  Anyone know a better way?

Answer:
You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName.
```
```
div.innerHTML = response;
var scripts = div.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
    eval(scripts[ix].text);
}
```
```


Question: In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?

Answer:
Use the following (remember to include System.Configuration assembly)
```
```
ConfigurationManager.OpenExeConfiguration(exePath)
```
```


Question:
I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this:

mysql> source script.sql

How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable.

I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.

Answer:
Like this:
```
```
set @department := 'Engineering';
```
```
Then, reference
```
@department
```
wherever you need to in script.sql:
```
```
update employee set salary = salary + 10000 where department = @department;
```
```


Question: I have a couple old services that I want to completely uninstall. How can I do this?

Answer:
Click
Start
|
Run
and type
```
regedit
```
in the Open: line. Click OK.
Navigate to
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
```
Scroll down the left pane, locate the service name, right click it and
select Delete
.
Reboot the system.


Question:
I am trying to solve numerically a set of partial differential equations in three dimensions. In each of the equations the next value of the unknown in a point depends on the current value of each unknown in the closest points.

To write an efficient code I need to keep the points close in the three dimensions close in the (one-dimensional) memory space, so that each value is called from memory just once.

I was thinking of using octtrees, but I was wondering if someone knows a better method.

Answer:
Octtrees are the way to go.  You subdivide the array into 8 octants:
```
1 2
3 4

---

5 6
7 8
```
And then lay them out in memory in the order 1, 2, 3, 4, 5, 6, 7, 8 as above.  You repeat this recursively within each octant until you get down to some base size, probably around 128 bytes or so (this is just a guess -- make sure to profile to determine the optimal cutoff point).  This has much, much better cache coherency and locality of reference than the naive layout.


Question: can anyone please suggest a good code example of vb.net/c# code to put the application in system tray when minized.

Answer:
Add a NotifyIcon control to your form, then use the following code:
```
```
private void frm_main_Resize(object sender, EventArgs e)
    {
        if (this.WindowState == FormWindowState.Minimized)
        {
           this.ShowInTaskbar = false;
           this.Hide();
           notifyIcon1.Visible = true;
        }
    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        this.Show();
        this.WindowState = FormWindowState.Normal;
        this.ShowInTaskbar = true;
        notifyIcon1.Visible = false;
    }
```
```
You may not need to set the ShowInTaskbar property.


Question:
I'm trying to keep dependencies to a minimum for a program I contribute to, it's a small text editor.

GTK Textview doesn't seem to come with a built-in undo function. Is there any reference implementation I've been missing on so far? Is everyone writing their own undo function for their TextView widgets?

I'll be happy about any sample code - most happy about python sample code, as our project is in python.

Answer:
As far as I know, GTK TextView doesn't include an undo function. So while I am not familiar with Python's GTK library, I would think it doesn't have one.
The Ruby-GNOME2 project has a
sample text editor
that has undo/redo functionality. Basically they are connecting to the insert_text and delete_range signals of the TextView widget and recording the events and associated data in a list.


Question:
I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this?

I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though.

This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information.

Answer:
Assuming that the points are indeed part of a rectangle, I'm giving a generic idea :
Find two points with max inter-distance: these most probably define a diagonal (exception: special cases where the rectangle is almost paralell to the YZ plane, left for the student). Call them A, C. Calculate the BAD, BCD angles. These, compared to right angles, give you orientation in 3d space. To find out about z distance, you need to correlate the projected sides to the known sides, and then, based on the 3d projection method (is it 1/z?) you're on the right track to know distances.


Question: Does anybody have experience of a decent J2SE (preferably at least Java JDK 1.5-level) Java Virtual Machine for Windows Mobile 6? If you know of any CLDC VMs, I'm also interested because even that would be better than what we currently have for the platform.

Answer:
Honestly I searched a while and there no decent JVM for windows mobile. The best bet I think is this :
http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html
but it's JDK 1.3 compliant the last time I checked.


Question:
I've only been able to find two thus far, namely TinyRadius, which itself discourages production use and AXL, which is pay-only.

JRadius seems tied to FreeRADIUS, which isn't a library and will need a lot of cajoling to function like one.

Answer:
List from
http://freeradius.org/related/opensource.html
(not copying the descriptions because the page says it's copyright
rolleyes
):
Cistron -
http://www.radius.cistron.nl/
GNU Radius -
http://www.gnu.org/software/radius/
FreeRADIUS -
http://freeradius.org/
JRadius -
http://www.coova.org/JRadius
ICRADIUS -
http://www.icradius.org/
OpenRADIUS -
http://www.openradius.net/
XtRADIUS -
http://xtradius.sourceforge.net/
YARD RADIUS -
http://sourceforge.net/projects/yardradius


Question:
In my SWT Java app I often want to return information from inside a Display.syncExec() call.  The best way I've found so far to do this is:

final ArrayList<Integer> result = new ArrayList<Integer>();
GUI.display().syncExec(new Runnable(){ public void run() {
   MessageBox mb = /* ... */;
    /* set up messagebox */
   result.add(mb.open());
}});
if (SWT.OK == result.get(0)) { /* ... */ }

I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?

Answer:
ArrayList is
not
thread-safe. From the relevant
Javadoc
:
Note that this implementation is not
  synchronized. If multiple threads
  access an ArrayList instance
  concurrently, and at least one of the
  threads modifies the list
  structurally, it must be synchronized
  externally.
If you need a thread-safe implementation of List, there are (at least) two provided in the JDK: CopyOnWriteArrayList and Vector.


Question: PHP5 has a "magic method" __call()that can be defined on any class that is invoked when an undefined method is called -- it is roughly equivalent to Ruby's method_missing or Perl's AUTOLOAD. Is it possible to do something like this in older versions of PHP?

Answer:
I recall using it, and a little bit of googling suggests that
```
```
function __call($method_name, $parameters, &$return)
{
  $return_value = "You called ${method_name}!";
}
```
```
as a member function will do the job.


Question:
Does anyone know a mechanism to calculate at compile-time the LCM (Least Common Multiple) and/or GCD (Greatest Common Denominator) of at least two number in C (not C++, I know that template magic is available there)?

I generally use GCC and recall that it can calculate certain values at compile-time when all inputs are known (ex: sin, cos, etc...).

I'm looking for how to do this in GCC (preferably in a manner that other compilers could handle) and hope the same mechanism would work in Visual Studio.

Answer:
I figured it out afterall...
```
```
#define GCD(a,b) ((a>=b)*GCD_1(a,b)+(a<b)*GCD_1(b,a))
#define GCD_1(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_2((b), (a)%((b)+!(b))))
#define GCD_2(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_3((b), (a)%((b)+!(b))))
#define GCD_3(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_4((b), (a)%((b)+!(b))))
#define GCD_4(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_5((b), (a)%((b)+!(b))))
#define GCD_5(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_6((b), (a)%((b)+!(b))))
#define GCD_6(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_7((b), (a)%((b)+!(b))))
#define GCD_7(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_8((b), (a)%((b)+!(b))))
#define GCD_8(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_last((b), (a)%((b)+!(b))))
#define GCD_last(a,b) (a)

#define LCM(a,b) (((a)*(b))/GCD(a,b))

int main()
{
    printf("%d, %d\n", GCD(21,6), LCM(21,6));
    return 0;
}
```
```
Note, depending on how large your integers go, you may need to include more intermediate steps (i.e. GCD_9, GCD_10, etc...).
I hope this helps!


Question:
I just got surprised by something in TSQL.  I thought that if xact_abort was on, calling something like

raiserror('Something bad happened', 16, 1);

would stop execution of the stored procedure (or any batch).

But my ADO.NET error message just proved the opposite.  I got both the raiserror error message in the exception message, plus the next thing that broke after that.

This is my workaround (which is my habit anyway), but it doesn't seem like it should be necessary:

if @somethingBadHappened
    begin;
        raiserror('Something bad happened', 16, 1);
        return;
    end;

The docs say this:

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.

Does that mean I must be using an explicit transaction?

Answer:
This is By Design
TM
, as you can see on
Connect
by the SQL Server team's response to a similar question:
Thank you for your feedback. By design, the XACT_ABORT set option does not impact the behavior of the RAISERROR statement. We will consider your feedback to modify this behavior for a future release of SQL Server.
Yes, this is a bit of an issue for some who hoped
```
RAISERROR
```
with a high severity (like
```
16
```
) would be the same as an SQL execution error - it's not.
Your workaround is just about what you need to do, and using an explicit transaction doesn't have any effect on the behavior you want to change.


Question:
Does ADOdb do data sanitation or escaping within the same functionality by default? Or am I just confusing it with Code Igniter's built-in processes?

Does binding variables to parameters in ADOdb for PHP prevent SQL injection in any way?

Answer:
yes, you pass the array of parameters.
```
```
$rs = $db->Execute('select * from table where val=?', array('10'));
```
```
Rest of their docs can be found
here
:


Question:
In what domains do each of these software architectures shine or fail?

Which key requirements would prompt you to choose one over the other?

Please assume that you have developers available who can do good object oriented code as well as good database development.

Also, please avoid holy wars :) all three technologies have pros and cons, I'm interested in where is most appropriate to use which.

Answer:
I agree that there are pros and cons to everything and a lot depends on your architecture. That being said, I try to use ORM's where it makes sense. A lot of the functionality is already there and usually they help prevent SQL Injection (plus it helps avoid re-inventing the wheel).
Please see these other two posts on the topic (dynamic SQL vs
stored procedures vs ORM) for more information
Dynamic SQL vs. stored procedures
Which is better: Ad hoc queries, or stored procedures?
ORMs vs. stored procedures
Why is parameterized SQL generated by NHibernate just as fast as a stored procedure?


Question:
I have a SQL Insert query inside a stored proc, for inserting rows into a linked server table.

Since the stored proc is getting called within a parent transaction, this Insert statement tries to use a DTC for inserting rows into the linked server.

I would like to avoid DTC from getting involved.

Is there any way I can do that (like a hint) for the Insert SQL statement to ignore transactional scope?

Answer:
My suggestion is that you store whatever you want to insert into a staging table, and once the procedure is over run the cross server insert.  To my knowledge there is no way of ignoring the transaction you are in once you are within the SProc execution.
In contrast, if you use .NET 2.0's System.Transaction namespace, you can tell specific statements not to participate in any parent scope transaction.  This would require you to write some of your logic in code rather than stored procedures, but would work.
Here's a
relevant link
.
Good luck,
Alan.


Question:
How can I create a regular expression that will grab delimited text from a string?  For example, given a string like

text ###token1### text text ###token2### text text

I want a regex that will pull out ###token1###.  Yes, I do want the delimiter as well.  By adding another group, I can get both:

(###(.+?)###)

Answer:
```
```
/###(.+?)###/
```
```
if you want the ###'s  then you need
```
```
/(###.+?###)/
```
```
the
?
means non greedy, if you didn't have the
?
, then it would grab too much.
e.g.
```
'###token1### text text ###token2###'
```
would all get grabbed.
My initial answer had a * instead of a +.  * means 0 or more.  + means 1 or more.  * was wrong because that would allow ###### as a valid thing to find.
For playing around with regular expressions. I highly recommend
http://www.weitz.de/regex-coach/
for windows.  You can type in the string you want and your regular expression and see what it's actually doing.
Your selected text will be stored in \1   or $1 depending on where you are using your regular expression.


Question:
In C#.NET I am trying to programmatically change the color of the border in a group box.

Update:  This question was asked when I was working on a winforms system before we switched to .NET.

Answer:
I'm not sure this applies to every case, but thanks to this thread, we quickly hooked into the Paint event programmatically using:
```
```
GroupBox box = new GroupBox();
[...]
box.Paint += delegate(object o, PaintEventArgs p)
{
    p.Graphics.Clear(someColorHere);
};
```
```
Cheers!


Question: I'd like to create a module in DNN that, similar to the Announcements control, offers a template that the portal admin can modify for formatting.  I have a control that currently uses a Repeater control with templates.  Is there a way to override the contents of the repeater ItemTemplate, HeaderTemplate, and FooterTemplate properties?

Answer:
I'm not sure this applies to every case, but thanks to this thread, we quickly hooked into the Paint event programmatically using:
```
```
GroupBox box = new GroupBox();
[...]
box.Paint += delegate(object o, PaintEventArgs p)
{
    p.Graphics.Clear(someColorHere);
};
```
```
Cheers!


Question: Is there a way in Ruby to find the version of a file, specifically a .dll file?

Answer:
For any file, you'd need to discover what format the file is in, and then open the file and read the necessary bytes to find out what version the file is.  There is no API or common method to determine a file version in Ruby.
Note that it would be easier if the file version were in the file name.


Question:
I have a file saved as UCS-2 Little Endian I want to change the encoding so I ran the following code:

cat tmp.log -encoding UTF8 > new.log

The resulting file is still in UCS-2 Little Endian.  Is this because the pipeline is always in that format? Is there an easy way to pipe this to a new file as UTF8?

Answer:
I would do it like this:
```
```
get-content tmp.log -encoding Unicode | set-content new.log -encoding UTF8
```
```
My understanding is that the -encoding option selects the encdoing that the file should be read or written in.


Question: Can't find anything relevant about Entity Framework/MySQL on Google so I'm hoping someone knows about it.

Answer:
You would need a mapping provider for MySQL. That is an extra thing the Entity Framework needs to make the magic happen.
This blog
talks about other mapping providers besides the one Microsoft is supplying. I haven't found any mentionings of MySQL.


Question: Under what circumstances - if any - does adding programmers to a team actually speed development of an already late project?

Answer:
If the existing programmers are totally incompetent, then adding competent programmers may help.
I can imagine a situation where you had a very modular system, and the existing programmer(s) hadn't even
started
on a very isolated module.  In that case, assigning just that portion of the project to a new programmer might help.
Basically the Mythical Man Month references are correct, except in contrived cases like the one I made up.  Mr. Brooks did solid research to demonstrate that after a certain point, the networking and communication costs of adding new programmers to a project will outweigh any benefits you gain from their productivity.


Question:
All I want is to be able to change the color of a bullet in a list to a light gray. It defaults to black, and I can't figure out how to change it.

I know I could just use an image; I'd rather not do that if I can help it.

Answer:
```
```

test

```
```
the big problem with this method is the extra markup. (the span tag)