q:
When commiting to SVN I can add a top level commit message to detail what is being committed, but I would ideally like  a means to comment on the individual files and what has changed within them. I have seen something similar in previous employment, but this was using CVS (and I can't recall whether this was achieved with a home brew script to produce the skeleton file)

I have had a look at changelists but again I don't think (although i am willing to be proved wrong) that this gives the kind of granularity as outlined below.

Ideally I am looking for something along the lines of:

Foo.vb

Added new function bar

Bar.vb

Removed function foo

Added functionality in xyz to do abc
  +/- Modified function to log error

[A]
I would just do this in the individual commit message.
TortoiseSVN
has filename autocompletion so that greatly aids in this.
Another thing you could do is svn st before you commit and copy/paste the filenames into your commit message.
Oh, and be sure to strongly question the value of this. I know some OSS projects (linux?) require this sort of fidelity, but for many projects this is just noise. Diff can tell you much more than this, and more accurately.
One other thing you may want to consider is using
Git
. Git allows you to commit locally, in smaller steps. You then push to the master server all of your commits individually or squashed into a single commit w/ all the commit messages in a single message. That was a way simplified explanation, but it probably is worth checking out.


q:
I am a big fan of the light colors on a dark background color scheme for programming - which is unfortunately  not what Quest's Toad comes with by default.

I notice that it is possible to export and import settings under the language management window, and I know that Toad has a large level of community involvement.  So I assume there must be some location where people are posting their custom coloring schemes.  However, in part because I don't know what the Toad guys call them (skins? colorization? themes?) and in part because its so hard to Google Toad +skins I cannot for the life of me find them.

Does anyone know if there is such a place so I don't have to set the colors by hand?

[A]
UPDATED ENTIRELY:
What's the official name?
The file extension (
```
.dvtcolortheme
```
) suggests
```
"Color Theme"
```
or
```
"DWT Color Theme"
```
are the official names. Most users on Toad forums seem to use the same terminology.
Where are they shared?
There does not seem to be a dedicated site for sharing color themes. However, there were a couple forums on
ToadWorld
, and
ToadForOracle
where folks were talking about swapping these color theme files. I would suggest hopping on the forum and asking if others have files to share or know of any repository sites.
Available Color Themes
* Nocturnal theme on GitHub:
https://github.com/grng/Nocturnal-Toad-Color-Scheme
* A nice dark-background theme:
http://toadfororacle.com/thread.jspa?messageID=93203
Rolling-your-own
I know you did not want to create your own, but it looks a lot easier than either of us expected. The
```
.dwtcolortheme
```
settings file is just XML.
I suggest visiting
http://studiostyl.es/
- as it's a large repository of Visual Studio themes. Find a thumbnail you like, take a screen shot, and use a color picker to capture the values. Plop them in your XML settings file and you are ready to go.

s: huggingface

c: devops

d: intermediate


q:
Within an XSLT document, is it possible to loop over a set of files in the current directory?

I have a situation where I have a directory full of xml files that need some analysis done to generate a report.  I have my stylesheet operating on a single document fine, but I'd like to extend that without going to another tool to merge the xml documents.

I was thinking along these lines:

<xsl:for-each select="{IO Selector Here}">
    <xsl:variable select="document(@url)" name="contents" />
    <!--More stuff here-->
</xsl:for-each>

[A]
I don't think XSL is set up to work that way: it's designed to be used by something else on one or more documents, and the something else would be responsible for finding files to which the XSLT should be applied.
If you had one main document and a fixed set of supporting documents, you could possibly use the
```
document()
```
function
to return specific nodes and/or values, but I suspect your case is different.


q: What are some of the advantages of using one over the other?

[A] Biggest single advantage for me would be the clear-cut separation between your Model, View, and Controller layers. It helps promote good design from the start.


q:
What's the best way to shut down the computer from a C# program?

I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.

[A]
You can launch the shutdown process:
```
shutdown -s -t 0
```
- Shutdown
```
shutdown -r -t 0
```
- Restart


q: I'm working on a drop in assembly that has predefined pages and usable controls.  I am having no difficulties with creating server controls, but I'm wondering what the "best practices" are with dealing with pages in an assembly.  Can you compile a page into an assembly and release it as just a dll?  How would this be accessed from the client browser's perspective as far as the address they would type or be directed to with a link?  As an example, I have a simple login page with the standard username and password text boxes, and the log in button and a "remember me" checkbox, with a "I can't remember my username and/or password" hyperlink. Can I access that page as like a webresource?  such as "http://www.site.name/webresource.axd?related_resource_id_codes"

[A]
You can add an httpHandler element to web.config pointing to your page. Something like:
```
```
<httpHandlers>
   <add verb="*" path="login.aspx" type="MyPages.LoginPage, MyPages" />
</httpHandlers>
```
```


q:
In my database (SQL 2005) I have a field which holds a comment but in the comment I have an id and I would like to strip out just the id, and IF possible convert it to an int:

activation successful of id 1010101

The line above is the exact structure of the data in the db field.

And no I don't want to do this in the code of the application, I actually don't want to touch it, just in case you were wondering ;-)

[A]
```
```
-- Test table, you will probably use some query
DECLARE @testTable TABLE(comment VARCHAR(255))
INSERT INTO @testTable(comment)
    VALUES ('activation successful of id 1010101')

-- Use Charindex to find "id " then isolate the numeric part
-- Finally check to make sure the number is numeric before converting
SELECT CASE WHEN ISNUMERIC(JUSTNUMBER)=1 THEN CAST(JUSTNUMBER AS INTEGER) ELSE -1 END
FROM (
       select right(comment, len(comment) - charindex('id ', comment)-2) as justnumber
       from @testtable) TT
```
```
I would also add that this approach is more set based and hence more efficient for a bunch of data values.  But it is super easy to do it just for one value as a variable.  Instead of using the column comment you can use a variable like
```
@chvComment
```
.


q:
Below is part of the XML which I am processing with PHP's XSLTProcessor:

<result>
    <uf x="20" y="0"/>
    <uf x="22" y="22"/>
    <uf x="4" y="3"/>
    <uf x="15" y="15"/>
</result>

I need to know how many "uf" nodes exist where x == y.

In the above example, that would be 2.

I've tried looping and incrementing a counter variable, but I can't redefine variables.

I've tried lots of combinations of xsl:number, with count/from, but couldn't get the XPath expression right.

Thanks!


q: I am looking for a way to have some control over the shape of a simple MessageBox in Winforms. I would like to control where the passed in text wraps so that the dialog rect is narrower. Windows seems to want to make the dialog as wide as possible before wrapping the text. Is there an easy way to control the maximum width of the dialog without resorting to creating my own custom form?

[A]
You can embed newlines in the text to force it to wrap at a certain point. e.g.
```
```
"message text...\nmore text..."
```
```
update: I posted that thinking it was a win32 API question, but I think the principle should still apply. I assume WinForms eventually calls MessageBox().


q: So essentially does margin collapsing occur when you don't set any margin or padding or border to a given div element?

[A]
"the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin."
Source:
Box Model - 8.3.1 Collapsing margins


q:
I'm looking to run a Jabber server on a Windows 2003 server(web farm) and like some practical advice from anyone who has run a live environment with ~500 concurrent users.

Criteria for comment:

Performance

Capacity (ie ~number of concurrent users)

Stability

[A]
I think you're going to need to be a bit more explicit - you looking for server configurations, or software e.g. Jabber Server?
If you're thinking Jabber server,
EJabberD
is probably the most stable, flexible, capable of being clustered etc.
Really useful comparison of Open Source servers here...
http://www.saint-andre.com/jabber/jsc/


q:
I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout.  This obviously isn't great for maintainability.  Generally, when I design a site I pick 3-5 main colours for a theme.  I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted.  How do you avoid this?  I was thinking of creating separate rules for each colour and just use those when I need to restyle.

i.e.

.color1 {
    color: #3d444d;
}

[A]
You could have a colours.css file with just the colours/images for each tag in.
Then you can change the colours just by replacing the file, or having a dynamically generated CSS file, or having different CSS files available and selecting based upon website URL/subfolder/property/etc.
Or you can have colour tags as you write, but then your HTML turns into:

Blah

CSS should have a feature where you can define values for things like colours that you wish to be consistent through a style but are defined in one place only. Still, there's search and replace.


q: I haven't used Visual Studio since VB 3 and am trying to give it a shot with ASP.NET. It seems that it should be able to connect to a website (via some sort of ftp like protocol I figure) and allow to edit without having to manually upload/download the files. Is this the way it is supposed to work or am I mis-understanding? I have tried using 'create new website' and 'open website' using my testing domain (hosted by godaddy, wondering if that may be the issue as well), each time it gives me errors. I'm not sure if I'm doing something wrong or trying to do something it wasn't meant to.

[A]
You really don't want to be working directly on a live web site, do you?  That's just crazy.  One little mistake and you've hosed the site.
Visual Studio now has it's own built in web server.  You use that for testing.  If you really don't want to use that you can put IIS on your local machine or set up a Dev/QA server somewhere.  In that case, you'd edit it via a file share.
You should be using some kind of source control.  Even for a single developer it's very important.  When finished with a programming session, you check your updates back into source control.
Finally, only after the site's gone through a suitable QA process, the production server is updated from source control, not from within visual studio.


q:
I need to create a PRIVATE message queue on a remote machine and I have resolved to fact that I can't do this with the .NET Framework in a straight forward manner.  I can create a public message queue on a remote machine, but not a PRIVATE one. I can create a message queue (public or private) locally.

I am wondering if anyone knows how to access MSMQ through WMI.

Edit: I don't see anything to do it with using the MSMQ Provider. May have to get tricky and use PSExec to log onto a remote server and execute some code.

[A]
A blog post about MSMQ and WMI is here:
http://msmq.spaces.live.com/blog/cns!393534E869CE55B7!210.entry
It says there is a provider here:
http://www.msmq.biz/Blog/MSMQWmiSetup.msi
It also says there is a reference here:
http://www.msmq.biz/Blog/MSMQ%20WMI%20Provider%20Objects.doc
Hope this helps.


q:
I need to retrieve a record from a database, display it on a web page (I'm using ASP.NET) but store the ID (primary key) from that record somewhere so I can go back to the database later with that ID (perhaps to do an update).

I know there are probably a few ways to do this, such as storing the ID in ViewState or a hidden field, but what is the best method and what are the reasons I might choose this method over any others?

[A]
```
```
Session["MyId"]=myval;
```
```
It would be a little safer and essentially offers the same mechanics as putting it in the viewstate


q:
I am trying to execute some stored procedures in groovy way.  I am able to do it quite easily by using straight JDBC but this does not seem in the spirit of Grails.

I am trying to call the stored procedure as:

sql.query( "{call web_GetCityStateByZip(?,?,?,?,?)}",[params.postalcode,
sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.VARCHAR),
sql.out(java.sql.Types.INTEGER), sql.out(java.sql.Types.VARCHAR)]) { rs ->
   params.city = rs.getString(2)
   params.state = rs.getString(3)
}

I tried various ways like sql.call. I was trying to get output variable value after this.

Everytime error:

Message: Cannot register out parameter.
Caused by: java.sql.SQLException: Cannot register out parameter.
Class: SessionExpirationFilter

but this does not seem to work.

Can anyone point me in the right direction?

[A]
This is still unanswered, so I did a bit of digging although I don't fully understand the problem. The following turned up from the Groovy source, perhaps it's of some help:
This line seems to be the origin of the exception:
http://groovy.codehaus.org/xref/groovy/sql/Sql.html#1173
This would seem to indicate that you have a Statement object implementing PreparedStatement, when you need the subinterface CallableStatement, which has the registerOutParameter() method which should be ultimately invoked.


q:
Can someone please remind me how to create a .Net class from an XML file?

I would prefer the batch commands, or a way to integrate it into the shell.

Thanks!

[A]
You might be able to use the xsd.exe tool to generate a class, otherwise you probably have to implement a custom solution against your XML
XML Schema Definition Tool
XML Serialization


q:
I was reading a MS Excel help article about pivotcache and wonder what they mean by OLE DB and ODBC sources

...You should use the CommandText
  property instead of the SQL property,
  which now exists primarily for
  compatibility with earlier versions of
  Microsoft Excel. If you use both
  properties, the CommandText property’s
  value takes precedence.

For OLE DB sources, the CommandType
  property describes the value of the
  CommandText property.

For ODBC sources, the CommandText
  property functions exactly like the
  SQL property, and setting the property
  causes the data to be refreshed...

I really appreciate your short answers.

[A]
On a very basic level those are just different APIs for the different data sources (i.e. databases). OLE DB is newer and arguably better.
You can read more on both in Wikipedia:
OLE DB
ODBC
I.e. you could connect to the same database using an ODBC driver or OLE DB driver. The difference in the database behaviour in those cases is what your book refers to.


q: How do you enumerate the fields of a certificate help in a store. Specifically, I am trying to enumerate the fields of personal certificates issued to the logged on user.

[A]
See
http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx
```
```
using System.Security.Cryptography.X509Certificates;
...
var store = new X509Store(StoreName.My);
foreach(var cert in store.Certificates)
...
```
```


q:
Is there a good Eclipse plugin for recording and playing back macros?

I've tried this one, but it didn't do me any good- it seemed like it wasn't ready for prime time.

I know about editor templates, but I'm looking for something that I can use to record my keystrokes and then apply multiple times against a wad of text.

This seems like a strange hole in an IDE. Am I missing some built-in facility for this?

[A]
This seems like a strange hole in an IDE, am I missing some builtin facility for this?
This is a common problem. There are around four bugs opened in Eclipse tracker for this. Unfortunately you would probably see macros in Eclipse in v4.0 or later.


q: Speaking entirely in technology-free terms, what is the best way to make a mobile friendly site?  That is, I want to make a site that will work on a regular computer but also have mobile versions of the pages.  Should I rewrite each page?  The pages will probably have different functionality, so should I rewrite the backend code?  Should it be an effectively different site with the same database?

[A]
I added a mobile presentation layer to an operational site about a year ago. Based on the architecture of the site (hopefully this isn't too technology dependent for you) I added a new set of JSPs to accommodate mobile browsers (sidenote: see
http://wurfl.sourceforge.net/
for a great way to build mobile pages independent of browser type). Additionally some of the back-end functionality was changed due to the limited functionality of most mobile browsers. So, in short, the integration wasn't as painful as one would expect.
Good luck!


q: From managed C++, I am calling an unmanaged C++ method which returns a double. How can I convert this double into a managed string?

[A]
C++ is definitely not my strongest skillset.  Misread the question, but this should convert to a std::string, not exactly what you are looking for though, but leaving it since it was the original post....
```
```
double d = 123.45;
std::ostringstream oss;
oss << d;
std::string s = oss.str();
```
```
This should convert to a managed string however..
```
```
double d = 123.45
String^ s = System::Convert::ToString(d);
```
```


q:
Do you use Luabind, toLua++, or some other library (if so, which one) or none at all?

For each approach, what are the pro's and con's?

[A]
To answer my own question in part:
Luabind: once you know how to bind methods and classes via this awkward template syntax, it's pretty straightforward and easy to add new bindings. However, luabind has a significant performance impact and shouldn't be used for realtime applications. About 5-20 times more overhead than calling C functions that manipulate the stack directly.


q: I've been playing around with OpenGL ES development on Android. OpenGL ES applications seem to run slowly in the Emulator on my development machine. Does this reflect likely performance of actual hardware? I'm concerned about spending too much time developing an application if the graphics performance is going to be sluggish.

[A]
The emulator is super slow on my
```
Mobile Intel Pentium M 725, 1600 MHz
```
.
I'm assuming the emulator isn't representative of real world performance.


q:
I'm using managed c++ to implement a method that returns a string. I declare the method in my header file using the following signature:

String^ GetWindowText()

However, when I'm using this method from C#, the signature is:

string GetWindowTextW();

How do I get rid of the extra "W" at the end of the method's name?

[A]
To get around the preprocessor hackery of the Windows header files, declare it like this:
```
```
#undef GetWindowText
String^ GetWindowText()
```
```
Note that, if you actually use the Win32 or MFC
```
GetWindowText()
```
routines in your code, you'll need to either redefine the macro or call them as
```
GetWindowTextW()
```
.


q:
I've got an open-source app that is hosted at code.google.com. It is cross platform ( Linux / Windows / Mac ). I uploaded the code initially from a WinXP machine using TortoiseSVN and it seems that none of the "configure" batch files that are used for the linux build have their "execute" bits set.

What would be the easiest way to set these for the files that need them? Using TortoiseSVN would be easier, I suppose, but if that can't be used, then I could also use the command line SVN on my linux machine.

[A]
Here's how to do it on the command line:
```
```
for file in `find . -name configure`; do
  svn ps svn:executable yes ${file}
done
```
```
Or for just one file (
```
configure
```
is the filename here):
```
```
svn ps svn:executable yes configure
```
```


q:
In SharePoint, it is easy to set up a List webpart consisting of Links to other documents, folders, sites, etc.  Unfortunately, when clicking these links, the default behavior is for the page to open in the current browser window.  That is, it does NOT open the page in a new instance of the browser.  This has proven annoying for a number of the users on my site.

Does anyone know of a way to have the default behavior be to open in a NEW browser window?

I'm hoping this is something that can be set in SharePoint rather than having users need to adjust some sort of setting in their browser.

[A]
It is not possible with the default Link List web part, but there are resources describing how to extend Sharepoint server-side to add this functionality.
Share Point Links Open in New Window
Changing Link Lists in Sharepoint 2007


q:
When attempting to call functions in math.h, I'm getting link errors like the following

undefined reference to sqrt

But I'm doing a #include <math.h>

I'm using gcc and compiling as follows:

gcc -Wall -D_GNU_SOURCE blah.c -o blah

Why can't the linker find the definition for sqrt?

[A]
You need to link the math library explicitly. Add
```
-lm
```
to the flags you're passing to gcc so that the linker knows to link
```
libm.a
```


q:
Years ago I created a programming collaboratory in Diversity University MOO -- a room written in MOOcode that used TCP/IP to communicate with a perl server back at my campus to compile and execute C, Perl, Bash and other programs and return results to the MOO collaboratory -- all for demonstrating programming languages in a MOO teaching environment.  The application is usually a romp in five or six languages and fun to play with.  Now I'd like to do the same thing in SecondLife using LSL. The only suggestion I've gotten so far from that crowd is to use a WWW request, presumeably constructing an http POST message to a CGI process.  I never cared much for html forms so I'd rather use TCP/IP or some other communications protocol.  Has anyone tried this who'd care to provide a few hints?  There are several good LSL demo sites in SecondLife but I'd like to demo other compiler and script languages, maybe even PowerShell.
Dick S.

[A]
REST
is now in fashion for web services. There is no real reason to get down to TCP/IP layer for something which from your description does not require super performance or response times. LSL HTTP support is quite good so you should not have any problems.
Of course it is not ideal to get the output of your programs back in real-time - for that you would need to open http connection on the server and constantly write to the body of the page (while the client would read that). But even with going back and forth between the server and the client you should get moderately good experience.


q:
Is there an easy way of finding out the host name of a machine that generated a user mode dump file via WinDbg?

Or at least any piece of identifying information to try and confirm that two dump files came from the same system.

[A]
From debugger.chm:
Finding the Computer Name in a Kernel-Mode Dump File
If you need to determine the name of the computer on which the crash dump was made, you can use the !peb extension and look for the value of COMPUTERNAME it its output.
Or you can use the following command:
```
```
0: kd> x srv!SrvComputerName
be8ce2e8  srv!SrvComputerName  = _UNICODE_STRING "AIGM-MYCOMP-PUB01"
```
```
Finding the IP Address in a Kernel-Mode Dump File
To determine the IP address of the computer on which the crash dump was made, find a thread stack that shows some send/receive network activity. Open one of the send packets or receive packets. The IP address will be visible in that packet.
EDIT: I will note that depending on how the dump file was created, the PEB information may not be available and so you won't
always
be able to find the computer name.  Particularly if something came through the Microsoft Winqual site, it has been sanitized.
Using the shortcut for environment variables in the PEB: !envvar COMPUTERNAME


q: I need to get the name of the machine my .NET app is running on.  What is the best way to do this?

[A]
```
System.Environment.MachineName
```


q:
I'm using start.jar and stop.jar to stop and start my jetty instance.
I restart by calling stop.jar, then start.jar.
The problem is, if I don't sleep long enough between stop.jar and start.jar I start getting these random ClassNotFoundExceptions and the application doesn't work correctly.

Sleeping for a longer period of time between stop and start is my current option.

I also heard from someone that I should have something that manages my threads so that I end those before jetty finishes.
Is this correct? The question I have about this is that stop.jar returns immediately, so it doesn't seem to help me, unless there's something I'm missing.
Another option might be to poll the log file, but that's pretty ugly.

What's the best way of restarting jetty?

Gilbert: The Ant task is definitely not a bad way of doing it.  However, it sleeps for a set amount of time, which is exactly what I'm trying to avoid.

[A]
Did you try JFGI?
Setting up Ant task that could do the work for you?
This blog post details how to setup targets that can start and stop jetty for you. You could easily cobble together another target called 'jetty-restart' which depends on 'jetty-stop' and then calls 'jetty-start'.
http://ptrthomas.wordpress.com/2006/10/10/how-to-start-and-stop-jetty-from-ant/


q: I've heard that the static_cast function should be preferred to C-style or simple function-style casting.  Is this true?  Why?

[A]
static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly defined in classes, as well as to perform standard conversions between fundamental types:
```
```
double d = 3.14159265;
int    i = static_cast<int>(d);
```
```


q:
I'm running some JUnit tests on my applications. Every test has a for loop calling respective method 10000 times.
The tested methods produce a lot of log.
These logs are also automatically collected by JUnit as test output.
This situation takes to OutOfMemoryError because the string buffer where JUnit keeps the output becomes too large.
I dont' need these logs during tests, so if there is a way to tell JUnit "don't keep program output" it would be enough.
Any ideas?

[A]
Some options:
Change your logging so that it dumps to a file instead of standard output.
Increase the maximum heap size with
```
-Xmx <some number>M
```
, like
```
-Xmx 256M
```
.


q:
If you need to open a SqlConnection before issuing queries, can you simply handle all non-Open ConnectionStates in the same way?  For example:

    if (connection.State != ConnectionState.Open)
    {
        connection.Open();
    }

I read somewhere that for ConnectionState.Broken the connection needs to be closed before its re-opened.  Does anyone have experience with this?  Thanks-

[A]
This isn't directly answering your question, but the best practice is to open and close a connection for every access to the database.  ADO.NET connection pooling ensures that this performs well.  It's particularly important to do this in server apps (e.g. ASP.NET), but I would do it even in a WinForms app that accesses the database directly.
Example:
```
```
using(SqlConnection connection = new SqlConnection(...))
{
   connection.Open();
   // ... do your stuff here

}  // Connection is disposed and closed here, even if an exception is thrown
```
```
In this way you never need to check the connection state when opening a connection.


q:
I have an ASP.net application that works fine in the development environment but in the production environment throws the following exception when clicking a link that performs a postback.  Any ideas?

Invalid postback or callback argument.
  Event validation is enabled using

  in configuration or <%@ Page
  EnableEventValidation="true" %> in a
  page.  For security purposes, this
  feature verifies that arguments to
  postback or callback events originate
  from the server control that
  originally rendered them.  If the data
  is valid and expected, use the
  ClientScriptManager.RegisterForEventValidation
  method in order to register the
  postback or callback data for
  validation.

Edit: This seems to only be happening when viewed with IE6 but not with IE7, any ideas?

[A]
It seems that the data/controls on the page are changed when the postback occurs. What happens if you turn off the event validation in the page directive.
```
```
<%@ Page ... EnableEventValidation = "false" />
```
```


q:
I have:

<?php

$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}

fclose($file);

?>

but it overwrites the beginning of the file.  How do I make it insert?

[A]
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
To insert text without over-writing the beginning of the file
, you'll have to open it for appending (
```
a+
```
rather than
```
r+
```
)
```
```
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}

fclose($file);
```
```
If you're trying to write to the start of the file
, you'll have to read in the file contents (see
```
file_get_contents
```
) first, then write your new string followed by file contents to the output file.
```
```
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
```
```
The above approach will work with small files, but you may run into memory limits trying to read a large file in using
```
file_get_conents
```
. In this case, consider using
```
rewind($file)
```
, which sets the file position indicator for handle to the beginning of the file stream.
Note when using
```
rewind()
```
, not to open the file with the
```
a
```
(or
```
a+
```
) options, as:
If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.


q:
Why was the arguments.callee.caller property deprecated in JavaScript?

It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript.  Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support.  Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable.

Is there a good reason to put this valuable functionality in limbo?

(Or alternately, is there a better way to grab a handle on the calling function?)

[A]
It is better to use
named functions
than arguments.callee:
```
```
function foo () {
     ... foo() ...
 }
```
```
is better than
```
```
function () {
     ... arguments.callee() ...
 }
```
```
The named function will have access to its caller through the
caller
property:
```
```
function foo () {
     alert(foo.caller);
 }
```
```
which is better than
```
```
function foo () {
     alert(arguments.callee.caller);
 }
```
```
The deprecation is due to current ECMAScript
design principles
.


q: I've read about and dabbled with some including active record, repository, data transfer objects.  Which is best?

[A] 'Best' questions are not really valid.  The world is filled with combination and variations.  You should start with the question that you have to answer:  What problem are you trying to solve.  After you answer that you look at the tools that work best with the issue.


q:
I'm working on a project that generates PDFs that can contain fairly complex math and science formulas.  The text is rendered in Times New Roman, which has pretty good Unicode coverage, but not complete. We have a system in place to swap in a more Unicode complete font for code points that don't have a glyph in TNR (like most of the "stranger" math symbols,) but I can't seem to find a way to query the *.ttf file to see if a given glyph is present.  So far, I've just hard-coded a lookup table of which code points are present, but I'd much prefer an automatic solution.

I'm using VB.Net in a web system under ASP.net, but solutions in any programming language/environment would be appreciated.

Edit: The win32 solution looks excellent, but the specific case I'm trying to solve is in an ASP.Net web system.  Is there a way to do this without including the windows API DLLs into my web site?

[A]
FreeType
is a library that can read TrueType font files (among others) and can be used to query the font for a specific glyph.  However, FreeType is designed for rendering, so using it might cause you to pull in more code than you need for this solution.
Unfortunately, there's not really a clear solution even within the world of OpenType / TrueType fonts; the character-to-glyph mapping has about a dozen different definitions depending on the type of font and what platform it was originally designed for.  You might try to look at the
cmap table definition
in Microsoft's copy of the
OpenType spec
, but it's not exactly easy reading.


q:
As an example, Google App Engine uses Google Datastore, not a standard database, to store data.  Does anybody have any tips for using Google Datastore instead of databases?  It seems I've trained my mind to think 100% in object relationships that map directly to table structures, and now it's hard to see anything differently.  I can understand some of the benefits of Google Datastore (e.g. performance and the ability to distribute data), but some good database functionality is sacrificed (e.g. joins).

Does anybody who has worked with Google Datastore or BigTable have any good advice to working with them?

[A]
Being rooted in the database world, a data store to me would be a giant table (hence the name "bigtable").  BigTable is a bad example though because it does a lot of other things that a typical database might not do, and yet it is still a database.  Chances are unless you know you need to build something like Google's "bigtable", you will probably be fine with a standard database.  They need that because they are handling insane amounts of data and systems together, and no commercially available system can really do the job the exact way they can demonstrate that they need the job to be done.
(bigtable reference:
http://en.wikipedia.org/wiki/BigTable
)


q:
Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately):

aspx:

<asp:Label runat="server" Text="default text" />

Code-behind (code called on an onclick event):

Label.Text = "foo";
Response.Redirect("Default.aspx");

When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks.

For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue.

[A]
ASP and ASP.Net are inherently stateless unless state is explicitly specified. Normally between PostBacks information like the value of a label is contained in the viewstate, but if you change pages that viewstate is lost because it is was being stored in a hidden field on the page.
If you want to maintain the value of the label between calls you need to use one of the state mechanisms (e.g. Session, Preferences) or communication systems (Request (GET, POST)).
Additionally you may be looking for Server.Transfer which will change who is processing the page behind the scenes. Response.Redirect is designed to ditch your current context in most cases.


q:
I know of the US GIS TIGER file format from years ago, but have never used it.

I'm very shortly going to need to very quickly implement simple geocoding and vector graphics of roads and other features.

Where do I go for information - are there tutorials, example queries, etc?

Are there other ways to include geocoding and basic mapping in a mobile (no internet) device?

-Adam

[A]
As far as I'm aware of, there aren't many applications that make use of the TIGER/Line format directly.  Most apps use TIGER files that have been translated into ESRI's shapefile format.
Edited to add:
Is there information on ESRI's format available?
There's an
ESRI whitepaper
describing the file format.
If you're planning to use shapefiles in an application, there are
various
libraries
out there.


q:
List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.

Say, I have a 2D list:

li = [[0,1,2],[3,4,5],[6,7,8]]

I would like to merge this either into one long list

li2 = [0,1,2,3,4,5,6,7,8]

or into a string with separators:

s = "0,1,2,3,4,5,6,7,8"

Really, I'd like to know how to do both.

[A]
```
```
import itertools
itertools.flatten( li )
```
```


q:
I am trying to install the ibm_db gem so that I can access DB2 from Ruby.  When I try:

sudo gem install ibm_db

I get the following request for clarification:

Select which gem to install for your platform (i486-linux)
 1. ibm_db 0.10.0 (ruby)
 2. ibm_db 0.10.0 (mswin32)
 3. ibm_db 0.9.5 (mswin32)
 4. ibm_db 0.9.5 (ruby)
 5. Skip this gem
 6. Cancel installation

I am always going to be installing the linux version (which I assume is the "ruby" version), so is there a way to pick which one I will install straight from the gem install command?

The reason this is a problem is that I need to automate this install via a bash script, so I would like to select that I want the "ruby" version ahead of time.

[A]
Try this:
```
```
sudo gem install --platform ruby ibm_db
```
```
Note that you can get help on the install command using:
```
```
gem help install
```
```
UPDATE:
Looks like this option only works for RubyGems 0.9.5 or above.


q:
I'm working on a document "wizard" for the company that I work for. It's a .dot file with a header consisting of some text and some form fields, and a lot of VBA code. The body of the document is pulled in as an OLE object from a separate .doc file.

Currently, this is being done as a Shape, rather than an InlineShape. I did this because I can absolutely position the Shape, whereas the InlineShape always appears at the beginning of the document.

The problem with this is that a Shape doesn't move when the size of the header changes. If someone needs to add or remove a line from the header due to a special case, they also need to move the object that defines the body. This is a pain, and I'd like to avoid it if possible.

Long story short, how do I position an InlineShape using VBA in Word?

The version I'm using is Word 97.

[A]
InlineShape is treated as a letter. Hence, the same technique.
```
```
ThisDocument.Range(15).InlineShapes.AddPicture "1.gif"
```
```


q:
I need to implement an in-memory tuple-of-strings matching feature in C.  There will be large list of tuples associated with different actions and a high volume of events to be matched against the list.

List of tuples:

("one", "four")
("one")
("three")
("four", "five")
("six")

event ("one", "two", "three", "four") should match list item ("one", "four") and ("one") and ("three") but not ("four", "five") and not ("six")

my current approach uses a map of all tuple field values as keys for lists of each tuple using that value.  there is a lot of redundant hashing and list insertion.

is there a right or classic way to do this?

[A]
I don't know of any classical or right way to do this, so here is what I would do :P
It looks like you want to decide if A is a superset of B, using set theory jargon. One way you can do it is to sort A and B, and do a merge sort-esque operation on A and B, in that you try to find where in A a value in B goes. Those elements of B which are also in A, will have duplicates, and the other elements won't. Because both A and B are sorted, this shouldn't be too horrible.
For example, you take the first value of B, and walk A until you find its duplicate in A. Then you take the second value of B, and start walking A from where you left off previously. If you get to end of A without finding a match, then A is not a superset of B, and you return false.
If these tuples can stay sorted, then the sorting cost is only incurred once.


q: I'm wanting to get the full value of a char[] variable in the VC6 watch window, but it only shows a truncated version. I can copy the value from a debug memory window, but that contains mixed lines of hex and string values.  Surely there is a better way??

[A]
Push come to shove you can put in the watch
given
```
```
char bigArray[1000];
```
```
watch:
```
```
&bigArray[0]
&bigArray[100]
&bigArray[200]
...
```
```
or change the index for where in the string you want to look...
Its clunky, but its worked for me in the past.


q:
I'm currently using .resx files to manage my server side resources for .NET.

the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings?

Ideally, I would like to store the strings in the .resx files to keep them with the rest of the localized resources.

I'm open to suggestions.

[A]
I would use an object/array notation:
```
```
var phrases={};
phrases['fatalError'] ='On no!';
```
```
Then you can just swap the JS file, or use an Ajax call to redefine your phrase list.


q: I know how to use rpm to list the contents of a package (rpm -qpil package.rpm). However, this requires knowing the location of the .rpm file on the filesystem. A more elegant solution would be to use the package manager, which in my case is YUM. How can YUM be used to achieve this?

[A]
I don't think you can list the contents of a package using yum, but if you have the .rpm file on your local system (as will most likely be the case for all installed packages), you can use the rpm command to list the contents of that package like so:
```
```
rpm -qlp /path/to/fileToList.rpm
```
```
If you don't have the package file (.rpm), but you have the package installed, try this:
```
```
rpm -ql packageName
```
```


q:
I noticed in another post, someone had done something like:

double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));

Why did they use the convert function, rather than:

double d = 3.1415;
int i = (int)d;

which has an implicit floor and convert.

Also, more concerning, I noticed in some production code I was reading:

double d = 3.1415;
float f = Convert.ToSingle(d);

Is that the same as:

float f = (float)d;

Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.

[A]
You can use Convert when you have a string that you want to convert to an int
```
```
int i = Convert.ToInt32("1234");
```
```
Convert and casting will both throw an exception if they fail.
i.e, this will still throw an exception, it will not return 0:
```
```
Convert.ToInt32("1234NonNumber");
```
```
In many cases Convert and casting will have the same result, but a cast is often times easier to read.


q:
Let's say we have the following method declaration:

Public Function MyMethod(ByVal param1 As Integer, _
    Optional ByVal param2 As Integer = 0, _
    Optional ByVal param3 As Integer = 1) As Integer

    Return param1 + param2 + param3
End Function

How does VB.NET make the optional parameters work within the confines of the CLR? Are optional parameters CLS-Compliant?

[A]
Contrary to popular belief, optional parameters do appear to be CLS-compliant. (However, my primary check for this was to mark the assembly, class and method all with the CLSCompliant attribute, set to True.)
So what does this look like in MSIL?
```
```
.method public static int32  MyMethod(int32 param1,
                                      [opt] int32 param2,
                                      [opt] int32 param3) cil managed
{
  .custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = ( 01 00 01 00 00 )
  .param [2] = int32(0x00000000)
  .param [3] = int32(0x00000001)
  // Code size       11 (0xb)
  .maxstack  2
  .locals init ([0] int32 MyMethod)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldarg.1
  IL_0003:  add.ovf
  IL_0004:  ldarg.2
  IL_0005:  add.ovf
  IL_0006:  stloc.0
  IL_0007:  br.s       IL_0009
  IL_0009:  ldloc.0
  IL_000a:  ret
} // end of method Module1::MyMethod
```
```
Note the [opt] markings on the parameters -- MSIL supports this natively, without any hacks. (Unlike MSIL's support for VB's Static keyword, which is another topic altogether.)
So, why aren't these in C#? I can't answer that, other than my speculation that it might be a presumed lack of demand. My own preference has always been to specify the parameters, even if they were optional -- to me, the code looks cleaner and is easier to read. (If there are omitted parameters, I often look first for an overload that matches the visible signature -- it's only after I fail to find one that I realize that optional parameters are involved.)


q: I have written a simple HTTP Proxy server in C# that I would like to integration/functional test.  Is there a product already created that I could use to do this?  If not, what is the best way to write my own tests for this (I already have unit tests)?

[A]
To test the integration by delivering a webpage you could try one of the following:
Selenium
WaTiN
Watir
You can run Watin tests directly from xUnit in C# too - we do this for our applications. I also believe it is possible to dynamically set the proxy settings in the browser for Watin (and probably the others too).
Alternatively to make HTTP requests to a given address try
JMeter
.


q:
In most modern IDEs there is a parameter that you can set to ensure javac gets enough heap memory to do its compilation.  For reasons that are not worth going into here, we are tied for the time being to JBuilder 2005/2006, and it appears the amount of source code has exceeded what can be handled by javac.

Please keep the answer specific to JBuilder 2005/2006 javac (we cannot migrate away right now, and the Borland Make compiler does not correctly support Java 1.6)

I realize how and what parameters should be passed to javac, the problem is the IDE doesn't seem to allow these to be set anywhere.  A lot of configuration is hidden down in the Jbuilder Install\bin*.config files, I feel the answer may be in there somewhere, but have not found it.

[A]
Have a look at
http://javahowto.blogspot.com/2006/06/fix-javac-java-lang-outofmemoryerror.html
The arguments that you need to pass to JBuilder's javac is "-J-Xms256m -J-Xmx256m". Replace the 256m with whatever is appropriate in your case. Also, remove the quotes.
This should work for java 1.4, java 1.5 and forward.
BR,
~A


q:
I have a crash dump of an application that is supposedly leaking GDI.  The app is running on XP and I have no problems loading it into WinDbg to look at it.  Previously we have use the Gdikdx.dll extension to look at Gdi information but this extension is not supported on XP or Vista.

Does anyone have any pointers for finding GDI object usage in WinDbg.

Alternatively, I do have access to the failing program (and its stress testing suite) so I can reproduce on a running system if you know of any 'live' debugging tools for XP and Vista (or Windows 2000 though this is not our target).

[A]
There was a
MSDN Magazine article from several years ago
that talked about GDI leaks.  This points to several different places with good information.
In WinDbg, you may also try the
```
!poolused
```
command for some information.
Finding resource leaks in from a crash dump (post-mortem) can be difficult -- if it was always the same place, using the same variable that leaks the memory, and you're lucky, you could see the last place that it will be leaked, etc.  It would probably be much easier with a live program running under the debugger.
You can also try using
Microsoft Detours
, but the license doesn't always work out.  It's also a bit more invasive and advanced.


q:
There is a case where a map will be constructed, and once it is initialized, it will never be modified again.  It will however, be accessed (via get(key) only) from multiple threads.  Is it safe to use a java.util.HashMap in this way?

(Currently, I'm happily using a java.util.concurrent.ConcurrentHashMap, and have no measured need to improve performance, but am simply curious if a simple HashMap would suffice.  Hence, this question is not "Which one should I use?" nor is it a performance question.  Rather, the question is "Would it be safe?")

[A]
http://www.docjar.com/html/api/java/util/HashMap.java.html
here is the source for HashMap. As you can tell, there is absolutely no locking / mutex code there.
This means that while its okay to read from a HashMap in a multithreaded situation, I'd definitely use a ConcurrentHashMap if there were multiple writes.
Whats interesting is that both the .NET HashTable and Dictionary<K,V> have built in synchronization code.


q: What are the benefits of doing static code analysis on your source code? I was playing around with FxCop and I was wondering if there any benefits beyond making sure you are following the coding standards.

[A]
actually, fxcop doesn't particularly help you follow a coding standard.  What it does help you with is designing a well-thought out framework/API.  It's true that parts of the coding standard (such as casing of public members) will be caught by FxCop, but coding standards isn't the focus.
coding standards can be checked with
stylecop
, which checks the source code instead of the MSIL like fxcop does.


q:
Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod_A, mod_B, mod_C etc. Each has the column section_id.

Now, I am looking for all entries for a specific section_id, and I'm hoping there's another way besides "Select * from mod_a, mod_b, mod_c ... mod_xyzzy where section_id=value"... or even worse, using a separate query for each module.

[A]
What about?
```
```
SELECT * FROM mod_a WHERE section_id=value
UNION ALL
SELECT * FROM mod_b WHERE section_id=value
UNION ALL
SELECT * FROM mod_c WHERE section_id=value
```
```


q: What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.

[A]
Put the following where you need it:
```
```
System.Diagnostics.Debugger.Break();
```
```


q:
I'm having an issue with my regex.

I want to capture <% some stuff %> and i need what's inside the <% and the %>

This regex works quite well for that.

$matches = preg_split("/<%[\s]*(.*?)[\s]*%>/i",$markup,-1,(PREG_SPLIT_NO_EMPTY  |  PREG_SPLIT_DELIM_CAPTURE));

I also want to catch &amp;% some stuff %&amp;gt;   so I need to capture <% or &amp;lt;% and %> or %&amp;gt; respectively.

If I put in a second set of parens, it makes preg_split function differently (because as you can see from the flag, I'm trying to capture what's inside the parens.

Preferably, it would only match &amp;lt; to &amp;gt; and < to > as well, but that's not completely necessary

EDIT:  The SUBJECT may contain multiple matches, and I need all of them

[A]
In your case, it's better to use preg_match with its additional parameter and parenthesis:
```
```
preg_match("#((?:<|<)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|>))#i",$markup, $out);
print_r($out);

Array
(
    [0] => <% your stuff %>
    [1] => <%
    [2] => your stuff
    [3] => %>
)
```
```
By the way, check this online tool to debug PHP regexp, it's so useful !
http://regex.larsolavtorvik.com/
EDIT : I hacked the regexp a bit so it's faster. Tested it, it works :-)
Now let's explain all that stuff :
preg_match will store everything he captures in the var passed as third param (here $out)
if preg_match matches something, it will be store in $out[0]
anything that is inside () but not (?:) in the pattern will be stored in $out
The patten in details :
```
```
#((?:<|<)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|>))#i can be viewed as ((?:<|<)%) + ([\s]*(?:[^ø]*)[\s]*?) + (%(?:>|>)).

((?:<|<)%) is capturing < or < then %
(%(?:>|>)) is capturing % then < or >
([\s]*(?:[^ø]*)[\s]*?) means 0 or more spaces, then 0 or more times anything that is not the ø symbol, the 0 or more spaces.
```
```
Why do we use [^ø] instead of . ? It's because . is very time consuming, the regexp engine will check among all the existing characters. [^ø] just check if the char is not ø. Nobody uses ø, it's an international money symbol, but if you care, you can replace it by chr(7) wich is the shell bell char that's obviously will never be typed in a web page.
EDIT2 : I just read your edit about capturing all the matches. In that case, you´ll use preg_match_all the same way.


q:
How do you install Boost on MacOS?
Right now I can't find bjam for the Mac.

[A]
Download
MacPorts
, and run the following command:
```
```
sudo port install boost
```
```


q:
I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result.

First version looked like this:

if([elementName compare:@"companyName"] == 0)
  [character setCorporationName:currentElementText];
else if([elementName compare:@"corporationID"] == 0)
  [character setCorporationID:currentElementText];
else if([elementName compare:@"name"] == 0)
  ...

But I don't like the if-else-if-else pattern this produces. Looking at the switch statement I see that i can only handle ints, chars etc and not objects... so is there a better implementation pattern I'm not aware of?

BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the if-else vs switch pattern in Objective-C

[A]
The most common refactoring suggested for eliminating if-else or switch statements is introducing polymorphism (see
http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html
).  Eliminating such conditionals is most important when they are duplicated.  In the case of XML parsing like your sample you are essentially moving the data to a more natural structure so that you won't have to duplicate the conditional elsewhere.  In this case the if-else or switch statement is probably good enough.


q:
I wrote an application in Java and when it runs on one customer's computer running OS X The Save and Export buttons are disabled. (Everything else works in the application.)

Both of these buttons open up a standard save file dialog.

Any ideas?

[A]
The fact that these buttons open a file dialog probably has nothing to do with it being disabled. Buttons can end up being disabled for a number of reasons,
its
```
setEnabled
```
can be called with
```
false
```
,
when using an action, its
```
setEnabled
```
can be called with
```
false
```
, and
when using an action, it can have a property "enabled" that potentially disables it; see
Action
for more information, there's a list of properties there.
Could you post how you 'implemented the JButtons'?


q:
How do I generate all the permutations of a list? For example:

permutations([])
[]

permutations([1])
[1]

permutations([1, 2])
[1, 2]
[2, 1]

permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

[A]
This solution implements a generator, to avoid holding all the permutations on memory:
```
```
def permutations (orig_list):
    if not isinstance(orig_list, list):
        orig_list = list(orig_list)

    yield orig_list

    if len(orig_list) == 1:
        return

    for n in sorted(orig_list):
        new_list = orig_list[:]
        pos = new_list.index(n)
        del(new_list[pos])
        new_list.insert(0, n)
        for resto in permutations(new_list[1:]):
            if new_list[:1] + resto <> orig_list:
                yield new_list[:1] + resto
```
```


q:
The Eclipse projects are all stored in the Eclipse Foundation CVS servers.  Using the source is a great way to debug your code and to figure out how to do new things.

Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build?


q:
How can styles be applied to CheckBoxList ListItems.  Unlike other controls, such as the Repeater where you can specify <ItemStyle>, you can't seem to specify a style for each individual control.

Is there some sort of work around?

[A]
It seems the best way to do this is to create a new CssClass.  ASP.NET translates CheckBoxList into a table structure.
Using something like
Style.css
```
```
.chkboxlist td
{
    font-size:x-large;
}
```
```
Page.aspx
```
```
<asp:CheckBoxList ID="chkboxlist1" runat="server" CssClass="chkboxlist" />
```
```
will do the trick


q: Has anyone else experienced this error? Sometimes it pops up at the beginning of loading the application with Argument Error 2082. The only way I can solve it is by rebooting my machine. Restarting the browser doesn't even solve it. I have read about some solutions on the web, but I am interested in knowing what others have tried using that solved the error for them? Thanks in advance.

[A]
Are you talking about the
Actionscript 3.0 Runtime Error 2082
?


q:
BITS, the Windows background intelligent transfer service.

Looks like there are a few C# wrappers around that manage the interop to BITS, does anybody have any opinions on the best one?

[A]
Check out the following:
http://www.codeproject.com/KB/cs/Managed_BITS.aspx
http://www.simple-talk.com/dotnet/.net-tools/using-bits-to-upload-files-with-.net/


q:
We have a warm sql backup.  full backup nightly, txn logs shipped every so often during the day and restored.  I need to move the data files to another disk.  These DB's are in a "warm backup" state (such that I can't unmark them as read-only - "Error 5063: Database '<dbname>' is in warm standby. A warm-standby database is read-only.
") and am worried about detaching and re-attaching.

How do we obtain the "warm backup" status after detach/attach operations are complete?

[A]
The only solution I know is to create a complete backup of your active database and restore this backup to a copy of the database in a 'warm backup' state. First create a backup from the active db:
```
```
backup database activedb to disk='somefile'
```
```
Then restore the backup on another sql server. If needed you can use the WITH REPLACE option to change the default storage directory
```
```
restore database warmbackup from disk='somefile'
       with norecovery, replace ....
```
```
Now you can create backups of the logs and restore them to the warmbackup with the restore log statement.


q: What's the widest overview and where are the deepest analysis of different replication methods and problems?

[A]
In my opinion, you should pick a mainstream database (such as Oracle) and study everything it offers and go from there.
Oracle offers:
Replication
Data guard (standby database and beyond- physical, logical)
Real Application Clusters - (multiple instances, one DB)
and more !
A bit of hands-on would not hurt so you can download a PC version and try various replication approaches on one PC!
Enjoy !


q:
Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps GM_getValue(). That would of course involve a special name syntax. I have tried, for example: GM_getValue("@name").

The motivation here is to avoid redundant specification.

If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for "// @". (That may be necessary in my case any way, since the value I'm really interested in is @version, which is an extended value read by userscripts.org.)

[A]
This answer is out of date :
As of Greasemonkey 0.9.16 (Feb 2012) please see
Brock's answer
regarding
```
GM_info
```
Yes. A very simple example is:
```
```
var metadata=<>
// ==UserScript==
// @name           Reading metadata
// @namespace      http://www.afunamatata.com/greasemonkey/
// @description    Read in metadata from the header
// @version        0.9
// @include        https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script
// ==/UserScript==
</>.toString();

GM_log(metadata);
```
```
See
this thread on the greasemonkey-users group
for more information. A more robust implementation can be found near the end.


q:
I haven't been able to find any documentation on hardware access via the iPhone SDK so far. I'd like to be able to send signals via the dock connector to an external hardware device but haven't seen any evidence that this is accessible via the SDK (not interested in possibilities on jailbroken iPhones).

Anyone have any pointers to docs for this or some idea of what deep dark corner i should look?

[A]
This falls into the range of capabilities that requires working with Apple to get a special license.  At, I presume, a special price.
This has changed to some extent with the 3.0 version of the iPhone firmware.  If PyjamaSam is correct there is still some special activity required to get the connector specifications.


q:
Everywhere I look always the same explanation pop ups.

Configure the view resolver.

<bean id="viewMappings"
      class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
    <property name="basename" value="views" />
</bean>

And then put a file in the classpath named view.properties with some key-value pairs (don't mind the names).

logout.class=org.springframework.web.servlet.view.JstlView
logout.url=WEB-INF/jsp/logout.jsp

What does logout.class and logout.url mean?

How does ResourceBundleViewResolver uses the key-value pairs in the file?

My goal is that when someone enters the URI myserver/myapp/logout.htm the file logout.jsp gets served.

[A]
ResourceBundleViewResolver uses the key/vals in views.properties to create view beans (actually created in an internal application context). The name of the view bean in your example will be "logout" and it will be a bean of type JstlView. JstlView has an attribute called URL which will be set to "WEB-INF/jsp/logout.jsp". You can set any attribute on the view class in a similar way.
What you appear to be missing is your controller/handler layer. If you want /myapp/logout.htm to serve logout.jsp, you must map a Controller into /myapp/logout.htm and that Controller needs to return the view name "logout". The ResourceBundleViewResolver will then be consulted for a bean of that name, and return your instance of JstlView.


q:
I've been trying to get into F# on and off for a while but I keep getting put off.  Why?

Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator ->.

However, nowhere have I found as yet that provides a clear simple explanation of what this operator means.  It's as though it must be so obvious that it doesn't need explanation even to complete newbies.

I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back.

Can someone please, explain it or point to a truly accessible resource that explains it?

[A]
It basically means "maps to". Read it that way or as "is transformed into" or something like that.
So, from the
F# in 20 minutes
tutorial,
```
```
> List.map (fun x -> x % 2 = 0) [1 .. 10];;
val it : bool list
= [false; true; false; true; false; true; false; true; false; true]
```
```
The code (fun i -> i % 2 = 0) defines
  an anonymous function, called a lambda
  expression, that has a parameter x and
  the function returns the result of "x
  % 2 = 0", which is whether or not x is
  even.


q:
Are there any good database schema comparison tools out there that support Sybase SQL Anywhere version 10?  I've seen a litany of them for SQL Server, a few for MySQL and Oracle, but nothing that supports SQL Anywhere correctly.

I tried using DB Solo, but it turned all my non-unique indexes into unique ones, and I didn't see any options to change that.

[A]
SQLDelta
is awesome. It is for SQL Server. I've used it with SQL 2000 and 2005. It will compare stored procedures, tables, views, permissions, indexes, etc. It can also compare data between tables I believe. You can sync the changes or generate SQL Scripts for later use. I use it often to script out db changes in development to production.
Ah...missed the Sybase remark. Not sure if SQLDelta can talk to it..but I'd probably give it a shot since Sybase is similar.


q: I am doing some research on Unicode for a white-paper I am writing. Does anyone remember the first version of MS Office on the Windows platform that was fully Unicode compliant? Not having much luck Googling this answer out of the net.

[A]
office 97:
"The universal character set provided by Unicode overcomes this problem. Office 97 was the first version of Office to support Unicode in all applications except Microsoft Access and Microsoft Outlook®. In Office 2000, Access and Microsoft Publisher gain Unicode support. Microsoft FrontPage® 2000 also supports Unicode on Web pages, but text typed into dialog boxes and other elements of the user interface are limited to characters defined by the user’s code page." - Microsoft
url:
http://office.microsoft.com/en-us/ork2000/HA011382921033.aspx


q: It's known that you should declare events that take as parameters (object sender, EventArgs args). Why?

[A]
This allows the consuming developer the ability to write a single event handler for multiple events, regardless of sender or event.
Edit:
Why would you need a different pattern?  You can inherit EventArgs to provide any amount of data, and changing the pattern is only going to serve to confuse and frustrate any developer that is forced to consume this new pattern.


q:
What is the best way to create a webservice for accepting an image.
The image might be quite big and I do not want to change the default receive size for the web application.
I have written one that accepts a binary image but that I feel that there has to be a better alternative.

[A]
Where does this image "live?" Is it accessible in the local file system or on the web? If so, I would suggest having your WebService accepting a URI (can be a URL or a local file) and opening it as a Stream, then using a StreamReader to read the contents of it.
Example (but wrap the exceptions in FaultExceptions, and add FaultContractAttributes):
```
```
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;

[OperationContract]
public void FetchImage(Uri url)
{
    // Validate url

    if (url == null)
    {
        throw new ArgumentNullException(url);
    }

    // If the service doesn't know how to resolve relative URI paths

    /*if (!uri.IsAbsoluteUri)
    {
        throw new ArgumentException("Must be absolute.", url);
    }*/

    // Download and load the image

    Image image = new Func<Bitmap>(() =>
    {
        try
        {
            using (WebClient downloader = new WebClient())
            {
                return new Bitmap(downloader.OpenRead(url));
            }
        }
        catch (ArgumentException exception)
        {
            throw new ResourceNotImageException(url, exception);
        }
        catch (WebException exception)
        {
            throw new ImageDownloadFailedException(url, exception);
        }

        // IOException and SocketException are not wrapped by WebException :(

        catch (IOException exception)
        {
            throw new ImageDownloadFailedException(url, exception);
        }
        catch (SocketException exception)
        {
            throw new ImageDownloadFailedException(url, exception);
        }
    })();

    // Do something with image

}
```
```


q:
Why isn't Collection.remove(Object o) generic?

Seems like Collection<E> could have boolean remove(E o);

Then, when you accidentally try to remove (for example) Set<String> instead of each individual String from a Collection<String>, it would be a compile time error instead of a debugging problem later.

[A]
Because if your type parameter is a wildcard, you can't use a generic remove method.
I seem to recall running into this question with Map's get(Object) method.  The get method in this case isn't generic, though it should reasonably expect to be passed an object of the same type as the first type parameter.  I realized that if you're passing around Maps with a wildcard as the first type parameter, then there's no way to get an element out of the Map with that method, if that argument was generic.  Wildcard arguments can't really be satisfied, because the compiler can't guarantee that the type is correct.  I speculate that the reason add is generic is that you're expected to guarantee that the type is correct before adding it to the collection.  However, when removing an object, if the type is incorrect then it won't match anything anyway.  If the argument were a wildcard the method would simply be unusable, even though you may have an object which you can GUARANTEE belongs to that collection, because you just got a reference to it in the previous line....
I probably didn't explain it very well, but it seems logical enough to me.


q:
I've got a (mostly) working plugin developed, but since its function is directly related to the project it processes, how do you develop unit and integration tests for the plugin.  The best idea I've had is to create an integration test project for the plugin that uses the plugin during its lifecycle and has tests that report on the plugins success or failure in processing the data.

Anyone with better ideas?

[A]
You need to use the
maven-plugin-testing-harness
,
```
<dependency>
        <groupId>org.apache.maven.shared</groupId>
        <artifactId>maven-plugin-testing-harness</artifactId>
        <version>1.1</version>
        <scope>test</scope>
    </dependency>
```
You derive your unit test classes from
AbstractMojoTestCase
.
You need to create a bare bones POM, usually in the
```
src/test/resources
```
folder.
```
<project>
        <build>
            <plugins>
                <plugin>
                    <groupId>com.mydomain,mytools</groupId>
                    <artifactId>mytool-maven-plugin</artifactId>
                    <configuration>
                        <!-- Insert configuration settings here -->
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>mygoal</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </project>
```
Use the AbstractMojoTest.lookupMojo(String,File) (or one of the other variations) to load the Mojo for a specific goal and execute it.
```
final File testPom = new File(PlexusTestCase.getBasedir(), "/target/test-classes/mytools-plugin-config.xml");
    Mojo mojo = this.lookupMojo("mygoal", testPom);
    // Insert assertions to validate that your plugin was initialised correctly
    mojo.execute();
    // Insert assertions to validate that your plugin behaved as expected
```
I created my a plugin of my own that you can refer to for clarification
http://ldap-plugin.btmatthews.com
,


q:
I have a winforms application that normally is at about 2-4% CPU.  We are seeing some spikes up to 27% of CPU for limited number of times.  What is the best profiling tool to determine what is actually causing this spike.  We use dottrace but i dont see how to map that to exactly the CPU spikes?

Appreciate the help

[A]
I've used 2 profiling tools before - RedGate's ANTS profiler, and the built in profiler found in Visual Studio Team System.
It's been some time since I used RedGate's (
http://www.red-gate.com/products/ants_profiler/index.htm
) profiler, though I used the built in in Visual Studio 2008 fairly recently.
That being said, I felt that the RedGate product felt more intuitive to use.  One thing that frustrated me back when I used the RedGate product was that I couldn't instruct the profiler to only profile my code starting at a certain point - I had a performance hit that couldn't be reached until a fair amount of code had already executed and therefore polluted my results.  They may have added that feature since then.
The built in version for Visual Studio is only available in their very-high end versions of the product.  Someone correct me if I am wrong, but I don't think even the "Professional" version has the profiler.  I am currently using Team System Developer Edition, which
does
have the code analysis tools.
One thing the VS version does do though, is enable you to pause the profiling, and even start your app with profiling paused, so you can really focus on the performance of something very specific.  This can be exceedingly helpful when you are trying to understand the analysis results.
EDIT: Both tools will show you memory usage, and the number of times a specific method was called, and how much time was spent in each method.  What they do not do, to the best of my knowledge, is show you CPU usage at any given point in time.  However, there are likely strong correlations between CPU usage and the amount of time spent in a given block of code.
If you can duplicate the CPU spikes consistently by invoking certain actions in the APP, then what I would do is try and get my hands on the VS profiler, start the app with profiling pause, enable profiling right before you do whatever typically results in the spike, and examine those results.
This assumes of course that you have some sort of deterministic behavior to recreate the spikes.  If not ... you might considering threaded processes or garbage collection a candidate for your performance hit.


q: I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.

[A]
The following works great for printing with the win32api from C++
```
```
char szPrinterName[255];
unsigned long lPrinterNameLength;
GetDefaultPrinter( szPrinterName, &lPrinterNameLength );
HDC hPrinterDC;
hPrinterDC = CreateDC("WINSPOOL\0", szPrinterName, NULL, NULL);
```
```
In the future instead of googling "unmanaged" try googling "win32 /subject/" or "win32 api /subject/"


q:
When I start Tomcat (6.0.18) from Eclipse (3.4), I receive this message (first in the log):

WARNING:
  [SetPropertiesRule]{Server/Service/Engine/Host/Context}
  Setting property 'source' to
  'org.eclipse.jst.jee.server: (project name)'
  did not find a matching property.

Seems this message does not have any severe impact, however, does anyone know how to get rid of it?

[A]
From
Eclipse Newsgroup
:
The warning about the source property
  is new with Tomcat 6.0.16 and may be
  ignored. WTP adds a "source" attribute
  to identify which project in the
  workspace is associated with the
  context. The fact that the Context
  object in Tomcat has no corresponding
  source property doesn't cause any
  problems.
I realize that this doesn't answer how to get rid of the warning, but I hope it helps.


q: I have a table with a "Date" column.  Each Date may appear multiple times.  How do I select only the dates that appear < k number of times?

[A]
```
```
SELECT * FROM [MyTable] WHERE [Date] IN
(
    SELECT [Date]
    FROM [MyTable]
    GROUP By [Date]
    HAVING COUNT(*) < @Max
)
```
```
See @[SQLMenace] 's response also.  It's very similar to this, but depending on your database his JOIN will probably run faster, assuming the optimizer doesn't make the difference moot.


q: When I am working in .NET 2.0 projects with the newest version of ReSharper (4.1) I am getting warnings about using the var keyword and lambadas etc.. Any idea how I can disable this only for .NET 2.0 projects?

[A]
You can actually use var in 2.0 projects.  It's syntactical sugar and the compiler works with it. Check out this for more info.
http://weblogs.asp.net/shahar/archive/2008/01/23/use-c-3-features-from-c-2-and-net-2-0-code.aspx


q:
In Python specifically, how do variables get shared between threads?

Although I have used threading.Thread before I never really understood or saw examples of how variables got shared.  Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing?

I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem.

Thanks in advance!

[A]
In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them.
The
```
Thread
```
object for a particular thread is not a special object in this regard. If you store the
```
Thread
```
object somewhere all threads can access (like a global variable) then all threads can access that one
```
Thread
```
object. If you want to atomically modify
anything
that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective.
If you want actual thread-local storage, that's where
```
threading.local
```
comes in. Attributes of
```
threading.local
```
are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in
_threading_local.py
in the standard library.


q: I'm currently using Wordpress to run my website.  However, with each new release I become more concerned with software bloat and the convoluted table structures used to store my data.  Maybe this is a fruitless pursuit.  Features are always added to blogging software until it claims to be a CMS--and at that point your data is probably stuck.

[A]
You do have the option of sticking with the 2.0 branch. This will be maintained with just bug fixes until 2010. Take a look at
http://wordpress.org/download/legacy/


q:
I'd like to run a long rsync command in Cygwin by double clicking on a .sh file in Windows.  It must start in the file's containing directory (e.g. /cygdrive/c/scripts/) so that relative paths work.  Anyone gotten this to work?

Note: I've just found here, a Cygwin package that manages Windows context menus (Bash Prompt Here).  It might have some clues.

[A]
One solution that works is to create a
```
.bat
```
file that will open cygwin and execute your script.
The script to execute the script
```
go.sh
```
located on my home directory:
```
```
@echo off

C:
chdir C:\cygwin\bin

bash --login -i ./go.sh
```
```


q:
We have a 12-year-old Ms Access app that we use for our core inventory warehousing and invoicing system. It IS already running on an SQL Server backend, but all the "logic", forms and reports are in Access. After experiencing the massive amounts of maintenance sludge it took to turn inventory transactions from non-temporal to temporal, I realized that I need to someday convert this thing into code so I can better manage the logic in a much more maintainable and testable environment.

What are some techniques that would allow me to convert it into a .Net application in a manageable and efficient manner?

One idea was to convert the queries to stored procedures, then convert the app into an Adp project.But I am still clueless as to how to handle the forms and reports.

Also, I am the only developer for my company, if that matters.

[A]
Short answer: the migration doesn't seem like something easily automated.
My guess is that your best bet is to rewrite (and install) the system one piece at a time, even if (perhaps) it forces your users to run the old and new versions side-by-side for a while to use different bits of functionality. You can minimize that hassle by careful consideration of which features to migrate and in which order.
For example, you might have one user whose job role requires him or her to use just one screen all day. If you migrate that screen first with accompanying functionality, that user can be on the new system immediately and leave the old one behind, reducing your maintenance load.
So those are just some ideas based on not too much information. I hope this helps anyway.


q: What is the difference between display:block and display:inline

[A]
Block elements will typically stack vertically whereas inline elements will line up horizontally.
Two Divs will stack on top of each other, but if you set them to display:inline, they will be next to each other horizontally. Vise-versa with Span tags.


q:
Is there any way to capture the trace statements of your Flex app while not running in debug mode?

Or is there any other way to output logging information when not running a debugger?

Currently I'm trying to fix a bug that only presents itself in very specific deployment scenario, but I could see this being useful in some instances for customers to send logs to tech support when they are reporting bugs or other problems.

[A]
I suppose you're talking about Adobe Flex, targeting the Flash Player?
If so, you can write your own logging wrapper class that propagates log messages sent to it to several targets (like the trace stack and internal memory so that you can access the log from within the app and e.g. send it to a server when the user agrees to send a bug report). Also see the
Flex logging framework
for something like this that already exists.
I've actually done something like this -- I have a class called
```
Log
```
with static methods like
```
log()
```
,
```
debug()
```
,
```
error()
```
etc. that I use in my apps, and this class forwards all messages sent to it into the trace stack via
```
trace()
```
, into a "log console" app running on the same host via LocalConnection and/or Socket (a socket connection is obviously a lot faster than LocalConnection) and also saves them locally into an array so that users can send bug reports along with the log output right from within the app.
This sort of a change of course means that you'd have to translate all
```
trace()
```
commands in your code into calls to the logging system, but that can be easily achieved with a regex search & replace.


q:
Our project uses Cruise Control to both build and hot deploy a web application to a remote server (via FTP) running Tomcat in the form of a .war file.  Unfortunately, "hot" deploys don't appear to work properly, causing us to reboot Tomcat in response to each deployment.  We would really like to do this auto-magically, much like the build itself.  Is there an easy way to do this?

Side note: both machines are running Windows (XP or server, I think).

Side note 2: Performance doesn't really matter.  This is an integration box.

[A]
if you have regularly scheduled builds you could easily put something in the cron like this
```
```
crontab -e
```
```
then stop tomcat at say 1:30 am
```
```
30 1 * * * ./path_to_tamcat/bin/catalina.sh stop
```
```
then start it up again 2 mins later
```
```
32 1 * * * ./path_to_tamcat/bin/catalina.sh start
```
```
granted this isn't the best for irregular deployment, but you could easily have regular deployment with scheduled restart.


q:
What are the major reasons for using WinDbg vs the Visual Studio debugger?

And is it commonly used as a complete replacement for the Visual Studio debugger, or more for when the need arises.

[A] I have used it when I've been sent .dmp files from an NT4.0 server - MSVC won't load these old format files.


q:
Working on a new back end system for my company, and one of their requests is for a window to become locked down and for the user to be sent to the login screen if they leave it idle for to long.

I figure I'd do this with JavaScript by attaching listeners to clicks, mouse moves and key-ups but I worry about messing with other scripts.

Any suggestions?


q:
Suppose I have a directory /dir inside which there are 3 symlinks to other directories
/dir/dir11, /dir/dir12, and /dir/dir13. I want to list all the files in dir including the ones in dir11, dir12 and dir13.

To be more generic, I want to list all files including the ones in the directories which are symlinks. find ., ls -R, etc stop at the symlink without navigating into them to list further.

[A]
The
```
-L
```
option to
```
ls
```
will accomplish what you want. It dereferences symbolic links.
So your command would be:
```
```
ls -LR
```
```
You can also accomplish this with
```
```
find -follow
```
```
The
```
-follow
```
option directs find to follow symbolic links to directories.
On Mac OS X use
```
```
find -L
```
```
as
```
-follow
```
has been deprecated.


q: See title. By lightweight markup I mean something like markdown or wikitext.

[A]
Well, silverstripe
http://www.silverstripe.com/
is thought to be a good option for people who care about web standards , as is modx
http://modxcms.com/
For a lighter editor, check out textpattern.com which uses textile (like markdown). If you're on rails,
http://webby.rubyforge.org/
might do the trick.
http://www.madebyfrog.com
is a port of the ruby CMS radiant that aims to be fast, light, and minimal.


q:
What is a "table-driven method"?

As mentioned by Bill Gates in the second Windows Vista commercial at 1:05.

[A]
Table-driven methods are schemes that allow you to look up information in a table rather than using logic statements (i.e. case, if). In simple cases, it's quicker and easier to use logic statements, but as the logic chain becomes more complex, table-driven code is simpler than complicated logic, easier to modify and more efficient.
Reference:
McConnell, Steve. Code Complete, Second Edition. Redmond (Washington): Microsoft, 2004. Print. Page 411, Paragraph 1.


q:
I have a dev, that will get around our code coverage by writing tests that never fail.

The code is just atrocious, but the tests never catch it because they assert(true).

I code review, but I can't do everyones work for them, all the time. How do you get people like this motivated to make good software?

Is there a build plugin for detecting tests that can't fail?

C#, mbUnit tests.

[A]
You should really specify the language / framework you're using.
In the simplest case, I suppose it should be easy to detect
```
assert(true)
```
strings with simple
```
grep
```
-ping.


q:
How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}

And it gives the following compile-time error:

'Suit' is a 'type' but is used like a 'variable'

It fails on the Suit keyword, the second one.

[A]
I think you can use
```
```
Enum.GetNames(Suit)
```
```


q:
I am maintaining a pretty sizable application and database and am noticing some poor database performance in a few of our stored procedures.

I always hear that "adding an index" can be done to help performance. I am certainly no DBA, and I do not understand what indexes are, why they help, and how to create them.

I basically need an indexes 101.

Can anyone give me resources so that I can learn?

[A]
An index basically sorts your data on the given columns and then stores that order, so when you want to find an item, the database can optimize by using binary search (or some other optimized way of searching), rather than looking at each individual row.
Thus, if the amount of data you are searching through is large, you will absolutely want to add some indexes.
Most databases have a tool to explain how your query will work (for db2, it's db2expln, something similar probably for sqlserver), and a tool to suggest indexes and other optimizations (db2advis for db2, again probably something similar for sqlserver).


q:
I think I've got it down to the most basic case:

int main(int argc, char ** argv) {
  int * arr;

  foo(arr);
  printf("car[3]=%d\n",arr[3]);
  free (arr);
  return 1;
}

void foo(int * arr) {
  arr = (int*) malloc( sizeof(int)*25 );
  arr[3] = 69;
}

The output is this:

> ./a.out
 car[3]=-1869558540
 a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer
                         being freed
 *** set a breakpoint in malloc_error_break to debug
>

If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.

[A]
You've allocated arr in foo, but that pointers value is stored in the call stack. If you want to do this, do it like this:
```
```
void foo( int ** arr) {
    *arr = (int *)malloc( sizeof(int) * 25 );
    (*arr)[3] = 69;
}
```
```
And in main, simply pass a pointer to foo (like foo(&arr))


q:
I have a problem to connect to my WCF service if customer is using proxy with credentials. I'm unable to find the way to set credential to generated client proxy.

If I use the web service, then it is possible to set proxy.

[A]
Not sure if this is what you are looking for but the below is a working code sample to authenticate using the client credentials.
```
```
Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService")
    client.ClientCredentials.UserName.UserName = "username"
    client.ClientCredentials.UserName.Password = "password"
    Dim ProductList As List(Of Product) = client.GetProducts()
    mView.Products = ProductList
    client.Close()
```
```


q:
Being a C# developer since version 1.0, F# has captured my free time for the past few weeks. Computers are now sold with 2, 4 .. Cores and multi-threading is not always simple to accomplish.

At the moment I see that F# has great potential for complicated and or heavy workloads.
Do you think that F# will (once RTM) become an important player in the Enterprise Software market?

[A]
I think regardless of whether F# becomes import for Enterprise Software being able to isolate pure functional portions of code in any language will be key to using the potential of multi-core computers.  For instance Microsoft's Parallel Extensions for .NET are great, but there is still a lot of room to make mistakes by parallelizing code that can't execute in parallel.  If the code is in the form of a pure functional language or a subset of your language that is purely functional, then you are assured that you can execute it in parallel.  The trick is then figuring out the most efficient way to assign the work.
The role that F# plays in this I would say would be more as a catalyst to get people's feet wet and start thinking in a more declarative way.


q: I have a VmWare virtual machine that is coming dangerously close to it's primarry HDD's limit and I need to extend it. How do I do this? I'm working with VmWare Workstation 6.0.5

[A]
This link
gives two approaches that should help.
It looks like this is the most straightforward method:
```
```
vmware-vdiskmanager -x 12GB path\to\disk.vmdk
```
```
where 12GB is the desired size of the expanded volume.


q: We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents?

[A]
You could use XSD.  No, I'm serious.  Go to a command prompt and type xsd and press Enter.
Here's what you will see (truncated):
```
```
I:\>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 1.0.3705.0]
Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.

xsd.exe -
    Utility to generate schema or class files from given source.

xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]
```
```
Just follow the instructions.


q:
The original query looks like this (MySQL):

SELECT *
FROM books
WHERE title LIKE "%text%" OR description LIKE "%text%"
ORDER BY date

Would it be possible to rewrite it (without unions or procedures), so that result will look like this:

list of books where title matches query ordered by date, followed by:

list of books where description matches query ordered by date

So basically just give a higher priority to matching titles over descriptions.

[A]
The union command will help you. Something along these lines:
```
```
SELECT *, 1 as order from books where title like '%text%'
union
SELECT *, 2 as order from books where description like '%text%'
ORDER BY order, date
```
```


q:
Is there a SQL or PHP script that I can run that will change the default collation in all tables and fields in a database?

I can write one myself, but I think that this should be something that readily available at a site like this. If I can come up with one myself before somebody posts one, I will post it myself.

[A]
Be careful! If you actually have utf stored as another encoding, you could have a real mess on your hands. Back up first. Then try some of the standard methods:
for instance
http://www.cesspit.net/drupal/node/898
http://www.hackszine.com/blog/archive/2007/05/mysql_database_migration_latin.html
I've had to resort to converting all text fields to binary, then back to varchar/text. This has saved my ass.
I had data is UTF8, stored as latin1. What I did:
Drop indexes.
Convert fields to binary.
Convert to utf8-general ci
If your on LAMP, don’t forget to add set NAMES command before interacting with the db, and make sure you set character encoding headers.


q:
Is it possible to use XPath to select only the nodes that have a particular child elements?  For example, from this XML I only want the elements in pets that have a child of 'bar'.  So the resulting dataset would contain the lizard and pig elements from this example:

<pets>
  <cat>
    <foo>don't care about this</foo>
  </cat>
  <dog>
   <foo>not this one either</foo>
  </dog>
  <lizard>
   <bar>lizard should be returned, because it has a child of bar</bar>
  </lizard>
  <pig>
   <bar>return pig, too</bar>
  </pig>
</pets>

This Xpath gives me all pets: "/pets/*", but I only want the pets that have a child node of name 'bar'.

[A]
Here it is, in all its glory
```
```
/pets/*[bar]
```
```
English: Give me all children of
```
pets
```
that have a child
```
bar
```


q:
Update: Looks like the query does not throw any timeout. The connection is timing out.

This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception.

I cannot use any of these techniques:
1) Increase timeout.
2) Run it asynchronously with a callback. This needs to run in a synchronous manner.

please suggest any other techinques to keep the connection alive while executing a time consuming query?

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

[A]
```
```
command.CommandTimeout *= 2;
```
```
That will double the default time-out, which is 30 seconds.
Or, put the value for CommandTimeout in a configuration file, so you can adjust it as needed without recompiling.


q: How can I print wstring in gdb?

[A]
Suppose you've got a
```
std::wstring str
```
. The following should work in gdb:
```
```
call printf("%ls", str._M_data())
```
```
(The -l option in printf makes it a long string, and I believe you need the "
```
call
```
" statement because the ordinary gdb printf doesn't like that option.)


q:
Does any one have a preference on how to check if a value is DBNull?  I've found these two statements give me the results I want, but just wondering if there's a preference?

if (any is System.DBNull)

same as:

if (any == System.DBNull.Value)

Thanks!

[A]
```
```
if (any == System.DBNull.Value) ...
```
```
I prefer that one, simply because I read that as comparing values, not types.


q:
I have an application with a REST style interface that takes XML documents via POST from clients. This application is written in Java and uses XML beans to process the posted message.

The XML schema definition for a field in the message looks like this:

<xs:element name="value" type="xs:string" nillable="true" />

How do I send a null value that meets this spec?

I sent <value xsi:nil="true" />
but this caused the XML parser to barf.

[A]
What about
```
<value xsi:nil="true"></value>
```
? That's what's
in the spec
.


q: Ideally I'd like a way to enable the mouse wheel for scrolling in old compiled java runtime apps, but java code to explicitly utilise it for an individual app would suffice.

[A]
Mousewheel scrolling is supported in current Swing applications. You could try compiling your application using JDK 1.4, 1.5 or 1.6. Depending on the complexity and environment moving to a new version may or may not be a viable option.
This tutorial
shows how to write your own mousewheel listener if you want something different to the normal behaviour.