q:
What's the best way to use NaNs in C++?

I found std::numeric_limits<double>::quiet_NaN() and std::numeric_limits<double>::signaling_NaN().  I'd like to use signaling_NaN to represent an uninitialized variable as follows:

double diameter = std::numeric_limits<double>::signaling_NaN();

This, however, signals (raises an exception) on assignment.  I want it to raise an exception on use, not on assignment.

Is there any way to use signaling_NaN without raising an exception on assignment?  Is there a good, portable alternative to signaling_NaN that will raise a floating point exception when used?

[A]
You can write a signalling NaN into a variable without triggering an exception with something like this (nb: untested)
```
```
void set_snan( double &d )
{
    long long *bits = (long long *)&d;
    *bits = 0x7ff0000080000001LL;
}
```
```
It'll work most places, but no, it's not 100% portable.


q:
In class, we learned about the halting problem, Turing machines, reductions, etc. A lot of classmates are saying these are all abstract and useless concepts, and there's no real point in knowing them (i.e., you can forget them once the course is over and not lose anything).

Why is theory useful? Do you ever use it in your day-to-day coding?

[A]
The things I use most:
computational complexity to write algorithms that scale gracefully
understanding of how memory allocation, paging, and CPU caching work so I can write efficient code
understanding of data structures
understanding of threading, locking, and associated problems
As to that stuff on Turing machines etc. I think it is important because it defines the constraints under which we all operate.  Thats important to appreciate.

s: huggingface

c: devops

d: intermediate


q:
What's the best way to unit test large data sets?  Some legacy code that I'm maintaining has structures of a hundred members or more; other parts of the code that we're working on create or analyze data sets of hundreds of samples.

The best approach I've found so far is to serialize the structures or data sets from disk, perform the operations under test, serialize the results to disk, then diff the files containing the serialized results against files containing expected results.  This isn't terribly fast, and it violates the "don't touch the disk" principle of unit testing.  However, the only alternative I can think of (writing code to initialize and test hundreds of members and data points) seems unbearably tedious.

Are there any better solutions?

[A]
This is still a viable approach. Although, I would classify this as a functional test, or just not a pure unit test. A good unit test would be to take a sampling of those records that gives to a good distribution of the edge cases you may encounter, and write those up. Then, you have your last "acceptance" or "functional" test with your bulk test on all the data.
I have use this approach when testing large amounts of data, and i find it works well enough because the small units are maintainable, and then I know that the bulk test works, and it's all automatic.


q:
I have trouble comparing 2 double in Excel VBA

suppose that I have the following code

Dim a as double
Dim b as double
a = 0.15
b = 0.01

After a few manipulations on b, b is now equal to 0.6

however the imprecision related to the double data type gives me headache because

if a = b then
 //this will never trigger
end if

Do you know how I can remove the trailing imprecision on the double type?

[A]
It is never wise to compare doubles on equality.
Some decimal values map to several floating point representations. So one 0.6 is not always equal to the other 0.6.
If we subtract one from the other, we probably get something like 0.00000000051.
We can now define equality as having a difference smaller that a certain error margin.


q:
Finding out what's selected in real browsers is as simple as:

var range = {
  start: textbox.selectionStart,
  end: textbox.selectionEnd
}

But IE, as usual, doesn't understand. What's the best cross-browser way to do this?

[A]
My current solution is verbose and based on
this thread
, but I'm open to better solutions.
```
```
function getSelection(inputBox) {
    if ("selectionStart" in inputBox) {
        return {
            start: inputBox.selectionStart,
            end: inputBox.selectionEnd
        }
    }

    //and now, the blinkered IE way
    var bookmark = document.selection.createRange().getBookmark()
    var selection = inputBox.createTextRange()
    selection.moveToBookmark(bookmark)

    var before = inputBox.createTextRange()
    before.collapse(true)
    before.setEndPoint("EndToStart", selection)

    var beforeLength = before.text.length
    var selLength = selection.text.length

    return {
        start: beforeLength,
        end: beforeLength + selLength
    }
}
```
```


q:
Given the following file:

department=value1
location=valueA
location=valueB
department=value2

I use the following to load the file into a Perl hash:

use File::Slurp;
use Data::Dumper;
my %hash = map {
   s/#.*//;
   s/^\s+//;
   s/\s+$//;
   m/(.*?)\s*=\s*(.*)/;
} read_file($file);
print Dumper(\%hash);

The result, however, is as follows:

$VAR1 = {
          'location' => 'valueB',
          'department' => 'value2'
        };

How can I load the above file into a hash with, say,

$VAR1 = {
          'location' => 'valueA,valueB',
          'department' => 'value1,value2'
        };

Thanks.

[A]
Here you go:
```
```
my %hash;
while (<FILE>)
{
   chomp;
   my ($key, $val) = split /=/;
   $hash{$key} .= exists $hash{$key} ? ",$val" : $val;
}
```
```
This walks through every line splitting on the '=' sign and either adds an entry or appends to an existing entry in the hash table.


q:
The way I do 80-column indication in Vim seems incorrect:set columns=80.
At times I also set textwidth, but I want to be able to see and anticipate line overflow with the set columns alternative.

This has some unfortunate side effects:

I can't set number for fear of splitting between files that have different orders of line numbers; i.e. < 100 line files and >= 100 line files will require two different set columns values because of the extra column used for the additional digit display.

I also start new (g)Vim sessions instead of splitting windows vertically. This is because vsplit forces me to set columns every time I open or close a pane, so starting a new session is less hassle.

How do you handle the 80-character indication when you want to set numbers, vertically split, etc.?

[A]
I'm afraid that you've put constraints on the set of solutions that, well, leave you with the null set.
Using
```
:set textwidth=80
```
will fix all of the problems you mentioned
except
that you can't easily see the line limit coming up. If you
```
:set ruler
```
, you'll enable the x,y position display on the status bar, which you can use to see which column you're in.
Aside from that, I'm not sure what to tell you. It's a shame to lose the number column, fold column and splits just because you have to
```
:set columns=80
```
.


q:
How do I sort the columns in a winforms datagrid control into alphabetical order?

Thanks

[A]
Have you tried binding the DataGrid to a DataTable object (instead of a view) and turning setting the "AllowSorting" property to true on the DataGrid? I believe the grid will then automatically sort the table source for you.
If not, you can always catch the event when a column header is clicked and rebuild a DataView to bind to the DataGrid.


q:
string [] files = new string[2];
files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml";
files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml";

//Resharper complains this is an "access to modified closure"
for (int i = 0; i < files.Length; i++ )
{
    // Resharper disable AccessToModifiedClosure
    if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(),
    delegate(string name) { return name.Equals(files[i]); }))
         return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]);
    // ReSharper restore AccessToModifiedClosure
}

The above seems to work fine though ReSharper complains that this is "access to modified closure".  Can any one shed light on this?

(this topic continued here)

[A]
In this case, it's okay, since you are actually executing the delegate
within
the loop.
If you were saving the delegate and using it later, however, you'd find that all of the delegates would throw exceptions when trying to access files[i] - they're capturing the
variable
```
i
```
rather than its value at the time of the delegates creation.
In short, it's something to be aware of as a
potential
trap, but in this case it doesn't hurt you.
See the
bottom of this page
for a more complex example where the results are counterintuitive.


q:
I was wondering about implementing my own sessions (more for an exercise than anything else) for a GAE app I'm working ... at first I was thinking of using the datastore to store the session data. However, every time something needs to be added to the session 'bucket', it would require saving to the datastore. Obviously that's bad since we want to minimize our writes. Then I thought about using memcache ... seemed like a good idea but then we're faced with issues of possible session corruption due to memcache being "evicted through memory pressure" by Google. So does that mean we are left with only the following options:

Storing all session data in cookies

Writing all session data to datastore and memcache, and then only reading from memcache

Anyone have any other ideas?

[A]
I suggest checking out (and contributing to) these three implementations of appengine sessions before rolling out your own:
app-engine-patch
gaeutilities
gae-session
Your options look fine but choosing between them probably depends on the size of the session data in your application.


q:
Can anyone suggest some references or other resources that are useful in learning MCML?

I have a small pet project I have been working on for a while using C# and .Net 3.5. I have reached a point where I want to be able to send output from it to Windows Media Center, but I have been having a hard time finding coherent explanations of how to create MCML elements to represent my C# data objects.  Particularly I am having  a hard time finding information on creating an MCML element for each element in a C# collection.  Any suggestions?


q: Is there a way to show IE/Firefox Back button style, dropdown menu button?

[A] Sure.  Put a toolbar on the page.  Right-click on the toolbar, add a button. Set the button's style to tbsDropDown.  Put a PopupMenu on the page.  Double click on the PopupMenu to define menu items.  Then, go back to the button you created and set its DropdownMenu property to point to the PopupMenu you just created.


q: What is the best way to validate a crontab entry with PHP? Should I be using a regex, or an external library? I've got a PHP script that adds/removes entries from a crontab file, but want to have some way to verify that the time interval portion is in a valid format.

[A]
You should be able to do that fairly easily with regex. In fact, I wouldn't be surprised if you could find an existing regex for just that on Google. This is untested, but perhaps something like:
```
```
/^((\*)|(\d+((-\d+)|(,\d+)+))\s+){5}/
```
```


q:
Using jQuery, how would you show() every div.foo on a page in a random order, with a new one appearing every X milliseconds?

Clarification: I want to start with all these elements hidden and end with all of them showing, so it wouldn't make sense to show() the same element twice.

I originally thought I'd make an array listing all the elements, randomly pick one, show that one, remove it from the array using splice(), and then randomly pick the next one from the remaining list - etc. But since my array is part of a jQuery object, splice() is not available.

[A]
I don't use jQuery myself, but what about this:
```
```
var intervalMilliseconds = X; // set to your value for X
var divFoos = $("div.foo").get();
var intervalId = setInterval(function() {
   $(divFoos.splice(Math.floor(Math.random() * divFoos.length), 1)).show();
   if(divFoos.length == 0) clearInterval(intervalId);
}, intervalMilliseconds);
```
```
That should do the trick.
UPDATE: Since your description isn't explicit about it, I assumed you meant that you ultimately want to show all of them, and that once they are visible, we are done. If not, please explain further so I can update this (if you can't already determine what you need from the code I provided).


q:
I am using a mock object in RhinoMocks to represent a class that makes calls to MessageQueue.GetPublicQueues. I want to simulate the exception thrown when message queueing is operating in workgroup mode, which is a MessageQueueException, to ensure that I am catching the exception correctly

The MessageQueueException has no public constructor, only the standard protected constructor for an exception. Is there an appropriate way to throw this exception from the mock object / Expect.Call statement?

[A]
Reflection can break the accessibility rulez.  You
will
void the warranty, a .NET update can easily break your code.  Try this:
```
```
using System.Reflection;
using System.Messaging;
...
        Type t = typeof(MessageQueueException);
        ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
          null, new Type[] { typeof(int) }, null);
        MessageQueueException ex = (MessageQueueException)ci.Invoke(new object[] { 911 });
        throw ex;
```
```


q:
I've seen with Microsoft COM and XPCOM, at least from what I've read and gathered so far, that the implementations of interfaces in a component have to essentially be in the single class that derives all the virtual interfaces. Is this correct? What am I missing?

Is there a way to have multiple objects (possibly in separate DLL's) each provide their functionality and still be able to freely transition between them using QueryIterface?

What I'm looking for is to have a component with some functionality, but still allow external client code to create new extensions of the component with (possibly) new interfaces. Ideally this should happen without divulging the current source of the component and its implementation.

[A]
This should be possible, although probably not supported by the standard high-level wrappers. Most of the wrappers (ATL, MFC, etc.) only support mapping a COM object to a single class. However, QueryInterface is allowed to return a different pointer and calls COM object code, so the first COM object could load a different DLL, instantiate a different object, and return a pointer to it's interface (vtable).
It's all possible as far as I know, you'll just likely be writing a lot of the low-level glue code yourself.


q: What is the best way to overwrite a specific line in a file? I basically want to search a file for the string '@parsethis' and overwrite the rest of that line with something else.

[A]
If the file isn't too big, the best way would probably be to read the file into an array of lines with
file()
, search through the array of lines for your string and edit that line, then
implode()
the array back together and
fwrite()
it back to the file.


q:
It seems like each body section in an axapta report can only print columns from a single table(consistantly).  For instance:
I have a report that has the following tables: SalesLine, InventTable and CustTable.  Then I would like to print columns from each of this tables on the same row.  It seems like I can do this when placing the fields in programmable sections but not when I place them in body sections.

I have found a few workaround that are either ugly or non-performant.  There has to be a nice clean way to do this?

[A]
It should be possible to do this, there are several reports in the base system that work this way. Look at the SalesContractShipment report in 4.0 as an example.
On your report, create a datasource for SalesLine, and under that create datasource each for InventTable and CustTable. On InventTable and CustTable, make sure the FetchMode is set to 1:1. If you create a custom fetch method, make sure you call send() in the correct order.  You should send CustTable first, then InventTable, then SalesLine last. On the report design, create a single body for SalesLine. You should then be able to use fields from any of the three tables in that body.
If you are still having trouble, I can think of two work arounds. One is to create a view based on those three tables, and create a report based on that view. The other is to create the report based on SalesLine and use displayMethods to lookup any fields you need from InventTable or CustTable.


q:
I was wondering what is the best data structure to deal with a lot of moving objects(spheres, triangles, boxes, points, etc)?  I'm trying to answer two questions, Nearest Neighbor and Collsion detection.

I do realize that traditionally, data structures like R trees are used for nearest neighbor queries and Oct/Kd/BSP are used for collision detection problems dealing with static objects, or with very few moving objects.

I'm just hoping that there is something else out there that is better.

I appreciate all the help.

[A]
Bounding Spheres probably would help you with many moving objects; you calculate the radius squared of the object, and track it from it's center.  If the squared distance between the centers of two objects is less than the sum of the squared radii of the two objects, then you have a potential collision.  Everything done with squared distances; no square roots.
You can sort nearest neighbors by the minimum squared distance between your objects.  Collision detection can get complex, of course, and with non-spherically shaped objects, Bounding Spheres won't necessarily get you collision information, but it can prune your tree of objects you need to compare for collision quite nicely.
You'll need, of course, to track the CENTER of your object; and ideally you'd like for each object to be rigid, to avoid having to recalculate bounding sphere sizes (although the recalculation isn't particularly tough, particularly if you use a tree of rigid objects each with their own bounding sphere for the objects which are non-rigid; but it gets complicated).
Basically, to answer your question about data structures, you can keep all of your objects in a master array; I'd have a set of "region" arrays which consist of references to the objects in the master array that you can sort the objects into quickly based upon their cartesian coordinates; the "region' arrays should have an overlap defined of at least 2x the largest object radius in your master object array (if that's feasible; a question of object bounding sphere scaling vs. number of objects obviously comes up).
Once you've got that, you can do a quick collision test by comparing distances of all objects within a region to each other; again, this is where region definition becomes important, because you're doing a significant tradeoff of number of regions to number of comparisons.  However, it's a little simpler just because your distance comparisons come down to simple subtractions (and abs() operations, of course).
Of course, then you have to do actual collision detection between your non-spherical objects, and that can be non-trivial, but you've reduced the number of potential comparisons very dramatically at that point.
Basically, it's a two-tiered system; the first is the region array, whereby you do a rough sort on your scene.  Second, you have your intra-region distance comparison; wherein you're going to do your basic collision detection and collision flagging on the objects which have collided.
There probably is room in this sort of algorithm for use of trees in dynamic region determination to even out your region sizes to assure that your region size doesn't grow too rapidly with "crowded" regions; that sort of thing, though, is non-trivial, because with objects of differing sizes, your sort on density becomes... complex, to say the least.


q:
There are many different styles of variable names that I've come across over the years.

The current wikipedia entry on naming conventions is fairly light...

I'd love to see a concise catalog of variable naming-conventions, identifying it by a name/description, and some examples.

If a convention is particularly favored by a certain platform community, that would be worth noting, too.

I'm turning this into a community wiki, so please create an answer for each convention, and edit as needed.

[A]
Sun published a list of variable name conventions for Java
here
.  The list includes conventions for naming packages, classes, interfaces, methods, variables, and constants.
The section on variables states
Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
Some examples include
```
```
int             i;
char            c;
float           myWidth;
```
```


q:
After looking at another question on SO (Using NaN in C++) I became curious about std::numeric_limits<double>::signaling_NaN().

I could not get signaling_NaN to throw an exception. I thought perhaps by signaling it really meant a signal so I tried catching SIGFPE but nope...

Here is my code:

double my_nan = numeric_limits<double>::signaling_NaN();
my_nan++;
my_nan += 5;
my_nan = my_nan / 10;
my_nan = 15 / my_nan;
cout << my_nan << endl;

numeric_limits<double>::has_signaling_NaN evaluates to true, so it is implemented on my system.

Any ideas?

I am using ms visual studio .net 2003's C++ compiler. I want to test it on another when I get home.

Thanks!

[A]
From
TFM
:
```
```
cout << "The signaling NaN for type float is:  "
    << numeric_limits<float>::signaling_NaN( )
    << endl;
```
```
->
The signaling NaN for type float is:  1.#QNAN
where the 'Q' stands for 'Quiet'. Dunno why it would return that, but that's why it doesn't throw an exception for you.
Out of curiosity, does this work better?
```
```
const double &real_snan( void )
{
    static const long long snan = 0x7ff0000080000001LL;
    return *(double*)&snan;
}
```
```


q:
I wanted to add a UTF-8 font in Gvim but I could not find out how to do this.
I tried to follow the step on this manual but it still did not work.
http://www.inter-locale.com/whitepaper/learn/learn_to_type.html (vim section halfway the page)

Can anyone tell me how to add a font in Vim so I can have Japanese characters displayed ?

[A]
Quote from the
vim documentation
:
For MS-Windows, some fonts have a limited number of Unicode characters.  Try
using the "Courier New" font.  You can use the Edit/Select Font... menu to
select and try out the fonts available.  Only fixed-width fonts can be used
though.  Example:
```
```
:set guifont=courier_new:h12
```
```
So, I guess, unless you find a fixed width font containing the characters you want to display, then you are out of luck.


q:
I was looking through a thread dump of a java process, and notice some threads blocked by signal dispatcher.

What is signal dispatcher?  What does it do?

[A]
I found an article about this on IBM developerWorks. When the OS raises a signal to the JVM, the signal dispatcher thread will pass the signal to the appropriate handler
Revelations on Java signal handling and termination
by Chris White, Software Engineer, IBM


q:
I'm writing a client-server app using BSD sockets.  It needs to run in the background, continuously transferring data, but cannot hog the bandwidth of the network interface from normal use.  Depending on the speed of the interface, I need to throttle this connection to a certain max transfer rate.

What is the best way to achieve this, programmatically?

[A]
The problem with sleeping a constant amount of 1 second after each transfer is that you will have choppy network performance.
Let BandwidthMaxThreshold be the desired bandwidth threshold.
Let TransferRate be the current transfer rate of the connection.
Then...
If you detect your TransferRate > BandwidthMaxThreshold then you do a SleepTime =  1 + SleepTime * 1.02 (increase sleep time by 2%)
Before or after each network operation do a
Sleep(SleepTime)
If you detect your TransferRate is a lot lower than your BandwidthMaxThreshold you can decrease your SleepTime.  Alternatively you could just decay/decrease your SleepTime over time always.  Eventually your SleepTime will reach 0 again.
Instead of an increase of 2% you could also do an increase by a larger amount linearly of the difference between TransferRate - BandwidthMaxThreshold.
This solution is good, because you will have no sleeps if the user's network is already not as high as you would like.


q: Do you primarily think of reasons TO implement it, or reasons NOT TO implement it? What are the advantages of each?

[A]
I think first about the stakeholder (the client).
Will that feature help
him
? Is it indeed a functional feature that brings value?
Then I think about technical implications and the resulting complexity, in order to evaluate the trade off between implementation cost vs. not having that feature.
Based on those two first elements of reflexions, I can begin to know if I must implement it or not.
I guess there is no clear cut between reasons to or not not implement it.


q: It should be trivial, and it might even be in the help, but I can't figure out how to navigate it. How do I indent multiple lines quickly in vi?

[A]
Use the
>
command. To indent five lines,
5
>
>
. To mark a block of lines and indent it,
V
j
j
>
to indent three lines (Vim only). To indent a curly-braces block, put your cursor on one of the curly braces and use
>
%
or from anywhere inside block use
>
i
B
.
If you’re copying blocks of text around and need to align the indent of a block in its new location, use
]
p
instead of just
p
. This aligns the pasted block with the surrounding text.
Also, the
```
shiftwidth
```
setting allows you to control how many spaces to indent.


q:
How can I convert an Int64 to an Int32 type in F# without using the Microsoft.FSharp.Compatibility.Int32.of_int64?

I'm doing this because interactive doesn't seem to work when I try:

open Microsoft.FSharp.Compatibility

With FSharp.PowerPack added as a reference it says:

error FS0039: The namespace 'Compatibility' is not defined.

Edit: Does anyone have an answer to the question?  The suggestions about the int types are useful and informative, but I'm having the same issue opening the powerpack namespace in F# interactive.

[A]
F# 1.9.6 has a type conversion function so you can do this:
```
```
let num = 1000
let num64 = int64(num)
```
```


q: Making a small app, and I want a function to execute 50% of the time.  So if I were to dbl click the exe half the time the function would execute, and the other half it wouldn't.  I can't seem to find anyway to easily do this, the one solution I tried seemed to determine the chance on compile rather than on run.  Thanks in advance!

[A] Generate a random decimal number between 0 and 1. If it is greater than 0.5 run, if it is less than or equal to 0.5 do not run.


q:
I am writing an application where I will be accessing the database from django and from a stand alone application. Both need to do session verification and the session should be the same for both of them. Django has a built in authentication/session verification, which is what I am using, now I need to figure out how to reuse the same session for my stand alone application.

My question is how can I look up a session_key for a particular user?

From what it looks there is nothing that ties together auth_user and django_session

[A]
This is somewhat tricky to do, because not every session is necessarily associated with an authenticated user; Django's session framework supports anonymous sessions as well, and anyone who visits your site will have a session, regardless of whether they're logged in.
This is made trickier still by the fact that the session object itself is serialized -- since Django has no way of knowing which data exactly you want to store, it simply serializes the dictionary of session data into a string (using Python's standard "pickle" module) and stuffs that into your database.
If you have the session key (which will be sent by the user's browser as the cookie value "sessionid"), the easiest way to get at the data is simply to query the Session table for the session with that key, which returns a Session object. You can then call that object's "get_decoded()" method to get the dictionary of session data. If you're not using Django, you can look at the source code (django/contrib/sessions/models.py) to see how the session data is deserialized.
If you have the user id, however, you'll need to loop through all of the Session objects, deserializing each one and looking for one which has a key named "_auth_user_id", and for which the value of that key is the user id.


q:
I have a (derived) Menu control, that displays a rather large list of items from a custom data source. I need to disable ViewState on the menu to avoid the very annoying "Can't select a disabled or unselectable menu item" when some other control causes the current selection to change on a postback.

Unfortunately, when ViewState is disabled for the Menu, the postbacks generated by the menu aren't raising any events. If I enable ViewState, the OnMenuItemClick event is raised. If I disable ViewState, OnMenuItemClick is not raised. I'm perplexed.

I need to leave ViewState off for the menu, so how can I handle postbacks from the actual menu?

At this point I'm leaning towards using the Menu's Load event, parsing the __EVENTTARGET to see if it's the Menu, and going from there. This would technically process the postback event before it would normally but that's ok, I guess.

Any better ideas?

[A]
I've figured out the essence of the problem. Using Reflector we can see the important part(s) of the low level method that handles the actual postback and then raises the event:
```
```
string str = HttpUtility.HtmlDecode(eventArgument);
...
MenuItem item = this.Items.FindItem(str.Split(new char[] { '\\' }), 0);
if (item != null)
    this.OnMenuItemClick(new MenuEventArgs(item));
```
```
As you can see the MenuEventArgs is handed a MenuItem. If one cannot be found in the current Items collection that matches the incoming post data, then the event is not raised. With ViewState disabled, the menu doesn't have any Items (they would have been rebuilt using ViewState). So the event won't be raised.
To work around this, I've told the menu to build itself during Load using the not-yet-updated data (at this point it will be the same as it was at the end of the last request). This is essentially the same as rebuilding the menu from ViewState, so I don't feel bad in regards to performance, or whatever. OnMenuItemClick is then fired as expected. Lastly, during PreRender I tell the Menu to rebuild once again, so it reflects the changes that happened during the postback processing portion of the lifecycle.
I wasted a lot of time on this, so hopefully this info can help somebody else in a similar situation.


q:
I am working on a web page that is using jQuery. I have an Ajax call that gets data from the server and updates a div. Inside that data there is a jQuery function, but the function is not being called after the data is loaded into the page. I have the proper js files included in the page already.

This is what is returned from the Ajax call and placed into a div:

<script type="text/javascript">
    $(function() {
         $('input').myFunction('param');
    });
</script>
<p> other html </p>

How do I get the returned javascript to run after the html is inserted into the page?

(I am using Rails with the jRails plugin )

[A]
If you want JavaScript tag evaluation, with html content, you should set the dataType option of the ajax call to "html":
```
```
$.ajax({
  type: "GET",
  url: "yourPage.htm",
  dataType: "html"
});
```
```
Or dataType "script", if you want to load and execute a .js file:
```
```
$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});
```
```
more info here:
Ajax/jQuery.ajax


q:
The most favorite feature of StackOverflow for me is that it can automatically detect code in post and set appropriate color to the code.

I'm wondering how the color is set. When I do a Ctrl+F5 on a page, the code seems first be black text, then change to be colorful. Is it done by jQuery?

[A]
From
Stack Overflow Podcast #11
:
Atwood:
It is. Okay, so that comes from, that's a project some Google engineer, I think, wrote it--it's called "Prettify." And it's a little interesting in that it actually infers all the syntax highlighting, which sounds like it couldn't possibly work--it sounds actually insane, if you think about it.  But it actually kind of works.  Now, he only supports it for, there's certain dialects that just don't really work well with it, but for all the dialects that sort of, you'd find on Google. I think it comes from Google's Google Code.  It's the actual code, it's the actual JavaScript which is on Google Code that highlights that the code that comes back when you're hosting projects on Google Code.  And you, and you, um, 'cause I think they use Subversion so you can actually click through...
Spolsky:
How do they know, how do they even know what language you're writing in? And therefore, what a comment is and...
Atwood:
I don't know.  It's crazy.  It's prettify.js, so if anyone's interested in looking at this, just do a web search for "prettify.js," and you'll find it.
And here's where you can find prettify.js:
http://code.google.com/p/google-code-prettify/


q: What is a Turing machine and why do people keep mentioning it? My IBM PC is all I need to do my computation! Why does anyone care about these machines?

[A]
A Turing machine is an abstract machine capable of computation.
From Wikipedia:
Turing machines are basic abstract symbol-manipulating devices which, despite their simplicity, can be adapted to simulate the logic of any computer algorithm. They were described in 1936 by Alan Turing. Turing machines are not intended as a practical computing technology, but a thought experiment about the limits of mechanical computation. Thus they were not actually constructed. Studying their abstract properties yields many insights into computer science and complexity theory.
A Turing machine that is able to simulate any other Turing machine is called a Universal Turing machine (UTM, or simply a universal machine). A more mathematically-oriented definition with a similar "universal" nature was introduced by Alonzo Church, whose work on lambda calculus intertwined with Turing's in a formal theory of computation known as the Church-Turing thesis. The thesis states that Turing machines indeed capture the informal notion of effective method in logic and mathematics, and provide a precise definition of an algorithm or 'mechanical procedure'.


q:
My understanding is that in unix, when memory is freed, the memory doesn't get returned back to the operating system, it stays in the process to be used again for the next call to malloc.

On windows, I understand that the memory actually gets returned to the operating system.

Is there any big difference between these two ways of doing things or are they just two different ways of doing the same thing?  And if there are any pros/cons to these two methods, what are they?

EDIT:  Thanks for the clarification.  I had always thought this was an OS thing (since processes never seem to decrease in size in UNIX-like systems, but do in windows).

[A]
From this
Memory Management
article
Malloc does not normally return the freed memory to the operating system; it remains owned by the process until it terminates. The process can reuse it the next time it requests more memory, but other programs will not have access to it, even if no other memory is available. As a corollary, then, the memory footprint of a program is the size of the largest allocation(s) made at any one time. Thus it is always wise to free objects you do not need, especially large ones as soon as possible, to minimize this footprint.
That article does suggest that in Windows, at least for C program, the memory is not returned to the OS.
So I am not sure about your generalization about windows memory deallocation.
That said, you can try and
Emulating UNIX Memory Management Under Microsoft Windows
, by implementing low level system calls sbrk and mmap/munmap on Windows.


q: How can I implement a diff function, such as Stack Overflow's question revision history?

[A]
You have here a
javascript example
of the implementation of a diff algorithm.
Based on:
P. Heckel, A technique for isolating differences between files
Comm. ACM, 21, (4), 264--268 (1978).
The implementation, itself, has two functions, one of which is recommended for use:
```
```
diffString( String oldFile, String newFile )
```
```
This method takes two strings and calculates the differences in each. The final result is the 'newFile' marked up with HTML (to signify both deletions from the oldFile and additions to the newFile).


q:
I've been reading many a tutorial/article on unmanaged DLLs in C++. For the life of me, however, I cannot seem to grasp the concept. I'm easily confused by the seeming disagreement about whether it needs a header file, how to export it, whether I need a .lib file and what have you.

So, let's assume I have just a function like so:

public int calculateSquare(int num)
{
    return num*num;
}

Ignoring the actual code, what do I require to make this simple function, by itself, into a DLL which I can then call? Do I just add __dllexport or whatever it is to the first line or do I require a header? I am perplexed by all of this.

[A]
I cannot stress this enough, the C++ compiler does not see header files, after the preprocessor is done, there's just one big source file ( also called the compilation unit ). So strictly you don't need a header to export this function from a dll.
What you do need is some form of conditional compilation to export the function in the dll that you are compiling and to import it in the client code.
Typically this is done with a combination of macros and header files. You create a macro called MYIMPORTEXPORT and through the use of macro conditional statements you make it work like __declspec ( dllexport ) in the dll, and __declspec( dllimport ) in the client code.
in file MYIMPORTEXPORT.h
```
```
#ifdef SOME_CONDITION
#define MYIMPORTEXPORT __declspec( dllexport )
#else
#define MYIMPORTEXPORT __declspec( dllimport )
#endif
```
```
in file MyHeader.h
```
```
#include <MyImportExport.h>

MYIMPORTEXPORT public int calculateSquare(int num)
{
    return num*num;
}
```
```
in dll .cpp file
```
```
#define SOME_CONDITION

#include <MyHeader.h>
```
```
in client code .cpp file
```
```
#include <MyHeader.h>
```
```
Of course you also need to signal to the linker that you are building a dll with the
/DLL option
.
The build process will also make a .lib file, this is a static lib - called the stub in this case - which the client code needs to link to as if it were linking to a real static lib. Automagically, the dll will be loaded when the client code is run. Of course the dll needs to be found by the OS through its lookup mechanism, which means you cannot put the dll just anywhere, but in a specific location.
Here
is more on that.
A very handy tool to see whether you exported the correct function from the dll, and whether the client code is correctly importing is
dumpbin
. Run it with /EXPORTS and /IMPORTS respectively.


q:
Why do some sites (or advertisers that give clients javascript code) employ a technique of splitting the <script> and/or </script> tags up within document.write() calls?

I noticed that Amazon does this as well, for example:

<script type='text/javascript'>
  if (typeof window['jQuery'] == 'undefined') document.write('<scr'+'ipt type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></sc'+'ript>');
</script>

[A]
I think is for prevent the browser's HTML parser from interpreting the <script>, and mainly the  </script> as the closing tag of the actual script, however I don't think that using document.write is a excellent idea for evaluating script blocks, why don't use the DOM...
```
```
var newScript = document.createElement("script");
...
```
```


q:
I've recently been trying to create units tests for some legacy code.

I've been taking the approach of using the linker to show me which functions cause link errors, greping the source to find the definition and creating a stub from that.

Is there an easier way?
Is there some kind of C++ parser that can give me class definitions, in some easy to use form, from which I can generate stubs?

[A]
You may want to investigate
http://os.inf.tu-dresden.de/vfiasco/related.html#parsing
. But C++ parsing is hard.
On the other hand, maybe ctags or something similar can extract class definitions...
You may also try to write your own simple (?) parser to generate class stubs from header files...
I tried to give you some pointers. As you see, the problem is not easy. But hopefully you can automate at least some part of it.


q:
I have a product idea that requires integration into the Microsoft Office suite.

Are there any licensing/limitation issues to be aware of for me to proceed?

[A]
Depends...
If your product uses their published APIs and you don't ship any components of theirs "in your box" then you are (probably) just a value added supplier on top of their platform.  You would be telling your customers to have the appropriate MS products in place and then install your App over the top.  That approach is fine and the only reason you need to tell MS is because you will get a lot more business if you are a preferred/certified supplier/partner.  (Depending on which product(s) you are integrating with you should check on MS to make sure that there are no specific license terms around using them).
If you put any of their code in your box then you have to make sure you are operating within the terms of their license and they will almost certainly make you jump through some hoops to get yourself approved by them.  You also have the problem of sharing revenues which is not likely to work in your favour.
In my experience MS don't like doing this with anyone - regardless of size - and certainly not with really small players.
You may be better off approaching them directly before you start and find out if there are incubation projects that you could join to surface your idea.


q: In XEmacs this is done by the calling the function char-to-ucs on a character.  GNU Emacs does not seem to have this function.  In GNU Emacs, characters seem to be ordinary integers.  Running C-x = on a latin character reveals that the Emacs codepoint is different from the Unicode codepoint for the corresponding character.  How do I find the Unicode codepoint of the character at point in GNU Emacs?

[A]
In a modern Emacs, M-x describe-char will tell you about the character at point.
An example:
```
```
character: ¢ (2210, #o4242, #x8a2, U+00A2)
    charset: latin-iso8859-1
         (Right-Hand Part of Latin Alphabet 1 (ISO/IEC 8859-1): ISO-IR-100.)
 code point: #x22
     syntax: w  which means: word
   category: l:Latin
buffer code: #x81 #xA2
  file code: #xC2 #xA2 (encoded by coding system utf-8)
    display: by this font (glyph code)
     -apple-monaco-medium-r-normal--12-120-72-72-m-120-mac-roman (#xA2)
```
```
Note the U+00A2 in the first part, which gives the Unicode codepoint of the character.


q:
Suppose I have this Windows wchar_t string:

L"\x4f60\x597d"

and

L"\x00e4\x00a0\x597d"

and would like to convert it (not necessarily programmatically; it will be a one-time thing) to GCC/Linux wchar_t format, which is UTF-32 AFAIK. How do I do it? (a general explanation would be nice, but example based on this concrete case would be helpful as well)

Please don't direct me to character conversion sites. I would like to convert from L"\x(something)" form and not "end character" form.

[A]
Would converting from UTF-16 (the Visual C++
```
wchar_t
```
form) to UTF-8, then possibly from UTF-8 to UCS-4 (the GCC
```
wchar_t
```
form), be an acceptable answer?
If so, then in Windows you could use the
```
WideCharToMultiByte
```
function (with
```
CP_UTF8
```
for the
```
CodePage
```
parameter), for the first part of the conversion. Then you could either paste the resulting UTF-8 strings directly into your program, or convert them further.
Here
is a message showing how one person did it; you can also write your own code or do it manually (the official spec, with a section on exactly how to convert UTF-8 to UCS-4, can be found
here
). There may be an easier way, I'm not overly familiar with the conversion stuff in Linux yet.


q:
How do I iterate over the words of a string composed of words separated by whitespace?

Note that I'm not interested in C string functions or that kind of character manipulation/access. I prefer elegance over efficiency. My current solution:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main() {
    string s = "Somewhere down the road";
    istringstream iss(s);

    do {
        string subs;
        iss >> subs;
        cout << "Substring: " << subs << endl;
    } while (iss);
}

[A]
The STL does not have such a method available already.
However, you can either use C's
```
strtok()
```
function by using the
```
std::string::c_str()
```
member, or you can write your own. Here is a code sample I found after a quick Google search (
"STL string split"
):
```
```
void Tokenize(const string& str,
              vector<string>& tokens,
              const string& delimiters = " ")
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}
```
```
Taken from:
http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
If you have questions about the code sample, leave a comment and I will explain.
And just because it does not implement a
```
typedef
```
called iterator or overload the
```
<<
```
operator does not mean it is bad code. I use C functions quite frequently. For example,
```
printf
```
and
```
scanf
```
both are faster than
```
std::cin
```
and
```
std::cout
```
(significantly), the
```
fopen
```
syntax is a lot more friendly for binary types, and they also tend to produce smaller EXEs.
Don't get sold on this
"Elegance over performance"
deal.


q:
I recently started using Git as my version control system for some Cocoa projects I'm working on and wondered if there are best practices for working with version control systems on Cocoa projects.

There is the obvious "build" directory which I exclude from versioning as it's not important and can change quite a bit when debugging some code and then there are those .pbxuser and .perspectivev3 which change ever time I open the project in Xcode but I don't really know if they are "important" enough to be checked in.

Is there a commonly used configuration for excluding unimportant files?

Thanks in advance

[A] I never commit the ${LOGNAME}.* files as they're basically preferences information for the current user; the project sources, targets, dependencies and so on are in the project.pbxproj file. And as you mentioned in your question, the build directory (assuming you have the Place Build Products in: Project directory option set) is where the derived files live, so there's no need to check that in. You can always re-generate its contents from the source code.


q:
I am using System.IO.Directory.GetCurrentDirectory() to get the current directory in my web service, but that does not give me the current directory. How do I get the current directory in a web service?

Thanks
Stuart

[A]
In a webservice, you are running in a http context. So,
```
```
HttpContext.Current.Server.MapPath("~/")
```
```
will give you the answer.


q: I want to be able to put preformatted text (i.e. containing line breaks) into a single cell of a FitNesse fixture table. Is there a way to manipulate the FitNesse wiki markup to do this?

[A]
One way to do this is to define a variable with the multi-line text and then refer to this from the table cell:
```
```
!define sql {  SELECT *
  FROM bar
  WHERE gaz = 14
}

|sql|
|${sql}|
```
```


q:
What is the best way to have my C# Compact Framework program running in the background on a Windows Mobile device ? I need to respond to different events, such as a text message arriving with a specific content. I would like not to start up any UI when the process is started, but just run in the background until UI is needed.

How can this be done ?

[A]
Just create the app as a Console app.  If you need a message pump, you need to call Run without any parameters, and the CF doesn't have that.  OpenNETCF's
Application2 class
in the
SDF
does.  At that point you can raise a UI any time by creating and showing a Form as usual.
You cannot create a true service for CE or WinMo with managed code because EE Hosting is not supported.


q:
I need to integrate a email client in my current python web app.
Anything available?

L.E.: I'm building my app on top of CherryPy

[A]
You can build one, using
email
for generating and parsing mail,
imaplib
for reading (and managing) incoming mail from your mail server, and
smtplib
for sending mail to the world.


q:
Is there a correct way in Windows Forms to flash a titlebar without having to drop to P/Invoking FlashWindow?

I'm using .NET 2.0 for compatibility and size reasons, so maybe I just missed the method because it's in newer versions of the .NET framework.

[A]
No, I dont think so. PInvoking the
```
FlashWindowEx
```
method is the only way I think.


q:
I have a select query that currently produces the following results:

Description   Code    Price
 Product 1     A        5
 Product 1     B        4
 Product 1     C        2

Using the following query:

SELECT DISTINCT np.Description, p.promotionalCode, p.Price
FROM            Price AS p INNER JOIN
                         nProduct AS np ON p.nProduct = np.Id

I want to produce the following:

Description  A  B  C
 Product 1   5  4  2

[A]
```
```
SELECT
    np.Id,
    np.Description,
    MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',
    MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',
    MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'
FROM
    Price AS p
INNER JOIN nProduct AS np ON p.nProduct = np.Id
GROUP BY
    np.Id,
    np.Description
```
```
Here is a simple test example:
```
```
DECLARE @temp TABLE (
    id INT,
    description varchar(50),
    promotionalCode char(1),
    Price smallmoney
)

INSERT INTO @temp
select 1, 'Product 1', 'A', 5
    union
SELECT 1, 'Product 1',  'B', 4
    union
SELECT 1, 'Product 1', 'C', 2

SELECT
    id,
    description,
    MIN(Case promotionalCode WHEN 'A' THEN Price ELSE NULL END) AS 'A',
    MIN(Case promotionalCode WHEN 'B' THEN Price ELSE NULL END) AS 'B',
    MIN(Case promotionalCode WHEN 'C' THEN Price ELSE NULL END) AS 'C'
FROM
     @temp
GROUP BY
    id,
    description
```
```


q:
I am playing around with MVC and have started setting up an existing site we have built in standard .Net Forms.

I am only including a JS file and as all the requests are being routed via .Net it is trying to compile it.

It is the standard compilation error you would see with invalid c#:

CS1012: Too many characters in character literal

How do you prevent client assets being compiled?

Many thanks

[A] I have resolved my problem. I had the script tag in my Master Page with a runat="server" in the declaration. This then made .NET try and compile the included JavaScript file?? I have done this quite happily in .NET 2.0 without problems.


q: Does anyone know where I can find an algorithm that given a set of values (dates) for an axis I can calculate a reasonable scale and tick interval?

[A]
The tick interval is going to be dependent on your display area.  You'll need to take the width of your graph (I'm assuming time is on the X axis) and the width of a date string in your selected font into account in order to come up with a good scale.
The basic algorithm will go something like this.
Scan the list of dates to find the minimum and maximum values.
Divide the graph width by the date string width (this can be done once with the result stored in a variable if *both* widths are constant).  This step will be easier if you use a fixed-width font and a MM-DD-YYYY date format.  If you use a variable-width font and a date format where you spell out the name of the month, you'll need to add extra padding to the string to make sure each date string is the same width.  Note that I said *extra* padding.  Even if you use a fixed date format, you'll want to pad it with at least one space to avoid crowding.  I'll call this value `ticks` because it's exactly how many ticks on your axis will fit based on the width of your graph.
Calculate how many days are between your minimum and maximum dates (inclusive).  How you do this will depend on what language you're using.  Hopefully you have good Date and Calendar implementations to fall back on.  I'll just call this value `days`.
Calculate the tick interval with the formula `interval = days / (ticks - 1)`.
Determine which days fall on tick intervals by adding `interval` to your minimum date until you reach your maximum date.  Again, this will depend on what language you use.


q:
<?php
function toconv(string)
{
    $gogo = array("a" => "b","cd" => "e");
    $string = str_replace(
        array_keys( $gogo ),
        array_values( $gogo ),
        $string
    );
    return $string;
}
?>

How can I implement that in JavaScript?

[A]
String.replace() in Javascript receives regexes instead of strings and here's a translation. You need to append the g modifier to the regex to replace all occurrences instead of only the first one.
```
```
<script>
function toconv(str) {
    replacements = ['b','e'];
    regexes = [/a/g,/cd/g];

    for (i=0; i < regexes.length; i++) {
       str = str.replace(regexes[i],replacements[i]);
    }
    return str;
}

alert(toconv('acdacd'));
alert(toconv('foobar'));
</script>
```
```


q:
I am using the following function to load a PlayList of Songs from 'PlayListJSON.aspx' but somethings seems wrong,evrytime OnFailure is getting called, I am unable to debug it further. any help would be really gr8.

Player.prototype.loadPlaylist = function(playlistId, play) {
  req = new Ajax.Request('/PlaylistJSON.aspx?id=' + playlistId, {
    method: 'GET',
    onSuccess: function(transport, json) {
      eval(transport.responseText);

      player.setPlaylist(playlist.tracklist, playlist.title, playlistId);
      player.firstTrack();

      if (play) player.playSong();
    },
    onFailure: function() {
      //error
    }
  });
}

[A]
Generally, OnFailure gets called when the page you are calling out to can't be reached for some reason.
Are you positive that the URL
/PlaylistJSON.aspx
is valid?
Have you tried passing the parameters argument instead of specifying them as part of the url?
```
```
req = new Ajax.Request('/PlaylistJSON.aspx',
    {

        method: 'GET',
        parameters:  {
                     'id': playlistId
                     },
        onSuccess: function(transport,json){

            eval(transport.responseText);

            player.setPlaylist(playlist.tracklist,playlist.title, playlistId);
            player.firstTrack();

            if (play)
                player.playSong();

         },
         onFailure: function() {
           //error

         }
     });
```
```


q:
For example, say one was to include a 'delete' keyword in C# 4. Would it be possible to guarantee that you'd never have wild pointers, but still be able to rely on the garbage collecter, due to the reference-based system?

The only way I could see it possibly happening is if instead of references to memory locations, a reference would be an index to a table of pointers to actual objects. However, I'm sure that there'd be some condition where that would break, and it'd be possible to break type safety/have dangling pointers.

EDIT: I'm not talking about just .net. I was just using C# as an example.

[A]
With garbage collection, as long as you have a referenced reference to the object, it stays alive. With manual delete you can't guarantee that.
Example (pseudocode):
```
```
obj1 = new instance;
obj2 = obj1;

//

delete obj2;
// obj1 now references the twilightzone.
```
```
Just to be short, combining manual memory management with garbage collection defeats the purpose of GC. Besides, why bother? And if you really want to have control, use C++ and not C#. ;-).


q:
I'm using Visual Studio icon library (VS2008ImageLibrary), there are some BMP files with a pink background. How can I make the pink background become transparent? What software can I use to do this? Any free one?

Thanks

[A]
I used IrfanView's batch conversion tool. It's still some work, because you have to click the pink area on every single icon instead of just specifying pink as transparent color, but it worked. It would be easy to write a simple conversion tool using GDI+ though, which I considered as well.
Note that even though you can use them then as transparent images, many of them unfortunately still have ugly edges when you render them on a dark background or use them as overlay. If you just want very few of them, consider tweaking them individually if you think you'll not always have a bright background.


q:
I need to compare the integer part of two doubles for inequality and I'm currently doing this:

int iA = (int)dA;
int iB = (int)dB;

if( iA != iB )
{
    ...
}

but I wonder if there's a better approach than this.

Thanks.

If I used Math.Truncate() instead of a cast to int, would it still be accurate to compare the two resulting double values for equality?

About the hungarian notation comments:

I never use HN myself, not at least in the way most of people do. But this is one of these rare cases where the semantic of a variable directly relates to its type. I could have chosen another syntax like  A_As_Integer and B_As_NonInteger but what would have been the difference then?

[A]
Yes, that is best approach.
Assuming from your wording in you question you arent worried about rounding... just the integerr part itself.
ie. (int)4.1  will give the same result as (int)4.9
As Ovid stated, if you only need the variables for the comparison, then you will only need to cast the doubles in the comparison statement. I was looking only at the theory.


q:
I remember reading somewhere that you can provide your own icons without having them pass them through the automatic gloss effect when compiling an iphone app, but I can't remember how to do it, and not sure where it was in the docs. Anyone here remembers?

thanks!

[A] Add the "UIPrerenderedIcon" to your info.plist file, change it to be a boolean and make it true. (In 2.0 of the iPhone OS you could also leave it as a string and use YES or NO, but that no longer works in 2.1.)


q: Are there any usable implementations of Smalltalk for the .NET runtime?

[A]
There's a project to build Smalltalk on top of the DLR. Unsurprisingly, it's called
IronSmaltalk
.


q:
I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base?

When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you do it in Python?

When you make changes deep inside the code, how do you find out what operations an instance provides, since you don't have a static type to lookup?

How do you handle/prevent typing errors (typos)?

Are UnitTest's used as a substitute for static type checking?

As you can guess I almost only worked with statically typed languages (C++/Java), but I would like to try my hands on Python for larger programs. But I had a very bad experience, a long time ago, with the clipper (dBase) language, which was also dynamically typed.

[A]
my 0.10 EUR:
i have several python application in 'production'-state. our company use java, c++ and python. we develop with the eclipse ide (pydev for python)
unittests are the key-solution for the problem.
(also for c++ and java)
the less secure world of "dynamic-typing" will make you less careless about your code quality
BY THE WAY
:
large scale development doesn't mean, that you use one single language!
large scale development often uses
a handful of languages specific to the problem
.
so i agree to
the-hammer-problem
:-)
PS:
static-typing & python


q:
What is the best compression algorithm that allows random reads/writes in a file?

I know that any adaptive compression algorithms would be out of the question.

And I know huffman encoding would be out of the question.

Does anyone have a better compression algorithm that would allow random reads/writes?

I think you could use any compression algorithm if you write it in blocks, but ideally I would not like to have to decompress a whole block at a time.   But if you have suggestions on an easy way to do this and how to know the block boundaries, please let me know. If this is part of your solution, please also let me know what you do when the data you want to read is across a block boundary?

In the context of your answers please assume the file in question is 100GB, and sometimes I'll want to read the first 10 bytes, and sometimes I'll want to read the last 19 bytes, and sometimes I'll want to read 17 bytes in the middle. .

[A]
I don't know of any compression algorithm that allows random reads, never mind random writes. If you need that sort of ability, your best bet would be to compress the file in chunks rather than as a whole.
e.g.
We'll look at the read-only case first. Let's say you break up your file into 8K chunks. You compress each chunk and store each compressed chunk sequentially. You will need to record where each compressed chunk is stored and how big it is. Then, say you need to read N bytes starting at offset O. You will need to figure out which chunk it's in (O / 8K), decompress that chunk and grab those bytes. The data you need may span multiple chunks, so you have to deal with that scenario.
Things get complicated when you want to be able to write to the compressed file. You have to deal with compressed chunks getting bigger and smaller. You may need to add some extra padding to each chunk in case it expands (it's still the same size uncompressed, but different data will compress to different sizes). You may even need to move chunks if the compressed data is too big to fit back in the original space it was given.
This is basically how compressed file systems work. You might be better off turning on file system compression for your files and just read/write to them normally.


q:
I'm working in a small company and weeks away from deploying a web-app that will be used a lot.  Everyone at one location will have to learn to use it, and although I think it's pretty easy and intuitive I may be biased.

I've written a help guide with plenty of screenshots that's available on every page, but I'll still need to train everyone.  What's the best way?  How do you take a step back and explain code you've been working on for weeks?

[A]
First try to avoid the training:
Perform
usability testing
to ensure your web app is intuitive. Usability testing is a very important aspect of testing and it is often ignored.  How you see your system will probably be very different as how a new user sees your system.
Also add contextual help as often as you can.  For example when I hover over a tag in stack overflow, I know exactly what clicking it will do, because it tells me.
Also this may seem obvious, but make sure you link to your documentation from the site itself.  People may not think of looking in your documentation unless its right in front of their eyes.
About training documentation:
Try to split up your material into how your users would use the system.  I personally like the "trails" option that Sun created for their
Java tutorials
.  In this tutorial you can do several things, and you can chose on which trail you'd like to go.
Support random reads in your help documentation.  If they have a task to do in your web app, then they should be able to get help on that without reading a bunch of unrelated content.
Make sure your documentation is searchable.
About actual training sessions:
If you are actually performing training sessions, stay away from explaining anything related to your code at all.   You don't need to know about the engine to drive a car.
Try to split up your training sessions into very focused aspects of your system.  If you only have 1 training session available to you then just do one specialized use case of your system + the overall description of the system.  Refer to the different parts of documentation where they can get help.
Letting the community help itself:
No matter how extensive your documentation is, you'll always have cases that you didn't cover.  That's why it's a good idea to have a forum available to all users of the system.  Allow them to ask each other questions.
You can review this forum and add content to your documentation as needed.
You could also open up a wiki for the documentation itself, but this is probably not desirable if your user base isn't very large.


q:
Or is there a chance that the operation will fail?

Thanks.

I chose the wrong term and what I really meant was rounding to 0, not truncation.

The point is, I need to compare the integer part of two doubles and I'm just casting them to int and then using ==, but, as someone pointed out in one of my earlier questions, this could throw an overflow exception if the double can't fit into the integer.

So the question would be 'Is it correct to use the == operator to compare two doubles that have previously been rounded to 0, or should I stick to the casting to int method and catch a possible exception?

[A]
It can still fail due to the normal problems with floating point representation.  Rather than truncating them, use a delta that would represent the equivalent precision.
It can fail in cases where you have two floats that you would normally consider the same,
10.19999999
10.20000001
but when you truncate them they give different results.
10.19
10.20
Whereas, if I had used a delta of 0.001 to compare to the difference, I would have seen that these two values are effectively the same.


q:
In honor of the Hutter Prize,
what are the top algorithms (and a quick description of each) for text compression?

Note: The intent of this question is to get a description of compression algorithms, not of compression programs.

[A]
There's always
lzip
.
All kidding aside:
Where compatibility is a concern, PKZIP (
```
DEFLATE
```
algorithm) still wins.
bzip2 is the best compromise between being enjoying a relatively broad install base and a rather good compression ratio, but requires a separate archiver.
7-Zip
(
```
LZMA
```
algorithm) compresses very well and is available for under the LGPL. Few operating systems ship with built-in support, however.
rzip
is a variant of bzip2 that in my opinion deserves more attention. It could be particularly interesting for huge log files that need long-term archiving. It also requires a separate archiver.


q:
When I type the following code in Emacs ruby-mode, the "#{foo}" is fontified in a different color than the enclosing string.  How do I do this in my own Emacs mode?  I tried to decipher the ruby-mode source code but couldn't understand it in a reasonable amount of time.

"a #{foo} a"

[A]
Search for where ruby-mode.el sets
```
font-lock-syntactic-keywords
```
:
```
```
(setq ruby-font-lock-syntactic-keywords
  '(
    ;; #{ }, #$hoge, #@foo are not comments
    ("\\(#\\)[{$@]" 1 (1 . nil))
```
```
Here's some documentation on the similar
```
font-lock-keywords
```
variable, which is what you should use to accomplish the same type of fontification.


q:
I know that there has been a couple questions about tutorials on rhino-mocks. But I am wondering if there are any sample apps out there that use rhino-mocks in the context of an n-tier business application using ado.net.

I find the tutes good, but they don't seem to bring everything all together into the big picture. Thus, I am looking for a sample app that brings the full picture together.

Also, I think there is a little bit of a lack of examples which specifically deal with mocking and testing the logic in the data access layer.

Cheers
Anthony

[A]
Rhino Mocks Documentation
TDD : Introduction to Rhino Mocks
Using Google you will fine more.
You should try to understand mocking, and that it's purpose is to make testing possible by
Mocking
some lower layer. It provides means of splitting
big picture
in lots of independent smaller pictures. That way you are able to test business layer without hitting database.
Stackoverflow: What is a mock and when should you use it?


q:
I'd like to do the same in C#. Is there anyway of using properties in C# with parameters in the same way I've done with the parameter 'Key' in this VB.NET example?

Private Shared m_Dictionary As IDictionary(Of String, Object) = New Dictionary(Of String, Object)

Public Shared Property DictionaryElement(ByVal Key As String) As Object
    Get
        If m_Dictionary.ContainsKey(Key) Then
            Return m_Dictionary(Key)
        Else
            Return [String].Empty
        End If
    End Get
    Set(ByVal value As Object)
        If m_Dictionary.ContainsKey(Key) Then
            m_Dictionary(Key) = value
        Else
            m_Dictionary.Add(Key, value)
        End If

    End Set
End Property

Thanks

[A]
Is there anyway of using properties in C# with parameters
No. You only can provide the
default
property in C# with an argument, to model indexed access (as in a dictionary):
```
```
public T this[string key] {
    get { return m_Dictionary[key]; }
    set { m_Dictionary[key] = value; }
}
```
```
Other properties can't have arguments. Use a function instead. By the way, it's recommented to do the same in VB so other .NET languages (C# …) can use your code.
By the way, your code is unnecessarily complicated. Four things:
You don't need to escape the
```
String
```
identifier. Use the keyword directly.
Why not use
```
""
```
?
Use
```
TryGetValue
```
, it's faster. You query the dictionary twice.
Your setter doesn't have to test whether the value already exists.
```
```
Public Shared Property DictionaryElement(ByVal Key As String) As Object
    Get
        Dim ret As String
        If m_Dictionary.TryGetValue(Key, ret) Then Return ret
        Return "" ' Same as String.Empty! '
    End Get
    Set(ByVal value As Object)
        m_Dictionary(Key) = value
    End Set
End Property
```
```


q:
I want to be able to selectively copy a list of files and preserve their directory structure.  The problem is that there are quite a few files that their path exceeds 256 character.  How is this problem usually handled?

Edit:
I should make it clear that I only want to selectively copy files, not folders.  I don't think robocopy can be efficiently used to copy an individual file and it's folder structure effectively.

[A]
I wrote a VBscript that checks path length and calls
```
subst
```
, as soon as  a certain threshold is reached. These calls are stacked on each other so that in the middle of a recursion, this layout exists:
```
```
C:\a\very\long\path
subst K: "C:\a\very\long\path"

K:\another\very\long\path
subst L: "K:\another\very\long\path"

L:\yet\another\very\long\path
subst M: "L:\yet\another\very\long\path"

xcopy M:\*.* "D:\target"
```
```
This way with each level of subst, a shorter path is generated. It also means, that you must copy your folders sequentially, to be able check for long paths before you issue the copy command.
Once all files in a folder are copied, the recursion does jump back one level (
```
subst /d
```
), freeing up one drive letter.
Using 4-5 drive letters, that subst each other when the path gets to deep I had been able to copy paths that had lengths waaaaay over the MAX_PATH limit.
EDIT
This describes the general procedure of doing it with subst. How you do it depends on your needs, I always used that little subst trick in a minimal, "solves this single problem" way.
For example, copying to an equally deep target path means you need another stack of subst'ed drive letters.
Unpacking all .zip files within a single, deeply nested directory structure may require only on stack, but you need to shorten the threshold a bit to account for folders in the .zip, etc.


q:
How do I get the directory where the rakefile.rb is located?

I want to use this as my root directory to locate everything off.

[A]
If this is a RoR app your Rakefile.rb should be in your RAILS_ROOT directory.  So in any script you can specify file location like
```
```
config.load_paths += %W( #{RAILS_ROOT}/extras )
```
```


q:
I built an application which displays the records from database in the window and checks the the database for new records every couple of seconds. The problem is that the window blinks each time I check for new records and I want to fix it. I have tried to compare the old datatable with the new one and refresh only if they are different.
Does anyone know what is the best practice for such cases? I tried to do it the following way but it doesn't work:

private bool GetBelongingMessages()
        {
            bool result = false;
            DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID);
            if(dtTemp != dtMessages)
            {
                dtMessages = dtTemp;
                result = true;
            }
            else
            {
                result = false;
            }
            return result;
        }

[A]
First off, it's important to recognize that what you're comparing in your code is the
references
of the datatables, not the
contents
of the datatables.  In order to determine if both datatables have the same contents, you're going to have to loop through all of the rows and columns and see if they're equal:
```
```
//This assumes the datatables have the same schema...
        public bool DatatablesAreSame(DataTable t1, DataTable t2) {
            if (t1.Rows.Count != t2.Rows.Count)
                return false;

            foreach (DataColumn dc in t1.Columns) {
                for (int i = 0; i < t1.Rows.Count; i++) {
                    if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {
                        return false;
                    }
                }
            }
            return true;
        }
```
```


q:
I am using C# 2.0 with Nunit Test. I have some object that needs to be serialized. These objects are quite complex (inheritance at different levels and contains a lot of objects, events and delegates).

How can I create a Unit Test to be sure that my object is safely serializable?

[A]
I have this in some unit test here at job:
```
```
MyComplexObject dto = new MyComplexObject();
MemoryStream mem = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
try
{
    b.Serialize(mem, dto);
}
catch (Exception ex)
{
    Assert.Fail(ex.Message);
}
```
```
Might help you... maybe other method can be better but this one works well.


q:
Given a large API (an in particular, the Java or J2EE standard libraries), is there a tool or search engine or other resource that can tells me which methods, classes, or even packages people in general tend to use the most?
I am annotating (see below) APIs and would like to focus my attention on popular areas.
The only thing I can think of is using google code with different method names but that is of course tedious.

Some background (if anyone is interested): As part of my PhD research I've developed a tool that allows users to highlight important "directives" in method documentation (their own or in existing APIs) and then pushes these annotations to users to increase chances that they become aware of it. Our lab studies show that this has potential, but to get people to use it in the field I have to provide "corpuses" of annotated APIs and I'm trying to prioritize which libraries to annotate.

[A]
I wouldn't know if such statistics are even feasible, but I think a pretty safe bet would be to start with the basics plus some famous third party libraries. For example:
Collections
Regular Expressions
Networking
Reflection
Swing
(and
AWT
)
As for third parties
Joda Time
Apache Commons
Jetty
(Servlet container, but usually embedded)


q:
For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?

<div id='header-inner'>
   <div class='titlewrapper'>
      <h1 class='title'>
      Some text I want to change
      </h1>
   </div>
</div>

Thanks!

[A]
```
```
function findFirstDescendant(parent, tagname)
{
   parent = document.getElementById(parent);
   var descendants = parent.getElementsByTagName(tagname);
   if ( descendants.length )
      return descendants[0];
   return null;
}

var header = findFirstDescendant("header-inner", "h1");
```
```
Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on
```
descendants
```
to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).


q:
I want my Qt application to be able to save simple vector graphics to clipboard in a compatible way. On windows I want to be able to paste the graphics into Microsoft Word or Powerpoint. On Linux I want to be compatible with the Open Office.

Which format would you recommend? Can Qt generate EMF in an easy way? Is SVG an option?

Update:

My current plan is to add a piece of native win32 code to render the graphics to emf on windows. This code will not be available on linux.

[A]
The QGraphicsView
class and its associated helpers can render to a QT metafile format through the
QPicture
class (for which you could write a translator to EMF), to SVG through the
QSVGGenerator
class and to postscript/pdf through
QPrinter
.  It can also render to bitmap formats and various other targets.
AFAIK it doesn't have a generic 'render to EMF' facility - you would have to write to something else like the QT Metafile and convert to EMF.  If you only need a subset of the graphics primitives you might only need to support that subset in the translator.  Otherwise you could go from SVG, which you can get directly from QT through QSVGGenerator.


q: I may be in the minority here, but I very much enjoy Perl's formats.  I especially like being able to wrap a long piece of text within a column ("~~  ^<<<<<<<<<<<<<<<<" type stuff).  Are there any other programming languages that have similar features, or libraries that implement similar features?  I am especially interested in any libraries that implement something similar for Ruby, but I'm also curious about any other options.

[A]
There is the
Lisp
```
(format ...)
```
function
. It supports looping, conditionals, and a whole bunch of other fun stuff.
for example (copied from above link):
```
```
(defparameter *english-list*
  "~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~}")

(format nil *english-list* '())       ;' ==> ""
(format nil *english-list* '(1))      ;' ==> "1"
(format nil *english-list* '(1 2))    ;' ==> "1 and 2"
(format nil *english-list* '(1 2 3))  ;' ==> "1, 2, and 3"
(format nil *english-list* '(1 2 3 4));' ==> "1, 2, 3, and 4"
```
```


q:
I have a web page that displays a long line graph inside a div with overflow-x: scroll.
This works well as a web page allowing the use to scroll back and forward through the graph.

However, when printing the page the scroll position is reset to zero.
Is there a way to overcome this?

[A]
I think you're going to have to specify an alternate CSS for printing where you somehow need to remove the overflow:
```
```
<link rel="stylesheet" type="text/css” href="sheet.css" media="print" />
```
```
However, maybe there is an approach with JavaScript or even Flash? If I understand correctly, you only want to have a part of the graph printed (the one "selected" by the user?) and not the full one? I'm pretty sure that's not possible with plain HTML/CSS, but I strongly believe that Flash or maybe JavaScript/AJAX (to only load a part of the image at a time) can solve it.


q:
Please help me with a sanity check. Assuming a many-to-many relationship:

Post, PostTagAssoc, Tag http://www.codingthewheel.com/pics/many_to_many.gif

What's the most succinct way (using LINQ to SQL) to get a result set showing, for each tag (or post), the aggregate number of posts (or tags) assigned to it?

Thanks!

[A]
```
```
from pta in db.PostTagAssoc
 group pta by pta.PostID into t
 select new {PostID = t.Key, TagCount=t.Count()}
```
```


q: How to cancel a keypress event in a textbox after pressing the return key.

[A]
Set the Handled property of KeyPressEventArgs handler parameter to true.
Example from msdn:
```
```
private void keypressed(Object o, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Return)
    {
        e.Handled = true;
    }
}
```
```
See
http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.handled.aspx
for more info.


q:
I have an IList of type Breadcrumb which is just a lightweight class that has NavigationTitle, NavigationUrl and IsCurrent properties. It is cached on the webserver. I have a method that builds out the current breadcrumb trail up until the first Breadcrumb that has IsCurrent set to true... using the code below. Its very ugly and definitely a quick dirtbag willie solution, but I was curious, can this be easily refactored into LINQ?

IList<Breadcrumb> crumbs = new List<Breadcrumb>();
bool foundCurrent = false;
for (int a = 0; a < cachedCrumbs.Count; a++)
{
    crumbs.Add(crumbs[a]);
    if (foundCurrent)
    {
      break;
    }
    foundCurrent = (crumbs[a + 1] != null && ((Breadcrumb)crumbs[a + 1]).IsCurrent);
}

[A]
First of all, that code doesn't work.  I'm gonna guess that some of those places where you used "crumbs" you meant "cachedCrumbs".  If so, the code can be reduced to:
```
```
IList<Breadcrumb> crumbs = new List<Breadcrumb>();
for (int a = 0; a < cachedCrumbs.Count; a++)
{
    crumbs.Add(cachedCrumbs[a]);
    if (cachedCrumbs[a] != null && cachedCrumbs[a].IsCurrent)
    {
          break;
    }
}
```
```


q:
I have a device that supports 4-color graphics (much like CGA in the old days).

I wanted to use PIL to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all.  I found some mailing list archive posts that seem to suggest other people have tried to do so and failed.

A simple python example would be much appreciated!

Bonus points if you add something that then converts the image to a byte string where each byte represents 4 pixels of data (with each two bits representing a color from 0 to 3)

[A]
First: your four colour palette (black, green, red, yellow) has
no
blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with.
Try this code:
```
```
import Image

def estimate_color(c, bit, c_error):
    c_new= c -  c_error
    if c_new > 127:
        c_bit= bit
        c_error= 255 - c_new
    else:
        c_bit= 0
        c_error= -c_new
    return c_bit, c_error

def image2cga(im):
    "Produce a sequence of CGA pixels from image im"
    im_width= im.size[0]
    for index, (r, g, b) in enumerate(im.getdata()):
        if index % im_width == 0: # start of a line
            r_error= g_error= 0
        r_bit, r_error= estimate_color(r, 1, r_error)
        g_bit, g_error= estimate_color(g, 2, g_error)
        yield r_bit|g_bit

def cvt2cga(imgfn):
    "Convert an RGB image to (K, R, G, Y) CGA image"
    inp_im= Image.open(imgfn) # assume it's RGB
    out_im= Image.new("P", inp_im.size, None)
    out_im.putpalette( (
        0, 0, 0,
        255, 0, 0,
        0, 255, 0,
        255, 255, 0,
    ) )
    out_im.putdata(list(image2cga(inp_im)))
    return out_im

if __name__ == "__main__":
    import sys, os

    for imgfn in sys.argv[1:]:
        im= cvt2cga(imgfn)
        dirname, filename= os.path.split(imgfn)
        name, ext= os.path.splitext(filename)
        newpathname= os.path.join(dirname, "cga-%s.png" % name)
        im.save(newpathname)
```
```
This creates a PNG palette image with only the first four palette entries set to your colours. This sample image:
becomes
It's trivial to take the output of
```
image2cga
```
(yields a sequence of 0-3 values) and pack every four values to a byte.
If you need help about what the code does, please ask and I will explain.
EDIT1: Do not reinvent the wheel
Of course, turns out I was too enthusiastic and —as Thomas discovered— the Image.quantize method can take a palette image as argument and do the quantization with far better results than my ad-hoc method above:
```
```
def cga_quantize(image):
    pal_image= Image.new("P", (1,1))
    pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252)
    return image.convert("RGB").quantize(palette=pal_image)
```
```
EDIT1, cont: Pack the pixels into bytes
For "added value", here follows code to produce the packed string (4 pixels per byte):
```
```
import itertools as it

# setup: create a map with tuples [(0,0,0,0)‥(3,3,3,3)] as keys
# and values [chr(0)‥chr(255)], because PIL does not yet support
# 4 colour palette images

TUPLE2CHAR= {}

# Assume (b7, b6) are pixel0, (b5, b4) are pixel1…
# Call it "big endian"

KEY_BUILDER= [
    (0, 64, 128, 192), # pixel0 value used as index
    (0, 16, 32, 48), # pixel1
    (0, 4, 8, 12), # pixel2
    (0, 1, 2, 3), # pixel3
]
# For "little endian", uncomment the following line
## KEY_BUILDER.reverse()

# python2.6 has itertools.product, but for compatibility purposes
# let's do it verbosely:
for ix0, px0 in enumerate(KEY_BUILDER[0]):
    for ix1, px1 in enumerate(KEY_BUILDER[1]):
        for ix2, px2 in enumerate(KEY_BUILDER[2]):
            for ix3, px3 in enumerate(KEY_BUILDER[3]):
                TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3)

# Another helper function, copied almost verbatim from itertools docs
def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n)

# now the functions
def seq2str(seq):
    """Takes a sequence of [0..3] values and packs them into bytes
    using two bits per value"""
    return ''.join(
        TUPLE2CHAR[four_pixel]
        for four_pixel in grouper(4, seq, 0))

# and the image related function
# Note that the following function is correct,
# but is not useful for Windows 16 colour bitmaps,
# which start at the *bottom* row…
def image2str(img):
    return seq2str(img.getdata())
```
```


q:
Please help, I am stuck here ---

irb> a = "line of text\n  line two\n  line three"
irb> system("cat > test_file << #{a}")
cat: of: No such file or directory
cat: text: No such file or directory
=> false

[A]
You need to quote the interpolated parameter:
```
```
system("cat > test_file << \"#{a}\"")
```
```
And, cat is expecting a filename, not some text to append to test_file, so, this would work as I think you intended:
```
```
system("echo \"#{a}\" >> test_file")
```
```
If you want to do this in pure Ruby let me know and I'll give you an example.


q:
I am using Ruby on Rails.

I want to create a filter field on a page such that whenever the input field's value changes I filter a list shown below via ajax. (Exaclty like the Users search works in Stackoverflow)

For now, I made it run with a form_remote_tag containing a text_field_tag and a submit_tag, and it filters my list when I push the submit button. I would like to remove the submit button and execute the filtering every time the value of the text input changes. How can I trigger a form submit every time the text in an input field changes?

I tried inside my form

<%= text_field_tag (:filter), "" , :onchange => "alert ('This is a Javascript Alert')" %>

just to get the onchange event, but somehow not even this alert appears...

[A]
Use
observe_field
helper with a single input, like the code bellow:
```
```
<%= text_field_tag 'filter' %>
<%= observe_field 'filter',
    :url => {:controller => 'your_controller', :action => 'filter'},
    :frequency => 1.2,
    :update => 'results',
    :with => "'typed_filter=' + $('filter').value" %>
```
```
And then just write a controller that, given a param named 'typed_filter', renders the results, wich will be shown in the element with id 'results' (probably a div).


q:
I find Google's In Quotes a really nifty application, and as a CS guy, I have to understand how it works. How do you think it turns news articles into a list of quotes attributed to specific persons?
Sure, there are some mistakes, but their algorithm seems to be smarter than just a simple heuristic or multiple regular expressions. For example, a quote can be attributed to someone even though his/her name was only mentioned in the last paragraph.

Any ideas? Any known paper on the subject?

[A]
I do not have any paper but some idea. Google take quotes from a set of person. Easy for them with Google News and other media access.
They have an other set of subject. Google match subject set with the set of person (both set are finite). The last set is all quote,
If you notice, the subject contain 1 word that is highlighted in the quote. So it has a relation between the set of subject and the set of quote for each set of person. Since Google is the master of information, it must be very easy to get a link between all these set.


q: How can I turn off the wavy red underlines in Netbeans? I don't want to be interrupted while I'm typing, and told that a half finished line of code is wrong.

[A]
Follow this path if you want to turn them off, (I'm using NeatBeans 5.5.1)
Tools ->
Options ->
Advanced Options ->
Open the "Editing" node and click on "Java sources" ->
Enter 0 for the "Error Annotation Limit"
That will completely turn off the red underlines. You can also change the "automatic parsing delay" at the same location if you want a longer pause instead.


q:
Perl and PHP do this with backticks. For example,

$output = `ls`;

Returns a directory listing. A similar function, system("foo"), returns the operating system return code for the given command foo. I'm talking about a variant that returns whatever foo prints to stdout.

How do other languages do this? Is there a canonical name for this function? (I'm going with "backtick"; though maybe I could coin "syslurp".)

[A]
Perl:
```
```
$output = `foo`;
```
```
ADDED: This is really a multi-way tie.  The above is also valid PHP, and Ruby, for example, uses the same backtick notation as well.


q:
I have a bunch of ASP.NET web pages (that have a standard layout) that are product documentation.  I want to create some sort of combination page that will pull all of the other page content in and concatenate them into one long page.

IFrames won't work because I don't know the size of each page.  I could have the combination page do a ton of #includes, and that would work, but I don't want to have to keep the master update to date (we have a database of page names that can change over time).

Ultimately I'm after something that can get a list of pages, and for each one do the equivalent of a #include for that page into the current page.

I hope that makes sense.  Any thoughts?

[A]
What does your pages look like?
I assume it's just plain HTMLs and have a consistent pattern across all pages, no? Like, it has proper HTML markup along with HEAD and BODY and such?
In which case you can just read it like you'd read normal text files and do some string parsing on them to extract the part inside BODY tags and then you can just concatenate those and print them out ASP-#include style.
To get the actual path name to a file on an ASP.NET website, you can use
```
Server.MapPath
```
```
```
var actualDiskFilename = Server.MapPath("~/somewhere/somepage.html");
```
```
All the
```
System.IO
```
classes work the same in ASP.NET, to fetch a list of files in a virtual directory, you can do:
```
```
var virtualDir = "~/somefolder/";
var actualDir = Server.MapPath(virtualDir);

var files = Directory.GetFiles(actualDir);
```
```
Is that what you're looking for?


q:
With DWR it is possible to group together several service calls into one single HTTP request :

dwr batch feature

 This feature is very useful to reduce the latency of an ajax application.
Is there a way to do something similar with GWT / GWT-RPC ?

Thanks for your help

[A]
GWT doesn't provide a one-step solution for batching several arbitrary RPCs.  However, keep in mind that GWT's automatic serialization makes it quite easy to write both serial and batched versions of each of your RPC methods.  For example, suppose you've defined this RPC:
```
```
FooResponse callFoo(FooRequest request);
```
```
It's this easy to write a "batch" version of the same RPC yourself:
```
```
ArrayList<FooResponse> batchCallFoo(ArrayList<FooRequest> requests) {
  ArrayList<FooResponse> responses = new ArrayList<FooResponse>();
  for (FooRequest request : requests) {
    responses.add(callFoo(request));
  }
}
```
```


q:
I have a PHP class that creates a PNG image on the fly and sends it to browser. PHP manual says that I need to make sure that imagedestroy function is called at end to release the memory. Now, if I weren't using a class, I would have some code like this:

function shutdown_func()
{
    global $img;
    if ($img)
        imagedestroy($img);
}
register_shutdown_function("shutdown_func");

However, I believe that appropriate place for my class would be to place a call to imagedestroy in class' destructor.

I failed to find out if destructors get called the same way shutdown functions does? For example, if execution stops when user presses the STOP button in browser.

Note: whatever you write in your answer, please point to some article or manual page (URL) that supports it.

[A]
I think one big thing that you have missed is that all the memory PHP has allocated during script execution is freed once the script terminates. Even if the user presses the stop-button, PHP processes the script until it is finished, gives it back to the HTTP daemon to be served to the visitor (or not, depending on how clever the daemon is).
So, explicitly freeing up memory at the end of script execution is a bit redundant. Some might argue that it would be a good thing to do, but it's still redundant.
But, on the topic of class destructors, they are called whenever the object is destroyed, either explicitly by
```
unset()
```
or at script completion/termination.
The recommendation of the developer explicitly freeing up the memory used in image manipulation is sure just to make absolutely sure not to have a memory leak, as bitmaps can be straining on the memory side of things (height * width * bit depth * 3 (+ 1 if you have an alpha channel))
To satisfy your Wikipedian needs:
http://php.net/manual/en/language.oop5.decon.php
http://php.net/manual/en/function.unset.php


q:
That's basically the question, is there a "right" way to implement operator<< ?
Reading this I can see that something like:

friend bool operator<<(obj const& lhs, obj const& rhs);

is preferred to something like

ostream& operator<<(obj const& rhs);

But I can't quite see why should I use one or the other.

My personal case is:

friend ostream & operator<<(ostream &os, const Paragraph& p) {
    return os << p.to_str();
}

But I could probably do:

ostream & operator<<(ostream &os) {
    return os << paragraph;
}

What rationale should I base this decision on?

Note:

 Paragraph::to_str = (return paragraph)

where paragraph's a string.

[A]
You can not do it as a member function, because the implicit
```
this
```
parameter is the left hand side of the
```
<<
```
-operator. (Hence, you would need to add it as a member function to the
```
ostream
```
-class. Not good :)
Could you do it as a free function without
```
friend
```
ing it? That's what I prefer, because it makes it clear that this is an integration with
```
ostream
```
, and not a core functionality of your class.


q:
I'm trying to extract an uploaded zip file and store its contents in the database, one entry per file.  The rubyzip library has nearly no useful documentation.

There is an assets table that has key :string (file name) and data :binary (file contents).

I'm using the rubyzip library, and have made it as far as this:

Zip::ZipFile.open(@file_data.local_path) do |zipfile|
  zipfile.each do |entry|
    next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?

    asset = self.assets.build
    asset.key = entry.name
    asset.data = ??  # what goes here?
  end
end

How can I set the data from a ZipEntry?  Do I have to use a temp file?

[A]
It would seem that you can either use the read_local_entry method like this:
```
```
asset.data = entry.read_local_entry {|z| z.read }
```
```
Or, you could save the entry with this method:
```
```
data = entry.extract "#{RAILS_ROOT}/#{entry.name}"
asset.data = File.read("#{RAILS_ROOT}/#{entry.name}")
```
```
I'm not sure how those will work, but maybe they'll help you find the right method (if this ain't it).
And, one more alternative:
```
```
asset.data = zipfile.file.read(entry.name)
```
```