q: Does anyone know of any good C++ code that does this?

[A]
CGICC
includes methods to do url encode and decode.
form_urlencode and form_urldecode


q:
Long story short, I need to put some text in my Flex application and I don't want users to be able to copy. I was going to use a label, but apparently labels do not support text wrapping. Can I make it so that users cannot select text in a Flex Text control?

Thanks.

[A]
You can set the enabled property to "false" which disables user interaction. You may want to also change the disabledcolor property to your choice.
```
```
print("
        <mx:Text enabled="false" disabledColor="0x000000" text=Text"/>
");
```
```

s: huggingface

c: devops

d: intermediate


q:
How important is it to make a website layout fit on 640 x 480 and 800 x 600 displays?  For some time I have been designing with the assumption of at least 1024 x 768, but I haven't been doing it professionally (just on my site which is just a blog that only 10-15 friends read).  Does anyone have any non-anecdotal statistics about the distribution of screen resolutions from real web users?

Note 1:  "Non-anecdotal" means please don't give answers like "I know lots of people using 640x480" or "my mom runs in 800x600 so it must be really common."  I'd rather have actual data (or links to actual data), especially if it is data about general users (rather than geeks).

Note 2: I'm not concerned with extremely-small displays like those on PDAs and cell phones (at least not at the moment).  I'm just talking about desktop/laptop monitors.

[A]
I think the general assumption these days is that 1024x768 is acceptable, thats certainly the route I take. A good benchmark is to look at big sites like the
BBC
, they recently switched to a 1024x768 design. Thats not to say every site has to be that, for smaller sites I often stick to 800x600 just so the content doesn't look pathetic :o)
Here is the source I often use for web statistics with its
august 2008 stats
showing 800x600 at 7%.


q:
Let's say that a class has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented.

To increment this field, which approach should be used, and why?

lock(this.locker) this.counter++;,

Interlocked.Increment(ref this.counter);,

Change the access modifier of counter to public volatile.

Now that I've discovered volatile, I've been removing many lock statements and the use of Interlocked. But is there a reason not to do this?

[A]
Interlocked functions do not lock.  They are atomic, meaning that they can complete without the possibility of a context switch during increment.  So there is no chance of deadlock or wait.
I would say that you should always prefer it to a lock and increment.
Volatile is useful if you need writes in one thread to be read in another, and if you want the optimizer to not reorder operations on a variable (because things are happening in another thread that the optimizer doesn't know about).  It's an orthogonal choice to how you increment.
This is a really good article if you want to read more about lock-free code, and the right way to approach writing it
http://www.ddj.com/hpc-high-performance-computing/210604448


q:
I'm writing a simple web service using Microsoft Visual Web Developer 2005 (Express Edition), and the dynamically generated WSDL has a minOccurs="0" for all the parameters.

How do I get minOccurs="1" for the required parameters without resorting to creating a static WSDL file?

I need to do this using a ASP.NET Web Service (.NET v2). So, no WCF.

[A]
from an msdn forum
"If you are creating a new web service, I highly recommend building the web service using the Windows Communication Foundation (WCF) instead of using ASP.NET Web Services.
In WCF, when you specify the data contract for your service you can speicfy that a given data member is required using the IsRequired property on the DataMemberAttribute.
"
source -
http://social.msdn.microsoft.com/forums/en-US/asmxandxml/thread/40ab5748-d32c-42a6-a47f-984ba18a1fe2/


q: I have to implement a middleware system for file sharing, and it has to split the files not unlike what happens on bittorrent, where it sends and receives separate pieces simultaneously from varios sources. How do i do that? Is it a library or i have to implement the file splitting myself?

[A]
Split the files into blocks let's say of 100KB each.  Then calculate a SHA hash (or some other hashing algorithm) on each of the blocks.  so if the file is 905KB, you would have 10  such hashes calculated.
The server would contain a hash definition file for each file that it serves.  This hash definition file would contain a list of all of the blocks of the file, along with the hash.   So if the server is serving our 905KB file called test.exe.  Then we would have another file called test.exe.hashes which contains a listing of the 10 hashes of the file.
The client would download the hash definition file, and ensure that it has all of the blocks.  The client can request each block individually and after it's downloaded, it can calculate the hash on its end again to ensure there is no corruption.
You don't need to physically split the file, splitting a file is just reading the part of it that you are interested in.  The first block of the file is from byte range 0 to 102399, the next block is from 102400 to 204800, and so on.  So just open the file, seek to that position, read the data, and close the file.


q:
In terms of Java, when someone asks:

what is polymorphism?

Would overloading or overriding be an acceptable answer?

I think there is a bit more to it than that.

IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?

I think overloading is not the right answer for sure.

[A]
The term overloading refers to having multiple versions of something with the same name, usually methods with different parameter lists
```
```
public int DoSomething(int objectId) { ... }
public int DoSomething(string objectName) { ... }
```
```
So these functions might do the same thing but you have the option to call it with an ID, or a name.  Has nothing to do with inheritance, abstract classes, etc.
Overriding usually refers to polymorphism, as you described in your question


q:
I get FLAC files a lot and want to automate the taging of the end point MP3 files after I have converted them.

What is my best library to interface with?  Vista machine and C# for my code base.

The flac files come with a text file for the show, and the numbers performed.  I'll edit that any way possible.

I use winamp for a player but will try others if free.  :)

TIA.

[A]
Check out libid3tag...
http://sourceforge.net/project/showfiles.php?group_id=12349
...
And, actually, the ID3 tag is prettty simple, it's just text (with fixed length fields) tacked on to the front of the MP3 file...
Just make sure you follow the standard, as not all players, etc. do.  For more on that, check out this article on
Wikipedia
link text


q:
IO.popen() and system() in Ruby is sorely lacking several useful features, such as:

obtaining the return value of the function

capturing both stdout and stderr (seperately and merged)

running without spawning an extra cmd.exe or /bin/sh process

Python has a module "subprocess" which I was thinking about using as inspiration for a similar module in Ruby. Now to the questions:

How are Ruby-programmers working around the issues above, for example obtaining the return value when doing a popen() call?

Is this something which has already been implemented?

[A]
system() exit status can be captured with
```
$?.exitstatus
```
stderr can be captured with something like
```
system 'command 2>&1'
```


q:
I've noticed that sometimes wrapper scripts will use ${1:+"$@"} for the parameters rather than just "$@".

For example, http://svn.macosforge.org/repository/macports/trunk/dports/editors/vim-app/files/gvim.sh uses

exec "$binary" $opts ${1:+"$@"}

Can anyone break ${1:+"$@"} down into English and explain why it would be an advantage over plain "$@"?

[A]
From the bash man page:
```
```
${parameter:+word}
          Use Alternate Value.  If parameter is null or unset, nothing  is
          substituted, otherwise the expansion of word is substituted.
```
```
So,
```
"$@"
```
is substituted unless
```
$1
```
is unset. I can't see why they couldn't have just used
```
"$@"
```
.


q:
At the moment we use HSQLDB as an embedded database, but we search for a database with less memory footprint as the data volume grows.

Derby / JavaDB is not an option at the moment because it stores properties globally in the system properties. So we thought of h2.

While we used HSQLDB we created a Server-object, set the parameters and started it. This is described here (and given as example in the class org.hsqldb.test.TestBase).

The question is: Can this be done analogous with the h2 database, too? Do you have any code samples for that? Scanning the h2-page, I did not find an example.

[A]
From the download, I see that the file tutorial.html has this
```
```
import org.h2.tools.Server;
...
// start the TCP Server
Server server = Server.createTcpServer(args).start();
...
// stop the TCP Server
server.stop();
```
```


q: Is anyone out there still using DataFlex? If so, what are you favorite tips and tricks for this venerable 4GL?

[A]
It all depends on the version of DF you're using, but here's a couple:
Do not use "While" when traversing record sets. Always use repeat. (see example at bottom)
The dataflex newsgroups (news.dataaccess.com) is the best place to ask questions.
Other useful sites include
http://sture.dk/wasp
and
http://www.vdf-guidance.com
Use entering_scope instead of activating to initialise values on forms.
With deferred modal objects, use a container object above the deferred object to pass in parameters.
I've got loads more. But I'm just going to have to go and lie down. I can't believe someone asked a dataflex question.
```
```
clear orders
move const.complete to orders.status
find ge orders by index.2
repeat
    if orders.status ne const.complete indicate finderr true
    if (not(finderr)) begin
        send doYourStuffHere
        find gt orders by index.2
    end
until (finderr)
```
```


q:
How would I create the equivalent Linq To Objects query?

SELECT MIN(CASE WHEN p.type = "In" THEN p.PunchTime ELSE NULL END ) AS EarliestIn,
       MAX(CASE WHEN p.type = "Out" THEN p.PunchTime ELSE NULL END ) AS LatestOUt
FROM Punches p

[A]
You can't efficiently select multiple aggregates in vanilla LINQ to Objects. You can perform multiple queries, of course, but that may well be inefficient depending on your data source.
I have a framework which copes with this which I call "Push LINQ" - it's only a hobby (for me and Marc Gravell) but we believe it works pretty well. It's available as part of
MiscUtil
, and you can read about it in
my blog post on it
.
It looks slightly odd - because you define where you want the results to go as "futures", then push the data through the query, then retrieve the results - but once you get your head round it, it's fine. I'd be interested to hear how you get on with it - if you use it, please mail me at skeet@pobox.com.


q:
I'm trying to retrieve numeric values from a DataGridView. So far, the only way I've found is to retrieve them as a string and convert them to numeric.

Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString());

There must be an easier way. The cell is originally populated from a DataSet with a numeric field value but since the DataGridViewCell object returns it as an object, I can't do a straight assignment. I must be missing something simple here.

Thanks.

[A]
What is the error you are getting?
```
Convert.ToDouble
```
has an overloaded method that takes an object, so you shouldn't need the
```
ToString()
```
? Unless you are doing a
```
TryParse
```
?


q: In java, I could do this with the 'final' keyword. I don't see 'final' in C#. Is there a substitute?

[A]
You're looking for the
```
sealed
```
keyword. It does exactly what the
```
final
```
keyword in Java does. Attempts to inherit will result in a compilation error.


q:
We are using the MVC framework (release 5) and the CrystalReportViewer control to show our reports.  I cannot get any of the buttons at the top of the report viewer control to work.

If I'm working with the report 'HoursSummary'.  If I hover over any of the buttons on the report viewer in IE the displayed link at the bottom of the pages is '../HoursSummary'.  This creates a url of 'http://localhost/HoursSummary'.  There is no 'HoursSummary' controller so I keep receiving 404 errors.

I believe I want to redirect to 'http://localhost/reports/HoursSummary' since I do have a reports controller.  If this is the correct method does anyone know which property I should set on the CrystalReportViewer control to make that happen?

Is there an easier method to handle this situation?


q: does the TableLayoutPanel exist in VS 2005?

[A]
Yes
.


q:
I want to talk to a flash server which uses RTMP, but I don't want to use Flash, but rather c# or java.

I was looking at Red5 but their client API seems to be a bit wobbly.

Does anyone have any other ideas?

[A]
There's a python implementation of the RTMP protocol,
RTMPy
. Other than that and Red5, I don't know of any other RTMP client implementations. (Well, besides flash itself of course).
What flash server are you using? Some of them allow you to communicate with other protocols as well, such as text-based or XML-based, and those might be better to use than RTMP if your client is not flash-based.


q:
I would find out the floppy inserted state:

no floppy inserted

unformatted floppy inserted

formatted floppy inserted

Can this determined using "WMI" in the System.Management namespace?

If so, can I generate events when the floppy inserted state changes?

[A]
This comes from
Scripting Center @ MSDN
:
```
```
strComputer = "."
Set objWMIService = GetObject( _
    "winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
    ("Select * From Win32_LogicalDisk Where DeviceID = 'A:'")

For Each objItem in colItems
    intFreeSpace = objItem.FreeSpace
    If IsNull(intFreeSpace) Then
        Wscript.Echo "There is no disk in the floppy drive."
    Else
        Wscript.Echo "There is a disk in the floppy drive."
    End If
Next
```
```
You'll also be able to tell if it's formatted or not, by checking other members of the
Win32_LogicalDisk class
.


q:
I need to create XML in Perl.  From what I read, XML::LibXML is great for parsing and using XML that comes from somewhere else.  Does anyone have any suggestions for an XML Writer?  Is XML::Writer still maintained?  Does anyone like/use it?

In addition to feature-completeness, I am interested an easy-to-use syntax, so please describe the syntax and any other reasons why you like that module in your answer.

Please respond with one suggestion per answer, and if someone has already answered with your favorite, please vote that answer up.  Hopefully it will be easy to see what is most popular.

Thanks!

[A]
XML::Writer is still maintained (at least, as of February of this year), and it's indeed one of the favorite Perl XML writers out there.
As for describing the syntax, one is better to look at the module's documentation (the link is already in the question).  To wit:
```
```
use XML::Writer;

my $writer = new XML::Writer();  # will write to stdout
$writer->startTag("greeting",
                  "class" => "simple");
$writer->characters("Hello, world!");
$writer->endTag("greeting");
$writer->end();

# produces <greeting class='simple'>Hello world!</greeting>
```
```


q:
We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection.

We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory.

But for some reason my Workflows just don't see the config file.

<configuration>
  <appSettings>
      <add key="ConnectString" value="Data Source=officeserver;Database=mydatabase;User ID=officeuser;Password=officeuser;" />
  </appSettings>
</configuration>

Given the above config file, the following code prints an empty string:

Console.WriteLine(ConfigurationManager.AppSettings["ConnectString"]);

I think what I want is to just specify a config filename, but I'm having problems here.  I'm just not getting results.
Anyone have any pointers?

[A]
Funny, where I'm at we're doing something very similar and the config file loads just fine.  In our case I think each new config file's name matches that of it's associated assembly.  So MyLibrary.dll would have a file named MyLibrary.dll.config with information for that file assembly.  Also, the example I have handy is using VB.Net rather than C# (we have some of each) and all the settings in there are for the VB-specific My.Settings namespace, so we don't use the ConfigurationManager class directly to read them.
The settings themselves look like this:
```
```
<applicationSettings>
    <MyLibrary.My.MySettings>
        <setting name="SomeSetting" serializeAs="String">
            <value>12345</value>
        </setting>
    </MyLibrary.My.MySettings>
</applicationSettings>
```
```


q:
I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present.

So something like:

dr.ToString.Substring(1, dr.ToString.Length);

But more conditionally in case the dollar sign ever made an appearance again.

I am trying to do this with explicitly defining another string.

[A]
```
```
Convert.ToString(dr(columnName)).Replace("$", String.Empty)
```
```
--
If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.


q: I'm looking for a way to create an online form that will update an Access database that has just a few tables. Does anyone know of a simple solution for this?


q:
I have a folder, c:\websites\test, and it contains folders and files that were checked out from a repository that no longer exists. How do I get Subversion to stop tracking that folder and any of the subfolders and files?

I know I could simply delete the .svn folder, but there are a lot of sub-folders in many layers.

[A]
Try
svn export
.
You should be able to do something like this:
```
```
svn export /path/to/old/working/copy /path/to/plain/code
```
```
And then just delete the old working copy.
TortoiseSVN also has an
export feature
, which behaves the same way.


q:
How can I convert a JavaScript string value to be in all lower case letters?

Example: "Your Name" to "your name"

[A]
Yes, any string in JavaScript has a
```
toLowerCase()
```
method that will return a new string that is the old string in all lower case.  The old string will remain unchanged.
So, you can do something like:
```
```
"Foo".toLowerCase();
document.getElementById('myField').value.toLowerCase();
```
```


q:
I was wrestling with some Perl that uses hash references.

In the end it turned out that my problem was the line:

$myhash{$key} |= {};

That is, "assign $myhash{$key} a reference to an empty hash, unless it already has a value".

Dereferencing this and trying to use it as a hash reference, however, resulted in interpreter errors about using a string as a hash reference.

Changing it to:

if( ! exists $myhash{$key}) {
  $myhash{$key} = {};
}

... made things work.

So I don't have a problem. But I'm curious about what was going on.

Can anyone explain?

[A]
Try this:
```
```
my %myhash;
$myhash{$key} ||= {};
```
```
You can't declare a hash
element
in a
```
my
```
clause, as far as I know. You declare the hash first, then add the element in.
Edit: I see you've taken out the
```
my
```
. How about trying
```
||=
```
instead of
```
|=
```
? The former is idiomatic for "lazy" initialisation.


q:
What is the easiest way to find out how much memory an object uses in .NET?

Preferably without having to resort to a third party tool.  Marshal.SizeOf or the sizeof operator look useful but only work with a restricted range of types.

Some related posts:

Object Memory Analysis in .NET

Does an empty array in .NET use any space?

[A]
Asked and answered here:
Determine how much memory a class uses?
The quick summary is that if you don't want to use a tool, you need to use the
.NET Profiling API
The Profiling API is amazingly powerful, but I don't think it would qualify as "easy" by any stretch of the imagination, so I would strongly recommend using a memory profiling tool - there are some free ones that are OK, and some not-too-expensive commercial ones (
JetBrains dotTrace
in particular) that are really good.


q: What book or website would you recommend to learn about QEMU?  I'd like to see some usage examples as well as how to use the APIs.

[A]
Best Resources:
Main QEMU Usage Documentation
Qemu Man Page
- Invaluable resource when working with qemu.
Quick Start Guide
- Slightly ubuntu/debian specific. Covers KVM.
Qemu Networking Guide
- Great resource, super useful.
Have fun qemu's a great tool.


q:
I've got a relatively large .Net system that consists of a number of different applications. Rather than having lots of different app.config files, I would like to share a single configuration file between all the apps.

I would also like to have one version when developing on my machine, one version for someone else developing on their machine, one version for a test system and one version for a live system.

Is there an easy way of doing this?

[A]
You could use a Post-build event (Properties -> Build Events) on your "child" projects to copy a config file from a master project to others, like this:
```
```
copy /Y c:\path\to\master\project\app.config $(TargetPath).config
exit 0
```
```
(The "exit 0" as the last line prevents a build error).
To have separate config files for different build targets ("RELEASE", "DEBUG", etc), you can edit the .csproj file (or .vbproj) in NOTEPAD.EXE to add an AppConfig tag for each of the target groups, like this:
```
```
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>.\bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <AppConfig>debug.app.config</AppConfig>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>.\bin\Devel\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <AppConfig>release.app.config</AppConfig>
  </PropertyGroup>
```
```
Notice the new
<AppConfig>
tags present in each group.


q:
I would like to embed a light weight web server in a Windows application developed in .NET. The web server has to support PHP.

I have looked at Cassini, but it seems it is ASP.NET only.

[A]
The .net class HttpListener exposes the underlying http.sys upon which IIS is built.  All machines since Windows XP2 have http.sys installed by default.
Here are some links to get you started.
XML-RPC SERVER USING HTTPLISTENER
HttpListener For Dummies
As for the PHP support, I don't know how you would enable this, but there is no technical reason you couldn't build it in.


q:
I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box?

There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />

[A]
Make the button a submit element, so it'll be automatic.
```
```
<input type = "submit"
       id = "btnSearch"
       value = "Search"
       onclick = "return doSomething();"
/>
```
```
Note that you'll need a
```
<form>
```
element containing the input fields to make this work (thanks Sergey Ilinsky).
It's not a good practice to redefine standard behaviour, the
Enter
key should always call the submit button on a form.


q: What is a good error handling practice for an asp.net site? Examples? Thanks!

[A]
One practice that I find to be especially useful is to create a generic error page, and then set your defaultRedirect on the customErrors node of the web.config to that error page.
Then setup your global.asax for logging all unhandled exceptions and then put them (the unhandled exceptions) in a static property on some class (I have a class called ErrorUtil with a static LastError property). Your error page can then look at this property to determine what to display to the user.
More details here:
http://www.codeproject.com/KB/aspnet/JcGlobalErrorHandling.aspx


q:
I have a test environment for a database that I want to reload with new data at the start of a testing cycle. I am not interested in rebuilding the entire database- just simply "re-setting" the data.

What is the best way to remove all the data from all the tables using TSQL? Are there system stored procedures, views, etc. that can be used? I do not want to manually create and maintain truncate table statements for each table- I would prefer it to be dynamic.

[A]
This is
one
way to do it... there are likely 10 others that are better/more efficient, but it sounds like this is done very infrequently, so here goes...
get a list of the
```
tables
```
from
```
sysobjects
```
, then loop over those with a cursor, calling
```
sp_execsql('truncate table ' + @table_name)
```
for each
```
iteration
```
.


q:
I have been learning about the basics of C# but haven't come across a good explanation of what this is:

var l = new List<string>();

I don't know what the <string> is doing or if it's the List that is doing the magic. I have also seen objects been thrown within the < > tags.

Can someone explain this to me with examples, please?

[A]
This is .NET Generics.  The type within the < > denotes the type of element contained in the list.
with ArrayList you'd have to cast the elements inside...
```
```
int x = (int)myArrayList[4];
```
```
with List you can avoid that step because the compiler already knows the type.
```
```
int x = myList[4];
```
```
Generics are available in .NET 2.0 and later.


q: Is there a way to hide the text limit line in netbeans 6.5?

[A] Are you talking about the line running thru the right side, by default at the 80 column point?  That is Options -> Editor -> Indentation -> Right margin.  I have it set at 200 columns which pushes it off the right side of the screen.


q:
I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything.

I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances.

[A]
```
READONLY
```
doesn't work on checkboxes as it prevents you from editing a field's
value
, but with a checkbox you're actually editing the field's
state
(on || off)
From
faqs.org
:
It's important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field.
If you don't want to use
```
disabled
```
but still want to submit the value, how about submitting the value as a hidden field and just printing its contents to the user when they don't meet the edit criteria? e.g.
```
```
// user allowed change
if($user_allowed_edit)
{
    echo '<input type="checkbox" name="my_check"> Check value';
}
else
{
    // Not allowed change - submit value..
    echo '<input type="hidden" name="my_check" value="1" />';
    // .. and show user the value being submitted
    echo '<input type="checkbox" disabled readonly> Check value';
}
```
```


q:
How do I go from this string: "ThisIsMyCapsDelimitedString"

...to this string: "This Is My Caps Delimited String"

Fewest lines of code in VB.net is preferred but C# is also welcome.

Cheers!

[A]
There's probably a more elegant solution, but this is what I come up with off the top of my head:
```
```
string myString = "ThisIsMyCapsDelimitedString";

for (int i = 1; i < myString.Length; i++)
{
     if (myString[i].ToString().ToUpper() == myString[i].ToString())
     {
          myString = myString.Insert(i, " ");
          i++;
     }
}
```
```


q:
I have a textarea with many lines of input, and a JavaScript event fires that necessitates I scroll the textarea to line 345.

scrollTop sort of does what I want, except as far as I can tell it's pixel level, and I want something that operates on a line level. What also complicates things is that, afaik once again, it's not possible to make textareas not line-wrap.

[A]
You can stop wrapping with the wrap attribute. It is not part of HTML 4, but most browsers support it.
You can compute the height of a line by dividing the height of the area by its number of rows.
```
```
<script type="text/javascript" language="JavaScript">
function Jump(line)
{
  var ta = document.getElementById("TextArea");
  var lineHeight = ta.clientHeight / ta.rows;
  var jump = (line - 1) * lineHeight;
  ta.scrollTop = jump;
}
</script>

<textarea name="TextArea" id="TextArea"
  rows="40" cols="80" title="Paste text here"
  wrap="off"></textarea>
<input type="button" onclick="Jump(98)" title="Go!" value="Jump"/>
```
```
Tested OK in FF3 and IE6.


q:
I'm looking to implement a function that retrieves a single frame from an input video, so I can use it as a thumbnail.

Something along these lines should work:

// filename examples: "test.avi", "test.dvr-ms"
// position is from 0 to 100 percent (0.0 to 1.0)
// returns a bitmap
byte[] GetVideoThumbnail(string filename, float position)
{
}

Does anyone know how to do this in .Net 3.0?

The correct solution will be the "best" implementation of this function.
Bonus points for avoiding selection of blank frames.

[A]
This project will do the trick for AVIs:
http://www.codeproject.com/KB/audio-video/avifilewrapper.aspx
Anything other formats, you might look into directshow.  There are a few projects that might help:
http://sourceforge.net/projects/directshownet/
http://code.google.com/p/slimdx/


q:
Can you suggest how to create a test environment to simulate various types of bandwidths and traffic in a web app?

Or maybe an open source program which does this against localhost?

I think this is a very important subject when programming web apps but it is not a usual topic, the only way i can imagine to create such kind of environment is to use some kind of proxy in a local network but before start looking into the squid documentation i would like to hear your suggestions.

[A]
The closest I can think of is doing something similar with
VEDekstop
from Shunra..
Simulating High Latency and Low Bandwidth in Testing of Database Applications
Shunra VE Desktop Standard is a Windows-based client software solution that simulates a wide area network link so that you can test applications under a variety of current and potential network conditions – directly from your desktop.


q:
Change Data Capture is a new feature in SQL Server 2008.  From MSDN:

Change data capture provides
  historical change information for a
  user table by capturing both the fact
  that DML changes were made and the
  actual data that was changed. Changes
  are captured by using an asynchronous
  process that reads the transaction log
  and has a low impact on the system

This is highly sweet - no more adding CreatedDate and LastModifiedBy columns manually.

Does Oracle have anything like this?

[A]
I believe Oracle has provided auditing features since 8i, however the tables used to capture the data are rather complex and there is a significant performance impact when this is turned on.
In Oracle 8i you could only enable this for an entire database and not a table at a time, however 9i introduced Fine Grained Auditing which provides far more flexibility. This has been expanded upon in 10/11g.
For more information see
http://www.oracle.com/technology/deploy/security/database-security/fine-grained-auditing/index.html
.
Also in 11g Oracle introduced the Audit Vault, which provides secure storage for audit information, even DBA's cannot change this data (according to Oracle's documentation, I haven't used this feature yet). More info can be found at
http://www.oracle.com/technology/deploy/security/database-security/fine-grained-auditing/index.html
.


q:
I have a double value f and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to the original but still strictly greater than (or less than) the original.

It doesn't have to be close down to the last bit—it's more important that whatever change I make is guaranteed to produce a different value and not round back to the original.

[A]
Check your math.h file. If you're lucky you have the
```
nextafter
```
and
```
nextafterf
```
functions defined. They do exactly what you want in a portable and platform independent way and are part of the C99 standard.
Another way to do it (could be a fallback solution) is to decompose your float into the mantissa and exponent part. Incrementing is easy: Just add one to the mantissa. If you get an overflow you have to handle this by incrementing your exponent. Decrementing works the same way.
EDIT
: As pointed out in the comments it is sufficient to just increment the float in it's binary representation. The mantissa-overflow will increment the exponent, and that's exactly what we want.
That's in a nutshell the same thing that nextafter does.
This won't be completely portable though. You would have to deal with endianess and the fact that not all machines do have IEEE floats (ok - the last reason is more academic).
Also handling NAN's and infinites can be a bit tricky. You cannot simply increment them as they are by definition not numbers.


q: What is the difference between a BitmapFrame and BitmapImage in WPF?  Where would you use each (ie. why would you use a BitmapFrame rather than a BitmapImage?)

[A]
You should stick to using the abstract class
BitmapSource
if you need to get at the bits, or even
ImageSource
if you just want to draw it.
The implementation BitmapFrame is just the object oriented nature of the implementation showing through. You shouldn't really have any need to distinguish between the implementations. BitmapFrames may contain a little extra information (metadata), but usually nothing but an imaging app would care about.
You'll notice these other classes that inherit from BitmapSource:
BitmapFrame
BitmapImage
CachedBitmap
ColorConvertedBitmap
CroppedBitmap
FormatConvertedBitmap
RenderTargetBitmap
TransformedBitmap
WriteableBitmap
You can get a BitmapSource from a URI by constructing a BitmapImage object:
```
```
Uri uri = ...;
BitmapSource bmp = new BitmapImage(uri);
Console.WriteLine("{0}x{1}", bmp.PixelWIdth, bmp.PixelHeight);
```
```
The BitmapSource could also come from a decoder. In this case you are indirectly using BitmapFrames.
```
```
Uri uri = ...;
BitmapDecoder dec = BitmapDecoder.Create(uri, BitmapCreateOptions.None, BitmapCacheOption.Default);
BitmapSource bmp = dec.Frames[0];
Console.WriteLine("{0}x{1}", bmp.PixelWIdth, bmp.PixelHeight);
```
```


q: Is there any one website which contains many good C# screencasts?

[A]
dnrTV
dnrTv is a fusion of a training video
  and an interview show. Training videos
  are typically sterile and one-way.
  Let's face it, you can only take so
  much. But you need to see the code! In
  this format, you get the spontaneity
  of an interview talk show, and the
  detail of a webcast or training video.
Carl Franklin is the host of the
  wildly popular mp3 talk show .NET
  Rocks!, which he started recording in
  August, 2002. dnrTV launched on
  January 12th, 2006, the same week as
  .NET Rocks! show number 159!
We see dnrTV as a natural adjunct to
  .NET Rocks!, allowing more technical
  topics to be explored in detail. As
  always, Carl keeps the atmosphere
  light and conversational, which makes
  for a nice way to spend your lunch
  hour!


q:
I have been thinking about design by contract lately and I was wondering what people think is the best way to assert pre-condition and post-condition of values in .NET?
i.e. validating argument values to a method.

Some people recommend Debug.Assert while others talk about using an if statement plus throwing an exception. What are the pros and cons of each?

What frameworks are available that you recommend?

[A]
I prefer exceptions over asserts because if it's supposed to be that way and isn't, I want to know about it so I can fix it, and the coverage we get in debug mode is nowhere near real-life usage or coverage, so just using Debug.Assert doesn't do enough.
Using asserts means that you won't add bloat to your release code, but it means you only get to see when and why these contracts get broken if you catch them at it in a debug build.
Using exceptions means you get to see the contract breaking whenever it happens, debug or release, but it also means your release build contains more checks and code.
You could go with an inbetween approach and use Trace to trace out your pre and post conditions to some kind of application log, which you could use to debug problems. However, you'd need a way of harvesting these logs to learn what issues your users are encountering. THere is also the possibility of combing this with exceptions so you get exceptions for the more severe problems.
The way I see it though, is that if the contract is worth enforcing then its worth throwing an exception when it breaks. I think that's somewhat down to opinion and target application though. If you do throw exceptions, you probably want some form of incident reporting system that provides crash reports when raised exceptions are left unhandled.


q:
We have a series of drop down controls that determine the sort order of columns.  The problem we are having is when the user selects a column as the 2nd column the other dropdown lists need to have their values changed so that there is only one "2nd".

Column A       [1]

Column B       [2]

Column C       [3]

Column D       [4]

Column E       [5]

In the list above, when you change Column D to [2], Column B becomes [3], C becomes [4], etc.  I can manage it on the server side but I was wondering if anybody had some clues how to do this on the client side with javascript.

[A]
Look at Javascript toolkits like
Scriptaculous
for client side reordering.
You add your elements as "
Sortables
" and code your own callbacks to execute when the items are dragged, then dropped -- such as sending an asynchronous request to the server to persist the new order.
Here is a
full tutorial
on creating sortable lists with Scriptaculous and PHP. For ASP, the client side code will be slightly different, but the process will be similar.


q:
I have a form element that I want to address via javascript, but it doesn't like the syntax.

<form name="mycache">
  <input type="hidden" name="cache[m][2]">
  <!-- ... -->
</form>

I want to be able to say:

document.mycache.cache[m][2]

but obviously I need to indicate that cache[m][2] is the whole name, and not an array reference to cache.  Can it be done?

[A]
UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute.
Here's some code that proves it:
```
```
<html>
<body>

<form id="form1">

<input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/>

<input type='button' value='Test' onclick='showtest();'/>

<script type="text/javascript">
function showtest() {
    var value = document.getElementById("field[m][2]").value;
    alert(value);
}
</script>

</form>

</body>
</html>
```
```
Update: You can also use the following to get the value from the form element:
```
```
var value = document.forms.form1["field[m][2]"].value;
```
```


q:
In JavaScript, you can do this:

var a = null;
var b = "I'm a value";
var c = null;
var result = a || b || c;

And 'result' will get the value of 'b' because JavaScript short-circuits the 'or' operator.

I want a one-line idiom to do this in ColdFusion and the best I can come up with is:

<cfif LEN(c) GT 0><cfset result=c></cfif>
<cfif LEN(b) GT 0><cfset result=b></cfif>
<cfif LEN(a) GT 0><cfset result=a></cfif>

Can anyone do any better than this?

[A]
ColdFusion doesn't have nulls.
Your example is basing the choice on which item is an empty string.
If that is what you're after, and all your other values are simple values, you can do this:
```
```
<cfset result = ListFirst( "#a#,#b#,#c#" )/>
```
```
(Which works because the standard list functions ignore empty elements.)


q: Based on several report parameters in SQL Server 2005 reporting services, I would like to automatically generate one or several chart(s) for each row in the return result and paginate or space them out. How do I go about that?

[A]
What you can do is place a
List control
on the page, set
List grouping
by record unique key (ID, or several fields if composite), and place a charts on the List. Next, set items visibility expressions to
control it with report parameters
.


q:
In Ruby:

for i in A do
    # some code
end

is the same as:

A.each do |i|
   # some code
end

for is not a kernel method:

What exactly is "for" in ruby

Is there a way to use other keywords to do similar things?

Something like:

 total = sum i in I {x[i]}

mapping to:

 total = I.sum {|i] x[i]}

[A]
```
for
```
is just syntax sugar for the
```
each
```
method. This can be seen by running this code:
```
```
for i in 1 do
end
```
```
This results in the error:
```
```
NoMethodError: undefined method `each' for 1:Fixnum
```
```


q:
The default chart object in the SQL Server (2005) Business Intelligence Development Studio doesn't seem to some have formatting options like :

specifying the text direction of labels in the x and y axis

adding a trendline to a bar chart

arbitrarily resizing items in a chart - for example, if I resize the chart object, everything gets resized accordingly but I can't keep the size of the chart the same while extending the area of the legend for instance.

multiline chart labels

So what I want to know is

is there any easy answer to the formatting problems mentioned above?

what websites/books/resources/examples would you recommend I look
    into for extending the functionality of the chart object?

[A]
yes you can specify the text direction of labels in the x and y axis
Go to chart properties and in the tab x and y axis enter the chart title and in the title align use the combination like left/right/center align.
you can change the legend line go to the chart properties click legend tab inside this
there is an option for "display legend inside plot area" and you can include the trendline there
you can use multiline text labels when the text limits extends


q: How do I convert a utf-8 string to a utf-16 string in PHP?

[A]
mbstring
supports UTF-16
, so you can use
```
mb_convert_encoding
```
.


q:
Are there any good methods for getting ASP.NET 2.0 to validate under the XHTML 1.0 Strict (or Transitional) DTD?  I'm interested to hear some ideas before I hack up the core of the HTTP response.

One major problem is the form tag itself, this is the output I got from W3C when I tried to validate:

Line 13, Column 11: there is no attribute "name".
<form name="aspnetForm" method="post" action="Default.aspx" onsubmit="javascript

That tag is very fundamental to ASP.NET, as you all know. Hmmmm.

[A]
Its possible to change the output of ASP.NET controls using techniques like the
CSS Adapters
. Although I wouldn't personally recommend you use these out of the box, it might give you some hints on a good solution.
I generally avoid using the ASP.NET controls where ever possible, except ones that don't generate markup on their own such as the Repeater control. I would look into the ASP.NET MVC framework (what StackOverflow is built on) as this gives you 100% control over markup.


q:
I need to create a unique ID for a given location, and the location's ID must be sequential.  So its basically like a primary key, except that it is also tied to the locationID.  So 3 different locations will all have ID's like 1,2,3,4,5,...,n

What is the best way to do this?
I also need a safe way of getting the nextID for a given location, I'm guessing I can just put a transaction on the stored procedure that gets the next ID?

[A]
You'll want to wrap both the code to find the next ID and the code to save the row in the same transaction.  You don't want (pseudocode):
```
```
transaction {
   id = getId
}

... other processing

transaction {
   createRowWithNewId
}
```
```
Because another object with that id could be saved during "... other processing"


q:
I recently installed the Eclipse Metrics Plugin and have exported the data for one of our projects.

It's all very good having these nice graphs but I'd really like to understand more in depth what they all mean. The definitions of the metrics only go so far to telling you what it really means.

Does anyone know of any good resources, books, websites, etc, that can help me better understand what all the data means and give an understanding of how to improve the code where necessary?

I'm interested in things like Efferent Coupling, and Cyclomatic Complexity, etc, rather than lines of code or lines per method.

[A]
I don't think that code metrics (sometimes referred to as
software metrics
) provide valuable data in terms of where you can improve.
With code metrics it is sort of nice to see how much code you write in an hour etc., but beyond they tell you nada about the quality of the code written, its documentation and code coverage. They are pretty much a week attempt to measure where you cannot really measure.
Code metrics also discriminate the programmers who solve the harder problems because they
obviously
managed to code less. Yet they solved the hard issues and a junior programmer whipping out lots of
crap code
looks good.
Another example for using metrics is the very popular
Ohloh
. They employ metrics to put a price tag on an opensource project (using number of lines, etc.), which in itself is an attempt which is
flawed as hell
- as you can imagine.
Having said all that the Wikipedia entry provides some overall insight on the topic, sorry to not answer your question in a more supportive way with a really great website or book, but I bet you got the drift that I am not a huge fan. :)
Something to employ to help you improve would be continuous integration and adhering to some sort of standard when it comes to code, documentation and so on. That is how you can improve. Metrics are just eye candy for meetings - "look we coded that much already".
Update
Ok, well my point being efferent coupling or even cyclomatic complexity can indicate something is wrong - it doesn't have to be wrong though. It can be an indicator to refactor a class but there is no rule of thumb that tells you when.
IMHO a rule such as 500+ lines of code, refactor or the
DRY principal
are more applicable in most cases. Sometimes it's as simple as that.
I give you that much that since cyclomatic complexity is graphed into a flow chart, it can be an eye opener. But again, use carefully.


q:
I need a way to allow each letter of a word to rotate through 3 different colors. I know of some not so clean ways I can do this with asp.NET, but I'm wondering if there might be a cleaner CSS/JavaScript solution that is more search engine friendly.

The designer is including a file like this for each page. I'd rather not have to manually generate an image for every page as that makes it hard for the non-technical site editors to add pages and change page names.

[A]
On the server-side you can do this easily enough without annoying search engines AFAIK.
```
```
// This server-side code example is in JavaScript because that's
// what I know best.
var words = split(message, " ");
var c = 1;
for(var i = 0; i < words.length; i++) {
   print("" + words[i] + " ");
   c = c + 1; if (c > 3) c = 1;
}
```
```
If you really want dead simple inline HTML code, write client-side Javascript to retrieve the message out of a given P or DIV or whatever based on its ID, split it, recode it as above, and replace the P or DIV's 'innerHTML' attribute.


q: Is there a way to determine the number of users that have active sessions in an ASP.NET application?  I have an admin/tools page in a particular application, and I would like to display info regarding all open sessions, such as the number of sessions, and perhaps the requesting machines' addresses, or other credential information for each user.

[A]
The way I've seen this done in the past is adding extra code to the Session_OnStart event in the Global.asax file to store the information in a session agnostic way, e.g. a database or the HttpApplicationState object. Depending upon your needs you could also use Session_OnEnd to remove this information.
You may want to initialise and clean up some of this information using the Application_Start and Application_End events.
The administration page can then read this information and display statistics etc.
This is explained in more depth at
http://msdn.microsoft.com/en-us/library/ms178594.aspx
and
http://msdn.microsoft.com/en-us/library/ms178581.aspx
.


q:
What references offer a good summary/tutorial for using RDF/OWL?  There seem to be enough tools (Protege, Topbraid, Jena, etc.) that knowing the syntax of the markup languages is not necessary, but knowing the concepts is, of course, still critical.

I'm working through the w3c documents (particularly the RDF Primer) but I'd like to find other resources/techniques to use as well.

[A]
For pragmatic use of RDF, Shelley Power's book
Practical RDF
is a good start.
The
ESW Wiki
is also a good resource
There's also
David Beckett's RDF Resource Guide
Tim Berners-Lee's notes
are always a good read
There's a
bunch of links
from the semantic-web@w3.org mailing list archives


q: Our network admins have disabled IMAP and POP for our exchange server, but do have RDP over HTTP enabled.  Does Mac Mail only use IMAP to communicate with exchange servers, or does it also know how to use RDP over HTTP?


q: Can someone provide a simple explanation of methods vs. functions in OOP context?

[A]
'method'
is the object-oriented word for
'function'
.  That's pretty much all there is to it (ie., no real difference).
Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference.
Really - there isn't all that much to it, just different words for the same thing.
[late addition]
In fact, as
Brian Neal
pointed out in a comment to
this question
, the C++ standard never uses the term 'method' when refering to member functions. Some people may take that as an indication that C++ isn't really an object-oriented language; however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.


q: I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?

[A]
```
```
int code = 2;
Environment.Exit( code );
```
```


q:
What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: xValues and yValues. (I'm trying to get the coordinates so I can animate an object along a path.)

Here's what I have so far:

circle: function(radius, steps, centerX, centerY){
    var xValues = [centerX];
    var yValues = [centerY];
    for (var i = 1; i < steps; i++) {
        xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2));
        yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2));
   }
}

[A]
If you already have half a circle, just mirror the points to get the other half
make sure you do this in the right order.
more speficically, for the other half you simply replace the "
```
+ sin(...)
```
" with a "
```
- sin(...)
```
"


q:
I have Flex based consumer website where I would like to change various look and feel type settings based on random and other criteria, and then track these through to what results in the most sales.

For instance I might completely switch out the homepage, show different things depending upon where people come from. I might show or hide certain features, or change certain text. The things i might change are as yet undefined and will likely become quite complicated.

I want to design the most flexible database schema but it must be efficient and easy to search. Currently I have a 'SiteVisit' table which contains information about each distinct visitor.

I want to find the right balance between a single table with columns for each setting, and a table containing just key value pairs.

Any suggestions?

[A]
Ok, this is very tricky. The reason for me to say that is because you are asking for two things:
relaxed repository schema so that you can store various data and change what gets saved dynamically later
fixed database schema so that you can query data effectively
The solution will be a compromise. You have to understand that.
Let's assume that you have User table:
```
```
+----------------
| User
+----------------
| UserId (PK)
| ...
+----------------
```
```
1) XML blob approach
You can either save your data as a blog (big XML) into a table (actually a property bag) but querying (filtering) will be a nightmare.
```
```
+----------------
| CustomProperty
+----------------
| PropId (PK)
| UserId (FK)
| Data of type memo/binary/...
+----------------
```
```
Advantage is that you (business logic) own the schema. This is at the same time disadvantage of this solution. Another HUGE disadvantage is that querying/filtering will be EXTREMELY difficult and SLOW!
2) Table per property
Another solution is to make a special table per property (homepage, etc.). This table would contain value per user (FK based realtionship to the User table).
```
```
+----------------
| HomePage
+----------------
| HomePageId (PK)
| UserId (FK)
| Value of type string
+----------------
```
```
Advantage of this approach is that you can very quickly see all the values for that property. Disadvantage is that you will have too many tables (one per custom property) and that you will join tables often during query operations.
3) CustomProperty table
In this solution you have one table holding all custom properties.
```
```
+----------------
| CustomPropertyEnum
+----------------
| PropertyId (PK)
| Name of type string
+----------------

+----------------
| CustomProperty
+----------------
| PropId (PK)
| PropertyId (FK)
| UserId (FK)
| Value of type string
+----------------
```
```
In this solution you store all custom properties in one table. You also have a special enum table that allows you to more efficiently query data. The disadvantage is that you will join tables often during query operations.
Choose for yourself. I would decide between 2 and 3 depending on your workload (most probably 3 because it is easier).


q:
I want to invert a 4x4 matrix. My numbers are stored in fixed-point format (1.15.16 to be exact).

With floating-point arithmetic I usually just build the adjoint matrix and divide by the determinant (e.g. brute force the solution). That worked for me so far, but when dealing with fixed point numbers I get an unacceptable precision loss due to all of the multiplications used.

Note: In fixed point arithmetic I always throw away some of the least significant bits of immediate results.

So - What's the most numerical stable way to invert a matrix? I don't mind much about the performance, but simply going to floating-point would be to slow on my target architecture.

[A]
I think the answer to this depends on the exact form of the matrix. A standard decomposition method (LU, QR, Cholesky etc.) with pivoting (an essential) is fairly good on fixed point, especially for a small 4x4 matrix. See the book 'Numerical Recipes' by Press et al. for a description of these methods.
This paper
gives some useful algorithms, but is behind a paywall unfortunately. They recommend a (pivoted) Cholesky decomposition with some additional features too complicated to list here.


q: I have saved input from a textarea element to a TEXT column in MySQL.  I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines).  I've tried a pre tag but it doesn't obey the width set in the containing div element.  Other than creating a PHP function to convert spaces to &nbsp and new lines to br tags, what are my options?  I'd prefer a clean HTML/CSS solution, but any input is welcome!  Thanks!

[A]
You can cause the text inside the
```
pre
```
to wrap by using the following CSS
```
```
pre {
 white-space: pre-wrap;       /* css-3 */
 white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
 white-space: -pre-wrap;      /* Opera 4-6 */
 white-space: -o-pre-wrap;    /* Opera 7 */
 word-wrap: break-word;       /* Internet Explorer 5.5+ */
}
```
```
Taken from
this site
It's currently defined in CSS3 (which is not yet a finished standard) but most browsers seem to support it as per the comments.


q:
I'm seeing an ambiguous error in Firebug. I don't think it's particularly related to the script I'm writing, however I don't have enough details to be able to determine that from this one error alone. Has anyone seen something similar and have a suggestion?

error:

[Exception... "Component is not available" nsresult: "0x80040111
  (NS_ERROR_NOT_AVAILABLE)" location: "JS frame ::
  file:///Applications/Firefox.app/Contents/MacOS/components/nsSessionStore.js
  :: sss_saveState :: line 1896" data: no] [Break on this error]
  this._writeFile(this._sessionFile, oState.toSource());

[A]
I have run across the same error myself, and it is an internal FireFox issue, not an issue with your script at all.  It is related to the saving of the FireFox state:
According to:
http://blogs.unbolt.net/index.php/brinley/2008/04/26/0x80040111_nssessionstore
, it is caused by a corrupted session state.
In short, I don't think there is anything you can do to avoid it (it is a bug in FireFox or perhaps a plugin).  However, that link claims you can just clear your session (via closing FireFox) to get rid of the problem when it crops up.
FYI, you may want to read the comments, as it seems closing FireFox won't necessarily eradicate the problem... but if all you care about is whether your script is at fault, then don't worry :-)


q: I have been looking at a few options for enabling localization and internationalization of a dynamic php application. There appears to be a variety of tools available such as gettext and Yahoo's R3 and I am interested in hearing from both developers and translators about which tools are good to use and what functionality is important in easing the task of implementation and translation.

[A]
We've been tinkering with
Zend_Translate
, since we use the Zend Framework anyway. It's very well documented and so far extremly solid.
In the past, I've pretty much used my own
home-grown
solution mostly. Which involves language files with constants or variables which hold all text parts and are just echo'ed in the view/template later on.
As for gettext, in the past I've heard references about PHP's gettext implementation being faulty, but I can't really back that up nor do I have any references right now.


q:
Here's my problem - I have some code like this:

<mx:Canvas width="300" height="300">
     <mx:Button x="800" />
</mx:Canvas>

So the problem is that the Button inside the canvas has an x property way in excess of the Canvas's width - since it's a child of the Canvas, the Canvas masks it and creates some scrollbars for me to scroll over to the button.

What I'd like is to display the button - 800 pixels to the left of the Canvas without the scrollbars while still leaving the button as a child of the Canvas.  How do I do that?

[A]
I figured it out - apparently the Container has a property called clipContent - here's the description from Adobe:
Whether to apply a clip mask if the positions and/or sizes of this container's children extend outside the borders of this container. If false, the children of this container remain visible when they are moved or sized outside the borders of this container. If true, the children of this container are clipped.
If clipContent is false, then scrolling is disabled for this container and scrollbars will not appear. If clipContent is true, then scrollbars will usually appear when the container's children extend outside the border of the container. For additional control over the appearance of scrollbars, see horizontalScrollPolicy and verticalScrollPolicy.
The default value is true.
So basically - to show the button outside of the bounds of the container I need to do the following:
```
```
<mx:Canvas width="300" height="300" clipContent="false" >
     <mx:Button x="800" />
</mx:Canvas>
```
```
That was easier than I thought it was going to be. :)
Here's the official doc...


q:
Internationalizing web apps always seems to be a chore.  No matter how much you plan ahead for pluggable languages, there's always issues with encoding, funky phrasing that doesn't fit your templates, and other problems.

I think it would be useful to get the SO community's input for a set of things that programmers should look out for when deciding to internationalize their web apps.

[A]
I have a couple apps that are "bilingual"
I used resource files in ASP.NET1.1
There is also something called the String Resource Tool
Basically you put all your strings in a .RES file for both languages and then determine what file to read from based on Culture or whether someone clicked a Link for the language
The biggest gotcha is making sure the Translations are done correctly


q: Please post a working source code example (or link) of how to search string in another process memory and getting offset of match if found. The similar way its done in game cheating utils which search for values in game memory using ReadProcessMemory.


q:
I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application.  If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page.  The prompt should not display if the user hasn't touched any of the controls.

Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this?  Ideally I'd like something that can easily be reused across multiple pages with minimal changes.

[A]
In the .aspx page, you need a Javascript function to tell whether or not the form info is "dirty"
```
```
<script language="javascript">
    var isDirty = false;

    function setDirty() {
        isDirty = true;
    }

    function checkSave() {
        var sSave;
        if (isDirty == true) {
            sSave = window.confirm("You have some changes that have not been saved. Click OK to save now or CANCEL to continue without saving.");
            if (sSave == true) {
                document.getElementById('__EVENTTARGET').value = 'btnSubmit';
                document.getElementById('__EVENTARGUMENT').value = 'Click';
                window.document.formName.submit();
            } else {
                 return true;
            }
        }
    }
</script>
<body class="StandardBody" onunload="checkSave()">
```
```
and in the codebehind, add the triggers to the input fields as well as resets on the submission/cancel buttons....
```
```
btnSubmit.Attributes.Add("onclick", "isDirty = 0;");
btnCancel.Attributes.Add("onclick", "isDirty = 0;");
txtName.Attributes.Add("onchange", "setDirty();");
txtAddress.Attributes.Add("onchange", "setDirty();");
//etc..
```
```


q:
I am working on an application that will sport a web-based point of sale interface.

The point of sale PC (I am not sure as of now whether it will run on Linux or Windows) must have a fiscal printer attached to it, but like any web app, it is the server which processes all stuff. Both server and PoS machines are on the same LAN.

I must send the sale data in real time, and via the fiscal printer which uses the serial port, so printing a PDF or even a web page is not an option.

I've been told I could have a little app listening on web services on the client, which in turn talks to the printer instead of the server or the browser, but don't have a clue how to do it. Also, I'll most likely need to listen to any printer feedback (coupon number, for instance, which is generated by the printer) and hand it back to the server.

Any ideas?

[A]
I did something similar to this a couple of yrs. ago. But in my case the server and the PC where in the same lan. Is your PoS within the lan? If so, I'll explain it to you.
In the mean time, if you have the "little app" covered you can take a look at the following:
http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html
The print service have a method to discover the printers registered within machine it is running on. So after you receive the message from the server on your app you just have to do something similar to the code shown in the link above:
Taked from,
http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html
```
```
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices =
             PrintServiceLookup.lookupPrintServices(flavor, aset);
if (pservices.length > 0) {
   DocPrintJob pj = pservices[0].createPrintJob();
   // InputStreamDoc is an implementation of the Doc interface //
   Doc doc = new InputStreamDoc("test.ps", flavor);
   try {
         pj.print(doc, aset);
    } catch (PrintException e) {
    }
}
```
```


q:
In my php web app, suppose I want to go the extra mile and in addition to going gang-busters and being anal-retentive about sanitizing my inputs, I also want to ensure that no JavaScript is being output in strings I am inserting into html templates.

Is there a standard way to make sure I don't put JavaScript in the generated html content?

[A]
not exactly a standard way; because what if you were doing:
```
<img src="${path}">
```
, and
```
${path}
```
expanded to
```
http://p0wned.com/jpg.jpg" /><script src="p0wned.com/js.js"/>
```
Anyway I like this regular expression:
```
```
#from http://www.perlmonks.org/?node_id=161281
sub untag {
  local $_ = $_[0] || $_;
# ALGORITHM:
#   find < ,
#       comment <!-- ... -->,
#       or comment <? ... ?> ,
#       or one of the start tags which require correspond
#           end tag plus all to end tag
#       or if \s or ="
#           then skip to next "
#           else [^>]
#   >
  s{
    <               # open tag
    (?:             # open group (A)
      (!--) |       #   comment (1) or
      (\?) |        #   another comment (2) or
      (?i:          #   open group (B) for /i
        ( TITLE  |  #     one of start tags
          SCRIPT |  #     for which
          APPLET |  #     must be skipped
          OBJECT |  #     all content
          STYLE     #     to correspond
        )           #     end tag (3)
      ) |           #   close group (B), or
      ([!/A-Za-z])  #   one of these chars, remember in (4)
    )               # close group (A)
    (?(4)           # if previous case is (4)
      (?:           #   open group (C)
        (?!         #     and next is not : (D)
          [\s=]     #       \s or "="
          ["`']     #       with open quotes
        )           #     close (D)
        [^>] |      #     and not close tag or
        [\s=]       #     \s or "=" with
        `[^`]*` |   #     something in quotes ` or
        [\s=]       #     \s or "=" with
        '[^']*' |   #     something in quotes ' or
        [\s=]       #     \s or "=" with
        "[^"]*"     #     something in quotes "
      )*            #   repeat (C) 0 or more times
    |               # else (if previous case is not (4))
      .*?           #   minimum of any chars
    )               # end if previous char is (4)
    (?(1)           # if comment (1)
      (?<=--)       #   wait for "--"
    )               # end if comment (1)
    (?(2)           # if another comment (2)
      (?<=\?)       #   wait for "?"
    )               # end if another comment (2)
    (?(3)           # if one of tags-containers (3)
      </            #   wait for end
      (?i:\3)       #   of this tag
      (?:\s[^>]*)?  #   skip junk to ">"
    )               # end if (3)
    >               # tag closed
   }{}gsx;          # STRIP THIS TAG
  return $_ ? $_ : "";
}
```
```


q: What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages?

[A]
I think
MSDN
is pretty clear in definition:
The SafeHandle class provides critical
  finalization of handle resources,
  preventing handles from being
  reclaimed prematurely by garbage
  collection and from being recycled by
  Windows to reference unintended
  unmanaged objects. Before the .NET
  Framework version 2.0, all operating
  system handles could only be
  encapsulated in the IntPtr managed
  wrapper object.
The SafeHandle class contains a
  finalizer that ensures that the handle
  is closed and is guaranteed to run,
  even during unexpected AppDomain
  unloads when a host may not trust the
  consistency of the state of the
  AppDomain.
For more information about the
  benefits of using a SafeHandle, see
  Safe Handles and Critical
  Finalization.
This class is abstract because you
  cannot create a generic handle. To
  implement SafeHandle, you must create
  a derived class. To create SafeHandle
  derived classes, you must know how to
  create and free an operating system
  handle. This process is different for
  different handle types because some
  use CloseHandle, while others use more
  specific methods such as
  UnmapViewOfFile or FindClose. For this
  reason, you must create a derived
  class of SafeHandle for each operating
  system handle type; such as
  MySafeRegistryHandle,
  MySafeFileHandle, and
  MySpecialSafeFileHandle. Some of these
  derived classes are prewritten and
  provided for you in the
  Microsoft.Win32.SafeHandles namespace.


q:
ADO.NET has the notorious DataRow class which you cannot instantiate using new.  This is a problem now that I find a need to mock it using Rhino Mocks.

Does anyone have any ideas how I could get around this problem?

[A]
Any time I can't mock something (I prefer MoQ over Rhino, but that's beside the point) I have to code around it.
The way I see it you only have two choices.  Pay for a superior framework such as TypeMock that can mock ANY class, or code a wrapper around classes that weren't written to be mocked.
Its a sad state of affairs in the framework.  TDD wasn't a big concern back in the 1.1 days.


q:
I am getting this error but only very occasionally.  99.9% of the time it works fine:

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

Does anyone have any idea on what the cause could be?  I only use that datatable for viewing and not updating so is it possible to easily turn off all constraints somehow?

[A]
This typically happens when the schema on your dataset is enforcing something that your database is not.
Visual Studio will automatically read schema and try and set up some primary keys on your dataset, but if you are using a view that can possibly return multiple rows it will fail. It is easy enough to remove these constraints from the DataSet itself by deleting the constraint in the designer.
Check to ensure that your dataset is not enforcing a primary key in a situation where you could possibly have two rows with the same key, like in a View that joins two tables together and therefore duplicates the rows in the parent table. VS by default will try and create the primary key of the parent table as a unique constraint on the dataset, but the view itself enforces no such constraint.


q:
I need to create an access (mdb) database without using the ADOX interop assembly.

How can this be done?

[A]
Before I throw away this code, it might as well live on stackoverflow
Something along these lines seems to do the trick:
```
```
if (!File.Exists(DB_FILENAME))
{
    var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_FILENAME;

    // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly.
    var catType = Type.GetTypeFromProgID("ADOX.Catalog");
    object o = Activator.CreateInstance(catType);
    catType.InvokeMember("Create", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr});

    OleDbConnection cnn = new OleDbConnection(cnnStr);
    cnn.Open();
    var cmd = cnn.CreateCommand();
    cmd.CommandText = "CREATE TABLE VideoPosition (filename TEXT , pos LONG)";
    cmd.ExecuteNonQuery();

}
```
```
This code illustrates that you can access the database using OleDbConnection once its created with the ADOX.Catalog COM component.


q: Can't seem to rename an existing Verity collection in ColdFusion without deleting, recreating, and rebuilding the collection.  Problem is, I have some very large collections I'd rather not have to delete and rebuild from scratch.  Any one have a handy trick for this conundrum?

[A]
I don't believe that there is an easy way to rename a Verity collection.  You can always use
```
```
<cfcollection action="map" ...>
```
```
to assign an alias to an existing collection, provided you do not need to re-use the original name.


q:
I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build.

Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running.

For windows I use:

ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL);

For Linux I currently use:

pid_t pid;
char *args[2];

char *prog=0;
char firefox[]={"/usr/bin/firefox"};

if(strstri(filename,".html"))
    prog=firefox;

if(prog)
{
    args[0]=(char *)filename;
    args[1]=0;
    pid=fork();
    if(!pid)
        execvp(prog,args);

}

[A]
If you're writing this for modern distros, you can use
```
xdg-open
```
:
```
```
$ xdg-open http://google.com/
```
```
If you're on an older version you'll have to use a desktop-specific command like
```
gnome-open
```
or
```
exo-open
```
.


q: I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.

[A]
If you have an NT-family Windows (one with
```
cmd.exe
```
as the shell), try
the FOR /F command
.


q:
The following code executes a simple insert command.  If it is called 2,000 times consecutively (to insert 2,000 rows) an OleDbException with message = "System Resources Exceeded" is thrown.  Is there something else I should be doing to free up resources?

using (OleDbConnection conn = new OleDbConnection(connectionString))
using (OleDbCommand cmd = new OleDbCommand(commandText, conn))
{
    conn.Open();
    cmd.ExecuteNonQuery();
}

[A]
The system resources exceeded error is not coming from the managed code, its coming from you killing your database (JET?)
You are opening way too many connections, way too fast...
Some tips:
Avoid round trips by not opening a new connection for every single command, and perform the inserts using a single connection.
Ensure that database connection pooling is working. (Not sure if that works with OLEDB connections.)
Consider using a more optimized way to insert the data.
Have you tried this?
```
```
using (OleDBConnection conn = new OleDBConnection(connstr))
{
    while (IHaveData)
    {
        using (OldDBCommand cmd = new OldDBCommand())
        {
            cmd.Connection = conn;
            cmd.ExecuteScalar();
        }
    }
}
```
```


q: I know about the HIG (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch).

[A]
Golden Rule: If you
```
alloc
```
then you
```
release
```
!
UPDATE: Unless you are using ARC


q:
I have an MDI application. When I show a message box using MessageBox.Show(), the entire application disappears behind all of my open windows when I dismiss the message box.

The code is not doing anything special. In fact, here is the line that invokes the message box from within an MDI Child form:

MessageBox.Show(String.Format("{0} saved successfully.", Me.BusinessUnitTypeName), "Save Successful", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly)

Me.BusinessUnitTypeName() is a read only property getter that returns a string, depending upon the value of a member variable. There are no side effects in this property.

Any ideas?

[A]
Remove the
```
MessageBoxOptions.DefaultDesktopOnly
```
parameter and it will work correctly.
```
DefaultDesktopOnly
```
specifies that "
The message box is displayed on the active desktop
" which causes the focus loss.


q:
Given this:

Public Sub timReminder_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If DateTime.Now() > g_RemindTime Then
        Reminders.ShowDialog()
        timReminder.Enabled = False
    End If
End Sub

I want to be able to say this (as I would in Delphi):

timReminder.Tick = timReminder_Tick

But I get errors when I try it.

Does anyone know how I can assign a custom event to a timer's on-tick event at runtime in VB.NET?

[A]
Use the 'AddHandler' and 'AddressOf' keywords to add a handler to the Tick event.
```
AddHandler timeReminder.Tick, AddressOf timeReminder_Tick
```


q:
I can't quite figure out this syntax problem with a case expression in a do block.

What is the correct syntax?

If you could correct my example and explain it that would be the best.

module Main where

main = do
     putStrLn "This is a test"
     s <- foo
     putStrLn s

foo = do
    args <- getArgs
    return case args of
                [] -> "No Args"
                [s]-> "Some Args"

A little update. My source file was a mix of spaces and tabs and it was causing all kinds of problems.
Just a tip for any one else starting in Haskell. If you are having problems check for tabs and spaces in your source code.

[A]
return is an (overloaded) function, and it's not expecting its first argument to be a keyword.  You can either parenthesize:
```
```
module Main where
import System(getArgs)

main = do
     putStrLn "This is a test"
     s <- foo
     putStrLn s

foo = do
    args <- getArgs
    return (case args of
                [] -> "No Args"
                [s]-> "Some Args")
```
```
or use the handy application operator ($):
```
```
foo = do
    args <- getArgs
    return $ case args of
                [] -> "No Args"
                [s]-> "Some Args"
```
```
Stylewise, I'd break it out into another function:
```
```
foo = do
    args <- getArgs
    return (has_args args)

has_args [] = "No Args"
has_args _  = "Some Args"
```
```
but you still need to parenthesize or use ($), because return takes one argument, and function application is the highest precedence.


q:
You can limit "Check-In Policy" rules via the "Custom Paths" policy. But the "Check-in Notes" tab doesn't seem to fit in to the same system. Why isn't "Check-In notes" just another "Check-In policy"??

I'm using Team Foundation Server 2008 SP1

[A]
That's an interesting question - the short answer is you cannot.
I have ran into the issue myself a lot where people get check-in notes and check-in policies confused because, while very different in implementation on the server, they often serve similar purposes.
Check-in notes are bits of structured meta-data that you want to collect on every check-in to a Team Project.  They can be thinks like who was the code reviewer or a reference to a ticket in an external CRM system or something.  You can make them required, or just have them defined for people to optionally fill out.
Check-in policies are bits of code that run on the client at the point of check-in that get a say if the check-in should be allowed or not.  These are useful for checking things like you have associated a check-in with a work item, given it a comment or the code you are check-in in passes certain key static code analysis rules (such as basic checking for SQL injection attacks etc).  If a check-in policy fails in the evaluation of the check-in then the user gets alerted and they get the ability to fix the problem or check-in anyway with a check-in policy override than can easily be reported on or alerted for by the TFS administrator.
Both check-in notes and check-in policies are defined and scoped at the Team Project level.  However, Microsoft got feedback that some people would like check-in policies would like to be applied to specific paths in version control rather than just the Team Project and so the Custom Path Policy was invented.
The Custom Path Policy is a bit of a hack that allows you to wrap check-in policies inside the custom path policy.  The custom path gets evaluated on every check-in and if it contains files inside the defined path then the wrapped check-in policies are evaluated for those files.  The Custom Path Policy ships in the
TFS Power Tools
and is not part of the "Out The Box" TFS experience.
So, to answer your question a different way - I suspect the answer is "because that's the way it was designed and not enough people have asked for it to be changed".
If you wanted to leave feedback at
http://connect.microsoft.com/VisualStudio
I know they take customer feedback very seriously.


q:
At work we have 4 people working together on a few different projects. For each project we each have a local copy we work on and then there is a development, staging, and live deployment, along with any branches we have (we use subversion). Our database is MySQL.

So my question is, what is a good way to manage which revisions to the database have been made to each deployment (and for the developers their local copies). Right now each change goes into a text file that is timestamped in the name and put into a folder under the project. This isn't working very well to be honest.. I need a solution that will help keep track of what has been applied where.

[A]
http://odetocode.com/Blogs/scott/archive/2008/01/30/11702.aspx
The above blog brought us to our current database version control system.  Simply put, no DB changes are made without an update script and all update scripts are in our source control repository.
We only manage schema changes but you may also be able/willing to consider keeping dumps of your data available in version control as well; creating such files is a pretty trivial exercise using mysqldump.
Our solution differs from the solution presented in the blog in one key manner: it's not automated.  We have to hand apply database updates, etc.  Though this can be slightly time consuming, it postponed some of the effort a fully automated system would have required.  One thing we did automate however, was the db version tracking in the software: this was pretty simple and it ensures that our software is aware of the database it's running against and will ONLY run if it knows the schema it's working with.
The hardest part of our solution was how to merge updates from our branches into our trunk.  We spent some time to develop a workflow to address the possibility of two developers trying to merge branches with DB updates at the same time and how to handle it.  We eventually settled on locking a file in version control (the file in question for us is actually a table mapping software version to db version which assists in our manual management strategy), much like you would a thread's critical section, and the developer who gets the lock goes about their update of the trunk.  When completed, the other developer would be able to lock and it is their responsibility to make any changes necessary to their scripts to ensure that expected version collisions and other bad juju are avoided.


q: I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?

[A]
Doing this seems like a hack, but it seems to work:
```
```
this.TopMost = true;  // as a result the form gets thrown to the front
this.TopMost = false; // but we don't actually want our form to always be on top
```
```
Edit: Note, this merely raises an already created form without stealing focus.


q: I am just starting with SL and WPF. I am using the DataGrid control and I need to remove the mouseover effect (I actually will need to do more customizations than that). How do I do this. I think I need to do it with a control template but not sure how. I'm researching and reading right now. Any help would be appreciated.

[A]
Yeah You have to change the Style and ControlTemplate , But are you using experssion blend to edit XAML? Blend is the easiest tool to do this.
Try changing the ControlTemplate for a Standard Button or ListBox and once you are comfortable then go to DatGrid. Why I am suggesting this is DataGrid is a complex combination of different UIElements so the control template will be hard to understand for a beginner.
Specific to MouseOver effect removal - There will be a
VSM
tag in the control template which has some storyboards , just remove the one with
```
<vsm:VisualState x:Name="MouseOver">
```
and you are good to go.


q:
I'm using CSS Filters to modify images on the fly within the browser. These work perfectly in Internet Explorer, but aren't supported in Firefox.

Does anyone know what the CSS Filter equivalent for these is for Firefox? An answer that would work cross browser (Safari, WebKit, Firefox, etc.) would be preferred.

<style type="text/css">
    .CSSClassName {filter:Invert;}
    .CSSClassName {filter:Xray;}
    .CSSClassName {filter:Gray;}
    .CSSClassName {filter:FlipV;}
</style>

Update: I know Filter is an IE specific feature. Is there any kind of equivalent for any of these that is supported by Firefox?

[A]
There are no equivalents in other browsers. The closest you could get is using a graphics library like Canvas and manipulating the images in it, but you'd have to write the manipulations yourself and they'd require JavaScript.
```
filter
```
is an IE-only feature -- it is not available in any other browser.


q: For an ecommerce website how do you measure if a change to your site actually improved usability?  What kind of measurements should you gather and how would you set up a framework for making this testing part of development?

[A]
Multivariate testing
and reporting is a great way to actually measure these kind of things.
It allows you to test what combination of page elements has the greatest conversion rate, providing continual improvement on your site design and usability.
Google Web Optimiser
has support for this.


q: Is there a framework equivalent to Guice (http://code.google.com/p/google-guice) for Python?

[A]
I haven't used it, but the
Spring Python
framework is based on Spring and implements
Inversion of Control
.
There also appears to be a Guice in Python project:
snake-guice


q:
What is the difference between the following 2 ways to allocate and init an object?

AController *tempAController = [[AController alloc] init];
self.aController = tempAController;
[tempAController release];

and

self.aController= [[AController alloc] init];

Most of the apple example use the first method. Why would you allocate, init and object and then release immediately?

[A]
Every object has a reference count.  When it goes to 0, the object is deallocated.
Assuming the property was declared as
```
@property (retain)
```
:
Your first example, line by line:
The object is created by
```
alloc
```
, it has a reference count of 1.
The object is handed over to
```
self
```
's
```
setAController:
```
method, which sends it a
```
retain
```
message (because the method doesn't know where the object is coming from), incrementing its reference count to 2.
The calling code no longer needs the object itself, so it calls
```
release
```
, decrementing the reference count to 1.
Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2.
The rule is that if you create an object, you are responsible for releasing it when you're done with it.  In your example, the code is done with tempAController after it sets the property.  It is the setter method's responsibility to call
```
retain
```
if it needs that object to stick around.
It's important to remember that
```
self.property = foo;
```
in Objective-C is really just shorthand for
```
[self setProperty:foo];
```
and that the
```
setProperty:
```
method is going to be retaining or copying objects as needed.
If the property was declared
```
@property (copy)
```
, then the object would have been copied instead of retained.  In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0.  So you would still want to write your code the same way.
If the property was declared
```
@property (assign)
```
, then
```
self
```
isn't claiming ownership of the object, and somebody else needs to retain it.  In this case, the first example would be incorrect.  These sorts of properties are rare, usually only used for object delegates.


q:
Is there a good reason why there is no Pair<L,R> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.

It seems that 1.6 is providing something similar (AbstractMap.SimpleEntry<K,V>), but this looks quite convoluted.

[A]
It depends on what you want to use it for.  The typical reason to do so is to iterate over maps, for which you simply do this (Java 5+):
```
```
Map<String, Object> map = ... ; // just an example
for (Map.Entry<String, Object> entry : map.entrySet()) {
  System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue());
}
```
```


q:
Yet again, my teacher was unable to answer my question. I knew who may be able to...

So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put

setbuf( stdout , NULL );

at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly.

My question is this: will this statement affect a cout statement, or simply a printf() statement that I call?

Thanks in advance!

[A]
By default, iostreams and stdio are synchronised.
Reference.
This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise
```
std::endl
```
or
```
std::flush
```
(from
```
<ostream>
```
), which may help you. e.g.,
```
```
std::cout << "Hello, world!" << std::endl;
```
```
or
```
```
std::cout << "Hello, world!\n" << std::flush;
```
```
Both of these do the same thing. (
```
std::endl
```
= print endline, then flush.)


q: The title is self explanatory. Is there a way of directly doing such kind of importing?

[A]
Although my MySQL background is limited, I don't think you have much luck doing that. However, you should be able to migrate over all of your data by restoring the db to a MSSQL server, then creating a SSIS or DTS package to send your tables and data to the MySQL server.
hope this helps


q:
We are putting up a company blog at companyname.com/blog but for now the blog is a Wordpress installation that lives on a different server (blog.companyname.com).

The intention is to have the blog and web site both on the same server in a month or two, but that leaves a problem in the interim.

At the moment I am using mod_rewrite to do the following:

http://companyname.com/blog/article-name redirects to http://blog.companyname.com/article-name

Can I somehow keep the address bar displaying companyname.com/blog even though the content is coming from the latter blog.companyname.com?

I can see how to do this if it is on the same server and vhost, but not across a different server?

Thanks

[A]
Rather than using mod_rewrite, you could use
mod_proxy
to set up a reverse proxy on companyname.com, so that requests to
http://companyname.com/blog/article-name
are proxied (rather than redirected) to
http://blog.companyname.com/article-name
.
Here are
more instructions and examples
.


q:
I need to pad numbers with leading zeros (total 8 digits) for display. I'm using oracle.

select to_char(1011,'00000000') OPE_NO from dual;
select length(to_char(1011,'00000000')) OPE_NO from dual;

Instead of '00001011' I get ' 00001011'.
Why do I get an extra leading blank space? What is the correct number formatting string to accomplish this?

P.S. I realise I can just use trim(), but I want to understand number formatting better.

@Eddie: I already read the documentation. And yet I still don't understand how to get rid of the leading whitespace.

@David: So does that mean there's no way but to use trim()?

[A]
From that same
documentation
mentioned by
EddieAwad
:
Negative return values automatically
  contain a leading negative sign and
  positive values automatically contain
  a leading space unless the format
  model contains the MI, S, or PR format
  element.
EDIT
: The right way is to use the FM modifier, as answered by Steve Bosman. Read the section about
Format Model Modifiers
for more info.


q:
I'm just trying to time a piece of code. The pseudocode looks like:

start = get_ticks()
do_long_code()
print "It took " + (get_ticks() - start) + " seconds."

How does this look in Python?

More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?

[A]
What you need is
```
time()
```
function from
```
time
```
module:
```
```
import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."
```
```
You can use
timeit
module for more options though.


q: I was inserting data into a MS Access database using JDBC-ODBC driver.  The blank mdb file was 2KB.  After populating this database, the size grew to 155MB.  Then I was deleting the data.  But I found the size of mdb remains the same as 155MB.  I don't get any errors.  But is it normal this way?  I would expect the file size reduces.  If it is designed in this way, what is the idea behind it?  Thanks

[A]
MS Access doesn't free up space used by records even after they are deleted. You can free the space manually when you need to or automatically each time you close the application.
To do it manually, use the Compact and Repair utility:
Backup your database, as there is a
bug in Access 2007
that may delete your database during the compacting procedure.
If you are compacting a multiuser (shared) database that is located on a server or shared folder, make sure that no one else has it open.
On the Tools menu, point to Database Utilities, and then click Compact and Repair Database.
To do it automatically when you close the application:
Open the database that you want MS Access to compact automatically.
On the Tools menu, click Options, and then choose the General tab.
Select the Compact On Close check box.
After deleting the data and compacting the database don't be surprised if is still larger than 100 KB. There is a certain amount of overhead that cannot be removed after you add data the first time.
Also, beware that AutoNumber field values behave differently than advertised after the compacting procedure: According to the MS Access 2000 documentation, if you delete records from the end of a table that has an AutoNumber field, compacting the database resets the AutoNumber value. So the AutoNumber value of the next record you add will be one greater than the AutoNumber value of the last undeleted record in the table.
I have
not
found this to be the case: If you have 100 Autonumbered records and delete the last 50, the next AutoNumber record (according to the documentation) should be numbered "51". But in my experience it is numbered "101", instead.


q:
I have one thread that writes results into a Queue.

In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:

def queue_get_all(q):
    items = []
    while 1:
        try:
            items.append(q.get_nowait())
        except Empty, e:
            break
    return items

Is this a good way to do it ?

Edit:

I'm asking because sometimes the
  waiting thread gets stuck for a few
  seconds without taking out new
  results.

The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling wx.WakeUpIdle, as is recommended.

[A]
I see you are using get_nowait() which according to the documentation, "return[s] an item if one is immediately available, else raise the Empty exception"
Now, you happen to break out of the loop when an Empty exception is thrown. Thus, if there is no result immediately available in the queue, your function returns an empty items list.
Is there a reason why you are not using the get() method instead? It may be the case that the get_nowait() fails because the queue is servicing a put() request at that same moment.