Question:
I'm looking for a way to embed an image in a library (Windows-only). I don't want to go the 'traditional' way of putting it in the resources (because of special circumstances that make it not so convenient to mess around with the resource handle.

Ideally, there would be something like xpm files: a 'text' representation of an image that is put in a c array and that some code converts into a bitmap in memory, which can then somehow be loaded into an HIMAGE or an HICON. The images I want to embed are 32-bit bitmaps (bmp). Any ideas? I'm using MFC so an MFC library would be fine, but of course I can use a library that doesn't use MFC too. Thanks.

Answer:
Google for a bin2c utility (something like
http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c
).  It takes a file's binary representation and spits out a C source file that includes an array of bytes initialized to that data.
Just link the file in and you have your image sitting in a chunk of memory.
Using this kind of tool is really common on embedded systems where such things as 'resources' and even files might not exist.


Question:
In regular Java, you can get the text of a stack trace by passing a PrintWriter to printStackTrace. I have a feeling I know the answer to this (i.e. "No") but,

Is there any way to obtain the text of a stack trace in JavaME as a String?

Update:

I should mention that I'm restricted to CLDC 1.0

Answer:
You can have the PrintWriter write to a ByteArrayOutputStream and reconstruct the String from the bytes.
```
```
try{
    throw new Exception("Message");
} catch (Exception ex){
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ex.printStackTrace(new PrintStream(out));
    System.out.println(new String(out.toByteArray()));
}
```
```
It's not pretty, but it should work pretty much everywhere. Before you try the above, make sure you don't have access to [Throwable#getStackTrace](
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace())
, Eclipse claims it's available in CDC/Foundation 1.1, but that doesn't say anything about other profiles.


Question:
Today I changed the application pool identity of our ASP.NET application from "Network Service" to a domain user.

I added the user to the local group "IIS_WPG", done a iisreset just in case, and
everything works fine with IE6 and Firefox 3.0

But when I go to the website with IE7, an authentication popup appears, I type my credentials, and then :

HTTP Error 401.1 - Unauthorized: Access is denied due to invalid credentials. Internet Information Services (IIS)

Any ideas ?

Answer:
Typically, if you see an issue with authentication where it works in IE 6 but not IE 7, I'd check to make sure Kerberos is configured correctly.
Running as Network Service, your Kerberos SPNs should attached to the machine account.  As a domain account, the SPN's need to be on that account.
As to why IE 6 is different than IE 7, its most likely due to some of the Kerberos HotFixes that apply to CNames and ticket time outs. Search MS Support for "kerberos HotFix"
To turn off Kerberos for the site:
cscript adsutil.vbs set w3svc/###/NTAuthenticationProviders "NTLM"
Where ### is the SiteID from the MetaBase.


Question:
Is there any way to display scrollabletext in loose xaml?  The equivalent in HTML would be

<div style="overflow:scroll">some long bit of text here</div>

Can you do this in loose xaml?

From my experiments so far it seems that in loose xaml:

You cannot use TextBox -- it must be TextBlock.

TextBlock doesn't seem to have any styling settings which would make it scrollable.

ScrollViewer doesn't seem to be allowed in loose xaml.

Any help gratefully appreciated.

Answer:
Typically, if you see an issue with authentication where it works in IE 6 but not IE 7, I'd check to make sure Kerberos is configured correctly.
Running as Network Service, your Kerberos SPNs should attached to the machine account.  As a domain account, the SPN's need to be on that account.
As to why IE 6 is different than IE 7, its most likely due to some of the Kerberos HotFixes that apply to CNames and ticket time outs. Search MS Support for "kerberos HotFix"
To turn off Kerberos for the site:
cscript adsutil.vbs set w3svc/###/NTAuthenticationProviders "NTLM"
Where ### is the SiteID from the MetaBase.


Question:
I have a Makefile that starts by running a tool before applying the build rules (which this tool writes for me). If this tool, which is a python script, exits with a non-null status code, I want GNU Make to stop right there and not go on with building the program.

Currently, I do something like this (top level, i.e. column 1):

$(info Generating build rules...)
$(shell python collect_sources.py)
include BuildRules.mk

But this does not stop make if collect_sources.py exits with a status code of 1. This also captures the standard output of collect_sources.py but does not print it out, so I have the feeling I'm looking in the wrong direction.

If at all possible, the solution should even work when a simple MS-DOS shell is the standard system shell.

Any suggestion?

Answer:
There might be a better way, but I tried the following and it works:
```
```
$(if $(shell if your_command; then echo ok; fi), , $(error your_command failed))
```
```
Here I did assume that
```
your_command
```
does not give any output, but it shouldn't be hard to work around such a situation.
Edit: To make it work with the default Windows shell (and probably any decent shell) you could write
```
your_command && echo ok
```
instead of the
```
if
```
within the
```
shell
```
function. I do not think this is possible for (older) DOS shells. For these you probably want to adapt
```
your_command
```
or write a wrapper script to print something on error (or success).


Question:
I'm creating a C# dll, which is going to be used by others developers in WinForms. For some reasons, I want to detect, if methods from this library, are called from Main (GUI) Thread and warn developer he has done such a thing (ie. in log file). Is there any reasonable way to detect calling method from main thread?
Remember I have no access to WinForm application.

Answer:
An easy solution in this case is to declare a static control in the library assembly that is created on the Main UI thread. If you want to detect if the library is called from the main thread, then use the following
```
```
if (MyLibraryControl.InvokeRequired)
  //do your thing here
```
```


Question: Where can I find algorithms for image distortions? There are so much info of Blur and other classic algorithms but so little of more complex ones. In particular, I am interested in swirl effect image distortion algorithm.

Answer:
I can't find any references, but I can give a basic idea of how distortion effects work.
The key to the distortion is a function which takes two coordinates (x,y) in the distorted image, and transforms them to coordinates (u,v) in the original image. This specifies the inverse function of the distortion, since it takes the distorted image back to the original image
To generate the distorted image, one loops over x and y, calculates the point (u,v) from (x,y) using the inverse distortion function, and sets the colour components at (x,y) to be the same as those at (u,v) in the original image. One ususally uses interpolation (e.g.
http://en.wikipedia.org/wiki/Bilinear_interpolation
) to determine the colour at (u,v), since (u,v) usually does not lie exactly on the centre of a pixel, but rather at some fractional point between pixels.
A swirl is essentially a rotation, where the angle of rotation is dependent on the distance from the centre of the image. An example would be:
```
```
a = amount of rotation
b = size of effect

angle = a*exp(-(x*x+y*y)/(b*b))
u = cos(angle)*x + sin(angle)*y
v = -sin(angle)*x + cos(angle)*y
```
```
Here, I assume for simplicity that the centre of the swirl is at (0,0). The swirl can be put anywhere by subtracting the swirl position coordinates from x and y before the distortion function, and adding them to u and v after it.
There are various swirl effects around: some (like the above) swirl only a localised area, and have the amount of swirl decreasing towards the edge of the image. Others increase the swirling towards the edge of the image. This sort of thing can be done by playing about with the angle= line, e.g.
```
```
angle = a*(x*x+y*y)
```
```


Question:
I think questions like this are the reason why I don't like working with PHP. The manual is good, if you can find what you are looking for. After reading through the Array Functions, I didn't see one that provides the functionality I need.

I have an array (in my case, numerically indexed) that I want to scan for a particular value and, if it's there, remove it. And then, when all instances of that value have been removed, I want to rearrange the array using array_values.

Answer:
```
array_diff
```
is what you want.
```
```
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
```
```
Result:
```
"blue"
```
.


Question:
I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely different parts of the DOM and mostly positioned using float.

All I need is some code to get the absolute position difference between 2 floating DOM elements, preferrably using jQuery. The only thing I found were some hacks parsing upwards the DOM but always very browser-specific (e.g. "this does not work well with Firefox or IE or whatever").

Best would be something like this:

var distance = getDistance(element1, element2);

or in jQuery notation:

var distance = $(element1).distanceTo($(element2));

Answer:
I never used jQuery, just looked up API, so I can assume you can do the following:
```
var o1 = $(element1).offset();
var o2 = $(element2).offset();
var dx = o1.left - o2.left;
var dy = o1.top - o2.top;
var distance = Math.sqrt(dx * dx + dy * dy);
```


Question: When printing RFC documents on my A4 format printer I noticed that I print more than it is considered to be one page in RFC document. I figure this is because probably RFC is written in North American paper letter format (216 × 279 mm) and I want to use ISO A4 format (210 × 297 mm). Info on Paper size. So my question is if there is some way or program with which I would at least be able to print every letter format page on to the separate A4 format page. I know there will be some unused space at the bottom but at least there will just be one text page per A4 paper page. I tried changing paper size on printer from A4 to letter, but it didn't help.

Answer:
The RFC documents contain page breaks and such in the form of line printer control codes. Just printing a plain text rfc out of vi / notepad / word / whatever will
probably
not work as expected. Try searching for the rfc in PDF form, they'll be easier to print and the page numbering should be correct. You may be able to find pdfs in A4, else the printer dialogues "shrink to fit" feature should handle it.
Oh and shop around, some PDFs are much nicer than others...
You could find PDF format here
http://tools.ietf.org/pdf/
, for RFC 1928, it's
http://tools.ietf.org/pdf/rfc1928.pdf
.


Question:
Can Thread.getContextClassLoader() be null ? The javadoc is not really clear.

Should a library take this case into account ?

Update: the reason I asked is that beansbinding.dev.java.net does not work in this case (and my code does setContextClassLoader(null)

Answer:
Yes you should, someone could have called
```
Thread.setContextClassLoader(null)
```
and your library IMO should be able to deal with that.


Question: Is there any plans for Microsoft to support LINQ to SQL beyond MS SQL server?

Answer:
I do not know whether Microsoft plans to do so, but it is probably unlikely. However, if you want to use something similar, you could probably use
DbLinq
meanwhile.


Question:
I have a site, and it will be sold to different clients but for maintenance reasons, we will be keeping one codebase. So this means that this one codebase will have to be dynamic enough to have different styles and so forth, depending on the client.

The domain would be a subdomain-type system, so: projectname.clientname.com , projectname.clientname.com, and so forth, where client name is the company who we have sold the system to.

What I'm trying to do is to have a different theme load up depending on the domain. So I may have ecards.savills.com, and for that, I have a folder in Themes called Savills, and inside that folder called Savills, a .CSS file and I want to load that. I've been playing with the request object, but no luck.

I've tried several methods to achieve this, using stylesheettheme (don't need to skin buttons btw), but I keep getting stack overflows in a system dll for .NET.

What is a robust way to achieve this?

Answer:
```
```
/* Do you have a folder in "Themes" or "APP_Themes" called Savillis? */
```
```
When you designate a Theme for a page, all stylesheets in that theme folder will be loaded. They will be loaded alphabetically, so watch the order.
On a page level, you can set the theme in the Page directive (aspx) or the PreInit (codebehind), or you can set a default theme in the web.config. (You can also set a global theme, but thats not usually used.
```
```
/* Are you doing that? */
```
```
Are there separate web site instances?


Question:
In order to handle concurrency issue, is locking-- any form of locking, whether it's row, table or database locking a good solution?

If not, how to handle concurrency issue?

Answer:
I think not, because it is all the way "down" and makes your application more complex. Most languages have excelent concurrency handling techniques, and even then the best way is to write code which can handle concurrency "natively".
For more info on concurrency in Java:
http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html


Question:
Using the client-side ASP.NET AJAX library, I have created an instance of a client component with the $create shortcut-method (http://msdn.microsoft.com/da-dk/library/bb397487(en-us).aspx). The object is attached to a DOM element. Now I need to get a reference to the instance, but it is neither registered on window or on the DOM element, and I cannot find it anywhere.

Does someone know how you can obtain a reference to the instance?

Best regards,

JacobE

Answer:
According to MSDN, Sys.Component.Create should return the object that it just created. And, $create is just a shortcut for Sys.Component.create.
```
```
Returns: A new instance of a component that uses the specified parameters.
```
```
So, try:
```
```
var instance = $create(someType);
```
```


Question:
I recently installed RailRoad gem to generate an .svg diagram of my app's models and controllers.

The rake task keeps breaking with a similar error:

1.8/usr/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/dependencies.rb:263:in `load_missing_constant': uninitialized constant

I tried the rake task on 2 seperate apps and the error keeps appearing with a different "constant" name.

Anyone using it with similar problems?

Answer:
I'm running it without any problems (though I did have to make a quick edit as it was representing the crows feet the wrong way).
This problem
also appears to be in their tracker
.  I would go ahead and add your stack trace to that ticket as well.  I'm curious if it's your version of ActiveSupport?  Bur your version and the version in use are both displaying the same problem so there's got to be a similarity somewhere.


Question: How do you add a page break into a document with XSL-FO? I'm using Apache FOP to create PDFs, if that makes a difference.

Answer:
The
FOP compliance page
says that it supports
```
page-break-after
```
,
```
page-break-before
```
, and
```
page-break-inside
```
in the later versions, plus partial support for
```
keep-together
```
,
```
keep-with-next
```
,
```
keep-with-previous
```
.


Question:
I have a singleton that uses the "static readonly T Instance = new T();" pattern. However, I ran into a case where T is disposable, and actually needs to be disposed for unit tests. How can I modify this pattern to support a disposable singleton?

The interface I would like is something like:

var x = Foo.Instance;
var y = Foo.Instance; // x == y
...
x.Release(); // this causes the next Foo.Instance to return a fresh object
             // also, it assumes no further operations on x/y will be performed.

Note - the pattern has to be thread-safe, of course.

Edit - for the purpose of production code, this is a true singleton. The thing is that it locks some files, and so for cleanup in unit tests we have to dispose it.

I would also prefer a pattern that can be reused, if possible.

Answer:
At that point I don't think I'd really consider it to be a singleton any more, to be honest.
In particular, if a client uses a singleton they're really not going to expect that they have to dispose of it, and they'd be surprised if someone else did.
What's your production code going to do?
EDIT: If you really, really need this for unit tests and
only
for unit tests (which sounds questionable in terms of design, to be frank) then you could always fiddle with the field using reflection. It would be nicer to work out whether it should
really
be a singleton or whether it should
really
be disposable though - the two very rarely go together.


Question:
Given a FieldInfo object and an object, I need to get the actual bytes representation of the field. I know that the field is either int,Int32,uint,short etc.

How can I get the actual byte representation? BinaryFormatter.Serialize won't help, since it'll give me more information than I need (it also records type name etc.). The Marshal class does not seem to have facilities to use bytes array (but maybe I'm missing something).

Thanks

Answer:
Use BitConverter.GetBytes()
You'll first have to convert the value to it's native type, than use BitConverter to get the bytes:
```
```
byte[] Bytes;

if (valType == typeof(int))
{
    int intVal = (int) GetFieldValue(....);
    Bytes = BitConverter.GetBytes(intVval);
}
else if (valType == typeof(long))
{
    int lngVal = (long) GetFieldValue(....);
    Bytes = BitConverter.GetBytes(lngVal);
} else ....
```
```


Question:
Is there an easy way to rename a group of files already contained in a directory, using Python?

Example:   I have a directory full of *.doc files and I want to rename them in a consistent way.

X.doc -> "new(X).doc"

Y.doc -> "new(Y).doc"

Answer:
Try:
http://www.mattweber.org/2007/03/04/python-script-renamepy/
I like to have my music, movie, and
  picture files named a certain way.
  When I download files from the
  internet, they usually don’t follow my
  naming convention. I found myself
  manually renaming each file to fit my
  style. This got old realy fast, so I
  decided to write a program to do it
  for me.
This program can convert the filename
  to all lowercase, replace strings in
  the filename with whatever you want,
  and trim any number of characters from
  the front or back of the filename.
The program's source code is also available.


Question:
For a web app I'm working on, I need to know the lat/lon of about 300 US cities.  I also need to know the lat/lon for every US zip code.

Does anyone know of a free source to get this information?

Answer:
Freebase
will likely be able to help you.
Here is New York
and it has Lat/Long.
The
Wal-Mart Expansion video
used Freebase to get it's data, and it sounds like you're doing something similar.


Question: Since a lot of email clients ignore the HEAD tag, can I embed an inline stylesheet in the body?

Answer:
The short answer is no. Gmail strips the tag and it's content.
Hotmail, Yahoo! Mail and Windows Live Mail does not strip style-tags in the body-element.
But take a look at
"The Ultimate Guide to CSS" for HTML email
over at Campaign Monitor.


Question:
I have to add a coupon table to my db. There are 3 types of coupons : percentage, amount or 2 for 1.

So far I've come up with a coupon table that contains these 3 fields. If there's a percentage value not set to null then it's this kind of coupon.

I feel it's not the proper way to do it. Should I create a CouponType table and how would you see it? Where would you store these values?

Any help or cue appreciated!

Thanks,

Teebot

Answer:
You're correct, I think a CouponType table would be fit for your problem.
Two tables: Coupons and CouponTypes.  Store the CouponTypeId inside the Coupons table.
So for an example, you'll have a Coupon record called "50% off", if would reference the percent off CouponType record and from there you could determine the logic to take 50% off the cost of the item.
So now you can create unlimited coupons, if it's a dollar amount coupon type it will take the "amount" column and treat it as a dollar amount.  If it's a percent off it will treat it as a percentage and if it's an "x for 1" deal, it will treat the value as x.
```
```
- Table Coupons
  - ID
  - name
  - coupon_type_id # (or whatever fits your style guidelines)
  - amount # Example: 10.00 (treated as $10 off for amount type, treated as
           # 10% for percent type or 10 for 1 with the final type)
  - expiration_date

- Table CouponTypes
  - ID
  - type # (amount, percent, <whatever you decided to call the 2 for 1> :))
```
```


Question:
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 ?

Answer:
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.


Question:
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?

Answer:
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.


Question:
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?

Answer:
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().


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

Answer:
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.


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

Answer:
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


Question:
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...

Answer:
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


Question:
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.

Answer:
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.


Question: 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.

Answer:
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.


Question:
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?

Answer:
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
```
.


Question:
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.

Answer:
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
```
.


Question:
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?

Answer:
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);
}
```
```


Question: 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?

Answer:
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.


Question:
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?

Answer:
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
)


Question:
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?

Answer:
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.


Question:
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?

Answer:
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).


Question:
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.

Answer:
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));
```
```


Question:
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.

Answer:
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.


Question:
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?

Answer:
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


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

Answer: 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.


Question:
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...

Answer:
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.


Question:
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.

Answer:
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
```
```


Question:
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

Answer:
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


Question:
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.

Answer:
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.


Question:
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.

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


Question:
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.

Answer:
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
.


Question: 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?

Answer:
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
.


Question:
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?

Answer:
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)
```


Question:
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?

Answer:
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.


Question:
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?

Answer:
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.


Question: 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?

Answer:
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.


Question:
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.

Answer:
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.


Question:
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?

Answer:
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.


Question:
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.

Answer:
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/


Question:
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?

Answer:
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.


Question:
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!

Answer:
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.


Question:
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?

Answer:
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.


Question:
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.

Answer:
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 ...


Question:
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.

Answer:
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.


Question:
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.

Answer:
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.


Question:
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*/

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


Question:
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?

Answer:
```
```
System.Web.HttpContext.Current
```
```
?


Question:
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?

Answer:
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.


Question:
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?

Answer:
You can build one with the
```
HttpListener
```
class to listen for incoming requests and the
```
HttpWebRequest
```
class to relay the requests.


Question:
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!

Answer:
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.


Question: 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?

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


Question:
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!

Answer:
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?


Question:
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.

Answer:
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);
```
```


Question: 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?

Answer:
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.


Question: 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?

Answer:
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.


Question:
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.

Answer:
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");
}
```
```


Question:
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?

Answer:
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
).


Question:
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.

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


Question:
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?

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


Question:
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?

Answer:
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.


Question:
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.

Answer:
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.


Question:
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.

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


Question:
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?

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


Question:
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?

Answer:
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.


Question:
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

Answer:
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
```
```


Question:
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.

Answer:
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!


Question:
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?

Answer:
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.


Question:
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';

Answer:
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);
}
```
```


Question:
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

Answer:
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.


Question: 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.

Answer:
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.


Question: 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.

Answer:
"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.


Question:
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;
}

Answer:
```
```
foreach(UserControl uc in plhMediaBuys.Controls)
{
  if (uc is MySpecificType)
  {
    return (uc as MySpecificType).PulblicPropertyIWantAccessTo;
  }
}
```
```


Question:
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.

Answer:
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.


Question:
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?

Answer:
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).


Question:
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

Answer:
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!


Question:
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.

Answer:
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
.


Question:
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.

Answer:
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.


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

Answer:
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.


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

Answer:
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 :)


Question:
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

Answer:
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


Question:
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?

Answer:
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.


Question:
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.

Answer:
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, ...
```
```