q:
VMware ESX, ESXi, and VirtualCenter are supposed to be able to support HTTP PUT uploads since version 3.5. I know how to do downloads, that's easy. I've never done PUT before.

Background information on the topic is here: http://communities.vmware.com/thread/117504

[A]
You should have a look at the
```
Send-PoshCode
```
function in the
PoshCode
cmdlets script module ... it uses a POST, not a PUT, but the technique is practically identical.  I don't have PUT server I can think of to test against, but basically, set your $url and your $data, and do something like:
```
```
param($url,$data,$filename,[switch]$quiet)

$request = [System.Net.WebRequest]::Create($url)
$data = [Text.Encoding]::UTF8.GetBytes( $data )

## Be careful to set your content type appropriately...
## This is what you're going to SEND THEM
$request.ContentType = 'text/xml;charset="utf-8"' # "application/json"; # "application/x-www-form-urlencoded";
## This is what you expect back
$request.Accept = "text/xml" # "application/json";

$request.ContentLength = $data.Length
$request.Method = "PUT"
## If you need Credentials ...
# $request.Credentials = (Get-Credential).GetNetworkCredential()

$put = new-object IO.StreamWriter $request.GetRequestStream()
$put.Write($data,0,$data.Length)
$put.Flush()
$put.Close()

## This is the "simple" way ...
# $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8
# write-output $reader.ReadToEnd()
# $reader.Close()

## But there's code in PoshCode.psm1 for doing a progress bar, something like ....

$res = $request.GetResponse();
if($res.StatusCode -eq 200) {
   [int]$goal = $res.ContentLength
   $reader = $res.GetResponseStream()
   if($fileName) {
      $writer = new-object System.IO.FileStream $fileName, "Create"
   }

   [byte[]]$buffer = new-object byte[] 4096
   [int]$total = [int]$count = 0
   do
   {
      $count = $reader.Read($buffer, 0, $buffer.Length);
      if($fileName) {
         $writer.Write($buffer, 0, $count);
      } else {
         $output += $encoding.GetString($buffer,0,$count)
      }
      if(!$quiet) {
         $total += $count
         if($goal -gt 0) {
            Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
         } else {
            Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
         }
      }
   } while ($count -gt 0)

   $reader.Close()
   if($fileName) {
       $writer.Flush()
       $writer.Close()
   } else {
       $output
   }
}
$res.Close();
```
```


q:
I get this error:

Can't locate Foo.pm in @INC

Is there an easier way to install it than downloading, untarring, making, etc?

[A]
```
sudo perl -MCPAN -e 'install Foo'
```

s: huggingface

c: devops

d: intermediate


q:
Is it recommended that I use an initialization vector to encrypt/decrypt my data? Will it make things more secure? Is it one of those things that need to be evaluated on a case by case basis?

To put this into actual context, the Win32 Cryptography function, CryptSetKeyParam allows for the setting of an initialization vector on a key prior to encrypting/decrypting. Other API's also allow for this.

What is generally recommended and why?

[A]
An IV is essential when the same key might ever be used to encrypt more than one message.
The reason is because, under most encryption modes, two messages encrypted with the same key can be analyzed together.  In a simple stream cipher, for instance, XORing two ciphertexts encrypted with the same key results in the XOR of the two messages, from which the plaintext can be easily extracted using traditional cryptanalysis techniques.
A weak IV is part of what made WEP breakable.
An IV basically mixes some unique, non-secret data into the key to prevent the same key ever being used twice.


q:
I would like to read the text and binary attachments in a saved Outlook message (.msg file) from a Java application, without resorting to native code (JNI, Java Native Interface).

Apache POI-HSMF seems to be in the right direction, but it's in very early stages of development...

[A]
You could use Apache POIFS, which
seems to be a little more mature,
but that would appear to duplicate the efforts of POI-HSMF.
You could use POI-HSMF and contribute changes to get the
features you need working.  That's
often how FOSS projects like that expand.
You
could use com4j, j-Interop, or some
other COM-level interop feature and
interact directly with the COM
interfaces that provide access to
the structured document.  That would
be much easier than trying to hit it
directly through JNI.


q:
This should be simple. I'm trying to import data from Access into SQL Server. I don't have direct access to the SQL Server database - it's on GoDaddy and they only allow web access. So I can't use the Management Studio tools, or other third-party Access upsizing programs that require remote access to the database.

I wrote a query on the Access database and I'm trying to loop through and insert each record into the corresponding SQL Server table. But it keeps erroring out. I'm fairly certain it's because of the HTML and God knows what other weird characters are in one of the Access text fields. I tried using CFQUERYPARAM but that doesn't seem to help either.

Any ideas would be helpful. Thanks.

[A]
It's never advisable to loop through records when a SQL Update can be used.
It's not clear from your question what database interface layer you are using, but it is possible with the right interfaces to insert data from a source outside a database
if
the interface being used supports both types of databases. This can be done in the FROM clause of your SQL statement by specifying not just the table name, but the connect string for the database. Assuming that your web host has ODBC drivers for Jet data (you're not actually using Access, which is the app development part -- you're only using the Jet database engine), the connect string should be sufficient.
EDIT: If you use the Jet database engine to do this, you should be able to specify the source table something like this (where tblSQLServer is a table in your Jet MDB that is linked via ODBC to your SQL Server):
```
```
INSERT INTO tblSQLServer (ID, OtherField )
SELECT ID, OtherField
FROM [c:\MyDBs\Access.mdb].tblSQLServer
```
```
The key point is that you are leveraging the Jet db engine here to do all the heavy lifting for you.


q:
I was asked this question in a job interview. The interviewer and I disagreed on what the correct answer was. I'm wondering if anyone has any data on this.

Update: I should have mentioned that the use of shuffle() was strictly forbidden... sorry.

[A]
```
```
shuffle($arr);
```
```
:)
edit: I should clarify... my definition of best involves not just algorithm efficiency but code readability and maintainability as well. Using standard library functions means maintaining less code and reading much less too. Beyond that, you can get into year-long debates with PhD professors about the best "true random" function, so somebody will always disagree with you on randomization questions.


q:
I want to use a file to store the current version number for a piece of customer software which can be used by a start-up script to run the binary in the correct directory.

For Example, if the run directory looks like this:

.
..
1.2.1
1.2.2
1.3.0
run.sh
current_version

And current_version contains:

1.2.2

I want run.sh to descend into 1.2.2 and run the program foo.

The current solution is this:

#!/bin/sh
version = `cat current_version`
cd $version
./foo

It works but is not very robust.  It does not check for file existence, cannot cope with multiple lines, leading spaces, commented lines, blank files, etc.

What is the most survivable way to do this with either a shell or perl script?

[A]
That's a common approach.  You can check for dir/file existence using test operators such as "if [ -d "somedirectory" ]; then" or [ -t "somefile" ]
I use symbolic links more often, though.  Then, you can just change your symbolic link to use the version you want.
For example,
```
$ ln -s 1.2.2 current_version
$ ls -al
total 20
drwxr-xr-x 5 dbreese dbreese 4096 2008-09-15 13:34 .
drwxr-xr-x 3 dbreese dbreese 4096 2008-09-15 13:34 ..
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.1
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.2
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.3.0
lrwxrwxrwx 1 dbreese dbreese    6 2008-09-15 13:34 current_version -> 1.2.2/
```
Then your script can just use "cd current_version".


q:
Is it possible to have XML-embedded JavaScript executed to assist in client-side (browser-based) XSL transformations?  How is it done and how official is it?

Microsoft's XML DOM objects allow this on the server-side (i.e. in ASP/ASP.NET).

Clarification: I do not mean HTML DOM scripting performed after the document is transformed, nor do I mean XSL transformations initiated by JavaScript in the browser (e.g. what the W3Schools page shows).  I am referring to actual script blocks located within the XSL during the transformation.

[A]
Yes. It's browser dependant but you can use Javascript. There is a small but practical tutorial on w3schools.com. It's part of the XSLT tutorial.
The page:
http://www.w3schools.com/xsl/xsl_client.asp
The XSLT tutorial:
http://www.w3schools.com/xsl/default.asp
That site will be more helpful than myself. Good luck!


q: I know you could make a helper pretty easily given the data. So, if possible, please only submit answers that also include getting the data.

[A]
We are using an action filter for this.
...
```
```
public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var controller = (Controller) filterContext.Controller;
        Breadcrumb[] breadcrumbs = _breadcrumbManager.PushBreadcrumb(_breadcrumbLinkText);
        controller.ViewData.Add(breadcrumbs);
    }
```
```
before you mention it, I too have a distaste for service location in the filter attributes - but we are left with few options.  IBreadcrumbManager looks like this:
```
```
public interface IBreadcrumbManager
{
    Breadcrumb[] PushBreadcrumb(string linkText);
}
```
```
The implementation puts Breadcrumb objects into the Session. The Url is
```
HttpContext.Current.Request.RawUrl
```


q:
I'm using Visual Studio (2005 and up). I am looking into trying out making an application where the user can change language for all menues, input formats and such. How would I go on doing this, as I suppose that there is some complete feature within .Net that can help me with this?

I need to take the following into account (and fill me in if I miss some obvious stuff)

Strings (menues, texts)

Input data (parsing floats, dates, etc..)

Should be easy to add support for another language

[A]
For strings you should just separate your strings from your code (having an XML/DLL that will transform string IDs to real strings is one way to go). However you do need to make sure that you are supporting double byte characters for some languages (this is relevant if you use C/C++).
For input data what you want is to have different locale's. In Java this is relatively easy, and if you use C# it probably is quite easy also. In C/C++ I don't really know. The basic idea is that the input parsers should be different based on the locale selected at that time. So each field (textfield, textbox, etc.) must have an abstract parser that is then implemented by a different class depending on the locale (right to left, double byte, etc.).
Check the Java implementation for details on how they did it. It is quite functional.


q:
I've seen examples like this:

public class MaxSeconds {
   public static final int MAX_SECONDS = 25;
}

and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.

[A]
That is perfectly acceptable, probably even the standard.
```
```
(public/private) static final TYPE NAME = VALUE;
```
```
where
```
TYPE
```
is the type,
```
NAME
```
is the name in all caps with underscores for spaces, and
```
VALUE
```
is the constant value;
I highly recommend NOT putting your constants in their own classes or interfaces.
As a side note:  Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.
For example:
```
```
public static final Point ORIGIN = new Point(0,0);

public static void main(String[] args){

    ORIGIN.x = 3;

}
```
```
That is legal and
```
ORIGIN
```
would then be a point at (3, 0).


q:
I'm responsible for some test database servers.  Historically, too many other poeple have access to them.  They run on SQL Server 2005.

I've been writing queries and wrapping them in scripts so I can run a regular audit of rights.  Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the sysadmin role on their login - it was a single line query for the latter.

But how to find out which logins have a User Mapping to a particular (or any) database?

I can find the sys.database_principals and sys.server_principals tables.  I have located the sys.databases table.  I haven't worked out how to find out which users have rights on a database, and if so, what.

Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?

[A]
```
```
select * from Master.dbo.syslogins l inner join sys.sysusers u on l.sid = u.sid
```
```
This will get you what users are mapped to which logins within a single database.


q: Is there any visible progress?  Is it now just an academic exercise?  Do you believe Perl will continue to evolve with or without Perl 6 or will soon be forgotten?

[A]
I feel like some good things may come from Perl 6 (e.g. parrot), but I'm not counting on ever doing anything with the language.
In the bioinformatics development group where I work, we're encouraging use of Python for new development where Perl would have been the language of choice in the past.  Python appears to provide a better path forward for us.


q:
I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart.

What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?

[A]
In the OnLoad event of the form, you could always explicitly set the location of each section. If starting at the top left with the first and assuming an array with the images in order:
```
```
images[0].Location = new Point(0,0);
for (int i = 1; i < images.Length; i++)
{
  images[i].Location = new Point(images[i - 1].Location.X + images[i - 1].Width, 0);
}
```
```
That will set the first image to the top left corner and all subsequent images to just after the last image.


q:
Do you refactor your SQL first? Your architecture? or your code base?
Do you change languages? Do you throw everything away and start from scratch? [Not refactoring]

[A]
This really depends on the state of the codebase... are there massive classes? one class with mega-methods? Are the classes tightly coupled? is configuration a burden?
Considering this, I suggest reading
Working Effectively with Legacy Code
, picking out your problems, and applying the recommendations.


q: When using Google Chrome, I want to debug some JavaScript code. How can I do that?

[A]
Try adding this to your source:
```
```
debugger;
```
```
It works in most, if not all browsers. Just place it somewhere in your code, and it will act like a breakpoint.


q:
I have a servlet that is used for many different actions, used in the Front Controller pattern.  Does anyone know if it is possible to tell if the data posted back to it is enctype="multipart/form-data"?  I can't read the request parameters until I decide this, so I can't dispatch the request to the proper controller.

Any ideas?

[A]
Yes, the
```
Content-type
```
header in the user agent's request should include
```
multipart/form-data
```
as described in (at least) the HTML4 spec:
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2


q:
I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects.
For example, the game menu is a Canvas object, and the actual game is a Canvas object too.
I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas.

Is there anyway to avoid this?

[A]
Do you use double buffering? If the device itself does not support double buffering you should define a off screen buffer (Image) and paint to it first and then paint the end result to the real screen. Do this for each of your canvases. Here is an example:
```
```
public class MyScreen extends Canvas {
   private Image osb;
   private Graphics osg;
   //...

   public MyScreen()
   {
         // if device is not double buffered
         // use image as a offscreen buffer
         if (!isDoubleBuffered())
         {
            osb = Image.createImage(screenWidth, screenHeight);
            osg = osb.getGraphics();
            osg.setFont(defaultFont);
         }
   }

   protected void paint(Graphics graphics)
   {
      if (!isDoubleBuffered())
      {
         // do your painting on off screen buffer first
         renderWorld(osg);

         // once done paint it at image on the real screen
         graphics.drawImage(osb, 0, 0, Tools.GRAPHICS_TOP_LEFT);
      }
      else
      {
         osg = graphics;
         renderWorld(graphics);
      }
   }
}
```
```


q:
Is there a way to check to see if an iPhone is online from a web app. That is, in mobile Safari, can I check the online status of the device to see if I should try an AJAX call or not.

In Firefox/regular WebKit, this would be:

if(navigator.onLine)
{
    onlineCode()
}

[A]
That same code should work in the WebKit nightly build as of May 16th 2008. I guess that means you need to hope the 2.1 update included a new build of safari.
https://bugs.webkit.org/show_bug.cgi?id=19105


q: Can ANTLR output C# using StringTemplate or any text I want it to like Yacc/Bison or does it only output to java?  From the examples I've looked at it appears to be a very java centric tool.

[A]
You can download the latest source code as a tar file from
here
.  The C# runtime (binary) is also available directly,
here
.
Which solution are you looking for?


q:
I have the following Java 6 code:

    Query q = em.createNativeQuery(
        "select T.* " +
        "from Trip T join Itinerary I on (T.itinerary_id=I.id) " +
        "where I.launchDate between :start and :end " +
        "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end",
        "TripResults" );

    q.setParameter( "start", range.getStart(), TemporalType.DATE );
    q.setParameter( "end", range.getEnd(), TemporalType.DATE );

    @SqlResultSetMapping( name="TripResults",
        entities={
            @EntityResult( entityClass=TripEntity.class ),
            @EntityResult( entityClass=CommercialTripEntity.class )
        }
    )

I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName".  Similar syntax error from javac.

What am I doing wrong?

[A]
The Hibernate annotations docs (
http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/
) suggest that this should be a class-level annotation rather than occurring inline within your code.  And indeed when I paste that code into my IDE and move it around, the compile errors are present when the annotation is inline, but vanish when I put it in above the class declaration:
```
```
@SqlResultSetMapping( name="TripResults",
        entities={
            @EntityResult( entityClass=TripEntity.class ),
            @EntityResult( entityClass=CommercialTripEntity.class )
        }
    )
public class Foo {
   public void bogus() {
      Query q = em.createNativeQuery(
        "select T.* " +
        "from Trip T join Itinerary I on (T.itinerary_id=I.id) " +
        "where I.launchDate between :start and :end " +
        "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end",
        "TripResults" );

      q.setParameter( "start", range.getStart(), TemporalType.DATE );
      q.setParameter( "end", range.getEnd(), TemporalType.DATE );
   }
}
```
```
...obviously I have no evidence that the above code will actually work.  I have only verified that it doesn't cause compile errors.


q:
I know that garbage collection is automated in Java. But I understood that if you call System.gc() in your code that the JVM may or may not decide to perform garbage collection at that point. How does this work precisely? On what basis/parameters exactly does the JVM decide to do (or not do) a GC when it sees System.gc()?

Are there any examples in which case it's a good idea to put this in your code?

[A]
In practice, it
usually
decides to do a garbage collection.  The answer varies depending on lots of factors, like which JVM you're running on, which mode it's in, and which garbage collection algorithm it's using.
I wouldn't depend on it in your code.  If the JVM is about to throw an OutOfMemoryError, calling System.gc() won't stop it, because the garbage collector will attempt to free as much as it can before it goes to that extreme.  The only time I've seen it used in practice is in IDEs where it's attached to a button that a user can click, but even there it's not terribly useful.


q: How do I get started?

[A]
You'll need an interface to the Oracle SQL database. As Bob pointed out, Allegro CL has such an interface.
GNU CLISP apparently comes with an interface to the database as well.


q:
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?

See the example below:

try {
    // code that may or may not throw an exception
} finally {
    SomeCleanupFunctionThatThrows();
    // if currently executing an exception, exit the program,
    // otherwise just let the exception thrown by the function
    // above propagate
}

or is ignoring one of the exceptions the only thing you can do?

In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.

[A]
No I do not believe so.  The catch block will run to completion before the finally block.
```
```
try {
    // code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
    SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}
```
```
Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.


q: I'm trying to convert old QuickTime framework code to the 64-bit Cocoa-based QTKit on OS X, which means that I can't drop down to the straight C function calls at any time.  Specifically, I'm trying to find a way to write QuickTime VR movies with QTKit, as they require some special metadata to set the display controller.  How can I do this with QTKit?

[A]
As far as I can tell from the QTKit Documentation there is not way to do this in straight QTKit cocoa calls.  You'll need to
do this using the Quicktime-C APIs
, which of course aren't available to 64-bit applications.
I've run into issues like this numerous times when trying to convert a 32-bit app that uses Quicktime into a 64-bit app.  Here's hoping that Quicktime X will have a more fully featured QTKit set of APIs.


q: I've created a python object, but I want to send signals on it.  I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

[A]
Here is how:
```
```
import gobject

class MyGObjectClass(gobject.GObject):
    ...

gobject.signal_new("signal-name", MyGObjectClass, gobject.SIGNAL_RUN_FIRST,
    None, (str, int))
```
```
Where the second to last argument is the return type and the last argument is a tuple of argument types.


q:
Are there any advantages compiling for .NET Framework 3.5 instead of 2.0?

For example less memory consumption, faster startup, better performance...

Personally I don't think so however, I may have missed something.

Edits

Of course there are more features in the 3.5 framework, but these are not the focus of this question.

There seem to be no advantages.

Yes I meant targeting the Framework. I have installed the latest 3.5 SP1 and VS 2008 so what's the difference between compiling with and targeting a framework? I can target the framework in the project options but how do I 'compile with' a specific framework version? I did not know that there is a difference.

So for now we agree that there are no advantages.

[A] 3.5 has classes that 2.0 doesn't. Func<...> for instance. If you aim for 2.0, you can't use them.


q:
How can i add a line break to the text area in a html page?
i use VB.net for server side coding.

[A]
Add a linefeed ("\n") to the output:
```
```
<textarea>Hello

Bybye</textarea>
```
```
Will have a newline in it.


q:
Where can I find a guide for integrating JavaScript and JMS (Java Messaging Service)?

I would like a best practice or established technology that allows me to directly or indirectly receive messages from a topic and update a site based on the message. I was thinking of creating two components, a servlet for the Web module, and an MDB (Message-Driven Bean) for the EJB module. The web client will comsume messages from the JMS topic, and the MDB will handle the onMessage.

Does this sound correct? Have you seen any examples?

Edit: I am using ActiveMQ for the JMS.

[A]
I would try using
DWR
to integrate JavaScript with your Java app. It makes Java to JavaScript communication transparent and only requires one servlet + configuration of what to expose. I haven´t done this with JMS, but it should work the same. There are three technologies that together solve all my integration problems,
Spring
,
Mule
, and DWR.


q:
I want a user-privileged (not root) process to launch new processes as user nobody. I've tried a straight call to setuid that fails with -1 EPERM on Ubuntu 8.04:

#include <sys/types.h>
#include <unistd.h>

int main() {
       setuid(65534);
       while (1);
       return 0;
}

How should I do this instead?

[A] As far as I know, you can't unless you're root or have sudo set up to allow you to switch users.  Or, you can have your executable have the suid bit set up on it, and have it owned by nobody.  But that requires root access too.


q:
I'm looking to find alternatives to Solr from the Apache Software Foundation.

For those that don't know, Solr is an enterprise search server. A client application uses a web-services like interface to submit documents for indexing and also to perform search queries. Solr has other features built in like caching and replication. I believe it was originally started by CNet and then open-sourced.

I'm looking for other search servers out there that might be seen as the competition.

[A]
IBM Omnifind Yahoo Edition
is an Enterprise search server which uses
Apache Lucene
for indexing. It is simple, easy to install and administer. It also has a built in Open Search API. It has multi-platform support and its Free!!
This product was launched by IBM to compete with
Google Mini
in the Enterprise Search market.


q:
So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java?

Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and hostnames? Sorry for the confusion and thanks for everybody who took/will take the time to answer this.


q:
We are automating Excel using VB.Net, and trying to place multiple lines of text on an Excel worksheet that we can set to not print. Between these we would have printable reports.
We can do this if we add textbox objects, and set the print object setting to false. (If you have another way, please direct me)

The code to add a textbox is:

ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 145.5, 227.25, 304.5, 21#)

but the positioning is in points. We need a way to place it over a specific cell, and size it with the cell. How can we find out where to put it when we just know which cell to put it over?

[A]
If you have the cell name or position, you can do:
```
```
With ActiveSheet
  .Shapes.AddTextbox msoTextOrientationHorizontal, .Cells(3,2).Left, .Cells(3,2).Top, .Cells(3,2).Width, .Cells(3,2).Height
End With
```
```
This will add a textbox over cell B3. When B3 is resized, the textbox is also.


q:
Is there an Eclipse command to surround the current selection with parentheses?

Creating a template is a decent workaround; it doesn't work with the "Surround With" functionality, because I want to parenthesize an expression, not an entire line, and that requires ${word_selection} rather than ${line_selection}.

Is there a way that I can bind a keyboard shortcut to this particular template? Ctrl-space Ctrl-space arrow arrow arrow isn't as slick as I'd hoped for.

[A]
Easy, Window->Prefs, then select Java->Editor->Templates
Create a new template with : (${line_selection}${cursor})
The "line_selection" means you have to select more than one line.
You can try creating another one with "word_selection", too.
Then, select text, right click, Surround With... and choose your new template.


q: Google maps in some region can serve traffic information showing the blocked roads and so on. I was wondering if there is any code example demonstrating how can I serve traffice information for my own region.

[A]
Google is mum on what source they use for their traffic data.  You might contact them directly to see if they want to implement something for you, but my guess is that they'd simply refer you to their provider if they really wanted your data.
Keep in mind that traffic data is available for more than just the metropolitan areas, but Google isn't using it for a variety of reasons - one of the big reasons is that the entire tile set for the traffic overlay in areas with traffic tiles has to be regenerated every 15 minutes or so.  It just doesn't scale.
So even if you managed to get your data in their flow, it likely won't be rendered.
-Adam


q:
I'm coding a framework along with a project which uses this framework. The project is a Bazaar repository, with the framework in a subfolder below the project.

I want to give the framework a Bazaar repository of its own. How do I do it?

[A]
As far as I know, there is not a way to do this easily with bazaar.   One possibility is to take the original project, branch it, and then remove everything unrelated to the framework.  You can then move the files in the subdir to the main dir.  It's quite a chore, but it is possible to preserve the history.
you will end up with something like:
```
```
branch project:
.. other files..
framework/a.file
framework/b.file
framework/c.file

branch framework:
a.file
b.file
c.file
```
```


q:
I am implementing a quite simple state-machine order processing application. It is a e-commerce application with a few twists. The users of the application will not be editing workflows by themselves.

Microsoft claims that asp.net and Windows Workflow is possible to combine. How hard is it to install and maintain a combination of asp.net and Windows Workflow? I would be keeping the workflow state in sql-server.

Is it easier for me to roll my own state machine code or is Windows Workflow the right tool for the job?

[A]
If your state machine is very simple, then I would say that you should just roll your own.  You have more control over everything.  You can deal with persistence on your own terms and not worry about how they do it.
WF does look pretty cool though, but I think that it's power probably lies in the fact that it is easy to tie it into frameworks like CRM and Sharepoint.  If you are going to use these in your application, then I would definitely consider using WF.
Full disclosure:  I am definitely not a WF expert.


q: I want to extend a WPF application with database functionality. Which database engine would you suggest and why? SQLite, SQL CE, other?

[A]
Depending on the applications use,
I would recommend using SQL Lite
because it doesn't require you to install any other software (SQL CE or Express, etc. usually would require a separate install).
A list of the most important benefits for SQL Lite from the provider link at the bottom of this post:
SQLite is a small C library that
  implements a self-contained,
  embeddable, zero-configuration SQL
  database engine. Features include:
Zero-configuration - no setup or
  administration needed.
Implements most of SQL92. (Features
  not supported)
A complete database is stored in a
  single disk file.
Database files can be freely shared
  between machines with different byte
  orders.
Supports databases up to 2 terabytes
  (2^41 bytes) in size.
Small code footprint: less than 30K
  lines of C code, less than 250KB
  code space (gcc on i486)
Faster than popular client/server
  database engines for most common
  operations.
Simple, easy to use API.
Self-contained: no external
  dependencies.
Sources are in the public domain.
  Use for any purpose.
Since you're using WPF I can assume you're using at least .NET 3.0.  I would then recommend going to .NET 3.5 SP1 (sames size as .NET 3.5 but includes a bunch of performance improvements) which includes LINQ.
When using SQLite, however, you would want to use the following SQLite Provider which should provide LINQ support:
An open source ADO.NET provider for the SQLite database engine


q:
We have a WinForms application written in C# that uses the AxAcroPDFLib.AxAcroPDF component to load and print a PDF file. Has been working without any problems in Windows XP. I have moved my development environment to Vista 64 bit and now the application will not run (on Vista 64) unless I remove the AxAcroPDF component. I get the following error when the application runs:

"System.Runtime.InteropServices.COMException:
Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))."

I have been advised on the Adobe Forums that the reason for the error is that they do not have a 64 bit version of the AxAcroPDF ActiveX control.

Is there some way around this problem?  For example can I convert the 32bit ActiveX control to a 64bit control myself?

[A]
You can't convert Adobe's ActiveX control to 64bit yourself, but you can force your application to run in 32bit mode by setting the platform target to x86.
For instructions for your version of Visual Studio, see section 1.44 of
Issues When Using Microsoft Visual Studio 2005


q:
There are various documents describing threading on Solaris/Linux, but nowwhere describing the Windows implementation. I have a passing interest in this, it seems strange that something so critical is (seemingly) not documented.

Threading is not the same on different OS' - "Write Once, Run Anywhere" isn't true for threading.

See http://java.sun.com/docs/hotspot/threads/threads.html

[A]
The document in question discusses the Solaris threading model and how the VM maps to it. This has nothing to do with Linux. Also, the document discusses performance only. The program's overall behaviour should not change no matter what you choose.
Java's exposed threading model is the same on every platform and defined in the Java specifications. To a Java application, the underlying OS should be completely transparent even for threading.
If you have to know, though ... The Sun JVM maps its threads 1:1 to Windows threads. It doesn't use multiple processes or fibers.


q: How do I determine using TSQL what roles are granted execute permissions on a specific stored procedure? Is there a system stored procedure or a system view I can use?

[A]
You can try something like this.  Note, I believe 3 is EXECUTE.
```
```
SELECT
grantee_principal.name AS [Grantee],
CASE grantee_principal.type WHEN 'R' THEN 3 WHEN 'A' THEN 4 ELSE 2 END - CASE 'database' WHEN  'database' THEN 0 ELSE 2 END AS [GranteeType]
FROM
sys.all_objects AS sp
INNER JOIN sys.database_permissions AS prmssn ON prmssn.major_id=sp.object_id AND prmssn.minor_id=0 AND prmssn.class=1
INNER JOIN sys.database_principals AS grantee_principal ON grantee_principal.principal_id = prmssn.grantee_principal_id
WHERE
(sp.type = N'P' OR sp.type = N'RF' OR sp.type='PC')and(sp.name=N'myProcedure' and SCHEMA_N
```
```
I got that example by simply using SQL Profiler while looking at the permissions on a procedure.  I hope that helps.


q: How do you iterate through every file/directory recursively in standard C++?

[A]
You need to call OS-specific functions for filesystem traversal, like
```
open()
```
and
```
readdir()
```
. The C standard does not specify any filesystem-related functions.


q: I have quite a few developers asking me if certain SQL jobs ran, and I would like to give them access to check it on their own without giving them sysadmin rights.  I know that in SQL 2005, you can grant them the SQLAgentReaderRole, but I am looking for a solution in SQL 2000.

[A]
Pretty sure there isn't one out of the box.  This thread seems to be pretty decent...halfway down they discuss creating a role and then locking that down further.  Also you could just create a mini-program (sp even?) to email the results of the job as a summary, or add to each job an on completion event to email an email group.
http://sqlforums.windowsitpro.com/web/forum/messageview.aspx?catid=60&threadid=43021&enterthread=y


q: I have an iframe.  The content is wider than the width I am setting so the iframe gets a horizontal scroll bar.  I can't increase the width of the iframe so I want to just remove the scroll bar.  I tried setting the scroll property to "no" but that kills both scroll bars and I want the vertical one.  I tried setting overflow-x to "hidden" and that killed the horizontal scroll bar in ff but not in IE. sad for me.

[A]
You could try putting the iframe inside a div and then use the div for the scrolling. You can control the scrolling on the div in IE without issues, IE only really has problems with iframe scrolling. Here's a quick example that should do the trick.
```
```

        <title>iframe test</title>

```
```


q: Why isn't there a Team Foundation Server Express Edition?

[A]
And individuals shouldn't be using TFS?? That's like saying source control is only for groups and not individuals.
If they had an express edition of TFS, then they'd probably get more people using it and paying for their company to use it.


q:
GNU sed version 4.1.5 seems to fail with International chars. Here is my input file:

Gras Och Stenar Trad - From Moja to Minneapolis DVD [G2007DVD] 7812 | X
<br>
Gras Och Stenar Trad - From Möja to Minneapolis DVD [G2007DVD] 7812 | Y

(Note the umlaut in the second line.)

And when I do

sed 's/.*| //' < in

I would expect to see only the X and Y, as I've asked to remove ALL chars up to the '|' and space beyond it. Instead, I get:

X<br>
Gras Och Stenar Trad - From M? Y

I know I can use tr to remove the International chars. first, but is there a way to just use sed?

[A]
```
sed
```
is not very well setup for non-ASCII text. However you can use (almost) the same code in
```
perl
```
and get the result you want:
```
```
perl -pe 's/.*\| //' x
```
```


q:
I have a "watcher" module that is currently using global hierarchies inside it.  I need to instantiate a second instance of this with a second global hierarchy.

Currently:

module watcher;
wire sig = `HIER.sig;
wire bar = `HIER.foo.bar;
...
endmodule

watcher w; // instantiation

Desired:

module watcher(input base_hier);
wire sig = base_hier.sig;
wire bar = base_hier.foo.bar;
...
endmodule

watcher w1(`HIER1); // instantiation
watcher w2(`HIER2); // second instantiation, except with a different hierarchy

My best idea is to use vpp (the Verilog preprocessor) to brute-force generate two virtually-identical modules (one with each hierarchy), but is there a more elegant way?

[A]
My preference is to have a single module (or a small number of modules) in your testbench that contains all your probes but no other functionality. All other modules in your testbench that require probes then connect to that "probe module". Use SystemVerilog interfaces in preference to raw wires if that's an option for you. This circumvents your problem since no watcher will require global hierarchies and your testbench on the whole will be considerably easier to maintain. See the
Law of Demeter
.
Alternatively... (but this puts hierarchy in your instantiations...)
```
```
module watcher(sig, bar);
  input sig;
  input bar;
...
endmodule

watcher w1(`HIER1.sig, `HIER1.foo.bar); // instantiation
watcher w2(`HIER2.sig, `HIER2.foo.bar); // second instantiation, except with a different hierarchy
```
```
Subsequently you can also:
```
```
`define WATCHER_INST(NAME, HIER) watcher NAME(HIER.sig, HIER.foo.sig)

`WATCHER_INST(w1, `HIER1);
`WATCHER_INST(w2, `HIER2);
```
```


q:
I'm fairly new to the STL, so I was wondering whether there are any dynamically sortable containers?  At the moment my current thinking is to use a vector in conjunction with the various sort algorithms, but I'm not sure whether there's a more appropriate selection given the (presumably) linear complexity of inserting entries into a sorted vector.

To clarify "dynamically", I am looking for a container that I can modify the sorting order at runtime - e.g. sort it in an ascending order, then later re-sort in a descending order.

[A]
```
std::set
```
is basically a sorted container.


q: How can I show a web page in a transparent window and have the white part of the web page also transparent.

[A] Can't you just write a link to a "zip server" or whatnot?  Why does the zip archive itself need to be served from Django?  A 90's era CGI script to generate a zip and spit it to stdout is really all that's required here, at least as far as I can see.


q:
Let's say the first N integers divisible by 3 starting with 9.

I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.

[A]
I can't say this is any good, I'm not a C# expert and I just whacked it out, but I think it's probably a canonical example of the use of
```
yield
```
.
```
```
internal IEnumerable Answer(N)
{
  int n=0;
  int i=9;
  while (true)
  {
    if (i % 3 == 0)
    {
      n++;
      yield return i;
    }

    if (n>=N) return;
    i++;
  }
}
```
```


q:
I'd like to have a TabNavigator component that has a close button for some of the tabs. How do I do that?

It seems that the TabNavigator component does not allow (or I could not find)  extensibility of this form.
Help. Thanks

[A]
You should take a look at the SuperTabNavigator component from the
FlexLib
project:
SuperTabNavigator example
SuperTabNavigator documentation
FlexLib Component list
If you don't want all of the tabs to have close buttons (I understand from the question that you don't) it looks like you could use the
setClosePolicyForTab()
method for specifying which tabs you want to have them.


q: I'm looking for a profiler in order to find the bottleneck in my C++ code. I'd like to find a free, non-intrusive, and good profiling tool. I'm a game developer, and I use PIX for Xbox 360 and found it very good, but it's not free. I know the Intel VTune, but it's not free either.

[A]
CodeXL
has now superseded the End Of Line'd
AMD Code Analyst
and both are free, but not as advanced as VTune.
There's also
Sleepy
, which is very simple, but does the job in many cases.
Note:
All three of the tools above are unmaintained since several years.


q:
I have a need to do auditing all database activity regardless of whether it came from application or someone issuing some sql via other means. So the auditing must be done at the database level. The database in question is Oracle. I looked at doing it via Triggers and also via something called Fine Grained Auditing that Oracle provides. In both cases, we turned on auditing on specific tables and specific columns. However, we found that Performance really sucks when we use either of these methods.

Since auditing is an absolute must due to regulations placed around data privacy, I am wondering what is best way to do this without significant performance degradations. If someone has Oracle specific experience with this, it will be helpful but if not just general practices around database activity auditing will be okay as well.

[A]
I'm not sure if it's a mature enough approach for a production
system, but I had quite a lot of success with monitoring database
traffic using a network traffic sniffer.
Send the raw data between the application and database off to another
machine and decode and analyse it there.
I used PostgreSQL, and decoding the traffic and turning it into
a stream of database operations that could be logged was relatively
straightforward. I imagine it'd work on any database where the packet
format is documented though.
The main point was that it put no extra load on the database itself.
Also, it was passive monitoring, it recorded all activity, but
couldn't block any operations, so might not be quite what you're looking for.


q:
The wikipedia article about Law of Demeter says:

The law can be stated simply as "use only one dot".

However a simple example of a fluent interface may look like this:

static void Main(string[] args)
{
   new ZRLabs.Yael.Pipeline("cat.jpg")
        .Rotate(90)
        .Watermark("Monkey")
        .RoundCorners(100, Color.Bisque)
        .Save("test.png");
}

So does this goes together?

[A]
Yes, although you have to apply some pragmatism to the situation. I always take the Law of Demeter as a guideline as opposed to a rule.
Certainly you may well want to avoid the following:
```
```
CurrentCustomer.Orders[0].Manufacturer.Address.Email(text);
```
```
perhaps replace with:
```
```
CurrentCustomer.Orders[0].EmailManufacturer(text);
```
```
As more of us use ORM which generally presents the entire domain as an object graph it might be an idea to define acceptable "scope" for a particular object. Perhaps we should take the law of demeter to suggest that you shouldn't map the entire graph as reachable.


q:
In Javascript:
How does one find the coordinates (x, y, height, width) of every link in a webpage?

[A]
Using jQuery, it's as simple as:
```
```
$("a").each(function() {
    var link = $(this);
    var top = link.offset().top;
    var left = link.offset().left;
    var width = link.offset.width();
    var height = link.offset.height();
});
```
```


q: I'm wanting to change my movie clips to actionscript classes in AS3. Is there a standard list of things I need to do to make sure the classes work?

[A]
Check out these resources:
Grant Skinners Introductory AS3 Workshop slidedeck
http://gskinner.com/talks/as3workshop/
Lee Brimelow : 6 Reasons to learn ActionScript 3
http://www.adobe.com/devnet/actionscript/articles/six_reasons_as3.html
Colin Moock : Essential ActionScript 3 (considered the "bible" for ActionScript developers):
http://www.amazon.com/Essential-ActionScript-3-0/dp/0596526946
mike chambers
mesh@adobe.com


q:
Are there any ports to WPF of Silverlight's MultiScaleImage (aka DeepZoom)?  Have Microsoft road-mapped this at all for WPF?

I want to move from WinForms to WPF and require something like DeepZoom, using Silverlight isn't an option.

[A]
At the moment there is no port. However, DeepZoom is based on the technology found in the "World Wide Telescope" and the "Microsoft Photo Synth", so they have desktop versions of the technology running. I guess it would be safe to assume that Microsoft will be releasing a multi scale image control for WPF soon. If you just want the "panning and zooming", and don't care about the efficient breakdown of high resolution images you can certainly achieve the same effects in WPF. This post is
one example on how to do zoom and pan
.


q:
How do I load a Python module given its full path?

Note that the file can be anywhere in the filesystem where the user has access rights.

See also: How to import a module given its name as string?

[A]
I believe you can use
```
imp.find_module()
```
and
```
imp.load_module()
```
to load the specified module.  You'll need to split the module name off of the path, i.e. if you wanted to load
```
/home/mypath/mymodule.py
```
you'd need to do:
```
```
imp.find_module('mymodule', '/home/mypath/')
```
```
...but that should get the job done.


q:
I'm looking for a way to extract the audio part of a FLV file.

I'm recording from the user's microphone and the audio is encoded using the Nellymoser Asao Codec. This is the default codec and there's no way to change this.

[A]
This isn't an exact answer, but some relevant notes I've made from investigating FLV files for a business requirement.
Most FLV audio is encoded in the MP3 format, meaning you can extract it directly from the FLV container. If the FLV was created from someone recording from their microphone, the audio is encoded with the Nellymoser Asao codec, which is proprietary (IIRC).
I'd check out
libavcodec
, which handles FLV/MP3/Nellymoser natively, and should let you get to the audio.


q:
Using Oracle 10g with our testing server what is the most efficient/easy way to backup and restore a database to a static point, assuming that you always want to go back to the given point once a backup has been created.

A sample use case would be the following

install and configure all software

Modify data to the base testing point

take a backup somehow (this is part of the question, how to do this)

do testing

return to step 3 state (restore back to backup point, this is the other half of the question)

Optimally this would be completed through sqlplus or rman or some other scriptable method.

[A]
You could use a feature in Oracle called
Flashback
which allows you to create a restore point, which you can easily jump back to after you've done testing.
Quoted from the site,
Flashback Database is like a 'rewind
  button' for your database. It provides
  database point in time recovery
  without requiring a backup of the
  database to first be restored. When
  you eliminate the time it takes to
  restore a database backup from tape,
  database point in time recovery is
  fast.


q:
How can I use .NET DataSet.Select method to search records that match a DateTime?
What format should I use to enter my dates in?

[A]
The best method is dd MMM yyyy (ie 15 Sep 2008). This means there is no possiblity of getting it wrong for different Locals.
```
```
ds.select(DBDate = '15 Sep 2008')
```
```
You can use the DateFormat function to convert to long date format as well and this will work fine too.


q:
In Google Reader, you can use a bookmarklet to "note" a page you're visiting. When you press the bookmarklet, a little Google form is displayed on top of the current page. In the form you can enter a description, etc. When you press Submit, the form submits itself without leaving the page, and then the form disappears. All in all, a very smooth experience.

I obviously tried to take a look at how it's done, but the most interesting parts are minified and unreadable. So...

Any ideas on how to implement something like this (on the browser side)? What issues are there? Existing blog posts describing this?

[A]
At it's very basic level it will be using
```
createElement
```
to create the elements to insert into the page and
```
appendChild
```
or
```
insertBefore
```
to insert them into the page.


q: I'd like to experiment with burn-down and planning game with the team I'm on.  People on my team are interested in making it happen, however I'm sure someone has done this before and has learned some lessons we hopefully don't have to repeat.  Does anyone know of an example Excel (or other tool) template available for burn-down or planning game activities?

[A]
This MSDN Blog article
Has quite a good review of using burndowns in combination with Cumulative Flow Diagrams which fleshes out the diagrams even more. In the resources links at the bottom of the article there is a
link to the Microsoft Scrum kit
which has a pre-built excel file.


q: If I add 3-400 databases to a single SQL Server instance will I encounter scaling issues introduced by the large number of databases?

[A]
This is one of those questions best answered by: Why are you trying to do this in the first place? What is the concurrency against those databases? Are you generating databases when you could have normalized tables to do the same functionality?
That said, yes MSSQL 2005 will handle that level of database per installation. It will more or less be what you are doing with the databases which will seriously impede your performance (incoming connections, CPU usage, etc.)


q:
In php, how can I get the number of apache children that are currently available
(status = SERVER_READY in the apache scoreboard)?

I'm really hoping there is a simple way to do this in php that I am missing.

[A]
You could execute a shell command of
```
ps aux | grep httpd
```
or
```
ps aux | grep apache
```
and count the number of lines in the output.
```
```
exec('ps aux | grep apache', $output);
$processes = count($output);
```
```
I'm not sure which status in the status column indicates that it's ready to accept a connection, but you can filter against that to get a count of ready processes.


q:
I am trying to create a query string of variable assignments separated by the & symbol (ex: "var1=x&var2=y&..."). I plan to pass this string into an embedded flash file.

I am having trouble getting an & symbol to show up in XSLT. If I just type & with no tags around it, there is a problem rendering the XSLT document. If I type &amp; with no tags around it, then the output of the document is &amp; with no change. If I type <xsl:value-of select="&" /> or <xsl:value-of select="&amp;" /> I also get an error. Is this possible? Note: I have also tried &amp;amp; with no success.

[A]
Use
```
disable-output-escaping="yes"
```
in your
```
value-of
```
tag


q:
I have an application that runs as a child application in a virtual directory.

I want to pass a value from the parent application, but I believe that Session is keyed per application, and won't work.

To further complicate things, the parent application is WebForms, while the child is NVelocity MVC.

Does anyone know a trick that allows me to use some sort of Session type functionality between virtual applications?

EDIT: A webservice isn't really what I had in mind, all I need to do is pass the logged in users username to the child app. Besides, if calling a webservice back on the parent, I won't get the same session, so I won't know what user.

[A]
Sounds like web service is the way to go. You could do something like the following:
Have the WebForms app create some data in its database with a key of some kind associated to it.
Pass that key in the URL to the NVelocity MVC application.
Allow the NVMVC application to call a web service (REST,XML-RPC,SOAP,whatever) on the WebForms app using the key that was passed.
This will get around any kind of session keying or cookie-domain problem you may have and allow you to pass some nicely structured data.


q:
I'm writing a web app that points to external links. I'm looking to create a non-sequential, non-guessable id for each document that I can use in the URL. I did the obvious thing: treating the url as a string and str#crypt on it, but that seems to choke on any non-alphanumberic characters, like the slashes, dots and underscores.

Any suggestions on the best way to solve this problem?

Thanks!

[A]
Use
Digest::MD5
from Ruby's standard library:
```
```
Digest::MD5.hexdigest(my_url)
```
```


q: I need to pass a UUID instance via http request parameter. Spring needs a custom type converter (from String) to be registered. How do I register one?

[A]
Not sure what you are asking?
Spring comes with a
CustomEditorConfigurer
to supply custom String <-> Object converters.
To use this, just add the CustomEditorConfigurer as bean to your config, and add the custom converters. However, these converters are typically used when converting string attributes in the config file into real objects.
If you are using Spring MVC, then take a look at the section on
annotated MVC
Specifically, have a look at the
@RequestParam
and the
@ModelAttribute
annotations?
Hope this helps?


q:
If I have a Resource bundle property file:

A.properties:

thekey={0} This is a test

And then I have java code that loads the resource bundle:

ResourceBundle labels = ResourceBundle.getBundle("A", currentLocale);
labels.getString("thekey");

How can I replace the {0} text with some value

labels.getString("thekey", "Yes!!!");

Such that the output comes out as:

Yes!!! This is a test.

There are no methods that are part of Resource Bundle to do this.  Also, I am in Struts, is there some way to use MessageProperties to do the replacement.

[A]
The class you're looking for is java.text.MessageFormat; specifically, calling
```
```
MessageFormat.format("{0} This {1} a test", new Object[] {"Yes!!!", "is"});
```
```
or
```
```
MessageFormat.format("{0} This {1} a test", "Yes!!!", "is");
```
```
will return
```
```
"Yes!!! This is a test"
```
```
[Unfortunately, I can't help with the Struts connection, although
this
looks relevant.]


q:
Let's say that on the C++ side my function takes a variable of type jstring named myString. I can convert it to an ANSI string as follows:

const char* ansiString = env->GetStringUTFChars(myString, 0);

is there a way of getting

const wchar_t* unicodeString = ...

[A]
A portable and robust solution is to use
iconv
, with the understanding that you have to know what encoding your system
```
wchar_t
```
uses (UTF-16 on Windows, UTF-32 on many Unix systems, for example).
If you want to minimise your dependency on third-party code, you can also hand-roll your own UTF-8 converter. This is easy if converting to UTF-32, somewhat harder with UTF-16 because you have to handle surrogate pairs too. :-P Also, you must be careful to reject
non-shortest
forms, or it can open up security bugs in some cases.


q:
I'm using BlogEngine.NET (a fine, fine tool) and I was playing with the TinyMCE editor and noticed that there's a place for me to create a list of external links, but it has to be a javascript file:

external_link_list_url : "example_link_list.js"

this is great, of course, but the list of links I want to use needs to be generated dynamically from the database. This means that I need to create this JS file from the server on page load.  Does anyone know of a way to do this? Ideally, I'd like to just overwrite this file each time the editor is accessed.

Thanks!

[A]
If you can't change the file extension (and just return plain text, the caller shouldn't care about the file extension, js is plain text) then you can set up a handler on IIS (assuming it's IIS) to handle javascript files.
See this link -
http://msdn.microsoft.com/en-us/library/bb515343.aspx
-  for how to setup IIS 6 within windows to handle any file extension. Then setup a HttpHandler to receive requests for .js (Just google httphandler and see any number of good tutorials like this one:
http://www.devx.com/dotnet/Article/6962/0/page/3
)


q:
I need to use XmlRpc in C++ on a Windows platform.  Despite the fact that my friends assure me that XmlRpc is a "widely available standard technology", there are not many libraries available for it.  In fact I only found one library to do this on Windows, (plus another one that claims "you'll have to do a lot of work to get this to compile on Windows).  The library I found was Chris Morley's "XmlRpc++".  However, it doesn't have support for SSL.

My question therefore is:  what library should I be using?

[A]
There are dozens of implementations of the XML-RPC
implementations
, some in C++, but most in other languages. For example, besides XmlRpc++ there is also
XML-RPC for C and C++
. Here is a
HOWTO
on how the XML-RPC for C and C++ library can be used.
The XML-RPC specification is somewhat simple and it would not be difficult to implement your own XML-RPC client. Not to mention, it would also be possible to take an existing XML-RPC implementation in C and bring into your C++ project.
The XML-RPC
home page
also provides a lot of useful information.


q:
What I currently do is I link the project to another location and give it the same name, then check the box where it says "Branch after share."
And then I would Check out the shared project and work off it. And finally merge with the original project.

This works okay, but it feels very clunky: I have multiple instances of the project on my drive; I have to change physical address of the website (i use asp.net 1.1) every time I work on a different branch;

That doesn't feel like the right way to do it. How do you branch your projects with VSS?

[A]
I think the way you describe in the question is the only way you can do it in sourceSafe.
I usually name the copied directory "V1.0" (or whatever is appropriate) and keep them all in a folder that is the main project name.


q:
Has anyone successfully implemented a Java based solution that uses Microsoft SQL Server 2005 Reporting Services?  Reporting Services comes with a set of Web Services that allow you to control the creation of a report, execution of a report, etc and I am just starting development on a POC of this integration.  A couple of choices I have yet to make is whether I want to use Axis2 for the wsdl-to-java functionality or use WebLogic's clientgen (wsdl 2 java) solution.  I guess I can also use JAX-WS and wsimport.  Before I dive into this, I wanted to see if anyone was doing this successfully with one of the many options available.

In the past, I've had a few issues on how null/blank/empty's are handled between .NET and Java web-services and I just wanted to see if this had come up as an issue with SSRS and Java integration.  Thanks

[A]
My experience with RS would lead me to suggest you go with just about anything else. I think the web services portion would work fine but I'd be concerned about how RS manages memory and how many reports you need to be running at once before making any decisions. I'm fighting with memory management problems today with RS and even on top of the line hardware it's hard to run large reports (large number of rows returned and a wide result set).
That being said if you think RS can handle your usage then it might be good. The development environment is sort of nice and it's easy to understand and lay out reports. The table layout paradigm it has is pretty good.


q:
I am new to ActionScript 3 and have run into a problem:

Using Flex Builder 3, I have a created a project with a few simple classes. If code in class A instantiates an object of class B (class B is in its own source file) then the code compiles fine, but I get the following run time error:

ArgumentError: Error #2012: B class cannot be instantiated.

Can someone explain what I'm doing wrong?

Update: Please see my own answer below (I could not vote it to the top since I'm not yet registered).

[A]
This usually means that the class information was not included in the SWF.
Make sure that you are importing the class, and that there is a reference to it somewhere (so the compiler will included it in the SWF).
btw, here are the runtime error codes:
http://livedocs.adobe.com/flex/201/langref/runtimeErrors.html
(not much useful info though)
mike chambers
mesh@adobe.com


q:
When defining a method on a class in Python, it looks something like this:

class MyClass(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype.

Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?

[A]
It's to minimize the difference between methods and functions. It allows you to easily generate methods in metaclasses, or add methods at runtime to pre-existing classes.
e.g.
```
```
>>> class C:
...     def foo(self):
...         print("Hi!")
...
>>>
>>> def bar(self):
...     print("Bork bork bork!")
...
>>>
>>> c = C()
>>> C.bar = bar
>>> c.bar()
Bork bork bork!
>>> c.foo()
Hi!
>>>
```
```
It also (as far as I know) makes the implementation of the python runtime easier.


q:
If you were running a news site that created a list of 10 top news stories, and you wanted to make tweaks to your algorithm and see if people liked the new top story mix better, how would you approach this?

Simple Click logging in the DB associated with the post entry?

A/B testing where you would show one version of the algorithm togroup A and another to group B and measure the clicks?

What sort of characteristics would you base your decision on as to whether the changes were better?

[A]
TagLib Sharp
has support for reading ID3 tags.


q: More and more mobile devices are consuming content on my eCommerce sites.  IPhones, Blackberries, PSPs, Windows Mobile, etc and I need some ideas how to handle repurposing my data using CSS templates for these devices.  Any ideas would be great.

[A]
I recommend you look at what Delta Airlines does with CSS at
http://mobile.delta.com
.  They get help from a company called MShift who does a bunch of mobile banking (which, obviously, has to work on many different devices).
You can get some inspiration from the stylesheet used by the Delta site with
https://my.mshift.com/deltacss.css
.
Finally, there are a long list of demo mobile sites from MShift at
http://www.mshift.com/demo.html
.
FWIW, I don't have any association with either Delta or MShift, I have just admired their mobile UI.


q:
Working on a project at the moment and we have to implement soft deletion for the majority of users (user roles). We decided to add an is_deleted='0' field on each table in the database and set it to '1' if particular user roles hit a delete button on a specific record.

For future maintenance now, each SELECT query will need to ensure they do not include records where is_deleted='1'.

Is there a better solution for implementing soft deletion?

Update: I should also note that we have an Audit database that tracks changes (field, old value, new value, time, user, ip) to all tables/fields within the Application database.

[A]
You could perform all of your queries against a view that contains the
```
WHERE IS_DELETED='0'
```
clause.


q: I create a new Button object but did not specify the command option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?

[A]
Sure; just use the
```
bind
```
method to specify the callback after the button has been created.  I've just written and tested the example below.  You can find a nice tutorial on doing this at
http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
```
```
from Tkinter import Tk, Button

root = Tk()
button = Button(root, text="Click Me!")
button.pack()

def callback(event):
    print "Hello World!"

button.bind("<Button-1>", callback)
root.mainloop()
```
```


q: From the Displays pane in System Preferences, I can manually change the main monitor by dragging the menu bar from one display to the other. I'd like to automate this and make it part of an AppleScript.

[A]
Much like you can tell System Events.app to sleep your Mac, you can tell Image Events.app to mess with your displays.  The Image Events application provides a "displays" collection.  Each display has a "profile" with lots of goodies.  However, everything I just mentioned is read-only, so I don't have a good way to do it from within script.
You might have better luck in Automator – Hit record, run System Preferences, go to Displays, drag the menu bar to the other screen, and hit stop.  I bet something will work.


q: Using the svnmerge.py tool it is possible to merge between branches, up and down.  It is hard to find the details for doing this.  Hopefully, v1.5 will have a neat method for doing this without using svnmerge.py - details requested!

[A]
It looks like you're asking about 1.5 merge tracking.  Here's a quick overview for doing merges to/from trunk (or another branch):
http://blog.red-bean.com/sussman/?p=92


q:
I am completely on board with the ideas behind TDD, Refactoring and Patterns however it does seem like there is a huge gaping whole in these ideas, mainly that they are great for dev teams of 1, but when you start refactoring code that 10 people are working on you start getting merge conflicts all over the place and most diff/merge software can't tell that you refactored a function into its own class.

How do you clean up your code, by refactoring, without causing major headaches for everyone on your team?

[A]
Well, in practice it is rarely an issue.  Usually the different team members are working on different areas of the code, so there is no conflict.  Also, the bulk of the refactoring will go in when you are doing your TDD (which might even be before you check your code in, but most definitely before others start using and modifying it).
If you find you are conflicting a lot due to refactorings, try checking in more frequently, or let people know who might be working on the same code that you are about to do some major rework.  Communication always helps.


q: Is there a way to send a file using POST from a Python script?

[A]
Yes. You'd use the
```
urllib2
```
module, and encode using the
```
multipart/form-data
```
content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:
```
```
user_agent = "image uploader"
default_message = "Image $current of $total"

import logging
import os
from os.path import abspath, isabs, isdir, isfile, join
import random
import string
import sys
import mimetypes
import urllib2
import httplib
import time
import re

def random_string (length):
    return ''.join (random.choice (string.letters) for ii in range (length + 1))

def encode_multipart_data (data, files):
    boundary = random_string (30)

    def get_content_type (filename):
        return mimetypes.guess_type (filename)[0] or 'application/octet-stream'

    def encode_field (field_name):
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"' % field_name,
                '', str (data [field_name]))

    def encode_file (field_name):
        filename = files [field_name]
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),
                'Content-Type: %s' % get_content_type(filename),
                '', open (filename, 'rb').read ())

    lines = []
    for name in data:
        lines.extend (encode_field (name))
    for name in files:
        lines.extend (encode_file (name))
    lines.extend (('--%s--' % boundary, ''))
    body = '\r\n'.join (lines)

    headers = {'content-type': 'multipart/form-data; boundary=' + boundary,
               'content-length': str (len (body))}

    return body, headers

def send_post (url, data, files):
    req = urllib2.Request (url)
    connection = httplib.HTTPConnection (req.get_host ())
    connection.request ('POST', req.get_selector (),
                        *encode_multipart_data (data, files))
    response = connection.getresponse ()
    logging.debug ('response = %s', response.read ())
    logging.debug ('Code: %s %s', response.status, response.reason)

def make_upload_file (server, thread, delay = 15, message = None,
                      username = None, email = None, password = None):

    delay = max (int (delay or '0'), 15)

    def upload_file (path, current, total):
        assert isabs (path)
        assert isfile (path)

        logging.debug ('Uploading %r to %r', path, server)
        message_template = string.Template (message or default_message)

        data = {'MAX_FILE_SIZE': '3145728',
                'sub': '',
                'mode': 'regist',
                'com': message_template.safe_substitute (current = current, total = total),
                'resto': thread,
                'name': username or '',
                'email': email or '',
                'pwd': password or random_string (20),}
        files = {'upfile': path}

        send_post (server, data, files)

        logging.info ('Uploaded %r', path)
        rand_delay = random.randint (delay, delay + 5)
        logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)
        time.sleep (rand_delay)

    return upload_file

def upload_directory (path, upload_file):
    assert isabs (path)
    assert isdir (path)

    matching_filenames = []
    file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)

    for dirpath, dirnames, filenames in os.walk (path):
        for name in filenames:
            file_path = join (dirpath, name)
            logging.debug ('Testing file_path %r', file_path)
            if file_matcher.search (file_path):
                matching_filenames.append (file_path)
            else:
                logging.info ('Ignoring non-image file %r', path)

    total_count = len (matching_filenames)
    for index, file_path in enumerate (matching_filenames):
        upload_file (file_path, index + 1, total_count)

def run_upload (options, paths):
    upload_file = make_upload_file (**options)

    for arg in paths:
        path = abspath (arg)
        if isdir (path):
            upload_directory (path, upload_file)
        elif isfile (path):
            upload_file (path)
        else:
            logging.error ('No such path: %r' % path)

    logging.info ('Done!')
```
```


q:
In Prototype I can show a "loading..." image with this code:

var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars,
onLoading: showLoad, onComplete: showResponse} );

function showLoad () {
    ...
}

In jQuery, I can load a server page into an element with this:

$('#message').load('index.php?pg=ajaxFlashcard');

but how do I attach a loading spinner to this command as I did in Prototype?

[A]
There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.
```
```
$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;
```
```
The ajaxStart/Stop functions will fire whenever you do any Ajax calls.
Update
: As of jQuery 1.8, the documentation states that
```
.ajaxStart/Stop
```
should only be attached to
```
document
```
. This would transform the above snippet to:
```
```
var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });
```
```


q:
My team is developing a new service oriented product with a web front-end.  In discussions about what technologies we will use we have settled on running a JBoss application server, and Flex frontend (with possible desktop deployment using Adobe AIR), and web services to interface the client and server.

We've reached an impasse when it comes to which server technology to use for our business logic.  The big argument is between EJB3 and Spring, with our biggest concerns being scalability and performance, and also maintainability of the code base.

Here are my questions:

What are the arguments for or against EJB3 vs Spring?

What pitfalls can I expect with each?

Where can I find good benchmark information?

[A]
I would definitely recommend EJB3 over spring. We find that it's more streamlined, nicer to code in, and better supported. I have in the past used Spring and found it to be very confusing, and not as well documented as EJB3 (or JPA I guess at the end of the day)
As of EJB3 you no longer have to deal with external config files, and there's only one POJO that you annotate per database table. This POJO can be passed to your web tier without any problems. IDEs like Netbeans can even auto-generate these POJOs for you. We've used EJB3 now as the back end for quite a few large scale applications, and haven't noticed any performance problems.
Your Session Beans can be easily exposed as web services which you could expose to your Flex frontend.
Session beans are easy to lock down at either a method or class level to assign roles and things like that if you need to.
I can't speak that much about spring, as I only tried it out for a few weeks. But my overall impression of it was very poor. That doesn't mean it's bad framework, but our team here has found EJB3 to be the best for the persistence/business layer.


q:
When trying to use libxml2 as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.

I have installed python25 and all libxml2 and libxml2-py25 related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo?

[A]
Check your path by running:
```
```
'echo $PATH'
```
```


q:
So, I am kinda new to ASP.net development still, and I already don't like the stock ASP.net controls for displaying my database query results in table format. (I.e. I would much rather handle the HTML myself and so would the designer!)

So my question is: What is the best and most secure practice for doing this without using ASP.net controls? So far my only idea involves populating my query result during the Page_Load event and then exposing a DataTable through a getter to the *.aspx page. From there I think I could just iterate with a foreach loop and craft my table as I see fit.

[A]
I believe you're looking for a
```
<Repeater>
```
control.  It contains some functionality similar to the GridViews, but allows you hand-craft all of the HTML for the Header, Item, and Footers yourself.  Simply call the databinding code as you would for a gridview, and change the ASPX page to suit your exact HTML needs.
http://msdn.microsoft.com/en-us/magazine/cc163780.aspx


q:
1, Create and build a default Windows Forms project and look at the project properties. It says that the project is targetting .NET Framework 2.0.

2, Create a Setup project that installs just the single executable from the Windows Forms project.

3, Run that installer and it always says that it needs to install .NET 3.5 SP1 on the machine. But it obviously only really needs 2.0 and so I do not want customers to be forced to install .NET 3.5 when they do not need it. They might already have 2.0 installed and so forcing the upgrade is not desirable!

I have looked at the prerequisites of the setup project and checked the .NET Framework 2.0 entry and all the rest are unchecked. So I cannot find any reason for this strange runtime requirement. Anybody know how to resolve this one?

[A] Even if you are targetting a 2.0 deployment, some of your assemblies might require 3.5.  For instance, LINQ requires 3.0.  This should, however, be reflected when you build.  Check each assembly to ensure that it's 2.0 compatible.  You don't want any 3.5 things sneaking in.  If this is the case, my guess would be a 3rd party control library with support for WPF.


q:
I am a C++/C# developer and never spent time working on web pages.  I would like to put text (randomly and diagonally perhaps) in large letters across the background of some pages.  I want to be able to read the foreground text and also be able to read the "watermark".  I understand that is probably more of a function of color selection.

I have been unsuccessful in my attempts to do what I want.  I would imagine this to be very simple for someone with the web design tools or html knowledge.

[A]
You could make an image with the watermark and then set the image as the background via css.
For example:
```
```

this is some text with the watermark as the background.

```
```
That should work.


q:
I have the following code snippet.

$items['A'] = "Test";
$items['B'] = "Test";
$items['C'] = "Test";
$items['D'] = "Test";

$index = 0;
foreach($items as $key => $value)
{
    echo "$index is a $key containing $value\n";
    $index++;
}

Expected output:

0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test

Is there a  way to leave out the $index variable?

[A]
Your $index variable there kind of misleading. That number isn't the index, your "A", "B", "C", "D" keys are. You can still access the data through the numbered index $index[1], but that's really not the point. If you really want to keep the numbered index, I'd almost restructure the data:
```
$items[] = array("A", "Test");
$items[] = array("B", "Test");
$items[] = array("C", "Test");
$items[] = array("D", "Test");

foreach($items as $key => $value) {
    echo $key.' is a '.$value[0].' containing '.$value[1];
}
```


q: I've seen this done in Borland's Turbo C++ environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?

[A]
In Windows Forms, set the control's AllowDrop property, then listen for DragEnter event and DragDrop event.
When the
```
DragEnter
```
event fires, set the argument's
```
AllowedEffect
```
to something other than none (e.g.
```
e.Effect = DragDropEffects.Move
```
).
When the
```
DragDrop
```
event fires, you'll get a list of strings. Each string is the full path to the file being dropped.


q:
This is re-posted from something I posted on the DDD Yahoo! group.

All things being equal, do you write phone.dial(phoneNumber) or phoneNumber.dialOn(phone)? Keep in mind possible future requirements (account numbers in addition to phone numbers, calculators in addition to phones).

The choice tends to illustrate how the idioms of Information Expert, Single Responsibility Principle, and Tell Don't Ask are at odds with each other.

phoneNumber.dialOn(phone) favors Information Expert and Tell Don't Ask, while phone.dial(phoneNumber) favors Single Responsibility Principle.

If you are familiar with Ken Pugh's work in Prefactoring, this is the Spreadsheet Conundrum; do you add rows or columns?

[A]
```
phone.dial()
```
, because it's the phone that does the dialing.
Actor.Verb( inputs ) -> outputs.


q:
I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer.

Here is my regex: "\w+ +\w+ *\(.*\) *\{"

For those who do not know what a java method looks like I'll provide a basic one:

int foo()
{

}

There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have.

Update:
My current Regex is "\w+ +\w+ *\([^\)]*\) *\{" so as to prevent the situation that Mike and adkom described.

[A]
Have you considered matching the actual possible keywords?  such as:
```
```
(?:(?:public)|(?:private)|(?:static)|(?:protected)\s+)*
```
```
It might be a bit more likely to match correctly, though it might also make the regex harder to read...


q: Is it possible in C# to have a Struct with a member variable which is a Class type?  If so, where does the information get stored, on the Stack, the Heap, or both?

[A]
Yes, you can.  The pointer to the class member variable is stored
on the stack
with the rest of the struct's values, and the class instance's data is stored on the heap.
Structs can also contain class definitions as members (inner classes).
Here's some really useless code that at least compiles and runs to show that it's possible:
```
```
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyStr m = new MyStr();
            m.Foo();

            MyStr.MyStrInner mi = new MyStr.MyStrInner();
            mi.Bar();

            Console.ReadLine();
        }
    }

    public class Myclass
    {
        public int a;
    }

    struct MyStr
    {
        Myclass mc;

        public void Foo()
        {
            mc = new Myclass();
            mc.a = 1;
        }

        public class MyStrInner
        {
            string x = "abc";

            public string Bar()
            {
                return x;
            }
        }
    }
}
```
```


q: How do I create class (i.e. static) variables or methods in Python?

[A]
Variables declared inside the class definition, but not inside a method are class or static variables:
```
```
>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3
```
```
As @
millerdev
points out, this creates a class-level
```
i
```
variable, but this is distinct from any instance-level
```
i
```
variable, so you could have
```
```
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
```
```
This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.
See
what the Python tutorial has to say on the subject of classes and class objects
.
@Steve Johnson has already answered regarding
static methods
, also documented under
"Built-in Functions" in the Python Library Reference
.
```
```
class C:
    @staticmethod
    def f(arg1, arg2, ...): ...
```
```
@beidy recommends
classmethod
s over staticmethod, as the method then receives the class type as the first argument.


q:
Suppose I have:

Toby

Tiny

Tory

Tily

Is there an algorithm that can easily create a list of common characters in the same positions in all these strings?  (in this case the common characters are 'T' at position 0 and 'y' at position 3)

I tried looking at some of the algorithms used for DNA sequence matching but it seems most of them are just used for finding common substrings regardless of their positions.

[A]
Finding a list of characters that are common in ALL strings at a certain position is trivially simple.  Just iterate on each string for each character position 1 character position at a time.  If any string's character is not the match of it's closest neighbor string's character, then the position does not contain a common character.
For any i = 0 to length -1... Once you find Si[x] != Si+1[x] you can skip to the next position x+1.
Where Si is the ith string in the list.  And [x] is the character at position x.


q:
Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN":

Clipboard.SetText(str);

This usually occurs the first time the Clipboard is used in the application and not after that.

[A]
Actually, I think this is the
fault of the Win32 API
.
To set data in the clipboard, you have to
open it
first.  Only one process can have the clipboard open at a time.  So, when you check, if another process has the clipboard open
for any reason
, your attempt to open it will fail.
It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you.  The only solution is to wait until Terminal Services closes the clipboard and try again.
It's important to realize that this is not specific to Terminal Services, though: it can happen with anything.  Working with the clipboard in Win32 is a giant race condition.  But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem.


q:
I'm using SQL Server 2000 to print out some values from a table using PRINT.  With most non-string data, I can cast to nvarchar to be able to print it, but binary values attempt to convert using the bit representation of characters.  For example:

DECLARE @binvalue binary(4)
SET @binvalue = 0x12345678
PRINT CAST(@binvalue AS nvarchar)

Expected:

0x12345678

Instead, it prints two gibberish characters.

How can I print the value of binary data?  Is there a built-in or do I need to roll my own?

Update: This isn't the only value on the line, so I can't just PRINT @binvalue.  It's something more like PRINT N'other stuff' + ???? + N'more stuff'.  Not sure if that makes a difference: I didn't try just PRINT @binvalue by itself.

[A]
```
```
DECLARE @binvalue binary(4)
SET @binvalue = 0x61000000
PRINT @binvalue
PRINT cast('a' AS binary(4))
PRINT cast(0x61 AS varchar)
```
```
Do not cast.
Casting converts the binary to text by value on the corresponding collation setting for the specific database.
[Begin Edit]
If you need the printed value in a string variable use the function suggested by Eric Z Beard.
```
```
DECLARE @mybin1 binary(16)
DECLARE @s varchar(100)
SET @mybin1 = 0x098F6BCD4621D373CADE4E832627B4F6
SET @s = 'The value of @mybin1 is: ' + sys.fn_varbintohexsubstring(0, @mybin1,1,0)
PRINT @s
```
```
If this function is not at your disposal due to server versions or because it needs special permissions, you can create your own function.
To see how that function was implemented in SQL Server 2005 Express edition you can execute:
```
```
sp_helptext 'fn_varbintohexsubstring'
```
```


q: What is the best solution of defaultButton and "Enter key pressed" for ASP.NET 2.0-3.5 forms?

[A]
Just add the "defaultbutton" attribute to the form and set it to the ID of the button you want to be the default.
```
<form defaultbutton="button1" runat="server">
    <asp:textbox id="textbox1" runat="server"/>
    <asp:button id="button1" text="Button1" runat="server"/>
</form>
```
NOTE: This only works in ASP.NET 2.0+


q: I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?

[A]
Opening sockets in python is pretty simple. You really just need something like this:
```
```
import socket
sock = socket.socket()
sock.connect((address, port))
```
```
and then you can
```
send()
```
and
```
recv()
```
like any other socket


q:
How does the compiler know the prototype of sleep function or even printf function, when I did not include any header file in the first place?

Moreover, if I specify sleep(1,1,"xyz") or any arbitrary number of arguments, the compiler still compiles it.
But the strange thing is that gcc is able to find the definition of this function at link time, I don't understand how is this possible, because actual sleep() function takes a single argument only, but our program mentioned three arguments.

/********************************/
int main()
{
 short int i;
 for(i = 0; i<5; i++)
 {
    printf("%d",i);`print("code sample");`
    sleep(1);
 }
 return 0;
}

[A]
C will guess int for unknown types.  So, it probably thinks sleep has this prototype:
```
```
int sleep(int);
```
```
As for giving multiple parameters and linking...I'm not sure.  That does surprise me.  If that really worked, then what happened at run-time?


q:
How can you measure the amount of time a function will take to execute?

This is a relatively short function and the execution time would probably be in the millisecond range.

This particular question relates to an embedded system, programmed in C or C++.

[A]
```
```
start_time = timer
function()
exec_time = timer - start_time
```
```


q: I have a personal pet project I'd like to start on, targeted at windows mobile 6.  I've never done win mobile dev and would like to know what resources are out there, good tools to use, perhaps a jump start tutorial, as well as any gotchas I might want to keep in mind when developing for the platform?

[A]
Depending on the scale of the project, look at .NET compact framework. If you're familiar at all Visual Studio then it's pretty easy to get started. Of course MSDN is the place for resources.
Running managed code on a mobile device does take a big performance hit, but for a small personal project it's pretty good.
Also, most devices have all sorts of odd and weird quirks as well as strange hardware configurations. Look for any sort of developer program from the maker of your device.


q:
Say I have a line in an emacs buffer that looks like this:

foo -option1 value1 -option2 value2 -option3 value3 \
    -option4 value4 ...

I want it to look like this:

foo -option1 value1 \
    -option2 value2 \
    -option3 value3 \
    -option4 value4 \
    ...

I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region.

Anybody know of an elisp function to do this?

[A]
In this case I would use a macro.  You can start recording a macro with C-x (, and stop recording it with C-x ).  When you want to replay the macro type C-x e.
In this case, I would type, C-a C-x ( C-s v a l u e C-f C-f \ RET SPC SPC SPC SPC C-x )
That would record a macro that searches for "value", moves forward 2, inserts a slash and newline, and finally spaces the new line over to line up.  Then you could repeat this macro a few times.
EDIT: I just realized, your literal text may not be as easy to search as "value1".  You could also search for spaces and cycle through the hits.  For example, hitting, C-s a few times after the first match to skip over some of the matches.
Note: Since your example is "ad-hoc" this solution will be too.  Often you use macros when you need an ad-hoc solution.  One way to make the macro apply more consistently is to put the original statement all on one line (can also be done by a macro or manually).
EDIT: Thanks for the comment about ( versus C-(, you were right my mistake!


q:
I'm using a Java socket, connected to a server.
If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?

I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only.

[A]
You can use time and curl and time on the command-line.  The -I argument for curl instructs it to only request the header.
```
```
time curl -I 'http://server:3000'
```
```


q: I have an array of objects that when another object hits one of them, the object will be removed. I have removed it from the stage using removeChild() and removed from the array using splice(), but somehow the object is still calling some of its functions which is causing errors. How do I completely get rid of an object? There are no event listeners tied to it either.

[A]
It sounds like you may be running into a garbage collection issue with the flash player.
A new API has been added to Flash Player 10 that should address this:
unloadAndStop()
Grant Skinner has more info on this on his blog:
http://www.gskinner.com/blog/archives/2008/07/unloadandstop_i.html
You can grab a beta of Flash Player 10 at:
http://labs.adobe.com/technologies/flashplayer10/
mike chambers
mesh@adobe.com


q: How can I split long commands over multiple lines in a batch file?

[A]
You can break up long lines with the caret
```
^
```
as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space.
(
More on that below.
)
Example:
```
```
copy file1.txt file2.txt
```
```
would be written as:
```
```
copy file1.txt^
 file2.txt
```
```


q:
When attempting to print using the SSRS Viewer Web Part in SharePoint I get the following error.

An error occured during printing. (0x8007F303)

The settings we are using in this box (production) are exactly the same as the settings in testing where this works perfectly fine.

Anyone have any good ideas or faced this before?

[A]
I found some ideas by Googling.
Someone had issue with "SSRS server configured for Sharepoint Integrated mode with Cumulative update package 3 for SQL Server 2005 Service Pack 2" but "the problem vanished after installing the .NET framework 3.0 SP1"
You can get this error if you have
"old instances of the old
ReportViewer control in your web sites bin directories or anywhere else it
could be accessed by your web application."
It's another error 0x800C0005, but there is
an incident where the error only occurred in production environment
. bradsy@Microsoft says
You can enable Client print logging by
  setting the follow reg key. Once
  enabled, you can look in your print
  users temporary (cd %temp%) directory
  and find a print log file. Windows
Registry Editor Version 5.00
```
[HKEY_CURRENT_USER\Software\Microsoft\Microsoft SQL Server\80\Reporting Services]
```
```
"LogRSClientPrintInfo"=dword:00000001
```
You can send the log file to me and I
  can take a look to see if there is any
  extra information.
Maybe you should collect the log and send it to the forum.


q:
We have a web application that uses SQL Server 2008 as the database. Our users are able to do full-text searches on particular columns in the database. SQL Server's full-text functionality does not seem to provide support for hit highlighting. Do we need to build this ourselves or is there perhaps some library or knowledge around on how to do this?

BTW the application is written in C# so a .Net solution would be ideal but not necessary as we could translate.

[A]
You might be missing the point of the database in this instance.  Its job is to return the data to you that satisfies the conditions you gave it.  I think you will want to implement the highlighting probably using regex in your web control.
Here is something a quick search would reveal.
http://www.dotnetjunkies.com/PrintContent.aspx?type=article&id=195E323C-78F3-4884-A5AA-3A1081AC3B35


q: Can someone describe what a symbol table is within the context of C and C++?

[A]
Briefly, it is the mapping of the name you assign a variable to its address in memory, including metadata like type, scope, and size. It is used by the compiler.
That's in general, not just C[++]*. Technically, it doesn't always include direct memory address. It depends on what language, platform, etc. the compiler is targeting.