q:
I'm making a twitter client, and I'm evaluating the various ways of protecting the user's login information.

IMPORTANT: I need to protect the user's data from other other applications. For example imagine what happens if a bot starts going around stealing Twhirl passwords or Hotmail/GMail/Yahoo/Paypal from applications that run on the user's desktop.

Clarification: I asked this before without the 'important' portion but stackoverflow's UI doesn't help with adding details later inside the Q/A conversation.

Hashing apparently doesn't do it

Obfuscating in a reversable way is like trying to hide behind my finger

Plain text sounds and propably is promiscuous

Requiring the user to type in his password every time would make the application tiresome

Any ideas ?

[A]
This is a catch-22. Either you make the user type in his password every time, or you store it insecurely (obfuscated, encrypted, whatever).
The way to fix this is for more operating systems to incorporate built-in password managers - like OS X's Keychain. That way you just store your password in the Keychain, the OS keeps it secure, and the user only has to type in 1 master password. Lots of applications (like Skype) on OS X use Keychain to do exactly what you are describing.
But since you are probably using Windows, I'd say just go with some obfuscation and encryption. I think you may be slightly paranoid about the password-stealing-bots; if your application doesn't have a large userbase, odds are pretty low that someone will target it and specifically try to steal the passwords. Besides that, they would also have to have access to their victim's filesystem. If that's the case, they probably have a virus/worm and have bigger problems.


q:
I'm trying to get a kernel module to load at boot.

If I run insmod /path/to/module.ko, it works fine. But this has to be repeated every time I reboot.

If I run modprobe /path/to/module.ko, it can't find the module.
I know modprobe uses a configuration file, but I can't get it to load the module even after adding /path/to/module.ko to /etc/modules.

What is the proper configuration?

[A]
You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.
```
```
sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module
```
```
If you add the module name to /etc/modules it will be loaded any time you boot.
Anyway I think that the proper configuration is to copy the module to the standard paths.

s: huggingface

c: devops

d: intermediate


q:
If I have a usercontrol (in Silverlight) that I've written, that uses XAML to define it's appearance, how can I make a customised version of it?

i.e. I have MyControl.xaml & MyControl.xaml.cs

What do I need to do if I want a "SpecialisedControl" child class? I assume I just make a new code file, then inherit from MyControl. But what if I want to change the appearance of the base class - then what do I do?

[A]
I wrote this thinking you were talking about WPF, rather than Silverlight, but there may be enough overlap for this to be helpful, so I'm posting it, anyway.
If by "change the appearance of the base class" you mean "provide a new template", then what you need is probably a CustomControl, not a UserControl.
The best way to accomplish this is to follow the example set by other Microsoft controls, such as Button or ListBox:
Create a class that derives directly from Control (or whatever is closest to your control).
If any properties will need to be exposed to the control (such as text on a button, for example), make sure that you properly define them as DependencyProperties.
As described
here
, create a ResourceDictionary called Themes/generic.xaml and add a style for your class that includes a template (don't give the style a key).
Use TemplateBindings for any properties of elements on your control that need to get values from your control.
If you'll need to attach any event handlers to elements in your template, give them a unique name. Microsoft uses the convention of prefixing these names with "PART_", and I think it's a good thing to do for the sake of consistency, but it's not strictly required.
Again, if you need to attach event handlers, overload OnApplyTemplate(). In this method, you should detach any old event handlers (we certainly don't want any memory leaks!), and look for elements that have the names your provided in your template--when you find them, attach event handlers, as necessary.
This is certainly much more work than simply deriving from UserControl, but if you want to be able to totally re-template controls, like you can with the built-in controls, this is the way to do it.
On the other hand
, if all you want to do is to provide a certain amount of limited customization, such as changing the background, or associating a Command with some user action, then the best thing to do is to expose DependencyProperties, which can then be set in styles for your control, or on instances of your control, itself.
In the case you mentioned of wanting to customize the look in an inherited control, the process is pretty similar: just add a default style for the new control with a new template; if you need to add more event handlers, just be absolutely certain that you call base.OnApplyTemplate().


q: Can anyone provide a clear explanation / example of what these functions do, and when it's appropriate to use them?

[A]
Straight from
the manual
...
We know that the foreign keys disallow creation of orders that do not relate to any products. But what if a product is removed after an order is created that references it? SQL allows you to handle that as well. Intuitively, we have a few options:
Disallow deleting a referenced product
Delete the orders as well
Something else?
```
```
CREATE TABLE order_items (
 product_no integer REFERENCES products ON DELETE RESTRICT,
 order_id integer REFERENCES orders ON DELETE CASCADE,
 quantity integer,
 PRIMARY KEY (product_no, order_id)
);
```
```
Restricting and cascading deletes are the two most common options. RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything. (The essential difference between these two choices is that NO ACTION allows the check to be deferred until later in the transaction, whereas RESTRICT does not.) CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well. There are two other options: SET NULL and SET DEFAULT. These cause the referencing columns to be set to nulls or default values, respectively, when the referenced row is deleted. Note that these do not excuse you from observing any constraints. For example, if an action specifies SET DEFAULT but the default value would not satisfy the foreign key, the operation will fail.
Analogous to ON DELETE there is also ON UPDATE which is invoked when a referenced column is changed (updated). The possible actions are the same.
edit:
You might want to take a look at this related question:
When/Why to use Cascading in SQL Server?
. The concepts behind the question/answers are the same.


q: What compatibility issues have you found when developing with Visual FoxPro 9 on Windows Vista?

[A]
My company has no current plans to move to vista, so we haven't tested compatability issues yet.   Doug Hennig has an excellent article on the subject however:
http://my.advisor.com/articles.nsf/aid/18897
These links describe some issues as well:
http://fox.wikis.com/wc.dll?Wiki~VistaAeroIssues~VFP
http://fox.wikis.com/wc.dll?Wiki~SP2problemwithVistaandBorderstyle~VFP


q:
There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you'd use one way over the other.

First type:

List<string> someList = <some way to init>
foreach(string s in someList) {
   <process the string>
}

Other Way:

List<string> someList = <some way to init>
someList.ForEach(delegate(string s) {
    <process the string>
});

I suppose off the top of my head, that instead of the anonymous delegate I use above, you'd have a reusable delegate you could specify...

[A]
I guess the
```
someList.ForEach()
```
call could be easily parallelized whereas the normal
```
foreach
```
is not that easy to run parallel.
You could easily run several different delegates on different cores, which is not that easy to do with a normal
```
foreach
```
.
Just my 2 cents


q:
My only problem is making them line up three-across and have equal spacing. Apparently, spans can not have width and divs (and spans with display:block) don't appear horizontally next to each other. Suggestions?

<div style='width:30%; text-align:center; float:left; clear:both;'> Is what I have now.

[A]
You can use divs with the
```
float: left;
```
attribute which will make them appear horizontally next to each other, but then you may need to use clearing on the following elements to make sure they don't overlap.


q: I have a form which takes both the user details and an image uploaded by them. I want to write the data to a user table and an image table but i am pretty sure that it cannot be done with just two separate insert statements. Any help would be much appreciated.

[A]
You need to insert the user first, then do "SELECT LAST_INSERT_ID()" to retrieve the id of the user. Then you can insert the image in the image table with the newly created user id. In PHP you can actually use
mysql_insert_id()
to retrieve the new id. If you use mysql with InnoDB, you can also wrap the inserts in a
transaction
, by issuing BEGIN, followed by the INSERTs, followed by either COMMIT if everything is successfully added, or ROLLBACK in case of failure.


q:
I've seen How to: Host Controls in Windows Forms DataGridView Cells which explains how to host a control for editing a cell in a DataGridView.  But how can I host a control for displaying a cell?

I need to display a file name and a button in the same cell.  Our UI designer is a graphic designer not a programmer, so I have to match the code to what he's drawn, whether it's possible - or wise - or not.  We're using VS2008 and writing in C# for .NET 3.5, if that makes a difference.

UPDATE: The 'net suggests creating a custom DataGridViewCell which hosts a panel as a first step; anyone done that?

[A]
As per your "UPDATE", creating a custom
```
DataGridViewCell
```
is the way this is done. I've done it, and it doesn't require that much modification from the example code available from the MSDN. In my case, I needed a bunch of custom editing controls, so I ended up inheriting from
```
DataGridViewTextBoxCell
```
and
```
DataGridViewColumn
```
. I inserted into my class (the one inherited from
```
DataGridViewTextBoxCell
```
) a new custom control which implemented
```
IDataGridViewEditingControl
```
, and it all just worked.
I suppose that in your case, you could write a
```
PanelDataGridViewCell
```
which would contain a control
```
MyPanelControl
```
which would inherit from Panel and implement
```
IDataGridViewEditingControl
```
.


q:
I have a partial that renders a select box using the following method:

<%= collection_select 'type', 'id', @types, "id", "name",
  {:prompt => true},
  {:onchange =>
              remote_function(
              :loading => "Form.Element.disable('go_button')",
              :url => '/sfc/criteria/services',
              :with => "'type_id=' + encodeURIComponent(value) + '&use_wizard=#{use_wizard}'"),
    :class => "hosp_select_buttons"
} %>

This partial gets used 2 times on every page, but at one point I need to get the value of the first select box. Using:

$('type_id')

returns the second select box. Is there a way to find the first one easily? Should I fix this using javascript or by redoing my partial?

Note: the dropdowns do get rendered in separate forms.


q:
Have you ever tried this before?

static void Main(string[] args)
{
    int x = 10;
    x = x++;
    Console.WriteLine(x);
}

Output: 10.

but for

static void Main(string[] args)
{
    int x = 10;
    x++;
    Console.WriteLine(x);
}

Output: 11.

Could anyone explain why this?

[A]
X++ will increment the value, but then return its old value.
So in this case:
```
```
static void Main(string[] args)
{
    int x = 10;
    x = x++;
    Console.WriteLine(x);
}
```
```
You have X at 11 just for a moment, then it gets back to 10 because 10 is the return value of (x++).
You could instead do this for the same result:
```
```
static int plusplus(ref int x)
{
  int xOld = x;
  x++;
  return xOld;
}

static void Main(string[] args)
{
    int x = 10;
    x = plusplus(x);
    Console.WriteLine(x);
}
```
```
It is also worth mentioning that you would have your expected result of 11 if you would have done:
```
```
static void Main(string[] args)
{
    int x = 10;
    x = ++x;
    Console.WriteLine(x);
}
```
```


q: I am learning to use LabVIEW as part of my honours project, and was wondering what benefits the graphical programming language has over a textual one?

[A]
I've used labview before for calculating parameters to tune an nMRI machine.  They exist because in theory it is easier for someone with little programming language experience create a program.  The control flow and decision structures can be arranged graphically and they can type in their formula's where they want.
For professors and lab assistants...helpful.
For real software developers...it would be easier to write in another language.


q:
As part of our build process we run a database update script as we deploy code to 4 different environments. Further, since the same query will get added to until we drop a release into production it has to be able to run multiple times on a given database.  Like this:

IF NOT EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[Table]'))
BEGIN
  CREATE TABLE [Table]
  (...)
END

Currently I have a create schema statement in the deployment/build script.  Where do I query for the existence of a schema?

[A]
Are you looking for
sys.schemas
?
```
```
IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'jim')
BEGIN
EXEC('CREATE SCHEMA jim')
END
```
```
Note that the
```
CREATE SCHEMA
```
must be run in its own batch (per
the answer below
)


q:
I am trying to use ResourceBundle#getStringArray to retrieve a String[] from a properties file. The description of this method in the documentation reads:

Gets a string array for the given key from this resource bundle or one of its parents.

However, I have attempted to store the values in the properties file as multiple individual key/value pairs:

key=value1
key=value2
key=value3

and as a comma-delimited list:

key=value1,value2,value3

but neither of these is retrievable using ResourceBundle#getStringArray.

How do you represent a set of key/value pairs in a properties file such that they can be retrieved using ResourceBundle#getStringArray?

[A]
Umm, looks like this is a common problem, from threads
here
and
here
.
It seems either you don't use the method and parse the value for an array yourself or you write your own ResourceBundle implementation and do it yourself :(.  Maybe there is an apache commons project for this...
From the JDK source code, it seems the PropertyResourceBundle does not support it.


q:
Possible Duplicate:

  When will C++0x be finished?

What are the latest news about C++0X? (or should I say C++1X) Any release date decided yet?

[A]
A new
draft
came out recently, so things are progressing. From this draft to the finalized version, it should be no more than a year before things are finalized. I should note that this draft is the feature-complete version; from here on it should only be revisions. I was just made aware, however, that the path from draft to actual, published, standard is a very long road. I'll push my estimate of a published, accepted standard out to 2010.
How long until we have full compiler compliance? That is a different story. GCC is making good progress on the language features that aren't libraries (see
list of features they have implemented
), but has no mention of progress on the concurrency features. I can't say anything for when MSVC/dinkumware/whatever other compilers you may use will start implementing things like lambda.
Boost already has much of TR1 implemented, and dinkumware has it all, so you can start using the new libraries already (maybe not in their final form, however).


q:
How do I load a true color image into a CImageList?

Right now I have

mImageList.Create(IDB_IMGLIST_BGTASK, 16, 1, RGB(255,0,255));

Where IDB_IMGLIST_BGTASK is a 64x16 True color image.  The ClistCtrl I am using it in shows 16 bpp color.  I don't see a Create overload that allows me to specify both the bpp and the resource to load from.

[A]
Needs 4 lines of code, but this works:
```
```
CBitmap bm;
bm.LoadBitmap(IDB_IMGLIST_BGTASK);
mImageList.Create(16, 16, ILC_COLOR32 | ILC_MASK, 4, 4);
mImageList.Add(&bm, RGB(255,0,255));
```
```


q:
I realise this is not the ideal place to ask about this in terms of searchability, but I've got a page whose JavaScript code throws "Stack overflow in line 0" errors when I look at it in Internet Explorer.

The problem is quite clearly not in line 0, but somewhere in the list of stuff that I'm writing to the document. Everything works fine in Firefox, so I don't have the delights of Firebug and friends to assist in troubleshooting.

Are there any standard causes for this? I'm guessing this is probably an Internet Explorer 7 bug or something quite obscure, and my Google-fu is bringing me little joy currently. I can find lots of people who have run into this before, but I can't seem to find how they solved it.

[A]
You can turn
off
the
```
"Disable Script Debugging"
```
option inside of Internet Explorer and start debugging with
```
Visual Studio
```
if you happen to have that around.
I've found that it is one of few ways to diagnose some of those
```
IE
```
specific issues.


q:
I've been reading about "web services" here on SO, on Wikipedia, Google, etc., and I don't quite understand what they are.  What is the plain English definition/description?

If I make a simple website using PHP that just, say, prints a random integer to the page... is this a "web service"?  If not, why not?

[A]
Yes that is a simple web service.
Web services are really nothing more than a request/ response mechanism that allows a client to remotely access/ modify data. There are formal standards for web services (SOAP, SOA etc), but your simple page is a service too.
The main downside to printing it to a page is that your service would return HTML. Preferable data formats are JSON and XML, because most client frameworks (and server frameworks) are designed around using JSON and XML.
So if you modified your service to return:
```
```
<RANDOM>some random number</RANDOM>
```
```
rather than:
```
```
...
some random number
```
```
then it would be more useful to most clients


q: What are the differences between a wiki and a CMS?  Is there any?

[A] Typically a Wiki is community editable, visitors to the site can edit it, take Wikipedia for example.  A CMS is more designed typially, for a set of site administrators to manage and display content.


q:
I'm trying to decode a WBXML encoded SyncML message from a Nokia N95.
My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> through by itself but it failed. Is there something I'm missing?

Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...

[A]
Funnily enough I've been working on the same problem.  I'm about halfway through writing my own pure-Python WBXML parser, but it's not yet complete enough to be useful, and I have very little time to work on it right now.
Those <Unknown> tags might be because pywbxml / libwbxml doesn't have the right tag vocabulary loaded.  WBXML represents tags by an index number to avoid transmitting the same tag name hundreds of times, and the table that maps index numbers to tag names has to be supplied separately from the WBXML document itself.  From a vague glance at
the libwbxml source
it seems like libwbxml has a bunch of tag tables hard coded.  It has tables for SyncML 1.0-1.2; I think my Nokia E71 sends SyncML 1.3 (if so, your N95 probably does too), which it looks like libwbxml doesn't support yet.
Getting it to work might be as simple as adding a SyncML 1.3 table to libwbxml.  That said, last time I tried, pywbxml doesn't compile against the vanilla libwbxml source, so you have to apply some patches first... so "simple" may be a relative term.


q:
When creating a new build in Team Foundation Server, I get the following error when attempting to run the new build:

The path
  C:\Build\ProductReleases\FullBuildv5.4.2x\Sources
  is already mapped to workspace
  BuildServer_23.

I am unable to see a workspace by that name in the workspaces dialog.

[A]
Use the command line utility
TF - Team Foundation Version Control Tool
(
tf
).
You can get a list of all workspaces by bringing up a
Visual Studio Command Prompt
then changing to your workspace folder and issuing the following commands:
```
```
C:\YourWorkspaceFolder>tf workspaces /owner:*
```
```
You should see your problem workspace in the list as well as it's owner.
You can delete the workspace with the following command:
```
```
C:\YourWorkspaceFolder>tf workspace /delete /server:BUILDSERVER WORKSPACENAME;OWNERNAME
```
```


q:
I could write myself a helper class that does this when given a functor, but I was wondering if there's a better approach, or if there's something already in the standard library (seems like there should be).

Answers I've found on StackOverflow are all for C# which doesn't help me.

Thanks

[A]
No - there isn't. Apache
```
commons-collections
```
has predicates for this sort of thing but the resultant code (using anonymous inner classes) is usually ugly and a pain to debug.
Just use a basic
for-loop
until they bring
closures
into the language


q:
I'm using polar plots (POLAR(THETA,RHO)) in MATLAB.

Is there an easy way to fix the range for the radial axis to say, 1.5?

I'm looking for something analogous to the xlim, ylim commands for cartesian axes. Haven't found anything in the docs yet.

[A]
Here's how I was able to do it.
The MATLAB polar plot (if you look at the Handle Graphics options available) does not have anything like xlim or ylim.  However, I realized that the first thing plotted sets the range, so I was able to plot a function with radius range [-.5 .5] on a [-1 1] plot as follows:
```
```
theta  = linspace(0,2*pi,100);
r      = sin(2*theta) .* cos(2*theta);
r_max  = 1;
h_fake = polar(theta,r_max*ones(size(theta)));
hold on;
h      = polar(theta, r);
set(h_fake, 'Visible', 'Off');
```
```
That doesn't look very good and hopefully there's a better way to do it, but it works.


q:
I'm trying to drag a CALayer in an iOS app.

As soon as I change its position property it tries to animate to the new position and flickers all over the place:

 layer.position = CGPointMake(x, y)

How can I move CALayers instantly? I can't seem to get my head around the Core Animation API.

[A]
You want to wrap your call in the following:
```
```
[CATransaction begin];
[CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions];
layer.position = CGPointMake(x, y);
[CATransaction commit];
```
```


q:
I am having trouble understanding how the System Registry can help me convert a DateTime object into the a corresponding TimeZone.  I have an example that I've been trying to reverse engineer but I just can't follow the one critical step in which the UTCtime is offset depending on Daylight Savings Time.

I am using .NET 3.5 (thank god) but It's still baffling me.

Thanks

EDIT: Additional Information: This question was for use in a WPF application environment. The code snippet I left below took the answer example a step further to get exactly what I was looking for.

[A]
You can use DateTimeOffset to get the UTC offset so you shouldn't need to dig into the registry for that information.
TimeZone.CurrentTimeZone returns additional time zone data, and TimeZoneInfo.Local has meta data about the time zone (such as whether it supports daylight savings, the names for its various states, etc).
Update: I think this specifically answers your question:
```
```
var tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset);
Console.WriteLine(dto);
Console.ReadLine();
```
```
That code creates a DateTime at -8 offset.  The default installed time zones are
listed on MSDN
.


q: I have a UIImagePickerController as one view in a TabBar setup.  Is it possible to tell the UIImagePickerController to not show the Cancel button in the top navigation bar when browsing photos libraries?


q:
I have SQL query, which is working nice on Oracle and MSSQL. Now I'm trying this on PostgreSQL and it gives a strange exception: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "main"

Here is the query:

SELECT *
FROM "main" main
     INNER JOIN "something_link" something_link ON main."id" = something_link."mainid"
     INNER JOIN "something" somehting ON something_link."somethingid" = something."id"
     INNER JOIN "type" type ON something."typeid" = type."id"

This is quite simple query and I can't see why it is not working on Windows XP SP2, PostgreSQL 8.3?

[A]
somehting=>something
```
postgres=# create database test
postgres-# ;
CREATE DATABASE

postgres=# \c test
You are now connected to database "test".

test=# select version();
                                            version
-----------------------------------------------------------------------------------------------
 PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)

test=# create table main(id int);
CREATE TABLE

test=# create table something_link(mainid int);
CREATE TABLE

test=# create table something(id int);
CREATE TABLE

test=# create table type(id int);
CREATE TABLE

test=# alter table something add column typeid int;
ALTER TABLE

test=# SELECT *
test-# FROM "main" main
test-#      INNER JOIN "something_link" something_link ON main."id" = something_link."mainid"
test-#      INNER JOIN "something" somehting ON something_link."somethingid" = something."id"
test-#      INNER JOIN "type" type ON something."typeid" = type."id"
test-# ;
ERROR:  column something_link.somethingid does not exist
LINE 4:      INNER JOIN "something" somehting ON something_link."som...
                                                 ^
test=# alter table something_link add column somethingid int;
ALTER TABLE

test=# SELECT *
FROM "main" main
     INNER JOIN "something_link" something_link ON main."id" = something_link."mainid"
     INNER JOIN "something" *somehting* ON something_link."somethingid" = something."id"
     INNER JOIN "type" type ON something."typeid" = type."id"
;

ERROR:  invalid reference to FROM-clause entry for table "something"
LINE 4: ...hing" somehting ON something_link."somethingid" = something....
                                                             ^
HINT:  Perhaps you meant to reference the table alias "somehting".

test=# SELECT *
FROM "main" main
     INNER JOIN "something_link" something_link ON main."id" = something_link."mainid"
     INNER JOIN "something" something ON something_link."somethingid" = something."id"
     INNER JOIN "type" type ON something."typeid" = type."id"
;

 id | mainid | somethingid | id | typeid | id

----+--------+-------------+----+--------+----

(0 rows)
```


q:
I am currently working for a company that has a website running mysql/php (all tables are also using the MYISAM table type).

We would like to implement replication, but I have read in the mysql docs and elsewhere on the internet that this will lock the tables when doing the writes to the binary log (which the slave dbs will eventually read from).

Will these locks cause a problem on a live site that is fairly write-heavy?  Also, is there a way to enable replication without having to lock the tables?

[A]
If you change your table types to innodb, row level locking is used.  Also, your replication will be more stable, as updates will be transactional.  MyISAM replication is a long-term pain.
Be sure that your servers are version-matched, and ALWAYS be sure to shut down the master before shutting down the slaves.  You can bring the master up again immediately after shutting down the slaves, but you do have to take it down.
Also, make sure you use appropriate autoextend options for InnoDB.  And, while you're at it, you'll probably want to migrate away from float and double to 'decimal' (which means mysql 5.1.)  That will save you some replication headaches.
That's probably a bit more than you asked for.  Enjoy.
P.s., yes the myisam locks can cause problems.  Also, innodb is slower than myisam, unless myisam is blocking for a huge select.


q:
When I first load data into a Silverlight DataGrid control, how can I make the screen look exactly as if the user had just clicked the header of the first column?  In other words, the data should be sorted in ascending order according to that column's values, AND the little sort arrow should be displayed in the first column's header.

Assuming that's possible, can I also make it look as if the user had clicked the first column and then shift-clicked the second?  In other words, can I programatically apply a two-part sort and have the screen look as if the user had done it?

[A]
I needed to do this as well, and looked hard and deep at whether the DataGrid could do this.
There IS in fact an appropriate method on the DataGridColumnHeader class, namely InvokeProcessSort, but it's internal and not surfaced anywhere else in the DataGrid classes.
All I've been able to do is pre-sort the data just before I bind it. I'm using a custom data collection that implements ICollectionView as well as ObservableCollection<>, and this works OK - but it's not optimal, and a load of work that's not necessarily needed.
Also, providing a pre-sorted collection means the grid doesn't show the sort marker.
I'll raise this as an issue on the DataGrid bug-tracker - this is a fairly major omission that'd be quite easy to fix - MS just needs to expose appropriate methods on DataGridColumn and DataGrid classes.


q: As every Haxe developer knows, you could use haxe.Timer.delayed() to delay function call for some time. But this function doesn't exist for Neko at all. Is there a way to achieve the same results?

[A]
Have to check it first but
```
```
function delayed(f, time) {
   neko.vm.Thread.create(function() {
       neko.Sys.sleep(time);
       f();
   });
}
```
```
might be the closest thing possible. The only cons is that application becomes multi threaded which could lead to serious problems.


q:
Someone at work just asked for the reasoning behind having to wrap a wait inside a synchronized.

Honestly I can't see the reasoning.  I understand what the javadocs say--that the thread needs to be the owner of the object's monitor, but why?  What problems does it prevent?  (And if it's actually necessary, why can't the wait method get the monitor itself?)

I'm looking for a fairly in-depth why or maybe a reference to an article.  I couldn't find one in a quick google.

Oh, also, how does thread.sleep compare?

edit: Great set of answers--I really wish I could select more than one because they all helped me understand what was going on.

[A]
If the object does not own the object monitor when it calls Object.wait(), it will not be able to access the object to setup a notify listener until the the monitor is released. Instead, it will be treated as a thread attempting to access a method on a synchronized object.
Or to put it another way, there is no difference between:
```
```
public void doStuffOnThisObject()
```
```
and the following method:
```
```
public void wait()
```
```
Both methods will be blocked until the object monitor is released. This is a feature in Java to prevent the state of an object from being updated by more than one thread. It simply has unintended consequences on the wait() method.
Presumably, the wait() method is not synchronized because that could create situations where the Thread has multiple locks on the object. (See
Java Language Specifications/Locking
for more info on this.) Multiple locks are a problem because the wait() method will only undo one lock. If the method were synchronized, it would guarantee that only the method's lock would be undone while still leaving a potential outer lock undone. This would create a deadlock condition in the code.
To answer your question on Thread.sleep(), Thread.sleep() does not guarantee that whatever  condition you are waiting on has been met. Using Object.wait() and Object.notify() allows a programmer to manually implement blocking. The threads will unblock once a notify is sent that a condition has been met. e.g. A read from disk has finished and data can be processed by the thread. Thread.sleep() would require the programmer to poll if the condition has been met, then fall back to sleep if it has not.


q:
I need a good stemming algorithm for a project I'm working on. It was suggested that I look at the Porter Stemmer. When I checked out the page on the Porter stemmer I found that it is deprecated now in favor of the "Snowball" stemmer.

I need a good stemmer, but I can't really spend significant time implementing (or optimizing) my own. What is the best "off the shelf", freely available stemmer? Are there any non-free stemmers available for a reasonable price? Or, is the Snowball stemmer my best bet?

[A]
It really depends on how you're planning to apply it.  The Natural Language Toolkit (
http://nltk.sourceforge.net
) has a number of stemmers implemented in it that should be able to handle most applications.  I prefer the Morphy stemmer.
Of course, it's available in Python, so if you're working with another language, you can always look through the code to glean the algorithm and transfer it to your language of choice.  Python is highly readable.


q:
Say I have a form like:

class GeneralForm(forms.Form):
    field1 = forms.IntegerField(required=False)
    field2 = forms. IntegerField(required=False)

And I want to show it twice on a page within one form tag each time with a different prefix e.g.,:

rest of page ...
<form ..>
GeneralForm(data,prefix="form1").as_table()
GeneralForm(data,prefix="form2").as_table()
<input type="submit" />
</form>
rest of page ...

When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it?

This was the only documentation I could find and it's peckish.

[A]
You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially.
Here's a slightly awkward example using the form you've given, as I don't know what the exact use case is:
```
```
def some_view(request):
    if request.method == 'POST':
        form1 = GeneralForm(request.POST, prefix='form1')
        form2 = GeneralForm(request.POST, prefix='form2')
        if all([form1.is_valid(), form2.is_valid()]):
            pass # Do stuff with the forms
    else:
        form1 = GeneralForm(prefix='form1')
        form2 = GeneralForm(prefix='form2')
    return render_to_response('some_template.html', {
        'form1': form1,
        'form2': form2,
    })
```
```
Here's some real-world sample code which demonstrates processing forms using the prefix:
http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/


q:
I seem to remember reading that it's possible to declare taglib directives such as:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

in web.xml. This eliminates the need to duplicate this directive in every JSP file where the taglib is used. Could someone tell me how these directives can be added to web.xml?

[A]
Sorry, you're slightly mistaken.  If a page uses a taglib, you have to have a taglib directive for it on the page. You could place the common taglib directives in an include file that all of your pages include with an include directive, but at compile time the taglib directive has to be there.
I prefer to NOT have the taglib elements in the web.xml, and instead have the taglib directive specify the URI value that is used in the "uri" element in the TLD that is inside the taglib jar file in your WEB-INF/lib.


q:
In Django templates, is there a variable in the context (e.g. {{ BASE\_URL }}, {{ ROOT\_URL }}, or {{ MEDIA\_URL }} that one can use to link to the home url of a project?

I.e. if Django is running in the root of a project, the variable (let's call it R) {{ R }} in a template would be /. If the root url is a sub-folder http://host/X/ the variable {{ R }} would be /X/ (or http://host/X/).

It seems painfully simple, but I can't find an answer. :) Thank you!

[A]
I always use something like
```
<a href="/">
```
(assuming your home is at the root, of course). I seem to recall looking this up once, and couldn't find a Django variable for this path; at any rate,
```
/
```
seemed pretty easy, anyway.


q:
I am dabbling in the world of web services and I've been making a simple web service which mimics mathematical operations. Firstly it was simple, passing in two integers and then a binary operator would be applied to these (plus, minus etc) depending on the method called.

Then I decided to make things a little more complex and started passing objects around, but then I discovered that a web service only exposes the data side of the class and not the functional side.

I was told that a good way to deal with this is to make the class on the service side a partial class (this side of the class encapsulating form) and on the client side have another partial class (where this side of the class encapsulates functionality). This seems like an elegant way of doing things..

So, I have set up two classes as described above, but it doesn't seem to be working as I was told.

Is what I am attempting possible? If so, where am I going wrong?

[A]
Not with partial classes. A partial class is a syntax construct that gives you the ability to have different parts of the class in different source files. However, all parts of the  partial class are ultimately compiled into the same binary.
You could use extension methods to add functionality to your class that represents the data contract.
You could also try implementing the class in a shared assembly and use the svcutil.exe /reference to get it imported in the client proxy instead of having a brand new declaration in the web service namespace.


q:
I am not very good with Regex but I am learning.

I would like to remove some html tag by the class name. This is what I have so far :

<div class="footer".*?>(.*?)</div>

The first .*? is because it might contain other attribute and the second is it might contain other html stuff.

What am I doing wrong? I have try a lot of set without success.

Update

Inside the DIV it can contain multiple line and I am playing with Perl regex.

[A]
Partly depends on the exact regex engine you are using - which language etc.   But one possibility is that you need to escape the quotes and/or the forward slash.  You might also want to make it case insensitive.
```
```
<div class=\"footer\".*?>(.*?)<\/div>
```
```
Otherwise please say what language/platform you are using - .NET, java, perl ...


q:
I've been spoiled by Visual studio 2008 and Eclipse and have to do a little maintainence work on a VB6 app.

Does anyone know of an alternative/ updated IDE for VB6?

A rewrite is not an option I'm just fixing a couple of bugs and it's a big codebase.

[A]
Some time ago I did some research and nothing came up. I don't believe you have have any real alternatives...
But you could consider checking this out:
http://www.axtools.com/products/cs2k3vb_screenshots.htm
It looks quite promising.
Addin for Visual Basic 6.0 packing more than 50 professional tools and
  assistants. The Code View Assistant
  enriches the standard VB6 code editor
  with branch lines for conditional
  statements, end-of-line details, and
  hotspots. Moreover, the Code Analyzer
  pinpoints dead and slow code, the
  SmartComplete and AutoText tools help
  you write code with a proficiency you
  never dreamed of, while the Enhanced
  Project Explorer with expanding code
  and Code Flow View can make accessing
  a code location the speedy action you
  always needed. Other tools: Extended
  Find, Find References, Designer
  Explorer, Code Formatter, TabOrder
  Designer (with auto-order), HotKey
  Designer, Error Handlers Inserter,
  Exception Protection, Spelling
  Checker, Strings Reviewer, Comments
  Conformity Checker, Task List Manager,
  Code Snippets Manager, Naming
  Standards Manager.Version 2007 adds
  Designer Analyzer, User Interface
  Standard Properties Manager, Library
  Explorer including Designer Snippets,
  many enhancements in most subsystems.


q:
I would like to update a dll for a server process without stopping the service. How do I do that?
A bit like how asp.net automatically picks up new dlls placed in the bin folder.

[A]
Asp.Net uses a technique called
shadow copy
If you copy an updated dll into an application’s bin subdirectory, the ASP.NET runtime recognizes there is new code to execute. Since ASP.NET cannot swap the dll into the existing AppDomain , it starts a new AppDomain. The old application domain is “drain stopped”, that is, existing requests are allowed to finish executing, and once they are all finished the AppDomain can unload. The new AppDomain starts with the new code and begins taking all new requests.
Typically, when a dll loads into a process, the process locks the dll and you cannot overwrite the file on disk. However, AppDomains have a feature known as Shadow Copy that allows assemblies to remain unlocked and replaceable on disk.
The runtime initializes ASP.NET with Shadow Copy enabled for the bin directory. The AppDomain will copy any dll it needs from the bin directory to a temporary location before locking and loading the dll into memory. Shadow Copy allows us to overwrite any dll in the bin directory during an update without taking the web application offline.


q:
How can I transform a time value into YYYY-MM-DD format in Java?

long lastmodified = file.lastModified();
String lasmod =  /*TODO: Transform it to this format YYYY-MM-DD*/

[A]
Something like:
```
```
Date lm = new Date(lastmodified);
String lasmod = new SimpleDateFormat("yyyy-MM-dd").format(lm);
```
```
See the javadoc for
SimpleDateFormat
.


q:
I have a web service in C# and would like to have a nested inner class, that abstracts away the session collection, something like this:

public class Service : System.Web.Services.WebService
{
    [WebMethod]
    public string Foo(string ticket)
    {
        SessionPool.getSession(ticket);
    }

    private class SessionPool
    {
        public static Session getSession(string ticket)
        {
            // this is what i want to do, but I can't access Context
            return (Session)Context.Session[ticket];
        }
    }
}

Is it possible to access the HTTP context of the WebService class via a nested class? If not, is there way I can store the reference to it?

[A]
```
```
System.Web.HttpContext.Current
```
```
?


q:
QA tester was reading HTML/JS code to write a functional test of a web form, and saw:

if (form_field == empty)
{
...do stuff for empty field
}
else if (form_field != empty)
{
...do stuff for non-empty field
}
else
{
...do stuff that will never be done
}

After a couple embarrassing attempts, tester realized that they couldn't trigger the alert strings hidden in the third block.

Things I'm wondering are if this Is this problem more or less language specific (can non-JS people learn lessons here?) and are there legitimate reasons code ended up this way?

How can I find/address the problem?

[A]
I don't believe that this problem is at all language specific.  You could construct similar (flawed) conditional statements in a wide variety of other languages.
Also, I don't think that there is a legitimate reason for the conditional statement to be structured this way.  As you state in the comment, the statements in the third block will just never be done.
You could probably find mistakes like this most effectively with code review.  However, since that requires quite a bit of time from at least one developer, you may be better served by developing quality unit tests and inspecting code coverage.  In this case, you probably would have noticed that the third portion of the conditional statement was never used.


q:
We have a netbeans project that has an xsd that we use to create a wsdl and we use the wsdl to create a webservice.  Since we are using types in our xsd jaxb is used and one of our webservice methods looks like this:

public void someMethod( org.netbeans.xml.schema.line.Line x )...

So that leaves us a problem with subversion since the Line objects are generated by netbeans.  So we want to do is either tell netbeans to place the files inside of the project?  Or tell netbeans that we will generate the jaxb code and that they should use our classes when the webservice calls are processed?  How can we accomplish one of these, what are some other alternatives?

[A]
You can build one with the
```
HttpListener
```
class to listen for incoming requests and the
```
HttpWebRequest
```
class to relay the requests.


q:
I'm developing a website (using asp.net by the way) and I'm having a problem with IE6.

When I use some icons near links, using background-image and padding-left on the links, the icons display nice on FF and Chrome but in IE6 they take a kind of "gray" background, and sometimes the flash strangely.

Any ideas? is there some CSS hack to solve this? Thanks everyone!

[A]
Are they .png files? IE6 has issues with alpha transparency in .pngs. There is a
javascript fix though
.
Edit, to clarify - If IE6 sees a .png with alpha transparency (which is different than the transparency in .gifs) it freaks out and renders that part the light gray I believe you are seeing. The javascript fix applies a filter to all the .pngs in the page. However, this does not work on .pngs that have been set as backgrounds via css.


q: I'd like to make anchors to every post in my asp.net forum. Every forum's post is rendered using repeater control. How can I render <a name="anchor_name"></a> in asp.net?

[A]
```
```
<a name='<%# Eval("PostId") %>' />
```
```
where PostId is the name of the property you want to appear in your anchor.


q:
Can anyone recommend any Ad Management components for .NET?  I have a customer who would like to sell his own advertising through his own site.  This rules out using packaged ad providers such as Google Ads.

I've googled several packages, but I'd like to see if anyone has any first hand experience with a particular package.

Or should I just roll my own ad management system?

Thanks!

[A]
If there is going to be any size or complexity to the ad system, I wouldn't roll your own.  Focus on your core competencies and outsource the rest, because ad people can be crazy and it's nearly impossible to implement all the features they would want.  Frequency capping, geotargeting, failover reporting, inventory management, just to name a few.
Check out Atlas Solutions, formerly Accipiter (now bought by Microsoft), which provides hosted ad serving solutions.  Of course, that will come with a price, but what doesn't?


q:
I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything.  The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 =< only.  Here is the code I have:

var oImg = document.createElement("img");
oImg.setAttribute('src', 'http://www.testtrackinglink.com');
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '1px');
oImg.setAttribute('width', '1px');
document.body.appendChild(oImg);

Is this the simplest but most robust (error free) way to do it?

I cannot use a framework like jQuery.  It needs to be in plain JavaScript.

[A]
Are you allowed to use a framework?
jQuery
and
Prototype
make this sort of thing pretty easy. Here's a sample in Prototype:
```
```
var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });
$(document).insert(elem);
```
```


q: When you use the PHP copy function, the operation blindly copies over the destination file, even if it already exists.  How do you copy a file safely, only performing the copy if there is no existing file?

[A]
I think you answered your own question - check to make sure the destination file exists before performing the copy. If the file exists, skip the copy.
Update: I see you really did answer your own question. You mention race conditions, but if you do find that the file already exists, how do you know that:
the file that is already there is really the one you want to copy
the other process copying the file has completed its job (the file data is all there)
the other process copying the file isn't going to fail (and leave an incomplete file, or delete the new file)
I think you should consider these questions when designing a solution to your problem.


q: I cannot get the internet explorer web developer tool bar to work with a pop-up, it won't render at the bottom of the pop-up.  Any suggestions?

[A]
I just tried this on my machine, and it seems to be working. Make sure you're using the
latest version
Otherwise update your question and I'll try to help out again.
update: Make sure the toolbar is docked to your parent window before the popup fires. When I have the toolbar docked (using the little dock icon at the top right of the window) it seems to follow to the new popup.


q:
I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.

How do you check that a date, given as a combination of day, month, and year, is a valid date?

For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.

[A]
The current way is to use the calendar class.  It has the
setLenient
method that will validate the date and throw and exception if it is out of range as in your example.
Forgot to add:
If you get a calendar instance and set the time using your date, this is how you get the validation.
```
```
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(yourDate);
try {
    cal.getTime();
}
catch (Exception e) {
  System.out.println("Invalid date");
}
```
```


q:
I 'm exploring for a browser solution / API that has the following features:

Must support the nowadays default web technologies

Must support client side XSLT

Must support executing arbitrary Javascript on the pages it loads

Must be able to catch events from the web page targeted to the browser or OS (I am specifically interested in window.print())

QtWebkit seemed like the way to go but it still doesn't support XSLT so I had to look for alternatives. SWT Browser is a wrapper around the native browser component of the underlying system and in linux that I 'm interested this would mean the firefox engine that supports the attributes I 'm interested in except that I haven't still found out how to catch window.print() and provide my own implementation instead of the default one that is opening up a print dialog.

Any suggestions?

[A]
If you know a way how to catch the event in javascript an prevent the native dialog from showing, you can use the method shown in this
snippet
to catch the event in your SWT code.
The other option might be better though: Use mozilla's classes to register your own print handler. Something similar is shown in this
snippet
for the download handler, but I haven't tested if it is possible for the print handler as well.
The catch for this second option is stated in the snippet's javadoc:
IMPORTANT: For this snippet to work properly all of the requirements for using JavaXPCOM in a stand-alone application must be satisfied (see
http://www.eclipse.org/swt/faq.php#howusejavaxpcom
).


q:
I came across a code snippet like this:

Timestamp expiryDate = Timestamp.valueOf(dateStr + " " + "23:59:59.000");

Here dateStr is a string entered by the user in a form, in the format yyyy-mm-dd. Now the behavior of Timestamp.valueOf is such that it converts non-existent dates into appropriate proper dates. Say 31st June 2008 into 01st July 2008.

How can I check in Java if the dateStr string is in fact a valid date ? I know I can manually do the check, but what I would like to know is whether any method is already available to do the same.

[A]
Try
SimpleDateFormat
.  You simply set a format such as the one in your example and then call parse on your dateStr.


q:
I've been working with code synthesis xsd to generate an xml tree to ensure constinency of the xml output to the original xsd.

After initial testing, everything looked ok but when I tried entering invalid values (correct type, but outside the defined range), the values were allowed.

Although the xml is well formed and conforms to the types set in the xsd, it is not a valid xml wrt the schema.

Has anybody else used this tool and/or come up across this problem?


q:
If I have hundreds/thousands of client computers WCP'ing to my server, should I respond with a '200 OK' type message stating that I received the data and stored it in the db successfully?

Is this already built-into WCF?

[A]
There's 2 ways you could do this - return a value from your wcf call indicating success or failure, or assume success and use a callback to tell the client if there's a problem.
My preference would be to use a
one-way
service call with a
duplex service
and use a callback contract for the service to notify the client of a failure. There's a good description of callback contracts
here
and
here
.
I think you get a nicer, more asynchronous architecture if you follow the second path, but for simple applications just returning success or failure may be easier.


q:
I'm wondering if anyone has good resources to read or code to experiment for "autcomplete"

I would like to know what's the theory behind autocompletion, where to start what are the commonn mistakes etc.

I found fascinating the way products like Enso, Launchy, Google chrome and even tcsh perform their auto complete, I started my self just for curiosity some sample code and I got to the conclusion this must be a field widely explored before.

I would appreciate if someone shares any good technical resource on how to implement this.

Thanks in advance.

[A]
http://humanized.com/weblog/2007/03/30/what_makes_a_good_autocomplete/
--
http://social.msdn.microsoft.com/Forums/en-US/vblanguage/thread/2ccb37b9-c7e1-4113-86ac-ad3d33b4b4b1/
-- in the .Net world
A
nasty
patent on autocompletion approach (still possibly worth   reading for the
theory
)
http://www.patentstorm.us/patents/5845300/description.html
http://ask.metafilter.com/91068/Fuzzy-text-completion-algorithm
for a high level discussion on strategies to take.


q:
Does anyone know of any good basic articles for creating Sharepoint Web Parts.

I have found a couple, but most of them jumped in a little quick.

Thanks.

[A]
You can try:
SharePoint developer portal
SharePoint forums @ MSDN
Codeplex
to look at others code


q:
I am writing a photo gallery/sharing website and want to (1) write EXIF data to the JPEGs stored on server, and (2) strip that EXIF data prior to writing to the output stream for display.

Is anyone aware of a dotNet library -- preferably open source -- that allows the editing (the key here is that I need to write/erase the EXIF data, not just read it) of EXIF data in image files?

[A]
Check this libraries:
EXIFextractor
Photo Properties
A library to simplify access to image metadata
ExifWorks
EXIF tag Editor


q:
I can't seem to grok the concept of "loose coupling." I suppose it doesn't help that the word "loose" usually has a negative connotation, so I always forget that loose coupling is a good thing.

Will somebody please show some "before" and "after" code (or pseudocode) that illustrates this concept?

[A]
Definition
Essentially, coupling is how much a given object or set of object relies on another object or another set of objects in order to accomplish its task.
High Coupling
Think of a car. In order for the engine to start, a key must be inserted into the ignition, turned, gasoline must be present, a spark must occur, pistons must fire, and the engine must come alive. You could say that a car engine is highly coupled to several other objects. This is high coupling, but it's not really a bad thing.
Loose Coupling
Think of a user control for a web page that is responsible for allowing users to post, edit, and view some type of information. The single control could be used to let a user post a new piece of information or edit a new piece of information. The control should be able to be shared between two different paths - new and edit. If the control is written in such a way that it needs some type of data from the pages that will contain it, then you could say it's too highly coupled. The control should not need anything from its container page.


q:
What is the best way to sync up two lists each of which may contain items not in the other?  As shown the lists are not sorted - although if necessary sorting them first would not be an issue.

List 1 = a,b,c,e
List 2 = b,e,c,d

Using the lists above, I'm looking for a solution that will write out to a spreadsheet in two columns:

a
b  b
c  c
   d
e  e

[A]
Here are some notes on using a disconnected recordset.
```
```
Const adVarChar = 200  'the SQL datatype is varchar

'Create arrays fron the lists
asL1 = Split("a,b,c,", ",")
asL2 = Split("b,e,c,d", ",")

'Create a disconnected recordset
Set rs = CreateObject("ADODB.RECORDSET")
rs.Fields.append "Srt", adVarChar, 25
rs.Fields.append "L1", adVarChar, 25
rs.Fields.append "L2", adVarChar, 25

rs.CursorType = adOpenStatic
rs.Open

'Add list 1 to the recordset
For i = 0 To UBound(asL1)
    rs.AddNew Array("Srt", "L1"), Array(asL1(i), asL1(i))
    rs.Update
Next

'Add list 2
For i = 0 To UBound(asL2)
    rs.MoveFirst
    rs.Find "L1='" & asL2(i) & "'"

    If rs.EOF Then
        rs.AddNew Array("Srt", "L2"), Array(asL2(i), asL2(i))
    Else
        rs.Fields("L2") = asL2(i)
    End If

    rs.Update
Next

rs.Sort = "Srt"

'Add the data to the active sheet
Set wks = Application.ActiveWorkbook.ActiveSheet

rs.MoveFirst

intRow = 1
Do
    For intField = 1 To rs.Fields.Count - 1
        wks.Cells(intRow, intField + 1) = rs.Fields(intField).Value
    Next intField

    rs.MoveNext
    intRow = intRow + 1
Loop Until rs.EOF = True
```
```


q:
I have an IList<T> that I need to sort, and I would rather not copy the list if possible.  I've noticed that ArrayList has an Adapter static method that wraps the passed list without copying it, but this takes an IList and I have an IList<T>.  Is it safe to cast from a System.Collections.Generic.IList<T> to a System.Collections.IList and just use the Adapter method?

Note that this is .Net 2.0, so LINQ is not an option.

[A]
From the blog of Paul Fox, I recommend the post "How to sort an IList":
http://foxsys.blogspot.com/2007/06/how-to-sort-generic-ilist.html
Just in case that blog goes away in the future, I'll copy the post here:
How to sort a generic IList
Update
You can read and updated post about
sorting generic IList and List
. Many people will prefer the methods mentioned in the updated post.
Sorting a generic IList
I was trying to sort a generic IList<> and found a fairly simple way of doing it.
Step 1
You need to implement IComparable for the type contained in your IList. For this example I am going to use a simple Language Dto class.
```
```
public class LanguageDto : IComparable {
 private String name;
 public string Name { get { return name; } set { name = value; } }

 public LanguageDto(string name) {
     this.name = name;
 }

 #region IComparable Members
 public int CompareTo(object obj) {
     if (obj is LanguageDto) {
     LanguageDto language = (LanguageDto)obj;
     return this.name.CompareTo(language.name);
     }
     throw new ArgumentException(string.Format("Cannot compare a LanguageDto to an {0}", obj.GetType().ToString()));
 }
 #endregion
}
```
```
STEP 2
Sort your IList. To do this you will use the ArrayList.Adapter() method passing in your IList, and then calling the Sort method. Like so...
```
```
ArrayList.Adapter((IList)languages).Sort();
```
```
Note: languages is of type "IList"
Languages should then be a sorted list of your type!


q:
I've used several apps now that launch the itunes store directly from the app. I'm even using some on my 2.1 iPod 2G.

I know there's a bug in 2.1 that prevents appstore links from working in safari, but somehow people are launching the appstore directly, not even through safari.

How do you do this? Is it an undocumented openURL feature?

[A]
From iTunes, drag the icon of your app to the desktop, this will give you a link you can use directly (for example,
http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=284036524&mt=8
launches the AppStore to Crosswords, both on a desktop and an iPhone).
Pop this into an NSURL and call openURL on it.


q:
In Java, given a timestamp, how to reset the time part alone to 00:00:00 so that the timestamp represents the midnight of that particular day ?

In T-SQL, this query will do to achieve the same, but I don't know how to do this in Java.

SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';

[A]
Assuming your "timestamp" is a java.util.Date, which is represented as the number of milliseconds since the beginning of the epoch (Jan 1, 1970), you can perform the following arithmetic:
```
```
public static Date stripTimePortion(Date timestamp) {
    long msInDay = 1000 * 60 * 60 * 24; // Number of milliseconds in a day
    long msPortion = timestamp.getTime() % msInDay;
    return new Date(timestamp.getTime() - msPortion);
}
```
```


q:
I have two tables Institutions and Results and I want to see if there are any results for institutions that way I can exclude the ones that don't have results.

Can I get better performance using a JOIN or using EXISTS?

Thank you,

-Nimesh

[A]
If you're referring to using a left (or right) outer join or a not exists subquery, I'm fairly certain the left outer join wins performance-wise. For example:
```
SELECT t1.* FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.id = t2.id WHERE t2.id IS NULL
```
The above should be quicker than the equivalent sub-query, and if you're referring specifically to exists - well, where structure allows, an inner join will always be the preferred option.


q: I am wondering what server control people generally use for surrounding and separating blocks of related controls and content in a Web Forms scenario.  Often times I need to surround a block of HTML and related Server controls with a 'panel' that I can show or hide based upon some UI logic in the code behind.  I am usually faced with either using a Panel, however this doesn't work if I need to surround multiple TR's in a table for example because the Panel renders as a div which is invalid inside a Table tag.  In this situation I usually just set each TR to runat server and show/hide each of them individually, but there must be a better way.  I have seen the PlaceHolder control used for this scenario, but wanted to know if anyone does this or has any other suggestions.

[A]
Even with the PlaceHolder control, Visual Studio will complain that you don't have valid HTML.
You might grit your teeth and do it via server side code blocks that access properties on the code behind:
```
```

     ....

  <% if( ShowSecretRow ) { %>

    shhh!

  <% } %>

```
```
Be careful though... it's a slippery slope and you don't want your ASPX to be too convoluted.


q: I'm wonder what the best way to convert a byte array (length 4) to an integer is in vb.net?  I'm aware of BitConverter, but it seems like quite a waste to do a function call to do something that should be able to be done by copying 4 bytes of memory. Along the same lines, what about converting a single/double from it's binary representation to an single/double variable.

[A]
"Copying bytes of memory" is something that .NET isn't particularly suited for (and VB.NET even less so). So, unless switching to C is an option for you, a function call is pretty much unavoidable for this.
BitConverter is a well-thought-out, tested function. Of course, you can avoid it by doing something like (in C#):
```
```
myInt = (*pbyte) | (*(pbyte + 1) << 8)  | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
```
```
(which is, incidentally,
exactly
what BitConverter does for you when converting a byte array to an Integer...).
However, this code:
Is much, much harder to read and understand than the BitConverter equivalent;
Doesn't do any of the error checking that BitConverter does for you;
Doesn't differentiate between little-endian and big-endian representations, like BitConverter does.
In other words: you might "save" a function call, but you will be significantly worse off in the end (even assuming you don't introduce any bugs). In general, the .NET Framework is very, very well designed, and you shouldn't think twice about using its functionality, unless you encounter actual (performance) issues with it.


q:
Is there a way to cast a user control as a specific user control so I have access to it's public properties? Basicly I'm foreaching through a placeholder's controls collection and I'm trying to access the user control's public properties.

foreach(UserControl uc in plhMediaBuys.Controls)
{
    uc.PulblicPropertyIWantAccessTo;
}

[A]
```
```
foreach(UserControl uc in plhMediaBuys.Controls)
{
  if (uc is MySpecificType)
  {
    return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
  }
}
```
```


q:
I am trying to dynamically load the contents of a div tag with a .cfm page that contains a cfchart in png format. When the user clicks on a link, I am using the load function to put the .cfm page into the div.

$("#bank").bind("click", function(){
    $("#chartx").load("bank.cfm");
});

I can get this to come up perfectly in Firefox, but not in IE6. It gives no error messages.

[A]
Have you tried jQuery.get? Maybe something like:
```
```
$("#bank").bind("click", function(){
    $.get("bank.cfm", function(data){
        $("#chartx").html(data);
    });
});
```
```
It's not as clean but it's more specific. Maybe it will take a different course from whatever is breaking.


q:
I have need to write an application which uses a speech recognition engine -- either the built in vista one, or a third party one -- that can display a word or phrase, and recognise when the user reads it (or an approximation of it).  I also need to be able to switch quickly between languages, without changing the language of the operating system.

The users will be using the system for very short periods.  The application needs to work without the requirement of first training the recognition engine to the users' voices.

It would also be fantastic if this could work on Windows XP or lesser versions of Windows Vista.

Optionally, the system needs to be able to read information on the screen back to the user, in the user's selected language.  I can work around this specification using pre-recorded voice-overs, but the preferred method would be to use a text-to-speech engine.

Can anyone recommend something for me?

[A]
If the engine is what you're asking about then I've found (beware, I'm just listing, I haven't tried any of them):
Lumenvox engine
you also have the
SAPI SDK
from Microsoft itself, I've only tried it for text to speech but according to its definition:
The SDK also includes freely distributable text-to-speech (TTS) engines (in U.S. English and Simplified Chinese)
and speech recognition (SR) engines
(in U.S. English, Simplified Chinese, and Japanese).


q:
I am new to sharepoint development but have about 10 years of expirence in C++, VB6 and C#. It is my experience that a great way to learn a new language or coding style is to spend some time "dissecting" one of the open source projects available at CodePlex or Google code.
In order to avoid picking up some bad habits without knowing it, I would like to hear which projects you can recommend.

TIA

[A]
Generally speaking, SharePoint "code" will come in the form of web parts and pages that are written for specific SharePoint installations. However, that doesn't mean that there aren't any SharePoint utilities and libraries out there.
In fact, I'm a big fan of
SmartPart
, which is hosted on Codeplex. This is a very useful SharePoint tool with a lot of downloads and some bugs that need to be fixed, so it's a great project to serve as your reference point
and
submit some code to!


q:
I am working on interactive SVG/AJAX interfaces where elements are created and repositioned on-the-fly by users. I'd like to support the ability for users to export their current view to a PNG image and/or an SVG document. I'd really like the SVG document to be as simple as possible (without a lot of nested transforms). Is there any framework that already supports this?

I'm currently asking my users to use the Ctrl+Alt+PrntScrn technique, and I don't want to ask them to install any software/plugins.

The server-side code is implemented in PHP right now, if that helps. I've already implemented the ability to generate a PNG image from the "original" document (before the client makes any modifications) using ImageMagick.

[A]
I'm assuming you need this to work only in browsers that support SVG.
Firefox, Safari, and Opera provide the non-standard
```
XMLSerializer
```
API, so you could do something like this:
```
```
var svg = document.getElementById('svg_root'); // or whatever you call it
var serializer = new XMLSerializer();
var str = serializer.serializeToString(svg);
```
```
From there, you can send it to the server and receive a PNG in return.
Here's
Mozilla's developer page on serializing XML from the DOM
.


q:
I am attempting to send an email using VB.NET.

There are two requirements:

The email be saved in their "Sent Items" folder in Outlook (their only email client).

A PDF (generated on the fly) is attached to the email.

I am currently creating a new MailMessage & sending via a SmtpClient, but I believe that this sends from the server, and not from the client.

Is this possible?

EDIT: This is a winforms application, the purpose is to send reports to clients.

[A]
You'll have to use the exchange server API or have a local copy of Outlook and use the outlook client API in order to make this happen. SMTP Client and exchange really have very little to do with each other, other than the fact that the Exchange server knows what to do with an SMTP message.
You might be better off just sending two copies of the e-mail, one to the sender and one to the sendee. It's not as seemless in having it show up in the sent items, but it would be much less work and accomplish the same goal.


q: What's the best performing way to convert a DataRowCollection instance to a DataRow[]?

[A]
This is kind of obvious, but:
```
DataRowCollection.CopyTo(DataRow[] array, Int32 offset)
```
?
It seems like no matter what, you're going to have to iterate the collection (CopyTo iterates the internal DataRowTree elements).
I suppose you could use reflection to access the non-public tree, but at a significant cost.


q: How do you extract an HD and Bios Unique ID, using python script?

[A]
Solutions that come to my mind:
use
Win32 Python Extensions
and call Windows APIs to do that directly
Use a WMI-wrapper for Python
(some
WMI interface code
for reference)
Edit
: I assumed your OS was MS Windows :)


q:
I need to convert a Word document into HTML file(s) in Java. The function will take input an word document and the output will be html file(s) based on the number of pages the word document has i.e. if the word document has 3 pages then there will be 3 html files generated having the required page break.

I searched for open source/non-commercial APIs which can convert doc to html but for no result. Anybody who have done this type of job before please help.

Thanks

[A]
You'd have to find the MS word doc specification ( since it is basically a binary dump of whatever is in word at that point in time ), and slowly go through it element by element converting ms word "objects/states" to the html equiv. you might be able to find a script to do it for u since this really isn't fun work and i'd advise against it ( converting file formats or even reading from commercial files on your own is always hard and often incomplete ).
PS: just
google doc2html


q:
I have a CVS repository on my local workstation. I've demonstrated to my employer that version control is a great idea. Alright! So now I want to migrate my CVS history from my local workstation onto a real server.

I have installed CVS on the server and it is working.

Now, can I just move my repository files? Or do I have to do some sort of import command?

I know I could just check the current codebase into the new CVS server, but that'd lose the history, right?

[A]
I just migrated one last week.
We're using Subversion at work, and all I did was move the root Subversion directory from one machine to the other. Then when I installed the
VisualSVN server
on the new machine, I just chose the existing Subversion root that I ported rather than creating a new repository. It seamlessly maintained history and files.
I'm not sure how well this will work with other source control systems.


q:
I know how to find a method in java using a fixed string,

someClass.getMethod("foobar", argTypes);

but is there a way to use a regular expression rather than a fixed string to find a method on a given class?

An example of the usage might be if I wanted to find a method that was called either "foobar" or "fooBar". Using a regular expression like "foo[Bb]ar" would match either of these method names.

[A]
You should apply your regexp on
getDeclaredMethods
() reflection method (or GetMethods() if you want only the public ones).
[Warning: both methods will throw a SecurityException if there is a security manager.]
You apply it on each name of each method returned by getDeclaredMethod() and only memorize in a Collection the compliant Methods.
Something like!
```
```
try
{
  final Pattern aMethodNamePattern = Pattern.compile("foo[Bb]ar");
  final List<Method> someMethods = aClass.getDeclaredMethods();
  final List<Method> someCompliantMethods = new ArrayList<Method>();
  for(final Method aMethod: someMethods)
  {
    final String aMethodName = aMethod.getName();
    final Matcher aMethodNameMatcher = aMethodNamePattern.getMatcher(aMethodName);
    if(aMethodNameMatcher.matches() == true)
    {
       someCompliantMethods.add(aMethod);
    }
}
catch(...) // catch all exceptions like SecurityException, IllegalAccessException, ...
```
```


q:
YUI Compressor does not accept wildcard parameters, so I cannot run it like this:

C:>java -jar yuicompressor.jar *.js

But I have over 500 files and would rather not have to create a batch file like this:

C:>java -jar yuicompressor.jar file1.js -o deploy\file1.js
C:>java -jar yuicompressor.jar file2.js -o deploy\file2.js
...
C:>java -jar yuicompressor.jar file500.js -o deploy\file500.js

And of course my file names are not in such uniform way.

Is there way to automate this without writing any code? :)

[A]
I might go for a makefile (I think it would probably be more maintainable long term), but if you want a quick-n-dirty Windows batch command something like the following should work:
```
```
for %%a in (*.js) do @java -jar yuicompressor.jar "%%a" -o "deploy\%%a"
```
```


q:
How can I find or generate thousands of company names for testing and demo purposes?  (Address, phone number, and related information would be nice too.)

I've got a system I'm building which includes business contact information.  Pretty common no doubt.

My test/demo database currently has randomly generated individual's names loaded (thanks to a handy IRS spreadsheet I found). This has worked great for internal testing and review purposes, but it looks really odd when shown to prospective customers.

I've tried various online public information sources (e.g. EDGAR, and county based property records searches), but these all require me to manually stitch together the results in blocks of 50 names or so at a time.  I could do this, but was really hoping for a search service or data store out there that had this type of information readily searchable and retrievable in very large batches.

[A]
I use
Fake Name generator
:
What can I use the Fake Name Generator identities for?
Thousands of individuals, companies, and government organizations have found useful and creative things to do with the Fake Name Generator. Here are a few examples:
Quality test data can be hard to come by, especially with laws (such as HIPAA) preventing use of real data. Read more on
the dangers of testing with real data
.
Many websites, such message boards, are poorly designed, making it difficult for visitors from foreign countries to sign up for accounts. Using fake information, you can easily fill out the sign up forms and log in to the site.
Use fake information when filling out forms to avoid giving out personal information.
Generate a false identity to use as your pseudonym on the internet. This allows you to keep your real life and your internet life separate.
Get ideas for names to use for characters in a book or story.
Generated credit cards can be used to test basic client-/server-side validation techniques without accidentally processing a real card.
Generated national identity numbers can be used to test basic client-/server-side validation techniques without risking disclosure of real information...


q:
I am building up a view with various text and image elements.

I want to display some text in the view with a blurry copy of the text behind it, but not just a text shadow.

How do I apply Gaussian blurred text onto a UIImage or layer?

[A]
On the desktop, no question, you'd use CoreImage to do this.
On the phone though, I don't think there exists a way to do this using CoreGraphics. If it is absolutely critical OpenGLES may be able to help.
However, I would suggest rethinking your interface. I would think the blurred text would be distracting.
Edit: mledford points out in the comments that you could use CoreAnimation. I don't know if CA on the phone includes blur radius like on the desktop, but you could try it.


q:
I have written a standalone app that controls a device through RS-232 port and some customers want to be able to use the device with LabVIEW.  I have seen some threads describing where to start when learning to use LabVIEW, but I was wondering if anyone has experience with writing a plugin/driver (is that the right word?) for LabVIEW and perhaps point me in the right direction.

The existing app is  GUI that allows people to control the device with higher level concepts - rather than have to know the syntax and protocol of the serial port comms stuff.  I want to abstract that away as well so that users can just plug something into LabVIEW and I suppose it exposes some verbs and methods that allow the device to be manipulated and also provide data to clients.

I think there is a serial port interface from LabVIEW, but I am sure the people using this device do not want to have to write the code (parsers and etc) to communicate with the device.

[A]
There are two options for what you're trying to do.
Create a DLL that users of your device can
call from LabVIEW
.
Rewrite your application in LabVIEW.
To reach the largest possible number of potential customers, option #1 would be the best solution for you.  If your customers are specifically asking for a LabVIEW driver then option #2 would probably be the least hassle for that specific customer.  The reason for this is that LabVIEW is very much a niche language (for automation and data acquisition), and for many LabVIEW developers it's the only language they know (or the only one they know well).


q:
I want to expose the functionality of an SAP program (transaction) as a BAPI.
I need to call a report and supply range filters such that the GUI is bypassed.

Does anyone have a working example of the SUBMIT ... WITH ... ABAP construct, or other suggestions on how to accomplish what I need to do?

[A]
Here is a working example:
```
```
SUBMIT SAPF140
    TO SAP-SPOOL                         "optional"
    SPOOL PARAMETERS print_parameters    "optional"
    WITHOUT SPOOL DYNPRO                 "optional (hides the spool pop-up)"
    VIA JOB jobname NUMBER l_number      "optional"
    AND RETURN                           "optional - returns to the calling prog"
    WITH EVENT   =  REVENT
    WITH BUKRS   IN RBUKRS
    WITH BELNR   IN lRBELNR
    WITH GJAHR   IN RGJAHR
    WITH USNAM   =  SY-UNAME
    WITH DATUM   =  SAVE_DATUM
    WITH UZEIT   =  SAVE_UZEIT
    WITH DELDAYS =  RDELDAYS
    WITH KAUTO   =  'X'
    WITH RPDEST  =  SAVE_PDEST
    WITH TITLE   =  TITLE.
```
```
All the "WITH" statements relates to selection fields on the called program where I use = it is a PARAMETER statement (single field), where I use IN it is a SELECT_OPTIONS statement (range)
Here is a simple example of how to fill a range:
```
```
REFRESH lrbelnr.
lrbelnr-sign = 'I'.
lrbelnr-option = 'EQ'.
lrbelnr-low = HBKORM-belnr.
CLEAR lrbelnr-high.
append lrbelnr.
```
```


q:
I need to round a value up to the nearest multiple of 2.5.

For example:

6 --> 7.5

7.6 --> 10

etc.

This seems like the best way to do this?

   Function RoundToIncrement(ByVal originalNumber As Decimal, ByVal increment As Decimal) As Decimal

        Dim num = Math.Round(originalNumber / increment, MidpointRounding.AwayFromZero) * increment
        If originalNumber Mod increment <> 0 And num < originalNumber Then
            num += increment
        End If
        Return num

    End Function

[A]
Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5.
You're close.
```
```
Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal
    Return Math.Ceiling( orignialNumber / increment ) * increment
End Function
```
```
Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.


q:
Consider the following code:

abstract class SomeClassX<T>
{
  // blah
}

class SomeClassY: SomeClassX<int>
{
  // blah
}

class SomeClassZ: SomeClassX<long>
{
  // blah
}

I want a collection of SomeClassX<T>'s, however, this isn't possible since SomeClassX<int> != SomeClassX<long> and List<SomeClassX<>> isn't allowed.

So my solution is to have SomeClassX<T> implement an interface and define my collection as, where ISomeClassX is the interface:

class CollectionOfSomeClassX: List<ISomeClassX>
{
  // blah
}

Is this the best way to do this, or is there better way?


q: How do I programmatically return the maximum of two integers without using any comparison operators and without using if, else, etc?

[A]
return (a > b ? a : b);
or
```
```
int max(int a, int b)
{
        int x = (a - b) >> 31;
        int y = ~x;
        return (y & a) | (x & b);
}
```
```


q:
I've run across the following line in a VB6 application.

mobjParentWrkBk.ExcelWorkBook.Application.Selection.Insert Shift:=xlToRight

Unfortunately Google and other search engines have not been very useful as they seem to omit the := part.

What would be a C# equivalent?

[A]
This is Visual Basic syntax for optional named parameters. The
```
Insert
```
function has a parameter named
```
Shift
```
, which is being specified.
C#, as far as I know, doesn't have an equivalent for optional named parameters. Instead, you'd need to call the
```
Insert
```
method, specifying
```
Type.Missing
```
for all parameters other than
```
Shift
```
.
See also the following StackOverflow question:
VB.NET := Operator
UPDATE (2008-10-29):
C# 4.0 is set to introduce optional and named parameters. See this
blog entry on codebetter.com
.


q:
I am planning a PHP application that needs to store date/times in an MSSQL database. (For the curious, it is a calendar application.) What is the preferred format to store this information?

MSSQL has its own datetime data type, which works well in the database itself and is very readable. However, there aren't any MSSQL functions to translate datetime values to PHP's preferred format--UNIX timestamp. This makes it a bit more painful to use with PHP. UNIX timestamp is attractive because that's what PHP likes, but it's certainly not as readable and there aren't a bunch of nice built-in MSSQL functions for working with the data.

Would you store this information as datetime data type, as UNIX timestamps (as int, bigint, or varchar datatype), as both formats side by side, or as something else entirely?

[A]
I'd recommend the same as i do for all dates in any db engine, the db native type. (DATETIME)
Just use "YYYY-MM-DD HH:MM:SS" for inserting in php:
```
date('Y-m-d H:i:s', $myTimeStampInSeconds);
```
-edit in response to comments below here -
for selected columns you can use
```
$timestamp =
strtotime
( $yourColumnValue );
```
i recommend storing in the databas native format because you can then use SQL to compare records using SQL date/time functions like DATEADD() etc.


q:
Here is my function (updated):

Public Shared Function shortenUrl(ByVal URL As String) As String
    Return shortenUrl(URL, 32)
End Function
Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String
    If URL.Length > maxLength Then
        String.Format("{0}...{1}", URL.Substring(0, (maxLength / 2)), URL.Substring(URL.Length - ((maxLength / 2) - 3)))
    Else
        Return URL
    End If
End Function

I fixed the problem where it didn't return maxLength chars because it didn't take into account the ellipses.

It seems to me that it is too complicated; any suggestions, comments, concerns are more than welcome.

[A]
Why not do this?
```
```
Public Shared Function shortenUrl(ByVal URL As String) As String
    Return shortenUrl(URL, 29)
End Function
Public Shared Function shortenUrl(ByVal URL As String, ByVal maxLength As Integer) As String
    If URL.Length > maxLength Then
        Return String.Format("{0}...{1}", URL.Substring(0, maxLength / 2),URL.Substring(URL.Length - (maxLength / 2)))
    Else
        Return URL
    End If
End Function
```
```
That at least gets rid of all of the tempoary declarations


q:
I'm attempting to determine the row length in bytes of a table by executing the following stored procedure:

CREATE TABLE #tmp
(
  [ID] int,
  Column_name varchar(640),
  Type varchar(640),
  Computed varchar(640),
  Length int,
  Prec int,
  Scale int,
  Nullable varchar(640),
  TrimTrailingBlanks varchar(640),
  FixedLenNullInSource varchar(640),
  Collation varchar(256)
)
INSERT INTO #tmp exec sp_help MyTable
SELECT SUM(Length) FROM #tmp
DROP TABLE #tmp

The problem is that I don't know the table definition (data types, etc..) of the table returned by 'sp_help.'

I get the following error:

Insert Error: Column name or number of supplied values does not match table definition.

Looking at the sp_help stored procedure does not give me any clues.

What is the proper CREATE TABLE statement to insert the results of a sp_help?

[A]
I can't help you with creating a temp table to store sp_help information, but I can help you with calculating row lengths. Check out this
MSDN article
; it helps you calculate such based on the field lengths, type, etc. Probably wouldn't take too much to convert it into a SQL script you could reuse by querying against sysobjects, etc.
EDIT:
I'm redacting my offer to do a script for it. My way was nowhere near as easy as Vendoran's. :)
As an aside, I take back what I said earlier about not being able to help with the temp table. I can: You can't do it. sp_help outputs seven rowsets, so I don't think you'll be able to do something as initially described in the original question. I think you're stuck using a different method to come up with it.


q:
I have a Rails application that in the erb code, I use a select box. What I would like to do is reload the page passing the sort parameter. My controller already handles it, but I don't know how to reload the page with the selected value from my select box. Here is my code:

<% @options = {:latest => 'lastest' , :alphabetical => 'alphabetical', :pricelow => 'price-low', :pricehigh =>'pricehigh'} %>
<%= select_tag 'sort[]', options_for_select(@options), :include_blank => true,:onchange => "location.reload('location?sort='+this.value)"%>

[A]
Have you considered using an ajax call on your list box? If you have a method on your controller that returns just the sorted list, based on sort parameter, then you could do:
```
```
<% @options = {:latest => 'lastest' , :alphabetical => 'alphabetical', :pricelow => 'price-low', :pricehigh =>'pricehigh'} %>
<%= select_tag 'sort[]', options_for_select(@options), :include_blank => true,:onchange => remote_function(:url => {:controller => 'your_controller', :action => 'list_sort_method'}, :with => "'sort='+this.value", :update => "div_containing_list") %>
```
```


q:
When I use this code to output some XML I parsed (and modified) with XmlParser

XmlParser parser = new XmlParser()
def root = parser.parseText(feedUrl.toURL().text)
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(root)
println writer.toString()

the namespace declarations on the root node are not printed, even though they are there in the toString() of root...  any ideas?

[A]
It looks like it's denormalizing the output and including the namespace context along with the nodes that actually need the namespace context.
For example, the webpage for this question comes in with creativeCommons namespace embedded:
```
```
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0">
  <!-- snip -->
  <creativeCommons:license>http://www.creativecommons.org/licenses/by-nc/2.5/rdf</creativeCommons:license>
  <!-- snip -->
</feed>
```
```
When you output the xml using this script:
```
```
def root = new XmlParser().parseText("http://stackoverflow.com/feeds/question/227447".toURL().text)
println new XmlNodePrinter().print(root)
```
```
It ends up moving the namespace to the license node that needs that namespace.  Not a huge deal in this case as there is only a single node in that namespace.  If most of the XML were namespaced, it'd probably bloat things quite a bit more.
```
```
<feed xmlns="http://www.w3.org/2005/Atom">
  <!-- snip -->
    <creativeCommons:license xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule">
http://www.creativecommons.org/licenses/by-nc/2.5/rdf
  </creativeCommons:license>
  <!-- snip -->
</feed>
```
```
If you actually wanted the nodes normalized, you'd have to make some tweaks to the XmlNodePrinter to do 2 passes through the XML, first to gather all of the used namespaces and 2nd to output them at the top rather than within each namespaced node.  The groovy source code is actually pretty readable and wouldn't be that hard to modify if you actually needed this.


q: How do I get the ASCII value of a character as an int in Python?

[A]
You are looking for:
```
```
ord()
```
```


q:
I want to do some basic filtering on a file. Read it, do processing, write it back.

I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with:

from __future__ import with_statement

filename = "..." # or sys.argv...

with open(filename) as f:
    new_txt = # ...some translation of f.read()

open(filename, 'w').write(new_txt)

The with statement makes things shorter since I don't have to explicitly open and close the file.

Any other ideas ?

[A]
This seems to work:
```
```
with open(filename, "r+") as f:
    new_txt = process(f.read())
    f.truncate(0)
    f.write(new_txt)
```
```


q:
I have a search form on each of my pages. If I use form helper, it defaults to $_POST. I'd like the search term to show up in the URI:

http://example.com/search/KEYWORD

I've been on Google for about an hour, but to no avail. I've only found articles on how $_GET is basically disabled, because of the native URI convention. I can't be the first person to want this kind of functionality, am I? Thanks in advance!

[A]
I don't know much about CodeIgniter, but it's PHP, so shouldn't
```
$_GET
```
still be available to you? You could format your URL the same way Google does:
```
mysite.com/search?q=KEYWORD
```
and pull the data out with
```
$_GET['q']
```
.
Besides, a search form seems like a bad place to use POST; GET is bookmarkable and doesn't imply that something is changing server-side.


q:
I need a well tested Regular Expression (.net style preferred), or some other simple bit of code that will parse a USA/CA phone number into component parts, so:

3035551234122

1-303-555-1234x122

(303)555-1234-122

1 (303) 555 -1234-122

etc...

all parse into:

AreaCode: 303

Exchange: 555

Suffix: 1234

Extension: 122


q: Would NTFS allocation blocks of 16KB or 32KB make compile time faster in comparison to the default 4KB?

[A]
I can't imagine that would make much of a difference - disk block size is pretty far removed from compile speed. With the amount of caching a modern OS does, it seems unlikely to be significant.
The real answer, of course, can be found by measuring it. Getting similar conditions between different machines with different disk block sizes might be tricky, though.


q:
Does anyone know how to programmaticly find out where the java classloader actually loads the class from?

I often work on large projects where the classpath gets very long and manual searching is not really an option.  I recently had a problem where the classloader was loading an incorrect version of a class because it was on the classpath in two different places.

So how can I get the classloader to tell me where on disk the actual class file is coming from?

Edit: What about if the classloader actually fails to load the class due to a version mismatch (or something else),  is there anyway we could find out what file its trying to read before it reads it?

[A]
Assuming that you're working with a class named
```
MyClass
```
, the following should work:
```
```
MyClass.class.getClassLoader();
```
```
Whether or not you can get the on-disk location of the .class file is dependent on the classloader itself.  For example, if you're using something like BCEL, a certain class may not even have an on-disk representation.


q:
I'm working on a JSP where I need to call methods on object that come from a Bean. The previous version of the page does not use JSTL and it works properly. My new version has a set up like this:

<jsp:useBean id="pageBean" scope="request" type="com.epicentric.page.website.PageBean" />
<c:set var="pageDividers" value="<%= pageBean.getPageDividers() %>" />
<c:set var="numColumns" value="${pageDividers.size()}" />

The variable pageDividers is a List object.

I'm encountering this issue: when I ask for pageDivider's size, an exception is thrown. I know this is a simple JTSL error -- what am I doing wrong?

The error message is:

The function size must be used with a prefix when a default namespace is not specified

How do I correctly access or call the methods of my pageDividers object?

[A]
To access the property of a bean using EL you simply name the property (not invoke the method). So lets say you have a method called getSize() in the bean then
```
```
${pageDividers.size}
```
```
Notice no ().
EDIT:Sorry...made an error in the original post.


q: How can I read an Open Office 3.0 spreadsheet (.ods) from Groovy?  I'd like to select specific columns from a named worksheet.  Ideally, it would be useful to add a 'where' clause, or other criteria clause.

[A]
Might be something here at
Spring Factories
or here at
Groovy and JMX
. There is a forum for
Groovy and Open Office
.


q: Are you aware of any open source libraries/projects that offer audio watermarking capability?

[A]
check wikipedia:
http://en.wikipedia.org/wiki/Steganography#Implementations
section 3 of this site site is on audio:
http://www.binary-universe.net/
same author did a project on codeplex.
these also do audio:
StegHide
mpeStego


q: I know that it is possible to check how much physical RAM is installed using GetPhysicallyInstalledSystemMemory or how much ram the operating system can see using GlobalMemoryStatusEx.  However, I am wondering if there is any way to check how much ram a user has installed by slot.  That is, to be able to programmatically tell the difference between 1x2GB of ram and 2x1GB of ram, thus checking if the computer can be upgraded easily via software.  Ideally, a way to check this without .Net.

[A]
Reviewing the MSDN docs for the functions listed
here
, I see that the function checks with the SMBIOS table, which is referenced by a standard
here
It appears that you indeed can find the information you seek through the BIOS. You may have to install a driver to get that information out to your program.
Good luck!


q: Does anyone have a good articles or tutorial on correctly using dispose and IDisposable.  I am trying to explain this to some junior dev and wanted to get some extra material, examples, etc.

[A]
A good place to start is this MSDN article by Shawn Farkas
http://msdn.microsoft.com/en-us/magazine/cc163392.aspx
. The definitive article is by Joe Duffy at
http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx
with some follow-up in
http://www.bluebytesoftware.com/blog/2008/02/18/IDisposableFinalizationAndConcurrency.aspx


q:
Is there a simple way to parse a date that may be in MM/DD/yyyy, or M/D/yyyy, or some combination? i.e. the zero is optional before a single digit day or month.

To do it manually, one could use:

String[] dateFields = dateString.split("/");
int month = Integer.parseInt(dateFields[0]);
int day = Integer.parseInt(dateFields[1]);
int year = Integer.parseInt(dateFields[2]);

And validate with:

dateString.matches("\\d\\d?/\\d\\d?/\\d\\d\\d\\d")

Is there a call to SimpleDateFormat or JodaTime that would handle this?

[A]
Yep, use setLenient:
```
```
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setLenient(true);
System.out.println(df.parse("05/05/1999"));
System.out.println(df.parse("5/5/1999"));
```
```


q: How do I copy a directory including sub directories excluding files or directories that match a certain regex on a Windows system?

[A]
I don't know how to do an exclusion with a copy, but you could work something up along the lines of:
```
```
ls -R1 | grep -v <regex to exclude> | awk '{printf("cp %s /destination/path",$1)}' | /bin/sh
```
```