q:
We have a couple of developers asking for allow_url_fopen to be enabled on our server. What's the norm these days and if libcurl is enabled is there really any good reason to allow?

Environment is: Windows 2003, PHP 5.2.6, FastCGI

[A]
You definitely want
```
allow_url_include
```
set to Off, which mitigates many of the risks of
```
allow_url_fopen
```
as well.
But because not all versions of PHP have
```
allow_url_include
```
, best practice for many is to turn off fopen.  Like with all features, the reality is that if you don't need it for your application, disable it.  If you do need it, the curl module probably can do it better, and refactoring your application to use curl to disable
```
allow_url_fopen
```
may deter the least determined cracker.


q:
I have come to realize that Windbg is a very powerful debugger for the Windows platform & I learn something new about it once in a while. Can fellow Windbg users share some of their mad skills?

ps: I am not looking for a nifty command, those can be found in the documentation. How about sharing tips on doing something that one couldn't otherwise imagine could be done with windbg? e.g. Some way to generate statistics about memory allocations when a process is run under windbg.

[A]
My favorite is the command
```
.cmdtree <file>
```
(undocumented, but referenced in previous release notes). This can assist in bringing up another window (that can be docked) to display helpful or commonly used commands. This can help make the user much more productive using the tool.
Initially talked about here, with an example for the
```
<file>
```
parameter:
http://blogs.msdn.com/debuggingtoolbox/archive/2008/09/17/special-command-execute-commands-from-a-customized-user-interface-with-cmdtree.aspx
Example:
alt text http://blogs.msdn.com/photos/debuggingtoolbox/images/8954736/original.aspx

s: huggingface

c: devops

d: intermediate


q:
I'm trying to use JVLC but I can't seem to get it work. I've downloaded the jar, I installed VLC and passed the -D argument to the JVM telling it where VLC is installed. I also tried:

NativeLibrary.addSearchPath("libvlc", "C:\\Program Files\\VideoLAN\\VLC");

with no luck. I always get:

Exception in thread "main"
  java.lang.UnsatisfiedLinkError: Unable
  to load library 'libvlc': The
  specified module could not be found.

Has anyone made it work?


q: How do I make Caps Lock work like Esc in Mac OS X?

[A]
The only thing I know how to do is to map Caps Lock to Control, or Option, or Command.  This can be done via the Keyboard & Mouse pane of System Preferences.  Click on "Modifier Keys" on the bottom left and you'll be able to remap Caps Lock, Control, Option, and Command, to any of those.
@Craig:
This suggests that Caps Lock
can
be used as a normal -- that is, non-toggle -- key.  On my MacBook, since I have re-mapped Caps Lock to Control, the Caps Lock light never lights up.  It simply acts like the Control key.


q: I have Java 1.5.0 installed on a Mac OS machine. I have the Java Embedding Plugin 0.9.6.4 installed and java enabled on the preferences panel. When I go to http://java.com/en/download/help/testvm.xml the applet appears blank. Does anyone has an idea of what is happening?

[A]
I have found the solution. The Java Embedding Plugin uses the installed JVM which itself gets its proxy definitions from MacOS and not from Firefox. So, proxy definitions have to be defined for both MacOS/Safari and Firefox.
I've also updated Firefox and selected Java 1.5 on the Java preferences panel. However I'm not sure if these two actions helped solve the issue.


q:
I'm trying to generate customized xml files from a template xml file in python.

Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file.  I wanted it to work something like this:

conf_base = ConvertXmlToDict('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']

conf_new = ConvertDictToXml(conf_base_dict)

now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write()

conf_new.write('config-new.xml')

Is there some way to do this, or can someone suggest doing this a different way?

[A]
I'm not sure if converting the info set to nested dicts first is easier. Using ElementTree, you can do this:
```
```
import xml.etree.ElementTree as ET
doc = ET.parse("template.xml")
lvl1 = doc.findall("level1-name")[0]
lvl1.remove(lvl1.find("leaf1")
lvl1.remove(lvl1.find("leaf2")
# or use del lvl1[idx]
doc.write("config-new.xml")
```
```
ElementTree was designed so that you don't have to convert your XML trees to lists and attributes first, since it uses exactly that internally.
It also support as small subset of
XPath
.


q:
I'm trying to install Maatkit following the maatkit  instructions. I can't get past having to install DBD::mysql. "Warning: prerequisite DBD::mysql 1 not found."
When I try to install DBD::mysql from cpan, I get very helpful "make had returned bad status, install seems impossible".

Perl is "v5.8.8 built for darwin-thread-multi-2level", the one that came with OS X. I also tried building from source with same result.

[A]
We need more of the error message. Most likely, you are missing the MySQL client development files. I don't know how to install these on OSX. Also see
this older post on OSX 10.5.2
, in which some other failures with the mysql client libraries are found.
Possibly post this question with more parts of your error message at
perlmonks.org
, if stackoverflow doesn't allow for convenient pasting of your
```
make
```
session or rather the last 20 or 10 lines of it.
Some more Googling with
```
site:perlmonks.org
```
also finds
this post
which has some more details on things to watch out for when installing DBD::MySQL. Depending on how comfortable you feel with the installation, you might want to manually run the tests, supplying a test database and test user or even skip testing the module.


q:
Is there a way to prevent someone from faking a mime type on a file upload and then running a php/exe/etc...

I have to make the file upload directory writeable and executable so that the files can be stored, but this allows anyone to run a script after.  One thing I can do is add random data to the file name so they can't guess the file name after (since they still can't read from the directory to get a listing).

I'm using file upload with php for the first time and I'm trying to cover all of the security issues.

[A]
The file upload directory should not be accessible to the web browser.  I.e. don't allow somebody to upload a file, say "
```
remove_all_my_files.php
```
", and then execute it on your system by giving the url to it, say "
```
http://xample.com/uploads/remove_all_my_files.php
```
".


q: When an error occurs in a function, I'd like to know the sequence of events that lead up to it, especially when that function is called from a dozen different places.  Is there any way to retrieve the call stack in VB6, or do I have to do it the hard way (e.g., log entries in every function and error handler, etc.)?

[A]
I'm pretty sure you have to do it the hard way.  At a previous job of mine, we had a very elegant error handling process for VB6 with DCOM components.  However, it was a lot redundant code that had to be added to every method, so much that we had home-grown tools to insert it all for you.
I can't provide too much insight on its implementation (both because I've forgotten most of it and there's a chance they may consider it a trade secret).  One thing that does stand out was that the method name couldn't be derived at run-time so it was added as a string variable (some developers would copy-paste instead of using the tool and it would lead to error stacks that lied...).
HTH


q:
I'm working on an existing report and I would like to test it with the database.  The problem is that the catalog set during the initial report creation no longer exists.  I just need to change the catalog parameter to a new database.  The report is using a stored proc for its data.  It looks like if try and remove the proc to re-add it all the fields on the report will disapear and I'll have to start over.

I'm working in the designer in Studio and just need to tweak the catalog property to get a preview.  I have code working to handle things properly from the program.

[A]
EDIT: Saw your edit, so i'll keep my original post but have to say.. I've never had a crystal report in design mode in VS so I can't be of much help there sorry.
```
```
report.SetDatabaseLogon(UserID, Password, ServerName, DatabaseName);
```
```
After that you have to roll through all referenced tables in the report and recurse through subreports and reset their logoninfo to one based on the reports connectioninfo.
```
```
private void FixDatabase(ReportDocument report)
    {
        ConnectionInfo crystalConnectionInfo = someConnectionInfo;

        foreach (Table table in report.Database.Tables)
        {
            TableLogOnInfo logOnInfo = table.LogOnInfo;

            if (logOnInfo != null)
            {
                logOnInfo.ConnectionInfo = crystalConnectionInfo;

                table.LogOnInfo.TableName = table.Name;
                table.LogOnInfo.ConnectionInfo.UserID = someConnectionInfo.UserID;
                table.LogOnInfo.ConnectionInfo.Password = someConnectionInfo.Password;
                table.LogOnInfo.ConnectionInfo.DatabaseName = someConnectionInfo.DatabaseName;
                table.LogOnInfo.ConnectionInfo.ServerName = someConnectionInfo.ServerName;
                table.ApplyLogOnInfo(table.LogOnInfo);

                table.Location = someConnectionInfo.DatabaseName + ".dbo." + table.Name;
            }
        }

        //call this method recursively for each subreport
        foreach (ReportObject reportObject in report.ReportDefinition.ReportObjects)
        {
            if (reportObject.Kind == ReportObjectKind.SubreportObject)
            {
                this.FixDatabase(report.OpenSubreport(((SubreportObject)reportObject).SubreportName));
            }
        }
    }
```
```


q:
I am building an MFC application for both XP and Vista. I have Visual Studio 2008 installed on the XP machine but I need to debug the application on Vista. How can I do that? Do I really have to install Visual Studio on a Vista machine?

When using remote debugging I assume that all executable and library files must be in my Vista virtual machine. But I can seem to copy the MFC debug DLLs to the Vista VM, and as a result I keep getting side-by-side configuration errors.

I would prefer to remote debug the application without having to copy any files, how can I do that? And if I can't, how can I install the MFC DLLs without having to install Visual Studio on the Vista machine?

Note: I have Vista installed on a virtual machine using Virtual PC. I just don't know how to run the debug version of my application there.

[A]
You can install VirtualPC (or other virtualization software) and install Vista as virtual system, so you don't need two computers.  For this part of the debugging, it probably better that you explicitly do
not
install visual studio to make sure there's not some hidden dependency in your program that visual studio provides.  At this point you want to be testing the fully-deployed version of the app.
The biggest rule I've found so far for developing for vista is making sure that you
never
write anything to the same folder where the program is installed.  Write to the Application Data folder instead.  This was a rule for XP, too, but it's much more strictly  enforced in vista.


q: How do I view the grants (access rights) for a given user in MySQL?

[A]
```
```
mysql> show grants for 'user'@'host'
```
```


q:
My project is currently using a svn repository which gains several hundred new revisions per day.
The repository resides on a Win2k3-server and is served through Apache/mod_dav_svn.

I now fear that over time the performance will degrade due to too many revisions.

Is this fear reasonable?

We are already planning to upgrade to 1.5, so having thousands of files in one directory will not be a problem in the long term.

Subversion on stores the delta (differences), between 2 revisions, so this helps saving a LOT of space, specially if you only commit code (text) and no binaries (images and docs).

Does that mean that in order to check out the revision 10 of the file foo.baz, svn will take revision 1 and then apply the deltas 2-10?

[A]
Subversion only stores the delta (differences), between 2 revisions, so this helps saving a LOT of space, specially if you only commit code (text) and no binaries (images and docs).
Additionally I´ve seen a lot of very big projects using svn and never complained about performance.
Maybe you are worried about checkout times? then I guess this would really be a networking problem.
Oh, and I´ve worked on CVS repositories with 2Gb+ of stuff (code, imgs, docs) and never had an performance problem. Since svn is a great improvement on cvs I don´t think you should worry about.
Hope it helps easy your mind a little ;)


q:
Can a firefox XPCOM component read and write page content across multiple pages?

Scenario:
A bunch of local HTML and javascript files. A "Main.html" file opens a window "pluginWindow", and creates a plugin using:

netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

var obj = Components.classes[cid].createInstance();

plugin = obj.QueryInterface(Components.interfaces.IPlugin);

plugin.addObserver(handleEvent);

The plugin that has 3 methods.

IPlugin.Read - Read data from plugin

IPlugin.Write - Write data to the plugin

IPlugin.addObserver - Add a callback handler for reading.

The "Main.html" then calls into the pluginWindow and tries to call the plugin method Write.

I receive an error:

Permission denied to call method UnnamedClass.Write


q:
I want to write a function that takes an array of letters as an argument and a number of those letters to select.

Say you provide an array of 8 letters and want to select 3 letters from that. Then you should get:

8! / ((8 - 3)! * 3!) = 56

Arrays (or words) in return consisting of 3 letters each.

[A]
Art of Computer Programming Volume 4: Fascicle 3
has a ton of these that might fit your particular situation better than how I describe.
Gray Codes
An issue that you will come across is of course memory and pretty quickly, you'll have problems by 20 elements in your set --
20
C
3
= 1140. And if you want to iterate over the set it's best to use a modified gray code algorithm so you aren't holding all of them in memory. These generate the next combination from the previous and avoid repetitions. There are many of these for different uses. Do we want to maximize the differences between successive combinations? minimize? et cetera.
Some of the original papers describing gray codes:
Some Hamilton Paths and a Minimal Change Algorithm
Adjacent Interchange Combination Generation Algorithm
Here are some other papers covering the topic:
An Efficient Implementation of the Eades, Hickey, Read Adjacent Interchange Combination Generation Algorithm
(PDF, with code in Pascal)
Combination Generators
Survey of Combinatorial Gray Codes
(PostScript)
An Algorithm for Gray Codes
Chase's Twiddle (algorithm)
Phillip J Chase, `
Algorithm 382: Combinations of M out of N Objects
' (1970)
The algorithm in C
...
Index of Combinations in Lexicographical Order (Buckles Algorithm 515)
You can also reference a combination by its index (in lexicographical order).  Realizing that the index should be some amount of change from right to left based on the index we can construct something that should recover a combination.
So, we have a set {1,2,3,4,5,6}... and we want three elements. Let's say {1,2,3} we can say that the difference between the elements is one and in order and minimal. {1,2,4} has one change and is lexicographically number 2. So the number of 'changes' in the last place accounts for one change in the lexicographical ordering. The second place, with one change {1,3,4} has one change but accounts for more change since it's in the second place (proportional to the number of elements in the original set).
The method I've described is a deconstruction, as it seems, from set to the index, we need to do the reverse – which is much trickier. This is how
Buckles
solves the problem. I wrote some
C to compute them
, with minor changes – I used the index of the sets rather than a number range to represent the set, so we are always working from 0...n.
Note:
Since combinations are unordered, {1,3,2} = {1,2,3} --we order them to be lexicographical.
This method has an implicit 0 to start the set for the first difference.
Index of Combinations in Lexicographical Order (McCaffrey)
There is
another way
:, its concept is easier to grasp and program but it's without the optimizations of Buckles. Fortunately, it also does not produce duplicate combinations:
The set
that maximizes
, where
.
For an example:
```
27 = C(6,4) + C(5,3) + C(2,2) + C(1,1)
```
. So, the 27th lexicographical combination of four things is: {1,2,5,6}, those are the indexes of whatever set you want to look at. Example below (OCaml), requires
```
choose
```
function, left to reader:
```
```
(* this will find the [x] combination of a [set] list when taking [k] elements *)
let combination_maccaffery set k x =
    (* maximize function -- maximize a that is aCb              *)
    (* return largest c where c < i and choose(c,i) <= z        *)
    let rec maximize a b x =
        if (choose a b ) <= x then a else maximize (a-1) b x
    in
    let rec iterate n x i = match i with
        | 0 -> []
        | i ->
            let max = maximize n i x in
            max :: iterate n (x - (choose max i)) (i-1)
    in
    if x < 0 then failwith "errors" else
    let idxs =  iterate (List.length set) x k in
    List.map (List.nth set) (List.sort (-) idxs)
```
```
A small and simple combinations iterator
The following two algorithms are provided for didactic purposes. They implement an iterator and (a more general) folder overall combinations.
They are as fast as possible, having the complexity O(
n
C
k
). The memory consumption is bound by
```
k
```
.
We will start with the iterator, which will call a user provided function for each combination
```
```
let iter_combs n k f =
  let rec iter v s j =
    if j = k then f v
    else for i = s to n - 1 do iter (i::v) (i+1) (j+1) done in
  iter [] 0 0
```
```
A more general version will call the user provided function along with the state variable, starting from the initial state. Since we need to pass the state between different states we won't use the for-loop, but instead, use recursion,
```
```
let fold_combs n k f x =
  let rec loop i s c x =
    if i < n then
      loop (i+1) s c @@
      let c = i::c and s = s + 1 and i = i + 1 in
      if s < k then loop i s c x else f c x
    else x in
  loop 0 0 [] x
```
```


q:
Why does the following method hang?

public void pipe(Reader in, Writer out) {
    CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
    while( in.read(buf) >= 0 ) {
      out.append(buf.flip());
    }
}

[A]
Answering my own question: you have to call
```
buf.clear()
```
between
```
read
```
s. Presumably,
```
read
```
is hanging because the buffer is full. The correct code is
```
public void pipe(Reader in, Writer out) {
    CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
    while( in.read(buf) >= 0 ) {
      out.append(buf.flip());
      buf.clear();
    }
}
```


q:
Where can I find the specifications for the various C# languages?

(EDIT: it appears people voted down because you could 'google' this, however, my original intent was to put an answer with information not found on google. I've accepted the answer with the best google results, as they are relevant to people who haven't paid for VS)

[A]
If you have Visual Studio 2005 or 2008, they are already on your machine!
For 2005 (English):
```
```
.\Microsoft Visual Studio 8\VC#\Specifications\1033
```
```
For 2008 (English):
```
```
.\Microsoft Visual Studio 9.0\VC#\Specifications\1033
```
```
For 2010 (English):
```
```
.\Microsoft Visual Studio 10.0\VC#\Specifications\1033
```
```
For 2012 (English):
```
```
.\Microsoft Visual Studio 11.0\VC#\Specifications\1033
```
```


q:
I need to parse RFC 3339 strings like "2008-09-03T20:56:35.450686Z" into Python's datetime type.

I have found strptime in the Python standard library, but it is not very convenient.

What is the best way to do this?

[A]
What is the exact error you get? Is it like the following?
```
```
>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format:  data=2008-08-12T12:20:30.656234Z  fmt=%Y-%m-%dT%H:%M:%S.Z
```
```
If yes, you can split your input string on ".", and then add the microseconds to the datetime you got.
Try this:
```
```
>>> def gt(dt_str):
        dt, _, us= dt_str.partition(".")
        dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
        us= int(us.rstrip("Z"), 10)
        return dt + datetime.timedelta(microseconds=us)

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)
```
```


q: I am attempting to read a large XML document and I wanted to do it in chunks vs XmlDocument's way of reading the entire file into memory. I know I can use XmlTextReader to do this but I was wondering if anyone has used SAX for .NET? I know Java developers swear by it and I was wondering if it is worth giving it a try and if so what are the benefits in using it. I am looking for specifics.

[A]
If you're talking about
SAX for .NET
, the project doesn't appear to be maintained.  The last release was more than 2 years ago.  Maybe they got it perfect on the last release, but I wouldn't bet on it.  The author, Karl Waclawek, seems to have disappeared off the net.
As for SAX under Java?  You bet, it's great.  Unfortunately, SAX was never developed as a standard, so all of the non-Java ports have been adapting a Java API for their own needs.  While DOM is a pretty lousy API, it has the advantage of having been designed for multiple languages and environments, so it's easy to implement in Java, C#, JavaScript, C, et al.


q:
I have a Publishing Portal site and I need to add some announcements to some of the pages.  I've read an article which says that i have to create an announcement list to be able add an announcement web part but i can't seem to find any resources on how i can add an announcement list.

Any help will be greatly appreciated.

TIA!

[A]
Giving you direct instructions on how to create the list would most likely leave you more lost than ever. If this is a publishing portal, there's a lot more to learn beyond just creating a list. Content must be approved, and is versioned. I'd strongy advise you not to start poking around in there as you run a large risk of messing up the portal. Don't get stressed by people demanding you perform such things without having received any training. Grab yourself a coffee, flip your boss the finger and watch some pertinant webcasts on
http://office.microsoft.com/en-us/sharepointserver/FX101211721033.aspx
Hope this helps,
Oisin


q:
I'm confused with how views are organized, and it is important to understand this as ASP.NET MVC uses conventions to get everything working right.

Under the views directory, there are subdirectories.  Inside these subdirectories are views.  I'm assuming that the subdirectories map to controllers, and the controllers act on the views contained within their subdirectories.

Is there an emerging expectation of what types of views are contained within these directories?  For instance, should the default page for each directory be index.aspx?  Should the pages follow a naming convention such as Create[controller].aspx, List[controller].aspx, etc?  Or does it not matter?

[A]
View directory naming and file naming are important, because the ASP.NET MVC framework makes certain assumptions about them.  If you do not conform to these assumptions, then you must write code to let the framework know what you are doing. Generally speaking, you should conform to these assumptions unless you have a good reason not to.
Let's look at the simplest possible controller action:
```
```
public ActionResult NotAuthorized()
    {
        return View();
    }
```
```
Because no view name has been specified in the call to View(), the framework will presume that the view filename will be the same as the Action name. The framework has a type called ViewEngine which will supply the extension.  The default ViewEngine is WebFormViewEngine, which will take that name and append an .aspx to it. So the full filename in this case would be NotAuthorized.aspx.
But in which folder will the file be found?  Again, the ViewEngine supplies that information.  With WebFormViewEngine, it will look in two folders: ~/Views/Shared and ~/Views/{controller}
So if your controller was called AccountController, it would look in ~/Views/Account
But there might be times when you don't want to follow these rules.  For instance, two different actions might return the same view (with a different model, or something).  In this case, if you specify the view name explicitly in your action:
```
```
public ActionResult NotAuthorized()
    {
        return View("Foo");
    }
```
```
Note that with WebFormViewEngine, the "view name" is generally the same as the filename, less the extension, but the framework does not require that of other view engines.
Similarly, you might also have a reason to want your application to look for views and non-default folders.  You can do that by creating your own ViewEngine.  I show the technique in
this blog post
, but the type names are different, since it was written for an earlier version of the framework.  The basic idea is still the same, however.


q:
Is there a specfic Gang Of Four Design Pattern that you frequently use, yet hardly see used in other peoples designs?  If possible, please describe a simple example where this pattern can be useful.  It doesn't have to necessarily be a Gang Of Four pattern, but please include a hyperlink to the pattern's description if you choose a non-GoF pattern.

Put another way:

What are some good/useful design patterns that I, or someone else who does have a passing knowledge of the main patterns, may not already know?

[A]
Strategy pattern maybe? I see not a lot of person using it and it's quite useful when calculations change or can be accumulated together. I use it when a part of the calculation can be replaced by another calculation. Often in program that use for enterprise rate for product.
Here is some documentation :
Wikipedia
DoFactory


q:
i have a control that is organized like this

and i want to have the javascript registered on the calling master pages, etc, so that anywhere this control folder is dropped and then registered, it will know how to find the URL to the js.

Here is what i have so far (in the user control )

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsClientScriptBlockRegistered("jqModal"))
        Page.ClientScript.RegisterClientScriptInclude("jqModal", ResolveClientUrl("~js/jqModal.js"));
    if (!Page.IsClientScriptBlockRegistered("jQuery"))
        Page.ClientScript.RegisterClientScriptInclude("jQuery", ResolveClientUrl("~/js/jQuery.js"));
    if (!Page.IsClientScriptBlockRegistered("tellAFriend"))
        Page.ClientScript.RegisterClientScriptInclude("tellAFriend", ResolveClientUrl("js/tellAFriend.js"));
}

Any ideas?

[A]
You can use a helper class with static method:
```
```
public static class PageHelper {
    public static void RegisterClientScriptIfNeeded( Page page, string key, string url ) {
        if( false == page.IsClientScriptBlockRegistered( key )) {
            page.ClientScript.RegisterClientScriptInclude( key , ResolveClientUrl( url ));
        }
    }
}
```
```
or you can have a similar instance method in some base class for page/webcontrol/usercontrol, which will do the same thing.


q:
What is the best way to create reverse index for full text search in Common Lisp ? Is there any proven and (relatively) bug-free open library for SBCL or LispWorks ?

I managed to create my own library on top of AllegroCache - it was fairly easy to create, reliable and fast, but lacks advanced search options (phrases, wildcarded words in phrases, etc).

Is there any open library that can be used with SBCL or LispWorks so I don't have to reinvent the wheel by writing my own ?

[A]
I know you're asking about Common Lisp, but there are a number of inverted text search service oriented applications.   One well known and respected on is
Lucene
.
Could a solution be to use that search engine, but interface your Common Lisp code via a web-service API?  (xml-rpc, xml over http or just text over http)?
Is there a further reason why you'd like it to be in Common Lisp?  Packages like Lucene may cover all the search related features you need, while using a remote api may still allow you to perform your more complex logic in Common Lisp.


q:
i m developing a little tool on my Pocket PC using WM6  SDK but i would like to implement a finger friendly user interface (iphone-like).
So i m looking for a free .NET framework that offers the possibility to easily integrate a finger friendly interface for Windows Mobile 6 Pro .

Any ideas ?

EDIT : Finger friendly means big icons, big buttons , scrollable screens with a simple touch of the thumb... Because the Winforms in Compact framework are made for the stylus, not fingers !!

[A]
I'm not entirely sure what you're asking here... Windows Mobile 6.0 Pro
is
touch-screen enabled, so you should simply have to create your project targeting the Windows Mobile 6.0 Pro (note, however, that your application will not be compatible with Windows Mobile 6.0 Standard devices).


q: When I iterate over the values or keys are they going to correlate?  Will the second key map to the second value?

[A]
The question confused me at first but @Matt cleared it up for me.
Consider using the entrySet() method that returns a set with the key-value pairs on the Map.
```
```
Map<Integer, Integer> a = new HashMap<Integer, Integer>(2);
a.put(1, 2);
a.put(2, 3);
for (Map.Entry<Integer, Integer> entry : a.entrySet()) {
    System.out.println(entry.getKey() + " => " + entry.getValue());
}
```
```
This outputs:
```
```
1 => 2
2 => 3
3 => 3
```
```


q:
In a CakePHP 1.2 app, I'm using

<?php $session->flash();?>

to output messages like "Record edited". It's working great.

However, I want to add a link called "Dismiss" that will fade out the message. I know how to construct the link, but I don't know how to insert into the output of the flass message.

The flash message wraps itself in a DIV tag. I want to insert my dismiss code into that div, but I don't know how.

[A]
Figured this out:
Create a new layout in your layouts folder:
```
```
layouts/message.ctp
```
```
In that layout, include the call to output the content:
```
```
<?php echo $content_for_layout; ?>
```
```
Then when you set the flash message, specify the layout to use:
```
```
$this->Session->setFlash('Your record has been created! Wicked!','message');
```
```


q:
I'm writing a custom file selection component. In my UI, first the user clicks a button, which pops a JFileChooser; when it is closed, the absolute path of the selected file is written to a JTextField.

The problem is, absolute paths are usually long, which causes the text field to enlarge, making its container too wide.

I've tried this, but it didn't do anything, the text field is still too wide:

fileNameTextField.setMaximumSize(new java.awt.Dimension(450, 2147483647));

Currently, when it is empty, it is already 400px long, because of GridBagConstraints attached to it.

I'd like it to be like text fields in HTML pages, which have a fixed size and do not enlarge when the input is too long.

So, how do I set the max size for a JTextField ?

[A]
It may depend on the layout manager your text field is in.  Some layout managers expand and some do not.  Some expand only in some cases, others always.
I'm assuming you're doing
```
```
filedNameTextField = new JTextField(80); // 80 == columns
```
```
If so, for most reasonable layouts, the field should not change size (at least, it shouldn't grow).  Often layout managers behave badly when put into
```
JScrollPane
```
s.
In my experience, trying to control the sizes via
```
setMaximumSize
```
and
```
setPreferredWidth
```
and so on are precarious at best.  Swing decided on its own with the layout manager and there's little you can do about it.
All that being said, I have no had the problem you are experiencing, which leads me to believe that some judicious use of a layout manager will solve the problem.


q: In a recent conversation, I mentioned that I was using JavaScript for a web application. That comment prompted a response: "You should use Flex instead. It will cut your development time down and JavaScript is too hard to debug and maintain. You need to use the right tool for the right job." Now, I don't know too much about Flex, but I personally don't feel like JavaScript is too hard to debug or maintain, especially if you use a framework. JavaScript is also one of the most used languages right now, so it would seem a better choice in that regard too. However, his reply piqued my interest. Would Flex be a good choice for a distributable web app for which 3rd party developers could build add-ons? What are the advantages of using it vs. a JavaScript framework? What are some of the disadvantages?

[A]
I have recently started to develop Flex applications, and I personally find it a refreshing framework for the web.
You get a state-ful application that runs completely client side. You get no worries about  cross-browser portability that you do with JavaScript, and you get some really neat things such as effects, graphing, and rich user interface components.
Flex also makes it easy to communicate to webservices and the XML parsing via ECMA is insanely powerful and simple.
I'm glad I have made the switch. As far as how popular it is...I'm not really sure, but I am fairly certain that the developer base is expanding rapidly.
The only real disadvantage I can think of is a flash player requirement, but I would say it is pretty safe to assume that most browser support flash player; even konquerer in Linux is supported; much more so then a silverlight runtime (which I NEVER plan on installing)


q:
In Java, I use a class in which some fields can be null. For example:

class Foo {
    String bar;
    //....
}

I want to write a BarComparator for this class,

    private static class BarComparator
            implements Comparator<Foo> {
        public int compare( final Foo o1, final Foo o2 )
        {
            // Implementation goes here
        }
    }

Is there a standard way to deal with the fact that any of o1, o2, o1.bar, o2.bar can be null, without writing lots of nested if...else?

Cheers!

[A]
I think early return statements would be the other alternative to lots of ifs
e.g.
```
```
if(o1==null) return x;
if(o2==null) return x;
if(o1.getBar()==null) return x;
if(o2.getBar()==null) return x;

// No null checks needed from this point.
```
```


q:
What do you think the benefits of functional programming are? And how do they apply to programmers today?

What are the greatest differences between functional programming and OOP?

[A]
It doesn't have to be one or the other: using a language like C#3.0 allows you to mix the best elements of each. OO can be used for the large scale structure at class level and above, Functional style for the small scale structure at method level.
Using the Functional style allows code to be written that declares its intent clearly, without being mixed up with control flow statements, etc. Because of the principles like side-effect free programming, it is much easier to reason about code, and check its correctness.


q:
I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox.

I cannot seem to find an easyway to essentially do the following:

if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text")
<asp:TextBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>
else
<asp:CheckBox runat="server" ID="txtField" Text='<%#((System.Xml.XmlNode)Container.DataItem).InnerText %>' CssClass="std"></asp:TextBox>

Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work

[A]
What about something similar to this in your markup in each the textbox and checkbox controls?
```
```
Visible=<%= Eval("type").tostring() == "text") %>
```
```


q:
Given an Item that has been appended to a Form, whats the best way to find out what index that item is at on the Form?

Form.append(Item) will give me the index its initially added at, but if I later insert items before that the index will be out of sync.

[A]
This was the best I could come up with:
```
```
private int getItemIndex(Item item, Form form) {
    for(int i = 0, size = form.size(); i < size; i++) {
        if(form.get(i).equals(item)) {
            return i;
        }
    }
    return -1;
}
```
```
I haven't actually tested this but it should work, I just don't like having to enumerate every item but then there should never be that many so I guess its ok.


q:
What is a good implementation of a IsLeapYear function in VBA?

Edit: I ran the if-then and the DateSerial implementation with iterations wrapped in a timer, and the DateSerial was quicker on the average by 1-2 ms (5 runs of 300 iterations, with 1 average cell worksheet formula also working).

[A]
```
```
Public Function isLeapYear(Yr As Integer) As Boolean

    ' returns FALSE if not Leap Year, TRUE if Leap Year

    isLeapYear = (Month(DateSerial(Yr, 2, 29)) = 2)

End Function
```
```
I originally got this function from Chip Pearson's great Excel site.
Pearson's site


q: What is currently the best tool for JavaME unit testing? I´ve never really used unit testing before (shame on me!), so learning curve is important. I would appreciate some pros and cons with your answer. :)

[A]
I'll be honest, the only unit tester I've used in Java is
JUnit
and a child project for it named
DBUnit
for database testing... which I'm assuming you won't need under J2ME.
JUnit's pretty easy to use for unit testing, as long as your IDE supports it (Eclipse has support for JUnit built in).  You just mark tests with the @Test annotation (org.junit.Test I think).  You can also specify methods that should be run
```
@Before
```
or
```
@After
```
each test, as well as before or after the entire class (with
```
@BeforeClass
```
and
```
@AfterClass
```
).
I've never used JUnit under J2ME, though... I work with J2EE at work.


q:
How to tag images in the image itself in a web page?

I know Taggify, but... is there other options?

Orkut also does it to tag people faces... How is it done?

Anyone knows any public framework that is able to do it?

See a sample bellow from Taggify:

[A]
I know this isn't javascript but C# 3.0 has an API for doing this. The
System.Windows.Media.Imaging
namespace has a class called
BitmapMetadata
which can be used to read and write image metadata (which is stored in the image itself). Here is a method for retrieving the metadata for an image given a file path:
```
```
public static BitmapMetadata GetMetaData(string path)
{
    using (Stream s = new System.IO.FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
    {
        var decoder = BitmapDecoder.Create(s, BitmapCreateOptions.None, BitmapCacheOption.OnDemand);
        var frame = decoder.Frames.FirstOrDefault();
        if (frame != null)
        {
            return frame.Metadata as BitmapMetadata;
        }
        return null;
    }
}
```
```
The BitmapMetadata class has a property for tags as well as other common image metadata. To save metadata back to the image, you can use the
InPlaceBitmapMetadataWriter Class
.


q:
For a project of mine I would love to provide auto completion for a specific textarea.  Similar to how intellisense/omnicomplete works.  For that however I have to find out the absolute cursor position so that I know where the DIV should appear.

Turns out: that's (nearly I hope) impossible to achieve.  Does anyone has some neat ideas how to solve that problem?

[A]
This
blog post seems to address your question, but unfortunately the author admits he has only tested it in IE 6.
The DOM in IE does not provide information regarding relative position in terms of characters; however, it does provide bounding and offset values for browser-rendered controls.  Thus, I used these values to determine the relative bounds of a character. Then, using the JavaScript TextRange, I created a mechanism for working with such measures to calculate the Line and Column position for fixed-width fonts within a given TextArea.
First, the relative bounds for the TextArea must be calculated based upon the size of the fixed-width font used.  To do this, the original value of the TextArea must be stored in a local JavaScript variable and clear the value.  Then, a TextRange is created to determine the Top and Left bounds of the TextArea.


q:
I am currently initializing a Hashtable in the following way:

Hashtable filter = new Hashtable();
filter.Add("building", "A-51");
filter.Add("apartment", "210");

I am looking for a nicer way to do this.

I tried something like

Hashtable filter2 = new Hashtable() {
    {"building", "A-51"},
    {"apartment", "210"}
};

However the above code does not compile.

[A]
In C# 3 it should compile fine like this:
```
```
Hashtable table = new Hashtable {{1, 1}, {2, 2}};
```
```


q:
Date coming out of a database, need to format as "mm/dd/yy"

For Each dr as DataRow in ds.Tables(0).Rows

Response.Write(dr("CreateDate"))

Next

[A]
```
```
Response.Write(DateTime.Parse(dr("CreateDate").ToString()).ToString("MM/dd/yyyy"))
```
```


q:
I'm writing an RSS to JSON parser and as a part of that, I need to use htmlentities() on any tag found inside the description tag. Currently, I'm trying to use preg_replace(), but I'm struggling a little with it. My current (non-working) code looks like:

$pattern[0] = "/\<description\>(.*?)\<\/description\>/is";
$replace[0] = '<description>'.htmlentities("$1").'</description>';
$rawFeed = preg_replace($pattern, $replace, $rawFeed);

If you have a more elegant solution to this as well, please share. Thanks.

[A]
Simple.  Use
```
preg_replace_callback
```
:
```
```
function _handle_match($match)
{
    return '<description>' . htmlentities($match[1]) . '</description>';
}

$pattern = "/\<description\>(.*?)\<\/description\>/is";
$rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed);
```
```
It accepts any callback type, so also methods in classes.


q: Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?

[A]
Upgrade. For me it was very simple: change
```
__str__()
```
to
```
__unicode__()
```
, write basic
```
admin.py
```
, and done. Just start running your app on 1.0, test it, and when you encounter an error use the documentation on
backwards-incompatible changes
to see how to fix the issue.


q:
PEP 8 states:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed?

Isn't this:

class SomeClass(object):

    def not_often_called(self)
        from datetime import datetime
        self.datetime = datetime.now()

more efficient than this?

from datetime import datetime

class SomeClass(object):

    def not_often_called(self)
        self.datetime = datetime.now()

[A]
The first variant is indeed more efficient than the second when the function is called either zero or one times.  With the second and subsequent invocations, however, the "import every call" approach is actually less efficient.  See
this link
for a lazy-loading technique that combines the best of both approaches by doing a "lazy import".
But there are reasons other than efficiency why you might prefer one over the other.  One approach is makes it much more clear to someone reading the code as to the dependencies that this module has.  They also have very different failure characteristics -- the first will fail at load time if there's no "datetime" module while the second won't fail until the method is called.
Added Note:
In IronPython, imports can be quite a bit more expensive than in CPython because the code is basically being compiled as it's being imported.


q:
I've just updated my ruby installation on my gentoo server to ruby 1.8.6 patchlevel 287 and have started getting an error on one of my eRuby apps. The error given in the apache error_log file is:

[error] mod_ruby: /usr/lib/ruby/1.8/cgi.rb:774: superclass mismatch for class Cookie (TypeError)

The strange thing is that it seems to work sometimes - but other times I get that error. Anyone any ideas?

[A]
That error shows up when you redeclare a class that’s already been declared, most likely because you’re loading two different copies of cgi.rb. See a
similar issue in Rails
.


q: We have our JBoss and Oracle on separate servers. The connections seem to be dropped and is causing issues with JBoss. How can I have the JBoss reconnect to Oracle if the connection is bad while we figure out why the connections are being dropped in the first place?

[A]
There is usually a configuration option on the pool to enable a validation query to be executed on borrow.  If the validation query executes successfully, the pool will return that connection.  If the query does not execute successfully, the pool will create a new connection.
The
JBoss Wiki
documents the various attributes of the pool.
```
```
<check-valid-connection-sql>select 1 from dual</check-valid-connection-sql>
```
```
Seems like it should do the trick.


q:
When is it a good idea to use PHP_EOL?

I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues?

[A]
Yes,
```
PHP_EOL
```
is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Note that
PHP_EOL
represents the endline character for the
current
system. For instance, it will not find a Windows endline when executed on a unix-like system.


q:
I'm trying to get the contents of a XML document element, but the element has a colon in it's name.

This line works for every element but the ones with a colon in the name:

$(this).find("geo:lat").text();

I assume that the colon needs escaping. How do I fix this?

[A]
Use a backslash, which itself should be escaped so JavaScript doesn't eat it:
```
```
$(this).find("geo\\:lat").text();
```
```


q: Seems so basic, I can't believe I don't know this! I just need a scratch folder to dump some temporary files to. I don't care if it gets wiped out between usages or not, and I don't think I should have to go through the hassle of creating one and maintaining it myself from within my application. Is that too much to ask?

[A]
Use
```
System.IO.Path.GetTempPath()
```
.


q:
Is there any easy way to create a class that uses IFormatProvider that writes out a user-friendly file-size?

public static string GetFileSizeString(string filePath)
{
    FileInfo info = new FileInfo(@"c:\windows\notepad.exe");
    long size = info.Length;
    string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic...
}

It should result in strings formatted something like "2,5 MB", "3,9 GB", "670 bytes" and so on.

[A]
I use this one, I get it from the web
```
```
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter)) return this;
        return null;
    }

    private const string fileSizeFormat = "fs";
    private const Decimal OneKiloByte = 1024M;
    private const Decimal OneMegaByte = OneKiloByte * 1024M;
    private const Decimal OneGigaByte = OneMegaByte * 1024M;

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (format == null || !format.StartsWith(fileSizeFormat))
        {
            return defaultFormat(format, arg, formatProvider);
        }

        if (arg is string)
        {
            return defaultFormat(format, arg, formatProvider);
        }

        Decimal size;

        try
        {
            size = Convert.ToDecimal(arg);
        }
        catch (InvalidCastException)
        {
            return defaultFormat(format, arg, formatProvider);
        }

        string suffix;
        if (size > OneGigaByte)
        {
            size /= OneGigaByte;
            suffix = "GB";
        }
        else if (size > OneMegaByte)
        {
            size /= OneMegaByte;
            suffix = "MB";
        }
        else if (size > OneKiloByte)
        {
            size /= OneKiloByte;
            suffix = "kB";
        }
        else
        {
            suffix = " B";
        }

        string precision = format.Substring(2);
        if (String.IsNullOrEmpty(precision)) precision = "2";
        return String.Format("{0:N" + precision + "}{1}", size, suffix);

    }

    private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)
    {
        IFormattable formattableArg = arg as IFormattable;
        if (formattableArg != null)
        {
            return formattableArg.ToString(format, formatProvider);
        }
        return arg.ToString();
    }

}
```
```
an example of use would be:
```
```
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 100));
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 10000));
```
```
Credits for
http://flimflan.com/blog/FileSizeFormatProvider.aspx
There is a problem with ToString(), it's expecting a NumberFormatInfo type that implements IFormatProvider but the NumberFormatInfo class is sealed :(
If you're using C# 3.0 you can use an extension method to get the result you want:
```
```
public static class ExtensionMethods
{
    public static string ToFileSize(this long l)
    {
        return String.Format(new FileSizeFormatProvider(), "{0:fs}", l);
    }
}
```
```
You can use it like this.
```
```
long l = 100000000;
Console.WriteLine(l.ToFileSize());
```
```
Hope this helps.


q: Pretty simple scenario. I have a web service that receives a byte array that is to be saved as a particular file type on disk. What is the most efficient way to do this in C#?

[A]
That would be
```
File.WriteAllBytes()
```
.


q: Are there any good packages or methods for doing extensive CRUD (create-retrieve-update-delete) interfaces in the Turbogears framework. The FastDataGrid widget is too much of a black box to be useful and CRUDTemplate looks like more trouble than rolling my own. Ideas? Suggestions?

[A]
While
CRUDTemplate
looks mildly complex, I'd say that you can implement CRUD/ABCD using just about any ORM that you choose. It just depends on how much of it you with to automate (which generally means defining models/schemas ahead of time). You may learn more and have better control if you put together your own using SQLAlchemy or SQLObject, woth of which work great with TurboGears.


q: Is it possible to use AIX's mksysb and savevg to create a bootable tape with the rootvg and then append all the other VGs?

[A]
First, use savevg to backup any extra volume groups to a file system on the rootvg:
```
```
savevg -f /tmp/vgname
```
```
Compress it if it will be too large, or use the -i option to exclude files.  The easiest way is to exclude all files on the volume group and restore those off of the regular backup device.  Once that is done, create your normal mksysb.
For DR purposes, restore the system using the mksysb, then use restvg to restore the volume groups out of your backup files.  Restore any extra files that may have been excluded, and you're running again.


q:
I really enjoy having "pretty" URLs (e.g. /Products/Edit/1 instead of /products.aspx?productID=1) but I'm at a loss on how to do this for pages that let you search by a large number of variables.

For instance, let's say you have a page that lets a user search for all products of a particular type with a certain name and near a specific address.  Would you do this with really long "pretty" URLs

/Products/Search/Type/{producttype}/Name/{name}/Address/{address}

or just resort to using url params

/Products/Search?productType={producttype}&name={name}&address={address}

[A]
The MVC (Model View Controller) framework is designed specifically to tackle this issue. It uses a form of url rewriting to redirect actions to pages and provides just the functionality you're looking for. It makes handling pretty urls a breeze.
With regard to the length of URLs, id still use pretty urls but a particularly long URL may be an indication that you may want to reconsider your grouping of the items, alter the classification if you will so Products/{NAME}/{Address} without intermediary url parts.
Examples of the MVC framework can be found at:
.Net -
http://www.asp.net/mvc/
PHP -
http://www.phpmvc.net/
Java -
http://struts.apache.org/


q:
I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn't do anything:

StreamReader reader=new  StreamReader("myfile.txt");
try
{
  int i = 5 / 0;
}
catch   // No args, so it will catch any exception
{}
reader.Close();

However, this is considered good form:

StreamReader reader=new  StreamReader("myfile.txt");
try
{
  int i = 5 / 0;
}
finally   // Will execute despite any exception
{
  reader.Close();
}

As far as I can tell, the only difference between putting cleanup code in a finally block and putting cleanup code after the try..catch blocks is if you have return statements in your try block (in that case, the cleanup code in finally will run, but code after the try..catch will not).

Otherwise, what's so special about finally?

[A]
"Finally" is a statement of "Something you must always do to make sure program state is sane". As such, it's always good form to have one, if there's any possibility that exceptions may throw off the program state. The compiler also goes to great lengths to ensure that your Finally code is run.
"Catch" is a statement of "I can recover from this exception". You should only recover from exceptions you really can correct - catch without arguments says "Hey, I can recover from anything!", which is nearly always untrue.
If
it were possible to recover from every exception, then it would really be a semantic quibble, about what you're declaring your intent to be. However, it's not, and almost certainly frames above yours will be better equipped to handle certain exceptions. As such,   use finally, get your cleanup code run for free, but still let more knowledgeable handlers deal with the issue.


q:
I'm sure there's some trivial one-liner with perl, ruby, bash whatever that would let me run a command in a loop until I observe some string in stdout, then stop.  Ideally, I'd like to capture stdout as well, but if it's going to console, that might be enough.

The particular environment in question at the moment is RedHat Linux but need same thing on Mac sometimes too.  So something, generic and *nixy would be best.  Don't care about Windows - presumably a *nixy thing would work under cygwin.

UPDATE: Note that by "observe some string" I mean "stdout contains some string" not "stdout IS some string".

[A]
There's a bunch of ways to do this, the first that came to mind was:
```
```
OUTPUT="";
while [ `echo $OUTPUT | grep -c somestring` = 0 ]; do
  OUTPUT=`$cmd`;
done
```
```
Where $cmd is your command to execute.
For the heck of it, here's a BASH function version, so you can call this more easily if it's something you're wanting to invoke from an interactive shell on a regular basis:
```
```
function run_until () {
  OUTPUT="";
  while [ `echo $OUTPUT | grep -c $2` = 0 ]; do
    OUTPUT=`$1`;
    echo $OUTPUT;
  done
}
```
```
Disclaimer: only lightly tested, may need to do some additional escaping etc. if your commands have lots of arguments or the string contains special chars.
EDIT
: Based on feedback from Adam's comment - if you
don't
need the output for any reason (i.e. don't want to display the output), then you can use this shorter version, with less usage of backticks and therefore less overhead:
```
```
OUTPUT=0;
while [ "$OUTPUT" = 0 ]; do
  OUTPUT=`$cmd | grep -c somestring`;
done
```
```
BASH function version also:
```
```
function run_until () {
  OUTPUT=0;
  while [ "$OUTPUT" = 0 ]; do
    OUTPUT=`$1 | grep -c $2`;
  done
}
```
```


q:
Several months ago my work deployed an in-house function that wraps the standard, php, mysql_query() function with additional options and abilities. A sample feature would be some handy debugging tools we can turn on/off.

I was wondering how popular query handlers are and what features people like to build into them.

[A]
I use a DBAL like
MDB2
,
Zend_Db
or
Doctrine
for similar reason. Primarily to be able to utilize all the shortcuts it offers, not so much for the fact that it supports different databases.
E.g., old:
```
```
<?php
$query  = "SELECT * FROM table";
$result = mysql_query($query);
if (!$result) {
  echo mysql_error();
} else {
  if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_obj($result)) {
      ...
    }
  }
}
?>
```
```
Versus (Zend_Db):
```
```
<?php
try {
  $result = $db->fetchAll("SELECT * FROM table");
  foreach($result as $row) {
    ...
  }
} catch (Zend_Exception $e) {
  echo $e->getMessage();
}
?>
```
```
IMHO, more intuitive.


q:
I want to install a gem on all my application servers, but gem install requires sudo access - how can I enable sudo only for running this capistrano command?

In other words, I don't wish to use sudo for all my deployment recipes, just when I invoke this command on the command line.

[A]
I'm not quite sure I understand the question, but I think you're asking how to restrict sudo to the one specific command and not have to grant unlimited capacity for mischief to all of your Ruby developers.
/etc/sudoers can be set up to restrict the commands which users are allowed to invoke as root. It is commonly set to ALL, but you can provide just a list of the allowed commands.


q:
When I started writing database queries I didn't know the JOIN keyword yet and naturally I just extended what I already knew and wrote queries like this:

SELECT a.someRow, b.someRow
FROM tableA AS a, tableB AS b
WHERE a.ID=b.ID AND b.ID= $someVar

Now that I know that this is the same as an INNER JOIN I find all these queries in my code and ask myself if I should rewrite them. Is there something smelly about them or are they just fine?

My answer summary: There is nothing wrong with this query BUT using the keywords will most probably make the code more readable/maintainable.

My conclusion: I will not change my old queries but I will correct my writing style and use the keywords in the future.

[A]
Nothing is wrong with the syntax in your example.  The 'INNER JOIN' syntax is generally termed 'ANSI' syntax, and came after the style illustrated in your example.  It exists to clarify the type/direction/constituents of the join, but is not generally functionally different than what you have.
Support for 'ANSI' joins is per-database platform, but it's more or less universal these days.
As a side note, one addition with the 'ANSI' syntax was the 'FULL OUTER JOIN' or 'FULL JOIN'.
Hope this helps.


q:
I have a base URL :

http://my.server.com/folder/directory/sample

And a relative one :

../../other/path

How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the Uri class or something similar.

It's for a standard a C# app, not an ASP.NET one.

[A]
```
```
var baseUri = new Uri("http://my.server.com/folder/directory/sample");
var absoluteUri = new Uri(baseUri,"../../other/path");
```
```
OR
```
```
Uri uri;
if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri);
```
```


q:
I usually format my project directory like J-P Boodhoo. a main dir containing solution file, then a lib folder for all third-party lib, a src dir, a tools lib for third-party that wont be deployed.... For more info look here

I set in my project the reference path for all the needed folder, but if a developper checkout the trunk, he have to set all the reference path. Is there a way to simplify this ?

And am I using Visual Studio 2008.

Thank you.

[A]
I'm not sure which Visual Studio language you use, but if it's C++, then then file paths are stored in the
```
.vcproj
```
project file which should also be under version control.  (NOTE: the
```
.sln
```
solution file does NOT store path settings) If you are careful to use relative, rather than absolute paths, it should be easily sharable among multiple developers.
In Visual C++ 2008,
project files are XML
so you can edit them directly.  If you want to get really fancy, you can use
```
.vsprops
```
property sheets
for additional control.


q:
I'm not committed to any particular GUI tookit or anything - just needs to be Java based. I want to do simple syntax highlighting ( XML and XQuery ) inside editable text areas.

My only candidate so far is Swing's JTextPane, as it supports seems to support the styling of text, but I have no idea how to implement it in this context.

If a particular toolkit has something like this out of the box, that would be awesome, but I'm open to doing this by hand if need be.

[A]
JSyntaxPane handles XML and can be extended
http://code.google.com/p/jsyntaxpane/wiki/Using
Or, it should be possible to extract the NetBeans editor, but that would probably be more work...
[edit] btw, I got the XML info from
here
...  it doesn't seem to mention it on the google code pages...


q:
I have a bash script that creates a Subversion patch file for the current directory. I want to modify it to zip the produced file, if -z is given as an argument to the script.

Here's the relevant part:

zipped=''
zipcommand='>'

if [ "$1" = "-z" ]
then
   zipped='zipped '
   filename="${filename}.zip"
   zipcommand='| zip >'
fi

echo "Creating ${zipped}patch file $filename..."

svn diff $zipcommand $filename

This doesn't work because it passes the | or > contained in $zipcommand as an argument to svn.

I can easily work around this, but the question is whether it's ever possible to use these kinds of operators when they're contained in variables.

Thanks!

[A]
I would do something like this (use bash -c or eval):
```
```
zipped=''
zipcommand='>'

if [ "$1" = "-z" ]
then
   zipped='zipped '
   filename="${filename}.zip"
   zipcommand='| zip -@'
fi

echo "Creating ${zipped}patch file $filename..."

eval "svn diff $zipcommand $filename"
# this also works:
# bash -c "svn diff $zipcommand $filename"
```
```
This appears to work, but my version of zip (Mac OS X) required that i change the line:
```
```
zipcommand='| zip -@'
```
```
to
```
```
zipcommand='| zip - - >'
```
```
Edit: incorporated @DanielBungert's suggestion to use eval


q:
How would I disable and later enable all indexes in a given schema/database in Oracle?

Note: This is to make sqlldr run faster.

[A]
From here:
http://forums.oracle.com/forums/thread.jspa?messageID=2354075
```
alter session set skip_unusable_indexes = true;
```
```
alter index your_index unusable;
```
do import...
```
alter index your_index rebuild [online];
```


q:
Essentially the only thing I can deploy to my deployment machine is a JAR file.  I can't install JRuby, nor can I install Glassfish or Tomcat.

Is it possible to package up a Rails application (including Rails, vendored, of course) to a JAR file such that I can do

c:\my_server> java rails_app.jar

and have it run WEBRick or Mongrel within the JVM?

[A]
I'd recommend that you checkout Jetty.  The process for
Embedding Jetty
is surprisingly easy, and it should be possible to give it your servlets from your current jar file.  I haven't used Ruby/Rails, though, so I'm not sure if there are any complications there.
Is it normally possible to embed all of your rails templates/models into a jar inside of a war file for deployment on Tomcat?  If so, then you should be able to get embedded Jetty to pull it from your single jar as well.


q:
I am writing a script for MS PowerShell.  This script uses the Copy-Item command.  One of the optional arguments to this command is "-container". The documentation for the argument states that specifying this argument "Preserves container objects during the copy operation."

This is all well and good, for I would be the last person to want unpreserved container objects during a copy operation.  But in all seriousness, what does this argument do?  Particularly in the case where I am copying a disk directory tree from one place to another, what difference does this make to the behavior of the Copy-Item command?

[A]
The container the documentation is talking about is the folder structure.  If you are doing a recursive copy and want to preserve the folder structure, you would use the -container switch. (Note: by default the -container switch is set to true, so you really would not need to specify it.  If you wanted to turn it off you could use
```
-container: $false
```
.)
There is a catch to this... if you do a directory listing and pipe it to Copy-Item, it will not preserve the folder structure.  If you want to preserve the folder structure, you have to specify the -path property and the -recurse switch.


q:
I've been a professional software engineer for about a year now, having graduated with a CS degree. I've known about assertions for a while in C++ and C, but had no idea they existed in C# and .NET at all until recently.

Our production code contains no asserts whatsoever and my question is this...

Should I begin using Asserts in our production code? And if so, When is its use most appropriate? Would it make more sense to do

Debug.Assert(val != null);

or

if ( val == null )
    throw new exception();

[A]
Put
```
Debug.Assert()
```
everywhere in the code where you want have sanity checks to ensure invariants. When you compile a Release build (i.e., no
```
DEBUG
```
compiler constant), the calls to
```
Debug.Assert()
```
will be removed so they won't affect performance.
You should still throw exceptions before calling
```
Debug.Assert()
```
. The assert just makes sure that everything is as expected while you're still developing.


q:
Sometimes I find myself in the situation where I want to execute several sequential commands like such:

try:
    foo(a, b)
except Exception, e:
    baz(e)
try:
    bar(c, d)
except Exception, e:
    baz(e)
...

This same pattern occurs when exceptions simply need to be ignored.

This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.

In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.

Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?

[A]
If they're simple one-line commands, you can wrap them in
```
lambda
```
s:
```
```
for cmd in [
    (lambda: foo (a, b)),
    (lambda: bar (c, d)),
]:
    try:
        cmd ()
    except StandardError, e:
        baz (e)
```
```
You could wrap that whole thing up in a function, so it looked like this:
```
```
ignore_errors (baz, [
    (lambda: foo (a, b)),
    (lambda: bar (c, d)),
])
```
```


q:
The resource definition in tomcat's server.xml looks something like this...

<Resource
    name="jdbc/tox"
    scope="Shareable"
    type="javax.sql.DataSource"
    url="jdbc:oracle:thin:@yourDBserver.yourCompany.com:1521:yourDBsid"
    driverClassName="oracle.jdbc.pool.OracleDataSource"
    username="tox"
    password="toxbaby"
    maxIdle="3"
    maxActive="10"
    removeAbandoned="true"
    removeAbandonedTimeout="60"
    testOnBorrow="true"
    validationQuery="select * from dual"
    logAbandoned="true"
    debug="99"/>

The password is in the clear.  How to avoid this?

[A]
We use C#'s    SHA1CryptoServiceProvider
```
```
print(SHA1CryptoServiceProvider sHA1Hasher = new SHA1CryptoServiceProvider();
        ASCIIEncoding enc = new ASCIIEncoding();

        byte[] arrbytHashValue = sHA1Hasher.ComputeHash(enc.GetBytes(clearTextPW));
        string HashData = System.BitConverter.ToString(arrbytHashValue);
        HashData = HashData.Replace("-", "");
        if (HashData == databaseHashedPassWO)
        {
            return true;
        }
        else
        {
            return false;
        });
```
```
)


q:
What's the most efficient way to read a stream into another stream?  In this case, I'm trying to read data in a Filestream into a generic stream.  I know I could do the following:

1. read line by line and write the data to the stream

2. read chunks of bytes and write to the stream

3. etc

I'm just trying to find the most efficient way.

Thanks

[A]
Reading a buffer of bytes and then writing it is fastest. Methods like
```
ReadLine()
```
need to look for line delimiters, which takes more time than just filling a buffer.


q:
I have recently been thinking about the difference between the two ways of defining an array:

int[] array

int array[]

Is there a difference?

[A]
They are semantically identical. The
```
int array[]
```
syntax was only added to help C programmers get used to java.
```
int[] array
```
is much preferable, and less confusing.


q:
Is there a way to statically/globally request a copy of the ApplicationContext in a Spring application?

Assuming the main class starts up and initializes the application context, does it need to pass that down through the call stack to any classes that need it, or is there a way for a class to ask for the previously created context?  (Which I assume has to be a singleton?)

[A]
Here's a nice way (not mine, the original reference is here:
http://sujitpal.blogspot.com/2007/03/accessing-spring-beans-from-legacy-code.html
I've used this approach and it works fine. Basically it's a simple bean that holds a (static) reference to the application context. By referencing it in the spring config it's initialized.
Take a look at the original ref, it's very clear.


q:
Ruby on Rails does not do multithreaded request-responses very well, or at least, ActiveRecord doesn't.

The notion of only one request-response active at the same time can be a hassle when creating web applications which fork off a shell-command that takes long to finish.

What I'd like are some of your views on these kinds of setups? Is Rails maybe not a good fit for some applications?

Also, what are the current state of affairs in regard to concurrency in Ruby on Rails? What are the best practices. Are there workarounds to the shortcomings?

[A]
Rails currently doesn't handle concurrent requests within a single MRI (Matz Ruby Interpreter) Ruby process. Each request is essentally wrapped with a giant mutex. A lot of work has gone into making the forthcoming Rails 2.2 thread-safe, but you're not going to get a lot of benefit from this when running under Ruby 1.8x. I can't comment on whether Ruby 1.9 will be different because I'm not very familiar with it, but probably not I'd have thought.
One area that does look very promising in this regard is running Rails using JRuby, because the JVM is generally acknowledged as being good at multi-threading.
Arun Gupta
from Sun Microsystems gave some
interesting performance figures
on this setup at RailsConf Europe recently.


q:
I have a many to many index table, and I want to do an include/exclude type query on it.

fid is really a integer index, but here as letters for easier understanding.  Here's a sample table :

table t

eid | fid
----+----
1   | A
1   | B
1   | C
2   | B
2   | C
3   | A
3   | C
4   | A
4   | B
5   | B

Here are some sample queries I want.

What eids have fid B, and NOT A?  (Answer eid 2 and 5)

What eids have fid C, and NOT A?  (Answer eid 2)

I can't seem to figure out a query that will do this.

I've tried a self join like this:

select *
from t as t1
join t as t2
where t1.eid=t2.eid
  and t1.fid!=t2.fid
  and t1.fid=B and t2.fid!=A

That won't work, because it will still return rows where eid=1 and fid=C.

Am I clear on what I want?

[A]
Use
set subtraction
```
```
Select eid from t where fid = 'B'
EXCEPT
select eid from t where fid = 'A'
```
```


q:
I have a Postgresql database on which I want to do a few cascading deletes.  However, the tables aren't set up with the ON DELETE CASCADE rule.  Is there any way I can perform a delete and tell Postgresql to cascade it just this once?  Something equivalent to

DELETE FROM some_table CASCADE;

The answers to this older question make it seem like no such solution exists, but I figured I'd ask this question explicitly just to be sure.

[A]
No.  To do it just once you would simply write the delete statement for the table you want to cascade.
```
```
DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table);
DELETE FROM some_table;
```
```


q:
There have been a few questions asked here about why you can't define static methods within interfaces, but none of them address a basic inconsistency: why can you define static fields and static inner types within an interface, but not static methods?

Static inner types perhaps aren't a fair comparison, since that's just syntactic sugar that generates a new class, but why fields but not methods?

An argument against static methods within interfaces is that it breaks the virtual table resolution strategy used by the JVM, but shouldn't that apply equally to static fields, i.e. the compiler can just inline it?

Consistency is what I desire, and Java should have either supported no statics of any form within an interface, or it should be consistent and allow them.

[A]
Two main reasons spring to mind:
Static methods in Java cannot be overridden by subclasses, and this is a much bigger deal for methods than static fields.  In practice, I've never even wanted to override a field in a subclass, but I override methods all the time.  So having static methods prevents a class implementing the interface from supplying its own implementation of that method, which largely defeats the purpose of using an interface.
Interfaces aren't supposed to have code; that's what abstract classes are for.  The whole point of an interface is to let you talk about possibly-unrelated objects which happen to all have a certain set of methods.  Actually providing an implementation of those methods is outside the bounds of what interfaces are intended to be.


q: This is likely going to be an easy answer and I'm just missing something, but here goes...If I have a Type, (that is, an actual System.Type...not an instance) how do I tell if it inherits from another specific base type?

[A]
EDIT: Note that the above solution will fail if the base type you are looking for is an interface.  The following solution will work for any type of inheritance, be it class or interface.
```
```
// Returns true if "type" inherits from "baseType"
public static bool Inherits(Type type, Type baseType) {
    return baseType.IsAssignableFrom(type)
}
```
```
(Semi)Helpful extract from the
MSDN
article:
true if [the argument] and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of [the argument], or if the current Type is an interface that [the argument] implements, or if [the argument] is a generic type parameter and the current Type represents one of the constraints of [the argument]. false if none of these conditions are true, or if [the argument] is a null reference (Nothing in Visual Basic).


q:
Forgive the vague title, I wasn't sure how to describe it.

If you have a generic model "Archive", how do you show different views/forms based on a user selected 'type'?

For example, the user creates a new "Archive", then gets the choice of video, book, audio etc. From there they get different forms based on the archive type.

Or would it be better to split them into different models - Video, Book, Audio?

Or can models inherit (like Video extends Archive). I guess this is basic OOP / classes, but have no idea how to apply that here.

Examples from any MVC framework are welcome!

[A]
Your models Video, Book and Audio can inherit from Archive.
And each model will have a controller.
http://yourserver/Books/Edit/11
You will have to get your user to pick the type of archive they want before you create the corresponding model.
EDIT (in response to comment)
In ASP.NET MVC your model will be a class.
```
```
public class Video : Archive
{
    public int Id {get;set}
    public string Name {get;set;}
    ...
}
```
```
You will also have a controller
```
```
public class VideoController : Controller
{
    public object Edit(int id)
    {
        Video myVideo = GetVideo(id);
        return View("Edit", myVideo);
    }
     ...
}
```
```
And you will have a view in the Views directory for example, the page which contains
```
```
public class Edit : View<Video>
{
    ...
}
```
```
So you can call this if you had a URL which was
http://localhost/Video/Edit/11
This was all done from memory, so there may be some mistakes, but the take-home message is that you specify the inheritance at the model.  The model is just a class.  In your case you want to inherit from Archive.  Once you've done that the model is pass around as normal.


q:
I often run into the problem that I have one stream full of data and want to write everything of it into another stream.

All code-examples out there use a buffer in form of a byte-array.

Is there a more elegant way to this?

If not, what's the ideal size of the buffer. Which factors make up this value?

[A]
Regarding the ideal buffer size:
"When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes)."
Any stream-reading process will use Read(char buffer[], int index, count), which is the method this quote refers to.
http://msdn.microsoft.com/en-us/library/9kstw824.aspx
(Under "Remarks").


q:
I understand the differences between optimistic and pessimistic locking.  Now, could someone explain to me when I would use either one in general?

And does the answer to this question change depending on whether or not I'm using a stored procedure to perform the query?

But just to check, optimistic means "don't lock the table while reading" and pessimistic means "lock the table while reading."

[A]
Optimistic assumes that nothing's going to change while you're reading it.
Pessimistic assumes that something will and so locks it.
If it's not essential that the data is perfectly read use optimistic. You might get the odd 'dirty' read - but it's far less likely to result in deadlocks and the like.
Most web applications are fine with dirty reads - on the rare occasion the data doesn't exactly tally the next reload does.
For exact data operations (like in many financial transactions) use pessimistic. It's essential that the data is accurately read, with no un-shown changes - the extra locking overhead is worth it.
Oh, and Microsoft SQL server defaults to page locking - basically the row you're reading and a few either side. Row locking is more accurate but much slower. It's often worth setting your transactions to read-committed or no-lock to avoid deadlocks while reading.


q: I'm writing a WinForms application and one of the tabs in my TabControl has a SplitContainer. I'm saving the SplitterDistance in the user's application settings, but the restore is inconsistent. If the tab page with the splitter is visible, then the restore works and the splitter distance is as I left it. If some other tab is selected, then the splitter distance is wrong.

[A]
I found the problem. Each tab page doesn't get resized to match the tab control until it gets selected. For example, if the tab control is 100 pixels wide in the designer, and you've just set it to 500 pixels during load, then setting the splitter distance to 50 on a hidden tab page will get resized to a splitter distance of 250 when you select that tab page.
I worked around it by recording the SplitterDistance and Width properties of the SplitContainer in my application settings. Then on restore I set the SplitterDistance to recordedSplitterDistance * Width / recordedWidth.


q:
I know that I can add the SourceSafeTypeLib to a project and can explore it in object browser and find obvious things (GetLatest, etc), but I am looking for some more thorough documentation or specific tutorials on things like "undo another user's checkout" or"determine who has a file checked out.

If anyone knows where to find this material, how to do advanced or non-obvious tasks with VSS, or knows how to disassemble a COM api (so I can engineer my own api) it would be much appreciated.

[A]
You might check out Microsoft's
documentation
on the Microsoft.VisualStudio.SourceSafe.Interop namespace (I assume that's what you've looked at). I used it to create a VB.NET utility that does get latest, check-outs, and check-ins against a VSS 2005 database.
A quick perusal revealed the IVSSItem.UndoCheckout method, and the IVSSCheckouts type, which is a collection of checkouts for a given file.


q:
I am writing a webpage in C# .NET.  In javascript there is a function called GetElementsByTagName... this is nice for javascript invoked from the .aspx page.  My question is, is there any way I can have this kind of functionality from my C# code-behind?

--

The scenario for those curious:  I used an asp:repeater to generate a lot of buttons, and now I'm essentially trying to make a button that clicks them all.  I tried storing all the buttons in a list as I created them, but the list is getting cleared during every postback, so I thought I could try the above method.

[A]
FindControl(), or iterate through the controls on the page...
```
```
For each ctl as Control in Me.Controls
  If ctl.Name = whatYouWant Then
    do stuff
Next 'ctl
```
```
--If you are creating the controls, you should be setting their ID's
```
```
Dim ctl as New Control()
ctl.ID = "blah1"
```
```
etc...


q:
How do I Configuring DoxyGen to document ActionScript files?

I've included the *.as and *.asi files in doxygen's search pattern, but the classes, functions and variables don't show there.

[A]
Instead of doxygen you should use a documentation generator that specifically supports the language. For ActionScript 2, you have a couple choices:
NaturalDocs
(
example
) (free)
ZenDoc
(free)
AS2Doc Pro
(
example
) (commercial)
If you are using ActionScript 3, Adobe includes a free documentation generator along with their open source compiler (the
Flex SDK
), called "
ASDoc
". If you are using
FlashDevelop
, the
latest beta
has a built in GUI for running ASDoc, so you don't have to dirty your hands with the commandline.


q:
When my browser renders the following test case, there's a gap below the image. From my understanding of CSS, the bottom of the blue box should touch the bottom of the red box. But that's not the case. Why?

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

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
  <title>foo</title>
</head>

<body>
  <div style="border: solid blue 2px; padding: 0px;">
    <img alt='' style="border: solid red 2px; margin: 0px;" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png" />
  </div>
</body>

</html>

[A]
Because the image is inline it sits on the baseline. Try
```
```
vertical-align: bottom;
```
```
Alternately, in IE sometimes if you have whitespace around an image you get that. So if you remove all the whitespace between the div and img tags, that may resolve it.


q:
Coming from a desktop background I'm not sure exactly how to pass the exceptions I have caught to an Error page in order to avoid the standard exception screen being seen by my users.

My general question is how do I pass the exception from page X to my Error page in ASP.net?

[A]
I think you can use the
global.asax
--
Application_Exception
handler to catch the exception and then store it for displaying in an error page.
But actually, your error page shouldn't contains code that might cause just another error. It should be simple "Oops! something went wrong" page.
If you want details on the error, use Windows' events viewer or
ELMAH
or employ some logging mechanism.


q:
I'm new to postgreSQL and I have a simple question:

I'm trying to create a simple script that creates a DB so I can later call it like this:

psql -f createDB.sql

I want the script to call other scripts (separate ones for creating tables, adding constraints, functions etc), like this:

\i script1.sql
\i script2.sql

It works fine provided that createDB.sql is in the same dir.

But if I move script2 to a directory under the one with createDB, and modify the createDB so it looks like this:

\i script1.sql
\i somedir\script2.sql

I get an error:

psql:createDB.sql:2: somedir: Permission denied

I'm using Postgres Plus 8.3 for windows, default postgres user.

EDIT:

Silly me, unix slashes solved the problem.

[A]
Postgres started on Linux/Unix.  I suspect that reversing the slash with fix it.
```
```
\i somedir/script2.sql
```
```
If you need to fully qualify something
```
```
\i c:/somedir/script2.sql
```
```
If that doesn't fix it, my next guess would be you need to escape the backslash.
```
```
\i somedir\\script2.sql
```
```


q:
If you are using Java or JavaScript, is there a good way to do something like a String subtraction so that given two strings:

org.company.project.component
org.company.project.component.sub_component

you just get:

sub_component

I know that I could just write code to walk the string comparing characters, but I was hoping there was a way to do it in a really compact way.

Another use-case is to find the diff between the strings:

org.company.project.component.diff
org.company.project.component.sub_component

I actually only want to remove the sections that are identical.

[A]
```
```
String result = "org.company.project.component.sub_component".replace("org.company.project.component","")
```
```
Should work...
EDIT: Apache commons libraries are also great to use
As noted below, the StringUtils class does in fact have a method for this:
StringUtils.remove()


q:
I have several long running report type transactions that take 5-10 minutes. Would I see any performance increase by using stored procs? Would it be significant?

each query runs once a night.

[A]
yes, the query plan for stored procs can be optimized
and even if it can't procs are preferred over embedded sql
"would you see any performance improvement" - the only way to know for certain is to try it
in theory, stored procedures pre-parse the sql and store the query plan instead of figuring out each time, so there should be some speedup just from that, however, i doubt it would be significant in a 5-10 minute process
if the speed is of concern your best bet is to look at the query plan and see if it can be improved with different query structures and/or adding indices et al
if the speed is not of concern, stored procs provide better encapsulation than inline sql


q: How does one write a unittest that fails only if a function doesn't throw an expected exception?

[A]
Use
```
TestCase.assertRaises
```
(or
```
TestCase.failUnlessRaises
```
) from the unittest module, for example:
```
```
import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)
```
```


q:
I'm using the following code to make sure all certificates pass, even invalid ones, but I would like to know if there is a better way, as this event gets called globally and I only want the certificate to pass for a certain HTTP call and not for any others that are happening asynchronously.

// This delegate makes sure that non-validating SSL certificates are passed
ServicePointManager.ServerCertificateValidationCallback = delegate(object certsender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
   return true;
};

The code above is just an example of ignoring any non-validation on the certificate. The problem that I'm having is that it is a global event. I can't see  which session the event is happening for. I might have a couple of http requests going through and I want to ask the user for an action for each request.

[A]
I have recently been looking into this issue but without the same requirements that you have.  I haven't seen a script that does what you want but have you considered instead checking if .NET 2.0 is installed and if not then prompt them to download it.  You can open a URL in the default browser and get the user to attempt the install again once the framework has been installed.
This is not an ideal situation from a user perspective but i think going with what your planning you will have to write some complex stuff to handle the different language constraints just to get it working.
Just my 2 cents.


q: What is the C# equivalent to the sql server 2005 real type?

[A]
it is a Single
see
here
for more info on SQL Server to .Net DataTypes


q: I am seeing both of them used in this script I am trying to debug and the literature is just not clear. Can someone demystify this for me?

[A]
Well Google really works for you on this one:
http://www.perlmonks.org/?node_id=94007
From the link:
Quick summary: 'my' creates a new
  variable, 'local' temporarily amends
  the value of a variable.
ie, 'local'
temporarily changes the
  value of the variable
, but only
within the scope
it exists in.
Generally use my, it's faster and doesn't do anything kind of weird.


q: I've installed TFS 2008, but I can't seem to access the server. When I try to connect to it in Visual Studio, I can't. If I try by browser on a remote PC, I get a generic page cannot be displayed. On the server, I get a 403. Nothing was touched in IIS and the service is running as a Network Service. Any ideas?

[A]
What happens if you send a simple HTTP request to the server directly?
ie:
telnet  8080 [enter]
GET / HTTP/1.1[enter]
[enter]
[enter]
That might give a hint about whether IIS is actually serving anything.  If you can do that on the server, what about from a different machine?  If the results are different a good guess is there are some security/firewall issues somewhere.  HTH a little.


q: I keep hearing this term tossed around in several different contexts. What is it?

[A]
Declarative programming is when you write your code in such a way that it describes what you want to do, and not how you want to do it. It is left up to the compiler to figure out the how.
Examples of declarative programming languages are SQL and Prolog.


q:
Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like
FindAllPostByTags(IList<Tag> tags)
 that returns all Posts that have all (not just some of) the Tags in the parameter. Any way I could accomplish this either with NHibernate Expressions or HQL? I've searched through the HQL documentation and couldn't find anything that suited my needs. I hope I'm just missing something obvious!

[A]
I don't have a system at hand with a Castle install right now, so I didn't test or compile this, but the code below should about do what you want.
```
```
Junction c = Expression.Conjunction();
foreach(Tag t in tags)
    c = c.Add( Expression.Eq("Tag", t);

return sess.CreateCriteria(typeof(Post)).Add(c).List();
```
```


q: Is there a catchall function somewhere that works well for sanitizing user input for SQL injection and XSS attacks, while still allowing certain types of HTML tags?

[A]
No.  You can't generically filter data without any context of what it's for.  Sometimes you'd want to take a SQL query as input and sometimes you'd want to take HTML as input.
You need to filter input on a whitelist -- ensure that the data matches some specification of what you expect.  Then you need to escape it before you use it, depending on the context in which you are using it.
The process of escaping data for SQL - to prevent SQL injection - is very different from the process of escaping data for (X)HTML, to prevent XSS.


q:
I ruined several unit tests some time ago when I went through and refactored them to make them more DRY--the intent of each test was no longer clear.  It seems there is a trade-off between tests' readability and maintainability.  If I leave duplicated code in unit tests, they're more readable, but then if I change the SUT, I'll have to track down and change each copy of the duplicated code.

Do you agree that this trade-off exists?  If so, do you prefer your tests to be readable, or maintainable?

[A]
Readability is more important for tests.  If a test fails, you want the problem to be obvious.  The developer shouldn't have to wade through a lot of heavily factored test code to determine exactly what failed.  You don't want your test code to become so complex that you need to write unit-test-tests.
However, eliminating duplication is usually a good thing, as long as it doesn't obscure anything, and eliminating the duplication in your tests may lead to a better API.  Just make sure you don't go past the point of diminishing returns.


q:
Can someone suggest a good module in perl which can be used to store collection of objects?

Or is ARRAY a good enough substitute for most of the needs?

Update:
I am looking for a collections class because I want to be able to do an operation like compute collection level property from each element.

Since I need to perform many such operations, I might as well write a class which can be extended by individual objects. This class will obviously work with arrays (or may be hashes).

[A]
i would stick with an ARRAY or a HASH.
```
```
@names = ('Paul','Michael','Jessica','Megan');
```
```
and
```
```
my %petsounds = ("cat" => "meow",
             "dog" => "woof",
             "snake" => "hiss");
```
```
source


q:
I've been using Winforms since .NET 1.1 and I want to start learning WPF.

I'm looking for some good resources for a beginner in WPF. What should I read, what tools do I need, and what are the best practices I should follow?

[A]
I'd recommend the book
Windows Presentation Foundation Unleashed
by Adam Nathan
Then I'd recommend you write an application.  Like every other dev environment, there are no perfect guidelines.  You have to find the ones that make the most sense for your circumstance.  The only way to do that is to just start coding.
As for tools, Visual Studio 2008 [Express] is your best bet.  Or you might be able to limp along with XamlPad.


q:
Hi I'd like to schedule an existing job in the Sql Server 2005 agent via C# code... i.e. when someone clicks a button on an asp.net web page.

How can I do this?

Thanks!

[A]
Have a look here:
SMO Job Class
The
SQL Server Management Objects (SMO) Class Library
lets you do practically anything programmatically in SQL Server.


q: I am working on a geometry problem that requires finding the intersection of two parabolic arcs in any rotation.  I was able to intesect a line and a parabolic arc by rotating the plane to align the arc with an axis, but two parabolas cannot both align with an axis.  I am working on deriving the formulas, but I would like to know if there is a resource already available for this.

[A]
I'd first define the equation for the parabolic arc in 2D without rotations:
```
```
x(t) = ax² + bx + c
  y(t) = t;
```
```
You can now apply the rotation by building a rotation matrix:
```
```
s = sin(angle)
  c = cos(angle)

  matrix = | c -s |
           | s  c |
```
```
Apply that matrix and you'll get the rotated parametric equation:
```
```
x' (t) = x(t) * c - s*t;
y' (t) = x(t) * s + c*t;
```
```
This will give you two equations (for x and y) of your parabolic arcs.
Do that for both of your rotated arcs and subtract them. This gives you an equation like this:
```
```
xa'(t) = rotated equation of arc1 in x
  ya'(t) = rotated equation of arc1 in y.
  xb'(t) = rotated equation of arc2 in x
  yb'(t) = rotated equation of arc2 in y.
  t1 = parametric value of arc1
  t2 = parametric value of arc2

  0 = xa'(t1) - xb'(t2)
  0 = ya'(t1) - yb'(t2)
```
```
Each of these equation is just a order 2 polynomial. These are easy to solve.
To find the intersection points you solve the above equation (e.g. find the roots).
You'll get up to two roots for each axis. Any root that is equal on x and y is an intersection point between the curves.
Getting the position is easy now: Just plug the root into your parametric equation and you can directly get x and y.


q:
If I want to put a form up on SharePoint, is it easier to use InfoPath or build a custom web part in C#?  Are there other options that I should consider?

What are the requirements and hurdles for each option?

[A]
Can you be more specific about the form and sharepoint version ?
It depends on your version of Sharepoint : if you got 2003, if you want to use InfoPath, it has to be installed on the clients as well. On SharePoint 2007, i
think
it is not required.
If it is a large form with few business rule, InfoPath can be the way to go -> wysiwyg, and easy deployment.
If your form involves more business rules, a web part or a page in _layouts can be "simpler" and more maintainable.


q:
It is a bit of a "chicken or egg" kind of query, but can someone dreamup a query that can return the name of the current database instance in which the query executes? Believe me when I say I understand the paradox: why do you need to know the name of the database instance if you're already connected to execute the query? Auditing in a multi-database environment.

I've looked at all the @@ globals in Books Online. "SELECT @@servername" comes close, but I want the name of the database instance rather than the server.

[A]
```
```
SELECT DB_NAME()
```
```
Returns the database name.