q: Hessian is a custom binary serialization protocol, (which is open-source - I think), that forms the basis for a binary cross platform remoting framework. I'd like to know if anyone here has used it, and if so, what sort of performance can we expect from a solution that bridges a Java app on one side with a C# app on the other. (Let us consider that we are serializing simple classes, and may be arrays, lists, dictionaries of simple classes.)

[A]
This is the sort of problem that web services were designed to solve.  Although no longer simple, the SOAP format allows you to serialize objects to an XML representation on a Java/C# application, transmit them across the wire and deserialize them in the corresponding Java/C# application (Java/C# may be replaced with virtually any language that can translate an XML document).  Although "serialize" is used here, it is also common for this process to be referred as "marshalling".
However, moving away from SOAP for web services is currently being considered by many.  Find out more about web services from Wikipedia:
http://en.wikipedia.org/wiki/Web_services


q:
For example: man(1), find(3), updatedb(2)?

What do the numbers in parentheses (Brit. "brackets") mean?

[A]
The section the command is documented in the manual. The list of sections is documented on man's manual. For example:
```
```
man 1 man
man 3 find
```
```
This is useful for when similar or exactly equal commands exist on different sections

s: huggingface

c: devops

d: intermediate


q:
Need to show a credits screen where I want to acknowledge the many contributors to my application.

Want it to be an automatically scrolling box, much like the credits roll at the end of the film.

[A] A quick and dirty method would be to use a Panel with a long list of Label controls on it that list out the various people and contributions. Then you need to set the Panel to be AutoScroll so that it has a vertical scrollbar because the list of labels goes past the bottom of the displayed Panel. Then add a time that updates the AutoScrollOffset by 1 vertical pixel each timer tick. When you get to the bottom you reset the offset to 0 and carry on. The only downside is the vertical scrollbar showing.


q:
Could someone write-up a step by step guide to developing a C++ based plugin for FireFox on Windows?

The links and examples on http://www.mozilla.org/projects/plugins/ are all old and inaccurate - the "NEW" link was added to the page in 2004.

The example could be anything, but I was thinking a plugin that lets JavaScript set the name and then displays "Hello {Name}".  To show 2-way communication, it could have a property that returns the full salutation.

Though not as important, it would be nice if the plugin would work in Chrome too.

[A]
It's fairly simple to make a plugin using NPAPI.  The key header files you'll need from the Gecko distribution are npapi.h and npupp.h.  You'll export functions from your plugin DLL or shared library with the names NP_Initialize, NP_Shutdown, NP_GetMIMEDescription, and NP_GetValue, and you'll need to also fill in the symbol table given to you in the NP_Initialize call with handlers for all of the NPP functions.
The key functions to implement from that set are NPP_New and NPP_Destroy.  Those define the lifecycle of a plugin instance.  If you're going to handle a media file linked from an <object> or <embed>, you'll need to also deal with NPP_NewStream, NPP_WriteReady, NPP_Write, and NPP_DestroyStream as a way for your plugin to get the file's data from the browser.  There's plenty more in
the Gecko Plugin developer's guide
.


q:
I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning.

Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser?

[A]
Try
setInterval
or
setTimeout
.
Here is an example:
```
```
(show = (o) => setTimeout(() => {

  console.log(o)
  show(++o)

}, 1000))(1);
```
```
```
```
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
```


q: I've just started developing an ExtJS application that I plan to support with a very lightweight JSON PHP service.  Other than that, it will be standalone. My question is, what is the best way to organize the files and classes that will inevitably come into existence?  Anyone have any experience with large ExtJS projects (several thousand lines).

[A]
While developing your application your file and folder structure shouldn't really matter as you're probably going to want to minimize the release code and stick it in a single JS file when you're done. An automated handler or build script is probably going to be the best bet for this (see
http://extjs.com/forum/showthread.php?t=44158
).
That said, I've read somewhere on the ExtJS forums that a single file per class is advisable, and I can attest to that from my own experience.


q:
Sorry for the subject line sounding like an even nerdier Harry Potter title.

I'm trying to use AS3's Socket class to write a simple FTP program to export as an AIR app in Flex Builder 3.  I'm using an FTP server on my local network to test the program.  I can successfully connect to the server (the easy part) but I can't send any commands.  I'm pretty sure that you have to use the ByteArray class to send these commands but there's some crucial piece of information that I'm missing apparently.  Does anyone know how to do this?  Thanks!
Dave

[A]
We will need more info to resolve this.. What you're saying here appears correct to me. You're using the Socket class to send data though, not ByteArray.
Are you sure data is not being sent? How are you receiving the response? It may be that it's working fine but you're just not aware of it? As i said, tell us more about what you're doing..
Lee Brimelow has a
screencast on gotoAndLearn
of writing an POP3 client. It's essentially the same of what you're doing so take a look.


q: I'm a very experienced Java programmer who has spent my entire time working with Java 1.4 and earlier.  Where can I find a quick reference that will give me everything I need to know about the new features in Java5 and later in a quick reference?

[A]
Here's a good place to start:
https://docs.oracle.com/javase/1.5.0/docs/relnotes/features.html
http://java.sun.com/developer/technicalArticles/releases/j2se15/


q:
When a previous Vim session crashed, you are greeted with the "Swap file ... already exists!" for each and every file that was open in the previous session.

Can you make this Vim recovery prompt smarter? (Without switching off recovery!) Specifically, I'm thinking of:

If the swapped version does not contain unsaved changes and the editing process is no longer running, can you make Vim automatically delete the swap file?

Can you automate the suggested process of saving the recovered file under a new name, merging it with file on disk and then deleting the old swap file, so that minimal interaction is required? Especially when the swap version and the disk version are the same, everything should be automatic.

I discovered the SwapExists autocommand but I don't know if it can help with these tasks.

[A]
I have vim store my swap files in a single local directory, by having this in my .vimrc:
```
```
set directory=~/.vim/swap,.
```
```
Among other benefits, this makes the swap files easy to find all at once.
Now when my laptop loses power or whatever and I start back up with a bunch of swap files laying around, I just run my
```
cleanswap
```
script:
```
```
TMPDIR=$(mktemp -d) || exit 1
RECTXT="$TMPDIR/vim.recovery.$USER.txt"
RECFN="$TMPDIR/vim.recovery.$USER.fn"
trap 'rm -f "$RECTXT" "$RECFN"; rmdir "$TMPDIR"' 0 1 2 3 15
for q in ~/.vim/swap/.*sw? ~/.vim/swap/*; do
  [[ -f $q ]] || continue
  rm -f "$RECTXT" "$RECFN"
  vim -X -r "$q" \
      -c "w! $RECTXT" \
      -c "let fn=expand('%')" \
      -c "new $RECFN" \
      -c "exec setline( 1, fn )" \
      -c w\! \
      -c "qa"
  if [[ ! -f $RECFN ]]; then
    echo "nothing to recover from $q"
    rm -f "$q"
    continue
  fi
  CRNT="$(cat $RECFN)"
  if diff --strip-trailing-cr --brief "$CRNT" "$RECTXT"; then
      echo "removing redundant $q"
      echo "  for $CRNT"
      rm -f "$q"
  else
      echo $q contains changes
      vim -n -d "$CRNT" "$RECTXT"
      rm -i "$q" || exit
  fi
done
```
```
This will remove any swap files that are up-to-date with the real files.  Any that don't match are brought up in a vimdiff window so I can merge in my unsaved changes.
--Chouser


q:
I would like to add a DataGridViewTextBoxCell cell to a DataGridViewCell control, but as well as being able to type in the text cell as normal it must also contain a '...' button that once clicks brings up the OpenFileDialog window to allow the user to select a file. Once selected, the text cell will be populated with the full file path.

What is the best way to go about this?

Thanks

[A]
This
MSDN article explains how to add a custom control to a
```
DataGridView
```
.
You should be able to make a
```
UserControl
```
that has a textbox and button on it and embed that in the
```
DataGridView
```
.


q: What is the Reuse/Release Equivalence Principle and why is it important?

[A]
The Reuse/Release Equivalence Principle (REP) says:
The unit of reuse is the unit of release. Effective reuse requires tracking of releases from a change control system. The package is the effective unit of reuse and release.
The unit of reuse is the unit of release
Code should not be reused by copying it from one class and pasting it into another. If the original author fixes any bugs in the code, or adds any features, you will not automatically get the benefit. You will have to find out what's changed, then alter your copy. Your code and the original code will gradually diverge.
Instead, code should be reused by including a released library in your code. The original author retains responsibility for maintaining it; you should not even need to see the source code.
Effective reuse requires tracking of releases from a change control system
The author of a library needs to identify releases with numbers or names of some sort. This allows users of the library to identify different versions. This requires the use of some kind of release tracking system.
The package is the effective unit of reuse and release
It might be possible to use a class as the unit of reuse and release, however there are so many classes in a typical application, it would be burdensome for the release tracking system to keep track of them all. A larger-scale entity is required, and the package fits this need well.
See also Robert Martin's article on
Granularity
.


q: If Java application requires certain JRE version then how can I check its availability on Mac OS X during installation?

[A]
It should be as simple as looking at /System/Library/Frameworks/JavaVM.framework/Versions/
E.g. from my machine:
```
```
manoa:~ stu$ ll /System/Library/Frameworks/JavaVM.framework/Versions/
total 56
774077 lrwxr-xr-x  1 root  wheel    5 Jul 23 15:31 1.3 -> 1.3.1
167151 drwxr-xr-x  3 root  wheel  102 Jan 14  2008 1.3.1
167793 lrwxr-xr-x  1 root  wheel    5 Feb 21  2008 1.4 -> 1.4.2
774079 lrwxr-xr-x  1 root  wheel    3 Jul 23 15:31 1.4.1 -> 1.4
166913 drwxr-xr-x  8 root  wheel  272 Feb 21  2008 1.4.2
168494 lrwxr-xr-x  1 root  wheel    5 Feb 21  2008 1.5 -> 1.5.0
166930 drwxr-xr-x  8 root  wheel  272 Feb 21  2008 1.5.0
774585 lrwxr-xr-x  1 root  wheel    5 Jul 23 15:31 1.6 -> 1.6.0
747415 drwxr-xr-x  8 root  wheel  272 Jul 23 10:24 1.6.0
167155 drwxr-xr-x  8 root  wheel  272 Jul 23 15:31 A
776765 lrwxr-xr-x  1 root  wheel    1 Jul 23 15:31 Current -> A
774125 lrwxr-xr-x  1 root  wheel    3 Jul 23 15:31 CurrentJDK -> 1.5
manoa:~ stu$
```
```


q: How would you make the contents of Flex RIA applications accessible to Google, so that Google can index the content and shows links to the right items in your Flex RIA. Consider a online shop, created in Flex, where the offered items shall be indexed by Google. Then a link on Google should open the corresponding product in the RIA.

[A]
There is a massive thread available here:
http://tech.groups.yahoo.com/group/flexcoders/message/58926
But essentially, google already indexes .SWF files (you can test this out yourself by restricting search results to just .SWF files). It can search any text content within the SWF file.
However, if the text information in your site comes from a database / web server. Then it won't be able to access this information easily.
One example of getting this to work is using an XML file as your index page, then using an XSLT transform to render it using Flex. "Ted On Flex" has good information about this.
http://flex.org/consultants


q: How do I select all the columns in a table that only contain NULL values for all the rows?  I'm using MS SQL Server 2005.  I'm trying to find out which columns are not used in the table so I can delete them.

[A]
```
```
SELECT cols
FROM table
WHERE cols IS NULL
```
```


q:
I have Sun webserver iws6 (iplanet 6) proxying my bea cluster.
My cluster is under /portal/yadda.
I want anyone who goes to

http://the.domain.com/

to be quickly redirected to

http://the.domain.com/portal/

I have and index.html that does a post and redirect, but the user sometimes sees it.
Does anyone have a better way?

Aaron

I have tried the 3 replies below. None of them worked for me. Back to the drawing board.
A

[A]
Does this help?
http://docs.sun.com/source/816-5691-10/essearch.htm#25618
To map a URL, perform the following steps:
Open the Class Manager and select the server instance from the drop-down list.
Choose the Content Mgmt tab.
Click the Additional Document Directories link.
The web server displays the Additional Document Directories page.
(Optional) Add another directory by entering one of the following.
URL prefix.
For example: plans.
Absolute physical path of the directory you want the URL mapped to.
For example:
C:/iPlanet/Servers/docs/marketing/plans
Click OK.
Click Apply.
Edit one of the current additional directories listed by selecting one of the following:
Edit
Remove
If editing, select edit next to the listed directory you wish to change.
Enter a new prefix using ASCII format.
(Optional) Select a style in the Apply Style drop-down list if you want to apply a style to the directory:
For more information about styles, see Applying Configuration Styles.
Click OK to add the new document directory.
Click Apply.
Choose Apply Changes to hard start /restart your server.


q: I have a case where a VB.Net winforms app needs to play WMV files from across the network. The user running the app cannot be given direct access to the network share. Through impersonation, I can see that the files exist (without impersonation, File.Exists returns false for the files on the network share). When I then try to load the file into a Windows Media Player control, the control just remains black. I have deduced that when the Windows Media Player control is loaded into memory, it is running on a separate unmanaged thread than the .Net managed thread. Is there any way to pass that security token from the managed thread to the unmanaged thread? Am I missing something completely?

[A]
I suppose you tried using
```
```
[DllImport("advapi32.dll", SetLastError=true)]
public static extern int LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
```
```
to log in the network share.
In my experience it doesn't care about threads.
I can show you a usage example if you think it can be useful at all. Kind of a long shot to mention it here.


q: How can I programatically cause a control's tooltip to show in a Winforms app without needing the mouse to hover over the control?  (P/Invoke is ok if necessary).

[A]
This is the code I use:
```
```
static HWND hwndToolTip = NULL;

void CreateToolTip( HWND hWndControl, TCHAR *tipText )
{
    BOOL success;

  if( hwndToolTip == NULL )
  {
    hwndToolTip = CreateWindow(  TOOLTIPS_CLASS,
                                 NULL,
                                 WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
                                 CW_USEDEFAULT, CW_USEDEFAULT,
                                 CW_USEDEFAULT, CW_USEDEFAULT,
                                 NULL, NULL,
                                 hInstResource,
                                 NULL );
  }

  if( hwndToolTip )
  {
    TOOLINFO ti;

    ti.cbSize   = sizeof(ti);
    ti.uFlags   = TTF_TRANSPARENT | TTF_SUBCLASS;
    ti.hwnd     = hWndControl;
    ti.uId      = 0;
    ti.hinst    = NULL;
    ti.lpszText = tipText;

    GetClientRect( hWndControl, &ti.rect );

    success = SendMessage( hwndToolTip, TTM_ADDTOOL, 0, (LPARAM) &ti );
  }
}
```
```
Call CreateToolTip function to create a tool tip for a certain control.


q:
How do I perform an IF...THEN in an SQL SELECT statement?

For example:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product

[A]
```
```
SELECT
(CASE
     WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
                                            ELSE 'NO'
 END) as Salable
, *
FROM Product
```
```


q:
Let's say I have a web page that currently accepts a single ID value via a url parameter:

    http://example.com/mypage.aspx?ID=1234

I want to change it to accept a list of ids, like this:

    http://example.com/mypage.aspx?IDs=1234,4321,6789

So it's available to my code as a string via context.Request.QueryString["IDs"].  What's the best way to turn that string value into a List<int>?

Edit: I know how to do .split() on a comma to get a list of strings, but I ask because I don't know how to easily convert that string list to an int list.  This is still in .Net 2.0, so no lambdas.

[A]
You can use string.Split() to split the values once you have extracted them from the URL.
```
```
string[] splitIds = ids.split(',');
```
```


q:
I'm absolutely stunned by the fact that MS just couldn't get it right to navigate to the definition of a method, when you're combining C# and VB projects in one solution.  If you're trying to navigate from VB to C#, it brings up the "Object Explorer", and if from C# to VB, it generates a metadata file.

Honestly, what is so complicated about jumping between different languages, especially if they're supposedly using the same CLR?

Does anyone know why this is, or if there's any workaround?
Did they get it right in VS 2008?

@Keith, I am afraid you may be right about your answer.  I am truly stunned that Microsoft screwed this up so badly.  Does anyone have any ideas for a workaround?

@Mladen Mihajlovic - that's exactly the situation I'm describing.  Try it out yourself; project references don't make a shred of difference.

[A]
This is general to both languages.
F12 in VB.Net always takes you to the object browser
F12 in C# always takes you to a meta-data definition
This is a deliberate mechanism to try and match expected behaviour for upgrading users. The C# way gives you the right information, but the VB way is what users of VBA or VB6 will expect.
The behaviour is the same in VS2008.
These are the rules for external projects, both should take you to the code if it is in the same solution.
You're quite right - VB projects treat C# projects as external and vice versa - you can't navigate from code in one to the other. I've tested this in the latest VS2008 and it's still an issue.
It also fails to get complete meta-data. Add a method to your C# code and it won't appear in VB's intellisense until you compile the C# assembly.
This is similar to how components appear in the toolstrip, so I figure the normal navigate to code functionality is a feature of code with a common compilers, and everything else uses some kind of reflection.
As long as you're still building a PDB it should be able to find the files, I guess it doesn't because they need it to support release builds too. It couldn't find the line of code without the PDB lookups.


q: Would like to programmically change the connecton string for a database which utilizes the membership provider of asp.net within a windows application. The system.configuration namespace allows changes to the user settings, however, we would like to adjust a application setting? Does one need to write a class with utilizes XML to modify the class? Does one need to delete the current connections (can one select a connection to clear) and add a new one? Can one adjust the existing connection string?

[A]
You can programatically open the configuration with using the System.configuration namespace:
```
Configuration myConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
```
Then you can access the connection strings collection at:
```
myConfig.ConnectionStrings.ConnectionStrings
```
You can modify the collection however you want, and when done call
```
.Save()
```
on the configuration object.


q: Shoes has some built in dump commands (Shoes.debug), but are there other tools that can debug the code without injecting debug messages throughout?  Something like gdb would be great.

[A]
Have you looked at the ruby-debug gem?
```
```
% sudo gem install ruby-debug
```
```
The rdebug executable gives you a similar interface to gdb (breakpoint setting, etc).  You just simply execute your script with rdebug instead of ruby.
You can also do something like this to avoid manually setting breakpoints:
```
```
class Foo
  require 'ruby-debug'
  def some_method_somewhere
    debugger # acts like a breakpoint is set at this point
  end
end
```
```
Here's a tutorial on ruby-debug:
http://www.datanoise.com/articles/2006/7/12/tutorial-on-ruby-debug


q:
I would like to save the programs settings every time the user exits the program. So I need a way to call a function when the user quits the program. How do I do that?

I am using Java 1.5.

[A]
You can add a shutdown hook to your application by doing the following:
```
```
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run() {
        // what you want to do
    }
}));
```
```
This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block.
Please note the
caveats
though!


q:
Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?

In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write Fraction<int> frac = new Fraction<int>(1,2) and/or Fraction<double> frac = new Fraction<double>(0.1, 1.0).

Unfortunately there is no interface representing the four basic operations (+,-,*,/). Has anybody found a workable, feasible way of implementing this?

[A]
First, your class should limit the generic parameter to primitives ( public class Fraction where T : struct, new() ).
Second, you'll probably need to create
implicit cast overloads
so you can handle casting from one type to another without the compiler crying.
Third, you can overload the four basic operators as well to make the interface more flexible when combining fractions of different types.
Lastly, you have to consider how you are handling arithmetic over and underflows.  A good library is going to be extremely explicit in how it handles overflows; otherwise you cannot trust the outcome of operations of different fraction types.


q: Is there a way I can configure the MidPointRounding enumeration default setting in a config file (I.e. web.config or app.config)  I have a considerable source code base, and I need to configure at the application scope how rounding will occur, whether used in Math.Round or decimal type rounding...  I would like to do this in order to get consistent rounding results throughout the application without changing every line that works with a decimal type or uses Math.Round....

[A]
Enum.Parse() is your friend here
```
```
MyEnum GetEnumValue(string enumString) {
  return (MyEnum)Enum.Parse(typeof(MyEnum),enumString);
}
```
```
Obviously you'd also need some error-checking on the string you're getting from you're config file in which case you might want to return a default.


q:
Why does the default IntelliJ default class javadoc comment use non-standard syntax? Instead of creating a line with "User: jstauffer" it could create a line with "@author jstauffer". The other lines that it creates (Date and Time) probably don't have javadoc syntax to use but why not use the javadoc syntax when available?

For reference here is an example:

/**
 * Created by IntelliJ IDEA.
 * User: jstauffer
 * Date: Nov 13, 2007
 * Time: 11:15:10 AM
 * To change this template use File | Settings | File Templates.
 */

[A]
I'm not sure why Idea doesn't use the
```
@author
```
tag by default.
But you can change this behavior by going to
```
File -> Settings -> File Templates
```
and editing the
```
File Header
```
entry in the
```
Includes
```
tab.
As of IDEA 14 it's:
```
File -> Settings -> Editor -> File and Code Templates -> Includes -> File Header
```


q:
I am developing a web page code, which fetches dynamically the content from the server and then places this content to container nodes using something like

container.innerHTML = content;

Sometimes I have to overwrite some previous content in this node. This works fine, until it happens that previous content occupied more vertical space then a new one would occupy AND a user scrolled the page down -- scrolled more than new content would allow, provided its height.

In this case the page redraws incorrectly -- some artifacts of the old content remain. It works fine, and it is even possible to get rid of artifacts, by minimizing and restoring the browser (or force the window to be redrawn in an other way), however this does not seem very convenient.

I am testing this only under Safari (this is a iPhone-optimized website).

Does anybody have the idea how to deal with this?

[A]
It sounds like you are having a problem with the browser itself.  Does this problem only occur in one browser?
One thing you might try is using a lightweight library like
jQuery
.  It handles browser differences fairly nicely.  To set the inner HTML for a div with the ID of
container
you would simply write this:
```
```
$('#container').html( content );
```
```
That will work in most browsers.  I do not know if it will fix your problem specifically or not but it may be worth a try.


q:
I want to implement in Java a class for handling graph data structures. I have a Node class and an Edge class. The Graph class maintains two list: a list of nodes and a list of edges. Each node must have an unique name. How do I guard against a situation like this:

Graph g = new Graph();

Node n1 = new Node("#1");
Node n2 = new Node("#2");

Edge e1 = new Edge("e#1", "#1", "#2");

// Each node is added like a reference
g.addNode(n1);
g.addNode(n2);
g.addEdge(e1);

// This will break the internal integrity of the graph
n1.setName("#3");
g.getNode("#2").setName("#4");

I believe I should clone the nodes and the edges when adding them to the graph and return a NodeEnvelope class that will maintain the graph structural integrity. Is this the right way of doing this or the design is broken from the beginning ?

[A]
In my opinion you should never clone the element unless you explicitly state that your data structure does that.
The desired functionality of most things needs the actual object to be passed into the data structure by-reference.
If you want to make the
```
Node
```
class safer, make it an inner class of the graph.


q:
The SQL Server Express 2008 setup allow you to assign different user account for each service.

For a development environment, would you use a domain user, local user, NT Authority\NETWORK SERCVICE, NT Authority\Local System or some other account and why?

[A]
It depends.
Local System - Never, it's too high
a privilege.
Network Service -
Perhaps, if you need to connect to
network resources, but that's
doubtful.
Local Service - Probably
the best choice, limited privileges,
do not unlock network connections
Local interactive user? Does it
truly need to have login rights, or
act as a user?
Domain user? Goodness
no, not unless you're accessing
network drives from within it; if
SQL runs amok then an attacker is
authenticated against the domain.


q: Semantically speaking, is there an appropriate place in today's websites (late 2008+) where using the bold <b> and italic <i> tags are more useful than the more widely used <strong> and <em> tags?

[A]
Never. They are removed in XHTML 2.0 as they are presentational tags.  CSS should be used to bold/italicise content.
edit:
If you're looking for a purely presentational tag, that's what the
```
SPAN
```
tag with a class and a little CSS is for.


q:
I have a Java application that launches another java application.  The launcher has a watchdog timer and receives periodic notifications from the second VM.  However, if no notifications are received then the second virtual machine should be killed and the launcher will perform some additional clean-up activities.

The question is, is there any way to do this using only java? so far I have to use some native methods to perform this operation and it is somehow ugly.

Thanks!

[A]
You should be able to do that
```
java.lang.Runtime.exec
```
and shell commands.


q: How can I find what databases I have a minimum of read access to in either basic SQL, MySQL specific or in PHP?

[A]
In MySQL, you can execute
```
SHOW DATABASES;
```
Description
```
SHOW DATABASES;
```
to see what you have at least minimal access to. Are you looking for something more programmatic?


q:
As I build *nix piped commands I find that I want to see the output of one stage to verify correctness before building the next stage but I don't want to re-run each stage. Does anyone know of a program that will help with that? It would keep the output of the last stage automatically to use for any new stages. I usually do this by sending the result of each command to a temporary file (i.e. tee or run each command one at a time) but it would be nice for a program to handle this.

I envision something like a tabbed interface where each tab is labeled with each pipe command and selecting a tab shows the output (at least a hundred lines) of applying that command to to the previous result.

[A]
Use 'tee' to copy the intermediate results out to some file as well as pass them on to the next stage of the pipe, like so:
```
```
cat /var/log/syslog | tee /tmp/syslog.out | grep something | tee /tmp/grep.out | sed 's/foo/bar/g' | tee /tmp/sed.out | cat >>/var/log/syslog.cleaned
```
```


q: I talked to a few friends who say that Drupal is amazing, and it is a way better than Joomla. What are the major differences/advantages?

[A]
The
API
. Every form and pretty much every bit of functionality can be modified via a module that hooks into the API, without having touch core code.  This makes upgrades
much
easier, as your customisations aren't overwritten.
The code it outputs by default is much nicer, as well.


q:
Does Java impose any extra restrictions of its own. Windows (upto Vista) does not allow names to include

\ / < > ? * :

I know HOW to validate names (a regular expression).

I need to validate filenames entered by users.

My application does not need to run on any other platform, though, of course, I would prefer to be platform independent!

[A]
No, you can escape any character that Java doesn't allow in String literals but the filesystem allows.
Also, if trying to port an Windows app to Mac or Unix it is best to use:
```
```
File.separator
```
```
To determine the correct file separator to use on each platform.


q: As a programmer I have no idea how one would go about programming menus for a DVD, I have heard that this is possible, and even seen basic games using DVD menus - although it may very well be a closed-system. Is it even possible and if so, what language, compilers etc exist for this?

[A]
There are a couple of open source projects that can create DVDs plus menus. I recently used
dvd-slideshow
to create a simple dvd with menus etc. Another one is
DVD Styler
. All of these programs are basically a front-end for various command-line tools for encoding, menu creation etc. Since these are open source projects you can have a look at the source and check out how they accomplish this.


q: Is there a preferred way to handle animation when using Flex -- For instance, if I want to render a ball and bounce it around the screen?

[A]
I prefer to use a tweening library for things like this.  Check these out:
Tweener
TweenLite / TweenMax
KitchenSync
I've had good luck actually using the first two, and have read great things about the last one.


q: Struts 1.3 application.  Main website is NOT served by struts/Java.  I need to forward the result of a struts action to a page in the website, that is outside of the struts context.  Currently, I forward to a JSP in context and use a meta-refresh to forward to the real location.  That seems kinda sucky.  Is there a better way?

[A]
You can't "forward", in the strict sense. Just call
```
sendRedirect()
```
on the
```
HttpServletResponse
```
object in your
```
Action
```
class's
```
execute()
```
method and then,
```
return null
```
.
Alternately, either call
```
setModule()
```
on the
```
ActionForward
```
object (that you are going to return) or set the path to an absolute URI.


q: Out of the box SSRS reports cannot have data exposed in the page header.  Is there a way to get this data to show?

[A] You have to do it through Parameters. Add a parameter for each piece of data you would like to display, then set the parameter to Hidden. Then set the default value to "From Query" and set the Dataset and Value field to the appropriate values.


q:
Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.

Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.

See also:

Hidden features of C#

Hidden features of Java

Hidden features of JavaScript

Hidden features of Ruby on Rails

Hidden features of Python

(Please, just one hidden feature per answer.)

Thank you

[A]
I find using the
define_method
command to dynamically generate methods to be quite interesting and not as well known.  For example:
```
```
((0..9).each do |n|
    define_method "press_#{n}" do
      @number = @number.to_i * 10 + n
    end
  end
```
```
The above code uses the 'define_method' command to dynamically create the methods "press1" through "press9."  Rather then typing all 10 methods which essentailly contain the same code, the define method command is used to generate these methods on the fly as needed.


q:
I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated.

How would I make the year update automatically with PHP 4 or PHP 5?


q: Is there a way to auto discover a specific WCF service in the network? I don't want to config my client with the address if this is possible.

[A]
What you want to look at is the WS-Discovery protocol.  I found a sample on
netfx3's
website of using the
specification
.  I would recommend searching services based on scope, by probing for services based on a specific endpoint.


q: It's a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?

[A]
A safe way is to serialize the object, then deserialize.  This ensures everything is a brand new reference.
Here's an article
about how to do this efficiently.
Caveats: It's possible for classes to override serialization such that new instances are
not
created, e.g. for singletons.  Also this of course doesn't work if your classes aren't Serializable.


q: How do I change font size on the DataGridView?

[A]
Use the Font-property on the gridview. See MSDN for details and samples:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx


q:
I have a small diagnostic VB.Net application ( 2 forms, 20 subs & functions) written using VB.Net 2008 that targets Framework 2.0 and higher, but now I realize I need to support Framework 1.1.   I'm looking for the most efficient way to accomplish this given these constraints:

I don't know which parts of the application are 2.0-specific.

I could reconstruct the forms without too much trouble.

I need to support SharpZipLib

My current idea is to find and install VB.Net 2003, copy over my code and iteratively re-create the tool.  Are there better options?

[A] Probably not. If you don't understand which bits are 2.0-specific, you're probably going to have to go the trial-and-error route. However, you can probably save yourself quite a bit of work if you go looking for generics beforehand. In my experience, those are the most numerous 1.1-incompatible bits that tend to make it into my code.


q:
In Python is there any way to make a class, then make a second version of that class with identical dat,a but which can be changed, then reverted to be the same as the data in the original class?

So I would make a class with the numbers 1 to 5 as the data in it, then make a second class with the same names for sections (or very similar). Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class.

The only alternative I've found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable.

[A]
A class is a template, it allows you to create a blueprint, you can then have multiple instances of a class each with different numbers, like so.
```
```
class dog(object):
    def __init__(self, height, width, lenght):
        self.height = height
        self.width = width
        self.length = length

    def revert(self):
        self.height = 1
        self.width = 2
        self.length = 3

dog1 = dog(5, 6, 7)
dog2 = dog(2, 3, 4)

dog1.revert()
```
```


q:
When a script is saved as a bundle, it can use the localized string command to find the appropriate string, e.g. in Contents/Resources/English.lproj/Localizable.strings. If this is a format string, what is the best way to fill in the placeholders? In other words, what is the AppleScript equivalent of +[NSString stringWithFormat:]?

One idea I had was to use do shell script with printf(1). Is there a better way?

[A]
As ugly as it is, calling out to
```
printf(1)
```
is the common solution.
A cleaner, though somewhat more complex, solution is to use AppleScript Studio, which allows you to call into Objective-C objects/classes from your AppleScript code with the
```
call method
```
syntax documented
here
.
With that, you'd be able to use something like this:
```
```
call method "stringWithFormat:" of class "NSString" with parameters {formatString, arguments}
```
```
The downside of this, of course, is that you need to write an AppleScript Studio app instead of just writing a simple script. You do get a good bit more flexibility in general with Studio apps, though, so it's not all together a terrible route to go.


q:
I'm reading lines of text that can come in any order. The problem is that the output can actually be indentical to the previous output. How can I detect this, without sorting the output first?

Is there some kind of hash function that can take identical input, but in any order, and still produce the same result?

[A]
So you have input like
```
```
A B C D
D E F G
C B A D
```
```
and you need to detect that the first and third lines are identical?


q:
I'm using an identical call to "CryptUnprotectData" (exposed from Crypt32.dll) between XP and Vista. Works fine in XP. I get the following exception when I run in Vista:

"Decryption failed. Key not valid for use in specified state."

As expected, the versions of crypt32.dll are different between XP and Vista (w/XP actually having the more recent, possibly as a result of SP3 or some other update).

More specifically, I'm encrypting data, putting it in the registry, then reading and decrypting using "CryptUnprotectData". UAC is turned off.

Anyone seen this one before?

[A]
The
CryptUnprotectData function
documentation states that it usually only works when the user has the same logon credentials as the encrypter.
This suggests to me that maybe the key is tied to the user's current token. Since you mention Vista, this makes me think UAC and restricted tokens.
Can you show us some code? Can you give us more information about what you're doing with the data -- i.e. are you moving it between processes, or users, or computers?


q:
We create new sites in IIS 6 (Windows Server 2003) using IIS Manager.  When these sites are created in IIS 6, the ASP.NET version defaults to ASP.NET 1.1.  We would like it to default to ASP.NET 2.0.  The reason this is a problem for us is that when you take any site on the server and switch the ASP.NET version from ASP.NET 1.1 to ASP.NET 2.0, all web sites recycle.

Is there a setting in the IIS metabase that controls this or a way to create a site via script that sets the ASP.Net version correctly so that we can avoid the IIS reset when setting up each site?

[A]
Find the directory for the version of .Net you want, for example;
C:\Windows\Microsoft.NET\Framework\v2.0.50727
Get a cmd prompt there and then run aspnet_regiis -i.
Further info @
http://weblogs.asp.net/owscott/archive/2006/05/30/ASPNet_5F00_regiis.exe-tool_2C00_-setting-the-default-version-without-forcing-an-upgrade-on-all-sites.aspx
Ryan


q: Does emacs have something like vi's “set number”, so that each line starts with its line number?

[A]
Take a look at this article. It explains various ways to add line numbers to emacs:
http://www.emacswiki.org/cgi-bin/wiki/LineNumbers


q: The design for the website I am working on calls for a custom image on lists instead of a bullet.  Using the image is fine, but I have been having difficulties ensuring that it is centered against the text of the list item across all browsers.  Does anyone know of a standard solution for this?

[A]
Have you tried adding the following code in your CSS file?
```
```
li
{
   background-image: URL('custom.png');
   background-repeat: no-repeat;
   background-position: center;
}
```
```


q:
I'm trying to load a page that is basically an edit form inside a
dialog (ui.dialog).  I can load this page fine from an external (I'm
using asp.net) page.

The problem is that inside of my "popup" form, I need to $(function()
{my function here}); syntax to do some stuff when the page loads,
along with registering some .fn extensions for some dynamic dropdowns
using ajax calls.

I have created my <script type="text/javascript" src="jquery.js"> but
I don't think these are being included, and also my $(function) is not
being called.

Is this possible to do or do I need to find another way of
accomplishing what I need to do?

[A]
If you really need to load that form via AJAX you could to do all the Javascript stuff in  $.ajax callback itself.
So, you load the popup form like this:
```
```
$.ajax({
   //...
   success: function(text) {
       // insert text into container
       // the code from $(function() {});
   }
});
```
```


q:
Emacs:  C-U (79) # » a pretty 79 character length divider

VIM:  79-i-# » see above

Textmate: ????

Or is it just assumed that we'll make a Ruby call or have a snippet somewhere?

[A]
I would create a bundle command to do this.
You can take editor selection as input to your script, then replace it with the result of execution.  This command, for example, will take a selected number and print the character '#' that number of times.
```
```
python -c "print '#' * $TM_SELECTED_TEXT"
```
```
Of course this example doesn't allow you to specify the character, but it gives you an idea of what's possible.


q: I want to serve a lot of big files in a Plone site. By big files I mean around 5MB (music) and a lot of them. I've already do it straight to the ZODB, not a good idea. I'm running Plone 3.1.1 and Zope 2.10.6.

[A]
As you may already know, the long-term solution for this is supposed to be the ZODB BLOB support.
Ticket 6805
is probably the most authorative source on this. Unfortunately, the milestone is set to 4.0, and running it in production on an older release is perhaps not a good solution.
There has, historically, existed a lot of Plone products for storing files externally, keeping only metadata in the ZODB. I have tried several of them, and from my experience, there is not a single one that works well with current Plone/Zope releases. Don't trust me on this, though, I have not tried any products of this type the last year or so.
Personally, I would go for a solution that is as simple as possible and doesn't involve Plone more than neccesary. Storing the music files on disk, serving them directly from apache/whatever web server you use, keeping only metadata in Plone - in a product you write yourself, will give you a robust solution with good performance. That is, your product should produce links to a path on your web server where the music files are available.
If you require authorization for download of the music files and assuming that you run lighthttpd or apache in front of your Zope, looking at a solution based on X-sendfile is probably the best option. With X-sendfile, you keep the files on disk, and add a header (X-sendfile) to the response when a music file should be sent to the client browser. The web server will pick this header up and send the file to the client, without Plone being involved.
Some pointers:
http://tn123.ath.cx/mod_xsendfile/
(The apache module)
http://john.guen.in/past/2007/4/17/send_files_faster_with_xsendfile/
(Ruby example)


q: I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients.  Security is also an issue - so secure login would be a plus.  I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.

[A]
Pyro
(Python Remote Objects) is fairly clever if all your server/clients are going to be in Python. I use
XMPP
alot though since I'm communicating with hosts that are not always Python. XMPP lends itself to being extended fairly easily too.
There is an excellent XMPP library for python called
PyXMPP
which is reasonably up to date and has no dependancy on Twisted.


q: I'd like to convert a Parallels Virtual Machine image on my mac into an image usable by Virtual PC 2007.  Does anyone know how to do that, or if it is possible?

[A]
It looks like qemu-img from
qemu
can do this, at least looking at its commandline help on a Ubuntu 8.04 machine where it claims support for, among others, the "parallels" and the "vpc" format.
Have not tried myself, though. Hope this helps.


q: Is there a good .Net implementation of the NNTP protocol?

[A]
There is a C# tutorial for reading posts using NNTP
here
.  It should be enough to get you started but if you wish to start getting into processing binary posts, you're probably going to have to deal with some mime-type content too.  I don't think this article covers that.


q: I'd like to use alternatives to System Center Virtual Machine Manager 2008 is possible, in other words, any FREE tools?

[A]
Google "Pysical to virtual conversion" or P2V.  There are several solutions available.  Unfortunately it sounds as though not many have had success with Microsoft's solution.
Try the following:
1. Download and install the VMWare Converter and follow the instructions to convert the physical machine.
2. Download the VMWare to VHD conversion utility from VMToolkit.com and convert the image.
This didn't work for me when I tried it last week, but I think it is because the drive I converted used PGP.


q:
I have a VB6 program that someone recently helped me convert to VB.NET

In the program, when saving files, I stamp them with the date which I was getting by calling the Today() function.

When I try to run the new VB.NET code in Vista it throws a permission exception for the Today() . If I run Visual Studio Express (this is the 2008 Express version) in Admin mode, then the problem doesn't occur, but clearly I want to end up with a stand-alone program which runs for all users without fancy permissions.

So how can a normal VB.NET program in Vista get today's date?

[A]
Use
```
DateTime.Now
```
or
```
DateTime.Today
```
.  These are entirely managed and shouldn't throw security exceptions.
The old VB6 functions, such as
```
Len()
```
,
```
Left()
```
,
```
Right()
```
,
```
OpenFile()
```
,
```
FreeFile()
```
are all present in the .NET Framework in the Microsoft.VisualBasic DLL.  To maintain backwards compatibility, they all call the old functions in unmanaged code.  Unmanaged code requires special security permissions because it can be dangerous.
Whenever possible, try and use the newer .NET functions.  They are usually much faster (File IO using Streams for instance) and safer.


q: I am rewriting code to handle some embedded communications and right now the protocol handling is implemented in a While loop with a large case/switch statement.  This method seems a little unwieldy. What are the most commonly used flow control methods for implementing communication protocols?

[A]
For cases where you key off of a field in a protocol header to direct you to the next stage of processing for that protocol, arrays of function pointers can be used. You use the value from the protocol header to index into the array and call the function for that protocol.
You
must
handle all possible values in this array, even those which are not valid. Eventually you will get a packet containing the invalid value, either because someone is trying an attack or because a future rev of the protocol adds new values.


q:
I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?

from smtplib import SMTP
import datetime

debuglevel = 0

smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')

from_addr = "John Doe <john@doe.net>"
to_addr = "foo@bar.com"

subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

message_text = "Hello\nThis is a mail from your server\n\nBye\n"

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
        % ( from_addr, to_addr, subj, date, message_text )

smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()

[A]
The main gotcha I see is that you're not handling any errors:
```
.login()
```
and
```
.sendmail()
```
both have
documented exceptions
that they can throw, and it seems like
```
.connect()
```
must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.


q:
How do I use Perl to create graphs?

I'm running scheduled job that creates text reports.  I'd like to move this to the next step (for the management) and also create some graphs that go along with this.  Is this possible / feasible?   It'd be great if I could do this using Office some how.

update: solutions i'm going to investigate in this order

Spreadsheet::WriteExcel (this seems to now have changed from the last time i investigated this .... wait, this was suggested by the author of the module.  cool.)

GD Graph - this is now available for ActivePerl(wasn't last time i looked)

SVG

Open Charts look interesting.

Chartdirector

[A]
```
```
Spreadsheet::WriteExcel::Chart
```
```
You might need something like strawberry or vanilla Perl to get this to compile. Or PPM might have the module.
Tutorial link:
http://search.cpan.org/dist/Spreadsheet-WriteExcel/charts/charts.pod


q:
I've started to work a bit with master pages for an ASP.net mvc site and I've come across a question.  When I link in a stylesheet on the master page it seems to update the path to the sheet correctly.  That is in the code I have

<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

but looking at the source once the page is fed to a browser I get

<link href="Content/Site.css" rel="stylesheet" type="text/css" />

which is perfect.  However the same path translation doesn't seem to work for script files.

<script src="../../Content/menu.js" type="text/javascript"></script>

just comes out as the same thing.  It still seems to work on a top level page but I suspect that is just the browser/web server correcting my error.  Is there a way to get the src path to be globbed too?

[A]
Use this instead:
```
```
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
```
```


q:
PHP's explode function returns an array of strings split on some provided substring. It will return empty strings when there are leading, trailing, or consecutive delimiters, like this:

var_dump(explode('/', '1/2//3/'));
array(5) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(0) ""
  [3]=>
  string(1) "3"
  [4]=>
  string(0) ""
}

Is there some different function or option or anything that would return everything except the empty strings?

var_dump(different_explode('/', '1/2//3/'));
array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}

[A]
```
```
function not_empty_string($s) {
  return $s !== "";
}

array_filter(explode('/', '1/2//3/'), 'not_empty_string');
```
```


q: I was discussing neural networks (NN) with a friend over lunch the other day and he claimed the the performance of a NN written in Java would be similar to one written in C++.  I know that with 'just in time' compiler techniques Java can do very well, but somehow I just don't buy it.  Does anyone have any experience that would shed light on this issue?  This page is the extent of my reading on the subject.

[A]
The Hotspot JIT can now produce code
faster
than C++.  The reason is run-time empirical optimization.
For example, it can see that a certain loop takes the "false" branch 99% of the time and reorder the machine code instructions accordingly.
There's lots of articles about this.  If you want all the details, read
Sun's excellent whitepaper
.  For more informal info,
try this one
.


q: Is it possible to use both JScript and VBScript in the same HTA? Can I call VBScript functions from JScript and vice-versa? Are there any "gotchas," like the JScript running first and the VBScript running second (classic ASP pages have this issue).

[A]
Yeah, just separate them into different script tags:
```
```
<script language="javascript">
   // javascript code
</script>

<script language="vbscript">
   ' vbscript code
</script>
```
```
Edit: And, yeah, you can cross call between Javascript and VBScript with no extra work.
Edit: This is also true of ANY Windows Scripting technology.  It works in WSF files and can include scripts written in any supported ActiveScript language such as Perl as long as the engine is installed.
Edit: The specific "gotcha" of all JScript being executed first, then VBScript is related to how ASP processes scripts. The MSHTA host (which uses IE's engine) does not have this problem. I'm not much into HTAs though, so I can't address any other possible "gotchas".


q:
Do I risk losing sales by disabling SSL 2.0 and PCT 1.0 in IIS5?

Clarification: Sales would be lost by client not being able to connect via SSL to complete ecommerce transaction because SSL 2.0 or PCT 1.0 is disabled on the web server.

Microsoft kbase article: http://support.microsoft.com/kb/187498

[A]
Only you can really answer that question. Your customers' experience of your site will be mediated by their browser. The first place to look for browser information is at a listing of the user-agents that are being used to access your website. Hopefully you have a good log analyzer such as Analog, Weblog, Google Analytics, WebTrends, etc. This is the first place to look and should give you a good idea of the SSL level that your general community supports.
You may also want to alter your application to check for the SSL level supported by your users' browsers that get to the "complete ecommerce transaction" part of your website. This is the best method to determine if you are turning away customers.
Remember that the SSL level is auto negotiated between the server and the client (best encryption used first) so you don't necessarily need to disable older versions, but you could pop up a message to the user encouraging them to upgrade.


q: I know next to nothing when it comes to the how and why of https connections.  Obviously, when I'm transmitting secure data like passwords or especially credit card information, https is a critical tool.  What do I need to know about it, though?  What are the most common mistakes you see developers making when they implement it in their projects?  Are there times when https is just a bad idea?  Thanks!

[A]
Be sure that, when on an HTTPS page, all elements on the page come from an HTTPS address. This means that elements should have relative paths (e.g. "/images/banner.jpg") so that the protocol is inherited, or that you need to do a check on every page to find the protocol, and use that for all elements.
NB: This includes all outside resources (like Google Analytics javascript files)!
The only down-side I can think of is that it adds (nearly negligible) processing time for the browser and your server. I would suggest encrypting only the transfers that need to be.


q: What's the proper way to convert from a scientific notation string such as "1.234567E-06" to a floating point variable using C#?

[A]
```
```
Double.Parse("1.234567E-06", System.Globalization.NumberStyles.Float);
```
```


q:
If I issue the find command as follows:

find . -name *.ear

It prints out:

./dir1/dir2/earFile1.ear
./dir1/dir2/earFile2.ear
./dir1/dir3/earFile1.ear

I want to 'print' the name and the size to the command line:

./dir1/dir2/earFile1.ear  5000 KB
./dir1/dir2/earFile2.ear  5400 KB
./dir1/dir3/earFile1.ear  5400 KB


q:
I'm using the JFrame plugin with jquery 1.2.6.

It works fine in FF3, however it won't display the requested pages in IE 7.

The jQuery library and the JFrame plugin are called in the included header.cfm.

Page code is here (note: ignore the ColdFusion calls, I don't think they're generating the problem): http://cfm.pastebin.com/m20c1b013

[A]
When you have a problem like this, the best way of tracking down the problem is to reduce the page to the minimum necessary to reproduce the problem.
"Ignore the [x] because I don't think that's the problem"
is no good, if you don't think that's the problem, save it to a temporary static page, delete the things you think are unrelated, and then you
know
whether or not they are the problem.  Keep deleting things you think are unrelated, and eventually you will either find the bit that's screwing things up when you remove it, or you will end up with a very small file that is:
Much easier to debug
Much more likely to attract help from people
Much better testcase for the times when it's a genuine bug in a library
Not many people are willing to pick apart Coldfusion and table layout code to get to your bug - after all, you're the one with the problem, and even you couldn't be bothered to do it, so why would anybody else?


q:
Theres is a little problem I want to solve with Haskell:
let substitute a function that change all of the wildcards in a string for one concrete parameter. The function has de signature of:

subs :: String -> String -> String -> String
-- example:
-- subs 'x' "x^3 + x + sin(x)" "6.2" will generate
--          "6.2^3 + 6.2 + sin(6.2)"

[A]
You could use the
Text.Regex
package.
Your example might look something like this:
```
```
import Text.Regex(mkRegex, subRegex)

subs :: String -> String -> String -> String
subs wildcard input value = subRegex (mkRegex wildcard) input value
```
```


q:
What is a non recursive algorithm for deciding whether a passed in amount can be built additively from a set of numbers.

In my case I'm determining whether a certain currency amount (such as $40) can be met by adding up some combination of a set of bills (such as $5, $10 and $20 bills).  That is a simple example, but the algorithm needs to work for any currency set (some currencies use funky bill amounts and some bills may not be available at a given time).

So $50 can be met with a set of ($20 and $30), but cannot be met with a set of ($20 and $40).  The non-recursive requirement is due to the target code base being for SQL Server 2000 where the support of recursion is limited.

In addition this is for supporting a multi currency environment where the set of bills available may change (think a foreign currency exchange teller for example).

[A]
Edit:
The following will work
some
of the time.  Think about why it won't work all the time and how you might change it to cover other cases.
Build it starting with the largest bill towards the smallest.  This will yeild the lowest number of bills.
Take the initial amount and apply the largest bill as many times as you can without going over the price.
Step to the next largest bill and apply it the same way.
Keep doing this until you are on your smallest bill.
Then check if the sum equals the target amount.


q: Coming from J2ME programming are there any similarities that would make it easy to adapt to Android API. Or is Android API completely different from the J2ME way of programming mobile apps.

[A]
A good start would be to watch the Android architecture videos and look at some of the documentation.
http://www.youtube.com/view_play_list?p=586D322B5E2764CF
http://code.google.com/android/what-is-android.html
Google is very good about documenting. From what I've heard Android very very similar to J2ME in its goals. It may be slightly different in programming style and structure but if you have J2ME experience you should be more then ready to move on to Android.
Good Luck!!!


q: How can I poll disk activity in Applescript? Check to see if disk X is being read, written, or idle every N seconds and do something.

[A]
In general, polling is less efficient than being notified when something happens. Additionally, if you're checking whether something is reading from a disk, you will probably be accessing said disk yourself, possibly influencing what you're trying to observe.
Since 10.5, OSX includes something called the File System Events framework, which provides course-grained notifications of changes to the file system. The problem in your case is that this is Objective-C only. Apple has some nice
documentation
about this API.
Fortunately, there is also the
```
call method
```
AppleScript command. This allows you to work with Objective-C objects from within AppleScript. Here's the
documentation
on that.
I have no experience with either, hence the documentation references. Hopefully, this should get you going.


q:
int i = 4;
string text = "Player ";
cout << (text + i);

I'd like it to print Player 4.

The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?


q:
Most text editors have a navigation pane that lets you see all the files you currently have open.  Or a pane that lets you browse a file directory.

How do I do this in Emacs?

[A]
C-x b TAB
will give you an auto complete with all open buffers.   Alternatively, click on the
```
Buffers
```
menu item if you are in a windowed version (not sure if there is a terminal equivalent of that).
EDIT: Also
C-x C-f
will let you open a file, and you can use
TAB
for autocomplete, then
TAB
again to view files/directories in that current directory (assuming the first tab did not autocomplete something).


q: Is there a way to substring in JSP files, using struts2 technologies? I mean, struts2 has its own taglib and also uses ognl. How can I get a substring from a stacked value or bean value?

[A]
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html
Look for fn:substring and its variants.
I've used Struts 1, but not 2.


q:
As of the fall of 2008 I'm about to embark on a new development cycle for a major product that has a winforms and an asp.net interface.  We use Telerik, DevExpress and Infragistics components in it and all are going to have a release within a month or so which will be the one I target for our spring release of our product.

They all support VS2005 and we will continue to target .net 2+ so I can't see any compelling reason so far to upgrade to VS2008.

Has anyone found a compelling reason for upgrading to VS2008?

[A] It's worth it. It's faster, the designer is vastly improved (split view, faster context switching), it has better support for javascript and when you're ready to target 3.5, you'll be ready to go.


q: I believe I need a DTD to define the schema and an XSLT if I want to display it in a browser and have it look "pretty". But I'm not sure what else I would need to have a well-defined XML document that can be queried using XQuery and displayed in a web browser.

[A]
Strictly speaking, you need nothing. XML, even without a schema definition, works.
A schema definition (in XSD, RelaxNG or DTD) helps various tools that work with the XML, because they can verify that the structure of the XML conforms to what you want.
An XSLT translation to HTML is nice if the XML contains information you'll want to look at with a browser. It's far from necessary, though.
To query the XML with XPath or XQuery, you need an XPath or XQuery processor.


q: Has anybody used C# to write a sample screen scraper for IBM as400?

[A] I wrote one in C many years ago for a project at Frigidaire.  The internal card would cause all sorts of fun with memory leaks but I eventually found a solution by allocating arrays at the boundary of the communication card.  This was over 8 years ago, I'm sure today's cards are much better and/or using native comm to read the AS400 screens.


q:
How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned?

      #define is_this_type_signed (my_type) ...

[A]
In C++, use
```
std::numeric_limits<type>::is_signed
```
.
```
```
#include <limits>
std::numeric_limits<int>::is_signed  - returns true
std::numeric_limits<unsigned int>::is_signed  - returns false
```
```
See
https://en.cppreference.com/w/cpp/types/numeric_limits/is_signed
.


q: I need to deploy an application on the WAS ND 6.1 and do not know anything about it and cannot afford to go to training...

[A]
There is the RedBook
WebSphere Application Server V6.1: System Management and Configuration
with Chapter 14 talking about application deployment, this could help.


q: During the load of my cocoa application, my program crashes with the messsage EXC_BAD_ACCESS.  The stack trace is not helpful.  Any clues to how I can find the problem?

[A]
This is one possible reason.  There is a IBOutlet object that isn't being initialized and a message is being invoked on nil.  The stack trace might look like this:
```
```
#0    0x90a594c7 in objc_msgSend
#1    0xbffff7b8 in ??
#2    0x932899d8 in loadNib
#3    0x932893d9 in +[NSBundle(NSNibLoading) _loadNibFile:nameTable:withZone:ownerBundle:]
#4    0x9328903a in +[NSBundle(NSNibLoading) loadNibFile:externalNameTable:withZone:]
#5    0x93288f7c in +[NSBundle(NSNibLoading) loadNibNamed:owner:]
#6    0x93288cc3 in NSApplicationMain
#7    0x00009f80 in main at main.mm:17
```
```
Since the stack trace is not helpful you will have to step through your code to find the error.  If for some reason you aren't able to set breakpoints early in your execution, try inserting some Debugger(); calls which will break to the debugger.


q:
Is it possible to select from show tables in MySQL?

SELECT * FROM (SHOW TABLES) AS `my_tables`

Something along these lines, though the above does not work (on 5.0.51a, at least).

[A]
Have you looked into querying INFORMATION_SCHEMA.Tables?  As in
```
```
SELECT ic.Table_Name,
    ic.Column_Name,
    ic.data_Type,
    IFNULL(Character_Maximum_Length,'') AS `Max`,
    ic.Numeric_precision as `Precision`,
    ic.numeric_scale as Scale,
    ic.Character_Maximum_Length as VarCharSize,
    ic.is_nullable as Nulls,
    ic.ordinal_position as OrdinalPos,
    ic.column_default as ColDefault,
    ku.ordinal_position as PK,
    kcu.constraint_name,
    kcu.ordinal_position,
    tc.constraint_type
FROM INFORMATION_SCHEMA.COLUMNS ic
    left outer join INFORMATION_SCHEMA.key_column_usage ku
        on ku.table_name = ic.table_name
        and ku.column_name = ic.column_name
    left outer join information_schema.key_column_usage kcu
        on kcu.column_name = ic.column_name
        and kcu.table_name = ic.table_name
    left outer join information_schema.table_constraints tc
        on kcu.constraint_name = tc.constraint_name
order by ic.table_name, ic.ordinal_position;
```
```


q:
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms.
Thus splitting the respective string by the space-character is not sufficient anymore.

Example:

input : 'foo bar "lorem ipsum" baz'
output: ['foo', 'bar', 'lorem ipsum', 'baz']

I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations.

Any help would be greatly appreciated!

[A]
```
```
'foo bar "lorem ipsum" baz'.match(/"[^"]*"|\w+/g);
```
```
the bounding quotes get included though


q: I want to create templates for base new reports on to have common designs.  How do you do it?

[A]
The need to produce reports with a common starting design and format is key to any project involving clients and their reports.  I have been working on reports for over 10 years now.  This has not been the largest portion of my jobs through the years but it has been a very import one.  The key to any report project is not to recreate the mundane aspects of the reports for each but to use templates.  The use of templates is not a common task or knowledge for Microsoft's SQL Server Reporting Services.  Knowing how to save reports templates so that you and your team can create these shortcuts at the creation of a new report in Visual Studio 2005 will help save time and have all reports use the same layout and design.
Create of a set of reports with the following suggestions:
Page size -- 8.5 by 11 (letter) and 8.5 by 14 (legal)
Orientation -- portrait and landscape for all paper sizes
Header -- Text Box for report name, Text Box for report subtitle, client or brand logo
Footer -- page number/total pages, date and time report printed
Take all the rdl files for the reports created from the suggestions and copy the files to the following directory:
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\ProjectItems\ReportProject
When creating a new report in your Visual Studio 2005 report project through Add|New Item
alt text http://www.cloudsocket.com/images/image-thumb14.png
The new report dialog will present the list of items from the directory where the new templates were placed.
alt text http://www.cloudsocket.com/images/image-thumb15.png
Select the report that fits the requirement needed and proceed to develop your reports without needing to create the basics.


q:
As stated in the title, i'm looking for an XML schema (XSD-file) for the Glade markup language?

Wikipedia states that Glade is a schema based markup language (list of schemas at wikipedia). I tried to search the web, wikipedia and the glade website,but i couldn't find an XSD for Glade.

Thx,
Juve

[A]
http://svn.async.com.br/cgi-bin/viewvc.cgi/libglade/glade-2.0.dtd?view=markup
(The main version @
http://glade.gnome.org/glade-2.0.dtd
doesn't seem to be working)


q: How do you create SQL Server 2005 stored procedure templates in SQL Server 2005 Management Studio?

[A]
You bring up
Template Explorer
using Ctrl+Alt+T or trough
View > Template Explorer
. Then you can right click tree nodes to add new Templates or new folders to organize your new templates.


q:
How do I create a unique constraint on an existing table in SQL Server 2005?

I am looking for both the TSQL and how to do it in the Database Diagram.

[A]
```
```
ALTER TABLE dbo.<tablename> ADD CONSTRAINT
            <namingconventionconstraint> UNIQUE NONCLUSTERED
    (
                <columnname>
    ) ON [PRIMARY]
```
```


q:
I'm working with a support person who is supposed to be able to install SSL certs on a web server he maintains.  He has local admin rights to the server via a domain security group.  He also has permissions on our internal CA running Windows 2003 Server Certificate Authority: "Request cert" and "Issue and Manage certs".

The server he's working with is running Windows 2000 SP4 / IIS 5.  When he attempts to create an online server cert the IIS wizard ends with "Failed to install.  Access is Denied.".  The event viewer is not working properly, so I can't find any details there.  I suspect the permission issue is locally and not with the CA.

My account is a domain admin account and I know I am able to do this operation, however I need to make this work for others that are not domain admins.

Any ideas why he can't perform this operation?

[A]
I had this exact same issue a few months ago when I was setting up a cert for a client.
There's a MachineKeys folder that the Administrator need rights -
```
```
\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys
```
```
give
Administrator
(or the Administrator group)
Full Control
over this directory.  I don't think you have to restart IIS, but it never hurts .
I have no idea why Admin doesn't control this as default.
Once this is changed, the Certificate Creation Wizard will successfully generate the certificate request.
I think there's even a Microsoft KB article about it somewhere.
EDIT: Here's the KB article :
http://support.microsoft.com/kb/908572
-Jon


q:
How would I remove the border from an iframe embedded in my web app? An example of the iframe is:

<iframe src="myURL" width="300" height="300">Browser not compatible.</iframe>

I would like the transition from the content on my page to the contents of the iframe to be seamless, assuming the background colors are consistent. The target browser is IE6 only and unfortunately solutions for others will not help.

[A]
Add the
```
frameBorder
```
attribute (note the
capital ‘B’
).
So it would look like:
```
```
<iframe src="myURL" width="300" height="300" frameBorder="0">Browser not compatible.</iframe>
```
```


q:
As far as I know, in gcc you can write something like:

#define DBGPRINT(fmt...) printf(fmt);

Is there a way to do that in VC++?

[A]
Almost. It's uglier than that though (and you probably don't want a trailing semi-colon in the macro itself:
```
```
#define DBGPRINT(DBGPRINT_ARGS) printf DBGPRINT_ARGS // note: do not use '(' & ')'
```
```
To use it:
```
```
DBGPRINT(("%s\n", "Hello World"));
```
```
(was missing a pair of parens).
Not sure why all the negatives, the original question didn't state a version of VC++, and variadic macros aren't supported by all compilers.


q:
I am refactoring some CSS on a website. I have been working on, and noticed the absence of traditional HTML IDs in the code.

There is heavy use of CssClass='&hellip;', or sometimes just class='&hellip;', but I can't seem to find a way to say id='…' and not have it swapped out by the server.

Here is an example:

<span id='position_title' runat='server'>Manager</span>

When the response comes back from the server, I get:

<span id='$aspnet$crap$here$position_title'>Manager</span>

Any help here?

[A]
.Net will always replace your id values with some mangled (every so slightly predictable, but still don't count on it) value.  Do you really NEED to have that id runat=server?  If you don't put in runat=server, then it won't mangle it...
ADDED:
Like leddt said, you can reference the span (or any runat=server with an id) by using ClientID, but I don't think that works in CSS.
But I think that you have a larger problem if your CSS is using ID based selectors. You can't re-use an ID. You can't have multiple items on the same page with the same ID. .Net will complain about that.
So, with that in mind, is your job of refactoring the CSS getting to be a bit larger in scope?


q:
If i have a simple named query defined, the preforms a count function, on one column:

  <query name="Activity.GetAllMiles">
    <![CDATA[
      select sum(Distance) from Activity
    ]]>

  </query>

How do I get the result of a sum or any query that dont return of one the mapped entities, with NHibernate using Either IQuery or ICriteria?

Here is my attempt (im unable to test it right now), would this work?

    public decimal Find(String namedQuery)
    {
        using (ISession session = NHibernateHelper.OpenSession())
        {
            IQuery query = session.GetNamedQuery(namedQuery);

            return query.UniqueResult<decimal>();
        }
    }

[A]
As an indirect answer to your question, here is how I do it without a named query.
```
```
var session = GetSession();
var criteria = session.CreateCriteria(typeof(Order))
            .Add(Restrictions.Eq("Product", product))
            .SetProjection(Projections.CountDistinct("Price"));
return (int) criteria.UniqueResult();
```
```


q:
Is there a performant equivalent to the isnull function for DB2?

Imagine some of our products are internal, so they don't have names:

Select product.id, isnull(product.name, "Internal)
From product

Might return:

1 Socks
2 Shoes
3 Internal
4 Pants

[A]
I'm not familiar with DB2, but have you tried COALESCE?
ie:
```
```
SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product
```
```


q:
I'd like to be able to write a PHP class that behaves like an array and uses normal array syntax for getting & setting.

For example (where Foo is a PHP class of my making):

$foo = new Foo();

$foo['fooKey'] = 'foo value';

echo $foo['fooKey'];

I know that PHP has the _get and _set magic methods but those don't let you use array notation to access items.  Python handles it by overloading __getitem__ and __setitem__.

Is there a way to do this in PHP?  If it makes a difference, I'm running PHP 5.2.

[A]
If you extend
```
ArrayObject
```
or implement
```
ArrayAccess
```
then you can do what you want.
ArrayObject
ArrayAccess


q:
We have a live MySQL database that is 99% INSERTs, around 100 per second. We want to archive the data each day so that we can run queries on it without affecting the main, live database. In addition, once the archive is completed, we want to clear the live database.

What is the best way to do this without (if possible) locking INSERTs? We use INSERT DELAYED for the queries.

[A]
Could you keep two mirrored databases around? Write to one, keep the second as an archive. Switch every, say, 24 hours (or however long you deem appropriate). Into the database that was the archive, insert all of todays activity. Then the two databases should match. Use this as the new live db. Take the archived database and do whatever you want to it. You can backup/extract/read all you want now that its not being actively written to.
Its kind of like having mirrored raid where you can take one drive offline for backup, resync it, then take the other drive out for backup.


q: What are the common algorithms being used to measure the processor frequency?

[A]
I'm not sure why you need assembly for this.  If you're on a machine that has the /proc filesystem, then running:
```
```
> cat /proc/cpuinfo
```
```
might give you what you need.


q: If I want to use the validation framework that you can use with ASP.NET MVC, will the JavaScript conflict with other JavaScript frameworks like jQuery or YUI?

[A]
There are many MVC frameworks. There are many JavaScript frameworks that have different functionalities. If you want a meaningful answer, you should choose an MVC and a JavaScript framework and ask concerning those two. Please be as detailed as possible in your questions.
As an example, the validation handling on ActiveRecord (used in Ruby on Rails) only performs validations on the server end. You can always add JavaScript validations on top of that, but the server-side validations are what really matters for data integrity.


q:
We are planning to use the jQuery library to augment our client side JavaScript needs.

Are there any major issues in trying to use both ASP.Net AJAX and jQuery? Both libraries seem to use $ for special purposes. Are there any conflicts that we need to be aware of?

We also use Telerik controls that use ASP.Net AJAX.

TIA

[A]
jQuery has a noConflict() method as a part of the core, but it then requires that you either use jQuery as your named function or something else of your choosing (instead of the dollar selector). However, I will say that the method is often dependent on the implementation of the "competing" library. I have tried to use it for a Ning social network (which used Dojo), and for Magento (which uses Prototype), and I could not get either to play right with jQuery. This is just my personal experience, and others have been very successful.
http://docs.jquery.com/Core/jQuery.noConflict


q: What's the easiest way to get the filename associated with an open HANDLE in Win32?

[A]
On unixes there is no real way of reliably doing this.  In unix with the traditional unix filesystem, you can open a file and then unlink it (remove its entry from the directory) and use it, at which point the name isn't stored anywhere.  In addition, because a file may have multiple hardlinks into the filesystem, each of the names are equivalent, so once you've got just the open handle it wouldn't be clear which filename you should map back towards.
So, you may be able to do this on Win32 using the other answers, but should you ever need to port the application to a unix enviornment, you'll be out of luck.  My advice to you is to refactor your program, if possible, so that you don't need the OS to be able to maintain an open resource to filename connection.


q:
Using jQuery, how can I dynamically set the size attribute of a select box?

I would like to include it in this code:

$("#mySelect").bind("click",
    function() {
        $("#myOtherSelect").children().remove();
        var options = '' ;
        for (var i = 0; i < myArray[this.value].length; i++) {
            options += '<option value="' + myArray[this.value][i] + '">' + myArray[this.value][i] + '</option>';
        }
        $("#myOtherSelect").html(options).attr [... use myArray[this.value].length here ...];
    });
});

[A]
Oops, it's
```
```
$('#mySelect').attr('size', value)
```
```


q:
I was recently asked to come up with a script that will allow the end user to upload a PSD (Photoshop) file, and split it up and create images from each of the layers.

I would love to stay with PHP for this, but I am open to Python or Perl as well.

Any ideas would be greatly appreciated.


q:
We have a number of web-apps running on IIS 6 in a cluster of machines. One of those machines is also a state server for the cluster. We do not use sticky IP's.

When we need to take down the state server machine this requires the entire cluster to be offline for a few minutes while it's switched from one machine to another.

Is there a way to switch a state server from one machine to another with zero downtime?

[A]
You could use the SQL server option to store state. I've used this in the past and it works well as long as the ASPState table it creates is in memory. I don't know how well it would scale as an on-disk table.
If SQL server is not an option for whatever reason, you could use your load balancer to create a virtual IP for your state server and point it at the new state server when you need to change. There'd be no downtime, but people who are on your site at the time would lose their session state. I don't know what you're using for load balancing, so I don't know how difficult this would be in your environment.


q:
I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception:

org.apache.axis.ConfigurationException: No service named <web service name> is available

any idea?

[A]
This is what my code looks like. It seems to work fine.
Are you using a service locator or just creating your service?
```
```
SomeServiceLocator locator = new SomeServiceLocator();
SomeService service = null;
try
{
    service = locator.getSomeServiceImplPort();
}
catch (ServiceException e)
{
    e.printStackTrace();
}
```
```


q:
How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func_name will still be "foo":

def bar(self):
    print "bar"

class MetaFoo(type):
    def __new__(cls, name, bases, dict):
        dict["foobar"] = bar
        return type(name, bases, dict)

class Foo(object):
    __metaclass__ = MetaFoo

>>> f = Foo()
>>> f.foobar()
bar
>>> f.foobar.func_name
'bar'

My problem is that some library code actually uses the func_name and later fails to find the 'bar' method of the Foo instance. I could do:

dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")

There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here?

[A]
I think what you want to do is this:
```
```
>>> class Foo():
...   def __init__(self, x):
...     self.x = x
...
>>> def bar(self):
...   print 'bar:', self.x
...
>>> bar.func_name = 'foobar'
>>> Foo.foobar = bar
>>> f = Foo(12)
>>> f.foobar()
bar: 12
>>> f.foobar.func_name
'foobar'
```
```
Now you are free to pass
```
Foo
```
s to a library that expects
```
Foo
```
instances to have a method named
```
foobar
```
.
Unfortunately, (1) I don't know how to use metaclasses and (2) I'm not sure I read your question correctly, but I hope this helps.
Note that
```
func_name
```
is only assignable in Python 2.4 and higher.


q: How does one automatically find categories for text based on content?

[A]
There is a good paper written on this:
http://www.cs.utexas.edu/users/hyukcho/classificationAlgorithm.html


q: When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?

[A]
Minify
seems to be one of the easiest ways to shrink Javascript.
Turning on zip at the web server level can also help.


q:
What techniques or tools are recommended for finding broken links on a website?

I have access to the logfiles, so could conceivably parse these looking for 404 errors, but would like something automated which will follow (or attempt to follow) all links on a site.

[A]
For Chrome Extension there is
hexometer
See
LinkChecker
for Firefox.
For Mac OS there is a tool
Integrity
which can check URLs for broken links.
For Windows there is
Xenu's Link Sleuth
.


q:
In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088).  I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.)

I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? )  But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range.   Any ideas?   A solution can be tightly bound to Tomcat for my application that's ok.

[A]
In Tomcat 6.0 it should be something like:
```
```
org.apache.catalina.ServerFactory.getServer().getServices
```
```
to get the services. After that you might use
```
```
Service.findConnectors
```
```
which returns a Connector which finally has the method
```
```
Connector.getPort
```
```
See the
JavaDocs
for the details.


q:
How would I get the here and and here to be on the right, on the same lines as the lorem ipsums? See the following:

Lorem Ipsum etc........here
blah.......................
blah blah..................
blah.......................
lorem ipsums.......and here

[A]
The first line would consist of 3
```
<div>
```
s. One outer that contains two inner
```
<div>
```
s. The first inner
```
<div>
```
would have
```
float:left
```
which would make sure it stays to the left, the second would have
```
float:right
```
, which would stick it to the right.
```
```

stuff

stuff

```
```
... obviously the inline-styling isn't the best idea - but you get the point.
2,3, and 4 would be single
```
<div>
```
s.
5 would work like 1.


q: I want to delete foo() if foo() isn't called from anywhere.

[A]
Resharper
does this, and not just with methods. It also does it with using statements, variables etcetera.


q:
I've been attempting to write a Lisp macro that would perfom the equivalent of ++ in other programming languages for semantic reasons.  I've attempted to do this in several different ways, but none of them seem to work, and all are accepted by the interpreter, so I don't know if I have the correct syntax or not.  My idea of how this would be defined would be

(defmacro ++ (variable)
  (incf variable))

but this gives me a SIMPLE-TYPE-ERROR when trying to use it.  What would make it work?

[A]
Remember that a macro returns an expression to be evaluated. In order to do this, you have to backquote:
```
```
(defmacro ++ (variable)
   `(incf ,variable))
```
```


q:
I'm a longtime Java programmer working on a PHP project, and I'm trying to get PHPUnit up and working.  When unit testing in Java, it's common to put test case classes and regular classes into separate directories, like this -

/src
  MyClass.java

/test
  MyClassTest.java

and so on.

When unit testing with PHPUnit, is it common to follow the same directory structure, or is there a better way to lay out test classes?  So far, the only way I can get the "include("MyClass.php")" statement to work correctly is to include the test class in the same directory, but I don't want to include the test classes when I push to production.

[A]
You need to modify PHP's include_path so that it knows where to find MyClass.php when you
```
include()
```
it in your unit test.
You could have something like this at the top of your test file (preceding your include):
```
```
set_include_path(get_include_path() . PATH_SEPARATOR . "../src");
```
```
This appends your
```
src
```
directory onto the include path and should allow you to keep your real code separate from your test code.


q: Someone told me it's more efficient to use StringBuffer to concatenate strings in Java than to use the + operator for Strings. What happens under the hood when you do that? What does StringBuffer do differently?

[A]
One shouldn't be faster than the other. This wasn't true before Java 1.4.2, because when concatenating more than two strings using the "+" operator, intermediate
```
String
```
objects would be created during the process of building the final string.
However, as the
JavaDoc for StringBuffer
states, at least since Java 1.4.2 using the "+" operator compiles down to creating a
```
StringBuffer
```
and
```
append()
```
ing the many strings to it. So no difference, apparently.
However, be careful when using adding a string to another inside a loop! For example:
```
```
String myString = "";

for (String s : listOfStrings) {
  // Be careful! You're creating one intermediate String object
  // for every iteration on the list (this is costly!)
  myString += s;
}
```
```
Keep in mind, however, that usually concatenating a few strings with "+" is cleaner than
```
append()
```
ing them all.


q: Maybe this is a silly question, but I've always assumed each number delineated by a period represented a single component of the software. If that's true, do they ever represent something different?  I'd like to start assigning versions to the different builds of my software, but I'm not really sure how it should be structured.  My software has five distinct components.

[A]
It can be very arbitrary, and differs from product to product. For example, with the Ubuntu distribution, 8.04 refers to 2008.April
Typically the left most (major) numbers indicate a major release, and the further you go to the right, the smaller the change involved.


q:
This link describes an exploit into my app using fckEditor:
http://knitinr.blogspot.com/2008/07/script-exploit-via-fckeditor.html

How do I make my app secure while still using fckEditor?   Is it an fckEditor configuration?   Is it some processing I'm supposed to do server-side after I grab the text from fckEditor?

It's a puzzle because fckEditor USES html tags for its formatting, so I can't just HTML encode when I display back the text.

[A]
The bug is not actually FCKeditors fault. As long as you let users edit HTML that will be displayed on your web site they will always have to possibility to do harm unless you check the data before you output it.
Some people use HTMLencoding to do this, but that will destroy all the formatting done by FCKeditor, not what you want.
Maybe you can use the
Microsoft Anti-Cross Site Scripting Library
. Samples on
MSDN


q:
I've been looking for this information for my commercial desktop product, with no avail.

Specifically, what I'm look for, is deployment statistics of the .NET framework for end-users (both granny "I'm just browsing the internet" XP, and high-end users, if possible), and in the commercial/business sector.

Edit: Other than the data points below, here's an interesting blog post about .NET deployment rates.

[A] I don't have any hard numbers, but these days, it is pretty safe to assume most Windows XP and Vista users have at least .NET 2.0. I believe this was actually dropped via Windows Update for XP, and Vista came with at least 2.0 (apparently with 3.0 as pointed out in the comments to this answer).


q:
I'm querying a bunch of information from cisco switches using SNMP.  For instance, I'm pulling information on neighbors detected using CDP by doing an snmpwalk on .1.3.6.1.4.1.9.9.23

Can I use this OID across different cisco models?  What pitfalls should I be aware of?  To me, I'm a little uneasy about using numeric OIDs - it seems like I should be using a MIB database or something and using the named OIDs, in order to gain cross-device compatibility, but perhaps I'm just imagining the need for that.

[A]
It is very consistent.
Monitoring tools depend on the consistency and the MIBs produced by Cicso rarely change old values and usually only implement new ones.
Check out the Cisco
OID look up tool
.
Notice how it doesn't ask you what product the look up is for.
-mw


q:
I worked on an embedded system this summer written in straight C.  It was an existing project that the company I work for had taken over.  I have become quite accustomed to writing unit tests in Java using JUnit but was at a loss as to the best way to write unit tests for existing code (which needed refactoring) as well as new code added to the system.

Are there any projects out there that make unit testing plain C code as easy as unit testing Java code with JUnit?  Any insight that would apply specifically to embedded development (cross-compiling to arm-linux platform) would be greatly appreciated.

[A]
One unit testing framework in C is
Check
; a list of unit testing frameworks in C can be found
here
and is reproduced below.  Depending on how many standard library functions your runtime has, you may or not be able to use one of those.
AceUnit
AceUnit (Advanced C and Embedded Unit) bills itself as a comfortable C code unit test framework. It tries to mimick JUnit 4.x and includes reflection-like capabilities. AceUnit can be used in resource constraint environments, e.g. embedded software development, and importantly it runs fine in environments where you cannot include a single standard header file and cannot invoke a single standard C function from the ANSI / ISO C libraries. It also has a Windows port. It does not use forks to trap signals, although the authors have expressed interest in adding such a feature. See the
AceUnit homepage
.
GNU Autounit
Much along the same lines as Check, including forking to run unit tests in a separate address space (in fact, the original author of Check borrowed the idea from GNU Autounit). GNU Autounit uses GLib extensively, which means that linking and such need special options, but this may not be a big problem to you, especially if you are already using GTK or GLib. See the
GNU Autounit homepage
.
cUnit
Also uses GLib, but does not fork to protect the address space of unit tests.
CUnit
Standard C, with plans for a Win32 GUI implementation. Does not currently fork or otherwise protect the address space of unit tests. In early development. See the
CUnit homepage
.
CuTest
A simple framework with just one .c and one .h file that you drop into your source tree. See the
CuTest homepage
.
CppUnit
The premier unit testing framework for C++; you can also use it to test C code. It is stable, actively developed, and has a GUI interface. The primary reasons not to use CppUnit for C are first that it is quite big, and second you have to write your tests in C++, which means you need a C++ compiler. If these don’t sound like concerns, it is definitely worth considering, along with other C++ unit testing frameworks. See the
CppUnit homepage
.
embUnit
embUnit (Embedded Unit) is another unit test framework for embedded systems. This one appears to be superseded by AceUnit.
Embedded Unit homepage
.
MinUnit
A minimal set of macros and that’s it! The point is to show how easy it is to unit test your code. See the
MinUnit homepage
.
CUnit for Mr. Ando
A CUnit implementation that is fairly new, and apparently still in early development. See the
CUnit for Mr. Ando homepage
.
This list was last updated in March 2008.
More frameworks:
CMocka
CMocka is a test framework for C with support for mock objects. It's easy to use and setup.
See
the CMocka homepage
.
Criterion
Criterion is a cross-platform C unit testing framework supporting automatic test registration, parameterized tests, theories, and that can output to multiple formats, including TAP and JUnit XML. Each test is run in its own process, so signals and crashes can be reported or tested if needed.
See the
Criterion homepage
for more information.
HWUT
HWUT is a general Unit Test tool with great support for C. It can help to create Makefiles, generate massive test cases coded in minimal 'iteration tables', walk along state machines, generate C-stubs and more. The general approach is pretty unique: Verdicts are based on 'good stdout/bad stdout'. The comparison function, though, is flexible. Thus, any type of script may be used for checking. It may be applied to any language that can produce standard output.
See
the HWUT homepage
.
CGreen
A modern, portable, cross-language unit testing and mocking framework for C and C++. It offers an optional BDD notation, a mocking library, the ability to run it in a single process (to make debugging easier). A test runner which discover automatically the test functions is available. But you can create your own programmatically.
All those features (and more) are explained in
the CGreen manual
.
Wikipedia gives a detailed list of C unit testing frameworks under
List of unit testing frameworks: C