q:
Should the model just be data structures?  Where do the services (data access, business logic) sit in MVC?

Lets assume I have a view that shows a list of customer orders.  I have a controller class that handles the clicks on the view controls (buttons, etc).

Should the controller kick off the data access code? Think button click, reload order query. Or should this go through the model layer at all?

Any example code would be great!

[A]
The View would relay what should happen on a click in the UI to the Control layer, which would contain ALL business logic, and would in turn call the Model layer which would only make database calls. Only the model layer should be making database calls, or you will defeat the purpose of the MVC design pattern.
Think about it this way. Let's say you change your database. You would want to limit the amount of code change required, and keep all those changes together without affecting other pieces of your application. So by keeping all data access in the Model layer, even the simple calls, you limit any changes required to the Model layer. If you were to bypass the Model layer for any reason, you would now have to extend any changes needed to any code that knows about the database, making such maintenance more complex than it should be.


q: Assume that write operation throws an exception half-way.  Is there any data written into the file, or is no data written in the file?

[A]
Short answer: Most likely some data will be written to the file, unless the disk is full at the start of the write operation.
Longer answer: It will depend on what CFileException is thrown from the Write call.
http://msdn.microsoft.com/en-us/library/as5cs056(VS.80).aspx

s: huggingface

c: devops

d: intermediate


q:
My question revolves around CSS Fixed Layout vs a Float Layout that extends to fill the width of the browser.

Right now the issue I'm running into is to have the masthead resize depending on the width of the page (something that I understand isn't possible given current browser implementation of CSS3's background-image: size;).  At this point, I feel like I've reached an impasse all around:  Do I rework the site to use a fixed CSS layout, or do I keep the current layout and try to make the masthead image expand to fill most of the space provided?  Moreover, what are the pros and cons of moving to a fixed width layout, and the other (unseen) ramifications of using one layout over another?

The site in question will be given as a comment to this question -- I don't want to be seen as trying to increase traffic to it.

Edit: Any other thoughts?

[A]
If you are trying to expand your background-image to the width of your page, it is better to use a fixed-sized layout as there is no cross-browser method to making a background-image expand to varying sizes that are dependent on the visitors resolution.
Fixed width layouts provide more flexibility for the designer, but not for the visitor. If you create a layout that is X pixels wide, then you are able to fine-tune your website pixel-by-pixel to your liking whereas "float" layouts (I call them liquid layouts) are based entirely on percent values and therefore differ from computer-to-computer. I find this difficult because you can test the layout on your screen and not know how it appears on someone else's, and (for ex.) a 20px margin has more of an effect on a 768px or 960px fixed-width layout than it does on a 1280px-liquid computer screen.
The major con, IMO, to a fixed-width layout is the fact that it looks too small on larger screens and too big on smaller screens. 768px used to be a fairly standard fixed-width layout, but now that is too small as the world moves away from 800x600. Now 960px is fairly standard, which is too big for 800x600 but still too small on 1280x1024.
It all depends on your audience and how your site fits together. Some layout can be made liquid and work perfectly fine, while others must be fixed (like the one you described).


q:
I really love the way Ajax makes a web app perform more like a desktop app, but I'm worried about the hits on a high volume site.  I'm developing a database app right now that's intranet based, that no more then 2-4 people are going to be accessing at one time.  I'm Ajaxing the hell out of it, but it got me to wondering, how much Ajax is too much?

At what point does the volume of hits, outweigh the benefits seen by using Ajax?  It doesn't really seem like it would, versus a whole page refresh, since you are, in theory, only updating the parts that need updating.

I'm curious if any of you have used Ajax on high volume sites and in what capacity did you use it?  Does it create scaling issues?

[A]
On my current project, we do use Ajax and we have had scaling problems. Since my current project is a J2EE site that does timekeeping for the employees of a large urban city, we've found that it's best if the browser side can cache data that won't change for the duration of a user session.  Fortunately we're moving to a model where we have a single admin process the timekeeping for as many employees as possible. This would be akin to how an ERP application might work (or an email application). Consequently our business need is that the browser-side can hold a lot of data, but we don't expect the volume of hits to be a serious problem. So we've kept an XML data island on the browser-side. In addition, we load data only on an as-needed basis.
I highly recommend the book
Ajax Design Patterns
or their
site
.


q:
Possible Duplicate:

  c# - How do I round a decimal value to 2 decimal places (for output on a page)

I want to truncate the decimals like below

i.e.

2.22939393 -> 2.229

2.22977777 -> 2.229

[A]
You can use
Math.Round
:
```
```
decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229
```
```
Or you can use ToString with the N3
numeric format
.
```
```
string roundedNumber = number.ToString("N3");
```
```
EDIT:
Since you don't want rounding, you can easily use
Math.Truncate
:
```
```
Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229
```
```


q: I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?

[A]
There's an
add-on Django application
to provide
TinyMCE
support for Django admin forms without having to muck around with admin templates or Django newform internals.


q:
I developed a greasemonkey script that refreshes a page and checks for certain updates. I would like to run this script in a tab and browse the internet in another tab, but then have the script automatically activate it's tab when an update is found.

Im not sure how clear that was, maybe this is better:

Tab 1 is running a greasemonkey script, refreshing every x seconds looking for the word "foo"

Tab 2 is browsing stackoverflow

-- Now on a refresh, the GM script finds the word "foo". This is when I want the tab focus to automatically shift from Tab 2 to Tab 1.

Is this possible, and if so, how do I achieve this?

Thanks.

[A]
I'm pretty sure that firefox gives focus to tabs that call
```
alert()
```
. So just pop up an
```
alert('found foo')
```


q: I'm trying to display a caret (^) in math mode in LaTeX to represent the exclusive or operation implemented in the "C languages". By default, ^ is for creating a superscript in math mode. The closest I can seem to get is by using \wedge, which isn't the same.


q:
I recently got a Dell XPS 64-bit Vista for myself. Eclipse doesn't have their 64-bit version, but I've read on forums that they download Eclipse and work with Java 1.5 on the Vista with only some problems. I have Java 1.6 and Netbeans was easily downloadable.

What's the basic/big difference that I'll notice if I shift to Netbeans from Eclipse now?

[A]
I think it will be mostly culture shock. Things in different places. Features named different things.
If you really want to give Netbeans a try force yourself to use it for a month. It will suck for the first day or so as none of the shortcuts will be the same, various idioms will be different etc.
At the end of the month you will be competent enough in it that these things should have gone away and you can objectively decide if you like it more. (I'm currently trying this with IntelliJ btw. Current state, confused ;-)


q: I have an object, and I want to list all the selectors to which it responds. It feels like this should be perfectly possible, but I'm having trouble finding the APIs.

[A]
Something like this should work (just put it in the object you're curious about). For example if you have an object that's a delegate and want to know what 'hooks' are available this will print out messages to give you that clue:
```
```
-(BOOL) respondsToSelector:(SEL)aSelector {
    printf("Selector: %s\n", [NSStringFromSelector(aSelector) UTF8String]);
    return [super respondsToSelector:aSelector];
}
```
```
Note that I discovered this in the
iPhone Developer's Cookbook
so I can't take credit! For example output I get from a
```
UIViewController
```
that implements the protocols
```
<UITableViewDelegate, UITableViewDataSource>
```
:
```
```
Selector: tableView:numberOfRowsInSection:
Selector: tableView:cellForRowAtIndexPath:
Selector: numberOfSectionsInTableView:
Selector: tableView:titleForHeaderInSection:
Selector: tableView:titleForFooterInSection:
Selector: tableView:commitEditingStyle:forRowAtIndexPath:
Selector: sectionIndexTitlesForTableView:
Selector: tableView:sectionForSectionIndexTitle:atIndex:
...
...
etc.,etc.
```
```


q:
I am trying to establish the best practice for handling the creation of child objects when the parent object is incomplete or doesn't yet exist in a web application. I want to handle this in a stateless way so in memory objects are out.

For example, say we have a bug tracking application.

A Bug has a title and a description (both required) and any number of attachments. So the "Bug" is the parent object with a list of "Attachment" children.

So you present a page with a title input, a description input, and a file input to add an attachment. People then add the attachments but we haven't created the Parent Bug as yet.

How do you handle persisting the added attachments ?

Obviously we have to keep track of the attachments added, but at this point we haven't persisted the parent "Bug" object to attach the "Attachment" to.

[A]
I would normally just create the Bug object and its child, the Attachment object, within the same HTTP response after the user has submitted the form.
If I'm reading you right, the user input consists of a single form with the aforementioned fields for bug title, description, and the attached file.  After the user fills out these fields (including the selection of a file to upload), then clicks on Submit, your application receives all three of these pieces of data simultaneously, as POST variables in the HTTP request.  (The attachment is just another bit of POST data, as described in
RFC 1867
.)
From your application's end, depending on what kind of framework you are using, you will probably be given a filename pointing to the location of the uploaded file in some suitable temporary directory.  E.g., with Perl's CGI module, you can do:
```
```
use CGI qw(:standard);
my $query = CGI->new;
print "Bug title: " . $query->param("title") . "\n";
print "Description: " . $query->param("description"). "\n";
print "Path to uploaded attachment: " . $query->param("attachment") . "\n";
```
```
to obtain the name of the uploaded file (the file data sent through the form by your user is automatically saved in a temporary file for your convenience), along with its metadata.  Since you have access to both the textual field data and the file attachment simultaneously, you can create your Bug and Attachment objects in whatever order you please, without needing to persist any incomplete data across HTTP responses.
Or am I not understanding you here?


q:
I'm not familiar with shell scripting, so I'm not sure how to do it or if it is possible.  If you can give me links or advice, that would be great.

What I want to do is:

Create a file, simple text file
EX:

param1  (RANDOMVALUE)

Where randomvalue is a random number generated.

run a program with that file we just created and output to a file

./program filewejustcreated > A

The program has already been created and it takes a filename as a parameter, no need to worry about that stuff.

run another program with the file we just created, the program already exists and out put it to a file

./Anotherprogram filewejustcreated > B

run a diff comamand on A, B

diff A B

Display what diff returns...

Thanks

[Edit] I am using shell: tcsh

[A]
You have almost written the script already. The only missing thing is the random number; I'll do it with Perl. Here is a quick & dirty solution in sh (or bash; I'm presuming you're on a Linux/Unix system):
```
```
#!/bin/sh
perl -e 'print "TheWord (", int(rand(1000)), ")\n"' > tempfile
./program tempfile > A
./Anotherprogram tempfile > B
# rm tempfile  # this would delete 'tempfile' if uncommented
diff A B
```
```
Now save this in a file (say, script.sh) and in a shell execute:
```
```
chmod +x script.sh
```
```
to make it executable, and
```
```
./script.sh
```
```
to run it.


q: I am stuck at properly aligning the generalization arrow between the classes. I could not make them appear as in the UML books.

[A]
UML Model Diagrams - Visio - Microsoft Office Online
One note. If you want UML diagramm looks like classic book examples you should use Rational Rose instead of Visio.


q:
In C#, it is possible to retrieve assembly related information like product name, version etc using reflection:

string productName = Assembly.GetCallingAssembly().GetName().Name;
string versionString = Assembly.GetCallingAssembly().GetName().Version.ToString();

How do I do the equivalent if the executing assembly is written in unmanaged C++ (say)? Is it even possible? Assume that I have a .NET dll which is being invoked in unmanaged code via a COM interface.

edit:

To make things absolutely clear, this is my scenario:

I have an executable written in
unmanaged C++

I have a dll written
in C#/.NET

The dll is invoked by the
executable via a COM interface

Within the .NET dll I want to be
able to retrieve information like
the product name and version of the
calling executable.

Possible?

[A]
you could use the following code in VB.Net to retrieve extended document properties:
```
```
Sub Main()
    Dim arrHeaders(41)

    Dim shell As New Shell32.Shell
    Dim objFolder As Shell32.Folder

    objFolder = shell.NameSpace("C:\tmp\")

    For i = 0 To 40
        arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)
    Next
    For Each strFileName In objfolder.Items
        For i = 0 To 40
            Console.WriteLine(i & vbTab & arrHeaders(i) & ": " & objFolder.GetDetailsOf(strFileName, i))
        Next
    Next

End Sub
```
```
Add a COM reference to Microsoft Shell Controls and Automation to your project to compile.
The output of the above program will be a list of the meta data assigned to all files in C:\tmp such as
```
```
0       Name: dpvoice.dll
1       Size: 208 KB
2       Type: Application Extension
3       Date Modified: 14.04.2008 04:41
4       Date Created: 14.04.2008 04:41
5       Date Accessed: 01.12.2008 09:56
6       Attributes: A
7       Status: Online
8       Owner: Administrators
9       Author:
10      Title:
11      Subject:
12      Category:
13      Pages:
14      Comments:
15      Copyright:
16      Artist:
17      Album Title:
18      Year:
19      Track Number:
20      Genre:
21      Duration:
22      Bit Rate:
23      Protected:
24      Camera Model:
25      Date Picture Taken:
26      Dimensions:
27      :
28      :
29      Episode Name:
30      Program Description:
31      :
32      Audio sample size:
33      Audio sample rate:
34      Channels:
35      Company: Microsoft Corporation
36      Description: Microsoft DirectPlay Voice
37      File Version: 5.3.2600.5512
38      Product Name: Microsoftr Windowsr Operating System
39      Product Version: 5.03.2600.5512
40      Keywords:
```
```


q:
Can someone tell me how to change directories using FtpWebRequest?  This seems like it should be an easy thing to do, but I'm not seeing it.

EDIT

I just want to add...I don't have my heart set on FtpWebRequest.  If there's a better (easier) way to do FTP in .NET please let me know.

Apparently there's no way to do it using a live connection, you need to change the uri to trick ftpwebrequest into using a different request (thanks Jon).

So I'm looking for a 3rd party client...

Some of the open source solutions I tried didn't work too well (kept crashing), but I found one open source solution that's passed some of my preliminary tests (.NET FTP Client).

[A]
There's a
blog post
from Mariya Atanasova which shows how you can fake it - basically you have to put the directory on the URL.
I suspect you may be better off with a dedicated FTP library though - one that doesn't try to force everything into the WebRequest way of doing things. I haven't personally used any 3rd party libraries for this, but a search for "FTP library .NET" finds lots of candidates.
Edit: jcolebrand (in case of 2006 blog linkrot possibility)
Many customers ask us how they can use the CWD command with our FtpWebRequest.
The answer is: you cannot use the command directly, but you can modify the uri parameter to achieve the same result.
Let's say you're using the following format:
```
```
String uri = "ftp://myFtpUserName:myFtpUserPassword@myFtpUrl";
FtpWebRequest Request = (FtpWebRequest)WebRequest.Create(uri);
Request.Method = "LIST";
```
```
The above example will bring you to your user's directory and list all the contents there. Now let's say you want to go 2 directories backwards and list the contents there (provided your user has permissions to do that). You close the previous FtpWebRequest and issue a new one with this uri
```
```
uri = "ftp://myFtpUserName:myFtpUserPassword@myFtpUrl/%2E%2E/%2E%2E";
```
```
This is equivalent to logging in with your user's credentials and then using
```
cd ../../
```
Note: if you try using the
```
”..”
```
directly without escaping them the uri class will strip them, so
```
"ftp://myFtpUserName:myFtpUserPassword@myFtpUrl/../.."
```
is equivalent to
```
"ftp://myFtpUserName:myFtpUserPassword@myFtpUrl/"
```
Now let's say you want to go to another user's directory which is one level above the root. If you don't specify a user name and password it's equivalent to logging in as anonymous user. Then you issue a new
```
FtpWebRequest
```
with the following uri
```
```
"ftp://myFtpUrl/%2F/anotherUserDir"
```
```
This is equivalent to logging in as anonymous and then doing
```
```
Cd /
cd anotherUserDirectory
```
```


q:
It's been quite a while since I last used D Programming Language, and now I'm using it for some project that involves scientific calculations.

I have a bunch of floating point data, but when I print them using writefln, I get results like: 4.62593E-172 which is a zero! How do I use string formatting % stuff to print such things as 0?

Right now I'm using a hack:

    if( abs(a) < 0.0000001 )
        writefln(0);
    else
        writefln(a);

it does the job, but I want to do it using the formatting operations, if possible.

UPDATE

someone suggested writefln("%.3f", a) but the problem with it is that it prints needless extra zeros, i.e. 0 becomes 0.000 and 1.2 becomes 1.200

Can I make it also remove the trailing zeros?

[A]
Try something like
```
```
writefln("%.3f", a);
```
```


q:
Checkstyle reports this code as "The double-checked locking idiom is broken", but I don't think that my code actually is affected by the problems with double-checked locking.

The code is supposed to create a row in a database if a row with that id doesn't exist. It runs in a multi-threaded environment and I want to avoid the primary-key-exists SQL-exceptions.

The pseudo-code:

private void createRow(int id) {
  Row row = dao().fetch(id);
  if (row == null) {
     synchronized (TestClass.class) {
        row = dao().fetch(id);
        if (row == null) {
           dao().create(id);
        }
     }
  }
}

I can agree that it looks like double-checked locking, but I am not using static variables and the code in fetch() and create() is probably too complex to be inlined and put out of order.

Am I wrong or checkstyle? :)

[A]
Assuming you want that innermost line to read:
```
```
row = dao().create(id);
```
```
It's not a classic double-checked lock problem assuming
```
dao().fetch
```
is properly mutexed from the create method.
Edit
: (code was updated)
The classic problem of a double-checked lock is having a value assigned before initialization occurs where two threads are accessing the same value.
Assuming the DAO is properly synchronized and will not return a partially initialized value, this doesn't suffer from the flaws of the double-checked lock idiom.


q:
I'm currently working on a DNA database class and I currently associate each row in the database with both a match score (based on edit distance) and the actual DNA sequence itself, is it safe to modify first this way within an iteration loop?

typedef std::pair<int, DnaDatabaseRow> DnaPairT;
typedef std::vector<DnaPairT>          DnaDatabaseT;

// ....

for(DnaDatabaseT::iterator it = database.begin();
    it != database.end(); it++)
{
    int score = it->second.query(query);
    it->first = score;
}

The reason I am doing this is so that I can sort them by score later.  I have tried maps and received a compilation error about modifying first, but is there perhaps a better way than this to store all the information for sorting later?

[A]
To answer your first question, yes. It is perfectly safe to modify the members of your pair, since the actual data in the pair does not affect the vector itself.
edit:
I have a feeling that you were getting an error when using a map because you tried to modify the
```
first
```
value of the map's internal pair. That would not be allowed because that value is part of the map's inner workings.
As stated by
dribeas
:
In maps you cannot change first as it would break the invariant of the map being a sorted balanced tree
edit:
To answer your second question, I see nothing at all wrong with the way you are structuring the data, but I would have the database hold
pointers
to
```
DnaPairT
```
objects, instead of the objects themselves. This would dramatically reduce the amount of memory that gets copied around during the sort procedure.
```
```
#include <vector>
#include <utility>
#include <algorithm>

typedef std::pair<int, DnaDatabaseRow> DnaPairT;
typedef std::vector<DnaPairT *>       DnaDatabaseT;

// ...

// your scoring code, modified to use pointers
void calculateScoresForQuery(DnaDatabaseT& database, queryT& query)
{
    for(DnaDatabaseT::iterator it = database.begin(); it != database.end(); it++)
    {
        int score = (*it)->second.query(query);
        (*it)->first = score;
    }
}

// custom sorting function to handle DnaPairT pointers
bool sortByScore(DnaPairT * A, DnaPairT * B) { return (A->first < B->first); }

// function to sort the database
void sortDatabaseByScore(DnaDatabaseT& database)
{
    sort(database.begin(), database.end(), sortByScore);
}

// main
int main()
{
    DnaDatabaseT database;

    // code to load the database with DnaPairT pointers ...

    calculateScoresForQuery(database, query);
    sortDatabaseByScore(database);

    // code that uses the sorted database ...
}
```
```
The only reason you might need to look into more efficient methods is if your database is so enormous that the sorting loop takes too long to complete. If that is the case, though,  I would imagine that your
```
query
```
function would be the one taking up most of the processing time.


q:
I'm using GPS units and mobile computers to track individual pedestrians' travels. I'd like to in real time "clean" the incoming GPS signal to improve its accuracy. Also, after the fact, not necessarily in real time, I would like to "lock" individuals' GPS fixes to positions along a road network. Have any techniques, resources, algorithms, or existing software to suggest on either front?

A few things I am already considering in terms of signal cleaning:
- drop fixes for which num. of satellites = 0
- drop fixes for which speed is unnaturally high (say, 600 mph)

And in terms of "locking" to the street network (which I hear is called "map matching"):
- lock to the nearest network edge based on root mean squared error
- when fixes are far away from road network, highlight those points and allow user to use a GUI (OpenLayers in a Web browser, say) to drag, snap, and drop on to the road network

Thanks for your ideas!

[A]
I assume you want to "clean" your data to remove erroneous spikes caused by dodgy readings. This is a basic dsp process. There are several approaches you could take to this, it depends how clever you want it to be.
At a basic level yes, you can just look for really large figures, but what is a really large figure? Yeah 600mph is fast, but not if you're in concorde. Whilst you are looking for a value which is "out of the ordinary", you are effectively hard-coding "ordinary". A better approach is to examine past data to determine what "ordinary" is, and then look for deviations. You might want to consider calculating the variance of the data over a small local window and then see if the z-score of your current data is greater than some threshold, and if so, exclude it.


q:
From my code (Java) I want to ensure that a row exists in the database (DB2) after my code is executed.

My code now does a select and if no result is returned it does an insert.  I really don't like this code since it exposes me to concurrency issues when running in a multi-threaded environment.

What I would like to do is to put this logic in DB2 instead of in my Java code.
Does DB2 have an insert-or-update statement? Or anything like it that I can use?

For example:

insertupdate into mytable values ('myid')

Another way of doing it would probably be to always do the insert and catch "SQL-code -803 primary key already exists", but I would like to avoid that if possible.

[A]
Yes, DB2 has the MERGE statement, which will do an UPSERT (update or insert).
```
```
MERGE INTO target_table USING source_table ON match-condition
{WHEN [NOT] MATCHED
          THEN [UPDATE SET ...|DELETE|INSERT VALUES ....|SIGNAL ...]}
[ELSE IGNORE]
```
```
See:
http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0010873.htm
https://www.ibm.com/support/knowledgecenter/en/SS6NHC/com.ibm.swg.im.dashdb.sql.ref.doc/doc/r0010873.html
https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/merge?lang=en


q:
I have an array full of random content item ids. I need to run a mysql query (id in the array goes in the WHERE clause), using each ID that's in the array, in the order that they appear in the said array. How would I do this?

This will be an UPDATE query, for each individual ID in the array.

[A]
Using the "IN" Clause
Might be what you're after
```
```
$ids = array(2,4,6,8);
$ids = implode($ids);
$sql="SELECT * FROM my_table WHERE id IN($ids);";
mysql_query($sql);
```
```
otherwise, what's wrong with
```
```
$ids = array(2,4,6,8);
foreach($ids as $id) {
    $sql="SELECT * FROM my_table WHERE ID = $id;";
    mysql_query($sql);
}
```
```


q:
Is it possible to create a stored procedure as

CREATE PROCEDURE Dummy
    @ID INT NOT NULL
AS
BEGIN
END

Why is it not possible to do something like this?

[A]
Parameter validation is not currently a feature of procedural logic in SQL Server, and NOT NULL is only one possible type of data validation. The CHAR datatype in a table  has a length specification. Should that be implemented as well? And how do you handle exceptions? There is an extensive, highly developed and somewhat standards-based methodology for exception handling in table schemas; but not for procedural logic, probably because procedural logic is defined out of relational systems. On the other hand, stored procedures already have an existing mechanism for raising error events, tied into numerous APIs and languages. There is no such support for declarative data type constraints on parameters. The implications of adding it are extensive; especially since it's well-supported, and extensible, to simply add the code:
```
```
IF ISNULL(@param) THEN
    raise error ....
END IF
```
```
The concept of NULL in the context of a stored procedure isn't even well-defined especially compared to the context of a table or an SQL expression. And it's not Microsoft's definition. The SQL standards groups have spent a lot of years generating a lot of literature establishing the behavior of NULL and the bounds of the definitions for that behavior. And stored procedures isn't one of them.
A stored procedure is designed to be as light-weight as possible to make database performance as efficient as possible. The datatypes of parameters are there not for validation, but to enable the compiler to give the query optimizer better information for compiling the best possible query plan. A NOT NULL constraint on a parameter is headed down a whole nother path by making the compiler more complex for the new purpose of validating arguments. And hence less efficient and heavier.
There's a reason stored procedures aren't written as C# functions.


q:
In an aspx page I get the Windows username with the function Request.LogonUserIdentity.Name. This function returns a string in the format "domain\user".

Is there some function to only get the username, without resorting to the IndexOf and Substring, like this?

public static string StripDomain(string username)
{
    int pos = username.IndexOf('\\');
    return pos != -1 ? username.Substring(pos + 1) : username;
}

[A]
I don't believe so. I have got the username using these methods before-
```
```
var user = System.Web.HttpContext.Current.User;
var name = user.Identity.Name;

var slashIndex = name.IndexOf("\\");
return slashIndex > -1
    ? name.Substring(slashIndex  + 1)
    : name.Substring(0, name.IndexOf("@"));
```
```
or
```
```
var name = Request.LogonUserIdentity.Name;

var slashIndex = name.IndexOf("\\");
return slashIndex > -1
    ? name.Substring(slashIndex  + 1)
    : name.Substring(0, name.IndexOf("@"));
```
```


q:
I have a greasemonkey user script with this single line of code...

window.close();

but firefox does not allow a user script to close a window (as reported by an error message in the error console)

Is there a work around to this problem?

[A]
You need to change configuration settings of Firefox (about:config) to allow this.
Steps:
Go to address bar and type
about:config
Go to parameter
dom.allow_scripts_to_close_windows
Set its value as
true
Now your script can close the TAB with 'window.close()'
eg.
```
```
function closeTab(){
    window.open('', '_self', '');
    window.close();
}
```
```


q: Is there any way to re-generate views from newly updated model?

[A]
The scaffold is not intended to
create
the interface, only to make a starting point for further development. I'm not sure it's even possible (without a lot of unnecessary work) to redo a scaffold, it's much quicker to manually edit the view and controller anyway.


q: As per c99 standard, size of long long should be minimum 64 bits. How is this implemented in a 32 bit machine (eg. addition or multiplication of 2 long longs). Also, What is the equivalent of long long in C++.

[A]
If you care about bit-sizes, you should use
```
```
#include <stdint.h>

int32_t n;
```
```
and friends.  This works for C++ as well.
64-bit numbers on 32-bit machines are implemented as you think,
by 4 extra bytes.  You could therefore implement your own 64-bit
datatype by doing something like this:
```
```
struct my_64bit_integer {
    uint32_t low;
    uint32_t high;
};
```
```
You would of course have to implement mathematical operators yourself.
There is an int64_t in the stdint.h that comes with my GCC version,
and in Microsoft Visual C++ you have an __int64 type as well.


q:
Given a string as below, I need to convert:

1 Dec 2008 06:43:00 +0100

to

MM/DD/YYYY HH:MM:SSAM

using jython what is the best way to do this?

[A]
I don't have jython handy, but I'd expect something like this to work:
```
```
import java
sdf = java.text.SimpleDateFormat

fmt_in = sdf('d MMM yyyy HH:mm:ss Z')
fmt_out = sdf('MM/dd/yyyy HH:mm:ssaa')

fmt_out.format(fmt_in.parse(time_str))
```
```


q:
While checking out the generic collection in .net i found about KeyedByTypeCollection. Although I worked with it and got to know how to use it, I did not get in which scenario it will be useful.

I read through ServiceProvider, cache etc. done with generics without cast, but could not get much.

I think, there must have a reason as to why it has been included in the .Net framework. Any body who have used the KeyedByTypeCollection can explain me why they used it or any body, if they know in which scenario potentially it can be used, can explain it to me.

As more of a curiosity does any other languages support this type of collection ?

[A]
AFAIK, this generic collection serves just as a simple wrapper for
```
KeyedCollection<KEY,VALUE>
```
when
```
KEY
```
is the Type of the
```
VALUE
```
to store.
For example, it is very convinient to use this collection if you want to implement a factory returning singletons:
```
```
public class Factory<T>
{
    private readonly KeyedByTypeCollection<T> _singletons = new KeyedByTypeCollection<T>();

    public V GetSingleton<V>() where V : T, new()
    {
        if (!_singletons.Contains(typeof(V)))
        {
            _singletons.Add(new V());
        }
        return (V)_singletons[typeof(V)];
    }
}
```
```
The use of this simple factory would be something like the following:
```
```
[Test]
    public void Returns_Singletons()
    {
        Factory<ICar> factory = new Factory<ICar>();
        Opel opel1 = factory.GetSingleton<Opel>();
        Opel opel2 = factory.GetSingleton<Opel>();

        Assert.IsNotNull(opel1);
        Assert.IsNotNull(opel2);
        Assert.AreEqual(opel1, opel2);
    }
```
```
Another usage for
```
KeyedByTypeCollection<T>
```
would be inside a service locator...


q:
Because this is not the kind of company where wiki's are accepted, we tend to do a lot of communication through outlook. Sending code snippets through it is painfull.
Is there some way to get the markdown thing we have here, but in outlook?

[A]
Since Outlook uses Word as an email editor (Outlook 2007, Outlook 2003 can be configured to use Word) you could use the AutoCorrect feature to apply simple formatting to your email.
```
__text__
```
will trigger italic and
```
**bold**
```
will trigger bold. List can be created automatically when typing
```
-
```
or
```
1.
```
Another option might be to run a VBA macro on sending the email which converts the Markdown formatting to (X)HTML.


q:
If I have a table where the cells in a column should not have the same values, how do I check this and update? (I know I can set constraints in the settings, but I don't want to do that.)

Say the column name is called unique hash name and contains

Peter
Peter
Peter
Dave
Dave

and so on. I want that to transform to:

Peter
Peter1
Peter2
Dave
Dave1

What is the T-SQL for SQL Server to do that?

Update: For clarity's sake, let's call the table "Persons" and the cell I want unique "UniqueName". Could you make it a SELECT-statement, so I can test the result before updating. And I am using SQL Server 2005 and above.

[A]
EDIT: I've changed the query to use your field names and added a "select-only" query for you to preview.
This is actually pretty easy to do... just use ROW_NUMBER() with a PARTITION clause:
```
```
UPDATE Persons SET UniqueName = temp.DeDupded FROM
    (SELECT ID,
        CASE WHEN ROW_NUMBER() OVER
            (PARTITION BY UniqueName ORDER BY UniqueName) = 1 THEN UniqueName
        ELSE UniqueName + CONVERT(VARCHAR, ROW_NUMBER()
            OVER (PARTITION BY UniqueName ORDER BY UniqueName)-1) END AS DeDupded
    FROM Persons) temp
WHERE Persons.ID = temp.ID
```
```
If you want a "select-only", then here you go:
```
```
SELECT ID,
    CASE WHEN ROW_NUMBER() OVER
        (PARTITION BY UniqueName ORDER BY UniqueName) = 1 THEN UniqueName
    ELSE UniqueName + CONVERT(VARCHAR, ROW_NUMBER()
        OVER (PARTITION BY UniqueName ORDER BY UniqueName)-1) END AS DeDupded
FROM Persons
```
```
EDIT Again: If you're looking for a SQL Server 2000 Solution...
```
```
CREATE TABLE #Persons ( ID INT IDENTITY(1, 1), UniqueName VARCHAR(100) )

INSERT INTO #Persons VALUES ('Bob')
INSERT INTO #Persons VALUES ('Bob')
INSERT INTO #Persons VALUES ('Bob')
INSERT INTO #Persons VALUES ('John')
INSERT INTO #Persons VALUES ('John')

SELECT
    ID,
    CASE WHEN Position = 0 THEN UniqueName
        ELSE UniqueName + (CONVERT(VARCHAR, Position))
    END AS UniqueName
FROM
    (SELECT
        ID,
        UniqueName,
        (SELECT COUNT(*) FROM #Persons p2 WHERE
            p1.UniqueName = p2.UniqueName AND p1.ID > p2.ID) AS Position
    FROM
        #Persons p1) _temp

DROP TABLE #Persons
```
```


q:
Is there a clean and OS independent way to determine the local machine's IP addresses from Perl?

So far I have found the following solutions:

parse the output of ifconfig and ipconfig (hard, different windows versions have different ipconfig outputs)

establish a network connection to a well-known IP and examine the socket's local IP address (won't work if I can't establish a connection and will determine only one IP address)

Any better suggestion?

[A]
use WMI?
Example of extracting IP addresses
(in Powershell, but it's pretty clear what's happening)
Example of accessing WMI from Perl
(not the same WMI functions, but again the process is reasonably clear)
EDIT: after a search on Google codesearch for Networkadapterconfiguration and language "perl":
Example looks like pretty much what you need
EDIT2: In fact the OCS code seems to contain code for most platforms to do this, so while there may be no one set of code that does this, you may be able to re-use their ideas. It's GPL'd, though.
For example,
here's the Solaris code
. Other bits cover BSD, Linux, MacOS...


q: How do I get the battery status on an iPhone?

[A] Iphone SDK 3.0 beta supports this.


q:
Explain why a nullable int can't be assigned the value of null e.g

int? accom = (accomStr == "noval" ? null  : Convert.ToInt32(accomStr));

What's wrong with that code?

[A]
The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:
```
```
int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
```
```


q:
I'm busy writing a class that monitors the status of RAS connections.  I need to test to make sure that the connection is not only connected, but also that it can communicate with my web service.  Since this class will be used in many future projects, I'd like a way to test the connection to the webservice without knowing anything about it.

I was thinking of passing the URL to the class so that it at least knows where to find it.  Pinging the server is not a sufficient test.  It is possible for the server to be available, but the service to be offline.

How can I effectively test that I'm able to get a response from the web service?

[A]
You are right that pinging the server isn't sufficient. The server can be up, but the web service unavailable due to a number of reasons.
To monitor our web service connections, I created a IMonitoredService interface that has a method CheckService(). The wrapper class for each web service implements this method to call an innocuous method on the web service and reports if the service is up or not. This allows any number of services to be monitored with out the code responsible for the monitoring knowing the details of the service.
If you know a bit about what the web service will return from accessing the URL directly, you could try just using the URL. For example, Microsoft's asmx file returns a summary of the web service. Other implementations may behave differently though.


q:
In my code i create a HyperLinkField object. Depending on a database field value, i want to set the NavigateUrl property. This is my problem, i don't know how.

With:

objHF.DataNavigateUrlFields = new[] { "id", "Stype" };

i get my database field. Now i want to check the Stype value. Depeding on this value i want to set the page where to navigate to. How can i do this??

At the end i set my datasource to the gridview and after that i call the bind() method.

I hope someone can help me out

[A]
Not in New Zealand at least.
Here, Fax-Numbers do not differ from normal numbers in terms of namespacing.
A fax number may be only 1 digit ( the rightmost ) different from their normal line, or even a company may not
have
distinct FAX/Phone lines, and they just share a line and use tone detection to initiate fax protocol instead.
Also, you don't need to register with anybody to have fax services work on your phone line, so there's no index you can look up to see if its a fax or not. The only way to know is initiate a call, and see if you get a fax response, and even then, if the Fax happens to be turned off, you'll get a false negative.
I think your question may turn out to result in hunting for phantoms.
Oh, and for additional fun, you may have desktops with their dialup modem plugged into the wall merely emulating a fax device :). If you don't want to include these as "fax machines". you will be most likely out-of-luck.


q: What is the difference between the selectitem and selectitems tags in jsf?

[A]
The difference is exactly what you would expect. The
```
selectitem
```
tag adds a single item to the HTML list while
```
selectitems
```
adds multiple items.
From
JSF Core Tag Reference
:
SelectItem:
The
```
SelectItem
```
tag adds a child
```
UISelectItem
```
component to the component associated with the enclosing tag. In the HTML renderkit, this creates a single element. It can be used with any of the select tags in the JSF HTML tag library. The body content of this tag must be empty.
Example:
```
```
<h:selectOneMenu id="list1">
    <f:selectItem itemLabel="Option 1" itemValue="1"></f:selectItem>
</h:selectOneMenu>
```
```
HTML Output:
```
```
<select id="list1" name="list1" size="1">
    <option value="1">Option 1</option>
</select>
```
```
SelectItems:
The
```
SelectItems
```
tag adds a child
```
UISelectItems
```
component to the component associated with enclosing tag. You can use this tag to set a list of objects in your domain model as the options for a select component. The body content of this tag must be empty.
Example:
```
```
<h:selectManyListbox id="list">
    <f:selectItems value="#{optionBean.optionList}"></f:selectItem>
</h:selectManyListbox>
```
```
HTML Output:
```
```
<select id="list" name="list" multiple="true" size="-2147483648">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>
```
```


q: I have a page with 3 layers, one for navigation, one for database records and one for results. When I click on a database record, the results are displayed in the result layer via ajax. For navigation, the links will simply be different queries. I am wondering if it would make sense to have each different query be sent as ajax data and palced into the records layer, or rather to have the query appended to the php file each time. Which is the more efficient approach?

[A]
Your
```
<script>
```
tag is never closed and your
JavaScript
instructions are not ended with semicolons. It might be the source of the problem.


q:
I'm having trouble searching for a decent Java library that provides Markov chains, and other advanced distributions (as in, statistics).

I've found http://sourceforge.net/projects/hydra-mcmc/   on source forge, and it looks somewhat useable, but does anyone know / use a more up-to-date package? (Haven't really have a trove through this package, but one would assume a more well maintained package would be desirable).

Anyone able to make a suggestion?

[A]
It is not a library per say, but it can give you some pointers:
Java-mcmc
introduced some sophisticated applets illustrating:
Common Metropolis-Hastings algorithms
Coupling constructions for Markov chains
The source code for this web demo of
Markov Chain Monte Carlo (MCMC)
is
available here
.
Other similar projects are
listed there
.


q:
My usage-scenario may seem a bit unusual, but here it is: When using vim (it's one of about 4 different editors I use regularly), I use it in two different situations. The first is via the GUI, in which I'll have multiple buffers and have some settings different than when I use it from the command-line (by testing "if has('gui_running')"). The other is when I need to do something short-and-quick, from the command-line, such as make a small change to a dot-file or other type of config.

What I would like to do, is have sessions enabled for the GUI, but have any command-line invocations ignore them. That is, I don't want to bring up the full existing session on a CL invocation, nor do I want it (and whatever buffer/file it involved) to alter the session that the GUI is using. As I'm fairly new to the post-vi-functionality of vim, I'm not really sure how to pull this off.

[A]
do your session magic in your
```
.gvimrc
```
and everything else in your
```
.vimrc
```
.  The GUI will source both, but the CL version will only source the
```
.vimrc
```
.
The session magic is to set up autocommands to write your session to a file on exit, and reload it by sourcing the file upon entrance.
```
```
au VimLeave * mksession ~/.gvimsession
au VimEnter * source ~/.gvimsession
```
```


q:
Is there a way to find a node matched on part of a value.

If I have the following:

<competition id="100" name="Barclays Premier League"/>
<competition id="101" name="CocaCola Championship" />
<competition id="102" name="CocaCola League 1" />

Given the string "Premier League" or even "Prem", how would I match the correct node and get id 100.

I have managed this using for-each and contains, but this is very inefficient and does not work fast enough for our requirements.

[A]
String handling is not something XSLT is amazing at but there are a few options.
In this case you might try:
```
```
//competition[contains(@name,'Prem')]
```
```
see
here
for more options and details


q:
Is there a way to make stack trace to display the whole generated SQL statement when there is an error instead just the first few characters of it?

This is what it currently displays

...\Zend\Db\Adapter\Pdo\Abstract.php(220): Zend_Db_Adapter_Abstract->query('UPDATE "diction...', Array)

..and I would like to see the whole update statement before sent to the db to track what is wrong with it.

Thanks for the help.
SWK

[A]
If you want to view the complete sql statement you can use Zend_Debug. For example if your sql statement is in the variable $select and you want to view the complete sql statement you can use the following line of code:
```
```
Zend_Debug::Dump($select);
exit;
```
```
Or if your code is created withe the Zend_Db_Table class you can use:
```
```
$select = new Zend_Db_Select(Zend_Registry::get('db'));
$select->from('string');
Zend_Debug::Dump($select->assemble());
exit;
```
```
I think the best way to view the sql statement is by using the profiling function on the database connection. This is combination withe the logging function and the firePHP add-on for Firefox is my favorite setup.
If you use the MVC configuration of Zend Framework this is done white this lines of code:
```
```
// setup the database connection
$db = Zend_Db::factory(Zend_Registry::get('config')->database->adapter,Zend_Registry::get('config')->database->params);

// create a new profiler
profiler = new Zend_Db_Profiler_Firebug('All DB Queries');

// enable profiling (this is only recommended in development mode, disable this in production mode)
$profiler->setEnabled(true);
// add the profiler to the database object
$db->setProfiler($profiler);

// setup the default adapter to use for database communication
Zend_Db_Table_Abstract::setDefaultAdapter($db);

// register the database object to access it in other parts of the project
Zend_Registry::set('db',$db);

/**
*
* This part is optional
*
* You can use this logger to log debug information to the firephp add-on for Firefox
* This is handy for debugging but must be disabled in production mode
*
*/

// create logger
$logger = new Zend_Log();

// create firebug writer
$firebug_writer = new Zend_Log_Writer_Firebug();

// add writer to logger
$logger->addWriter($firebug_writer);

// register the logger object to access it in other parts of the project
Zend_Registry::set('log',$logger);
```
```
The firebug add-on (requirement for firephp) can be found on this website:
Firebug
The FirePHP add-on can be found on this website:
FirePHP
Ivo Trompert


q:
I have a table of time-series data of which I need to find all columns that contain at least one non-null value within a given time period. So far I am using the following query:

select max(field1),max(field2),max(field3),...
   from series where t_stamp between x and y

Afterwards I check each field of the result if it contains a non-null value.

The table has around 70 columns and a time period can contain >100k entries.

I wonder if there if there is a faster way to do this (using only standard sql).

EDIT:
Unfortunately, refactoring the table design is not an option for me.

[A]
Edit: I think I misread the question... this will give you all the
rows
with a non-null value.  I'll leave it here in case it helps someone but it's not the answer to your question.  Thanks @Pax
I think you want to use
```
COALESCE
```
:
```
SELECT ... WHERE COALESCE(fild1, field2, field3) IS NOT NULL
```


q:
What does ::Base part mean in Person < ActiveRecord::Base class declaration?
I'm new to ruby and from what I've gathered so far, Person < ActiveRecord should be used.
Thank you.

[A]
in Ruby,
```
::
```
accesses static class or module constants.
```
ActiveRecord::Base
```
indicates that the
```
ActiveRecord
```
class or module has a static inner class called
```
Base
```
that you're extending.
Edit:
as Mike points out, in this case
```
ActiveRecord
```
is a module...


q:
I want to make a schedule for many pastors. The conditions are:

Every month, each pastor must must go to another church,

The pastor must not go to same church where he came

In 1 year he must go to 12 different churches

There is 13 churches and 13 pastors and every church accepts only 1 pastor every month

I can't use random(1 to 12) because there is a chance the pastor could go to the same church (8,3% chance he goes to the same church).

I want to make the chance small (around 3% or less) that he goes to same church.

[A]
Your conditions don't require that the next church for a given pastor be randomly selected. Couldn't you just iterate through the church list?
That is, assign each pastor a number, 0-12. Assign each church a number, 0-12. The first month:
Month 0:
pastor-0 --> church-0
pastor-1 --> church-1
pastor-2 --> church-2
...
pastor-n --> church-n
The next month, just increment one of the counters (with wrap-around)
Month 1:
pastor-0 --> church-1
pastor-1 --> church-2
pastor-2 --> church-3
...
pastor-n --> church-0
Then repeat for the remaining months:
Month 3:
pastor-0 --> church-2
pastor-1 --> church-3
pastor-2 --> church-4
...
pastor-(n-1) --> church-0
pastor-n --> church-1
There's a very simple loop to all this (O(n)). If it's confusing to you, I suggest trying the loop on paper with say n=3.
If the randomness is a requirement then please update your question.
EDIT BY PAX
I'm deleting my answer and up-voting this one since it's O(n) and the expansion of mine to cater for the edits would have been at least O(n^2).
You can still have randomness by making the pastor-0 through pastor-N values indexes into an array of pastors that has been randomly sorted so that makes this solution at least as good as mine.
END EDIT BY PAX


q:
I'm using the following query, but I currently have to enter a value in every parameter for the query to work. Is there a way of making the parameters optional, so that 1 or more values will return a result?

SELECT * FROM film
WHERE day LIKE '%day%'
AND month LIKE '%month%'
AND year LIKE '%year%'

something like

 function queryData(year,month,day)

 declare Y

 if year == nothing
     Y = '%'
 else
     Y = '%' + year + '%'

 declare M

 if month == nothing
     M = '%'
 else
     M = '%' + month + '%'

 declare D

 if day == nothing
     D = '%'
 else
     D = '%' + day + '%'

 return result of :

 SELECT * FROM film
 WHERE day LIKE D
 OR month LIKE M
 OR year LIKE Y

[A]
```
```
SELECT * FROM film
WHERE day LIKE '%day%'
OR month LIKE '%month%'
OR year LIKE '%year%'
```
```
You will still be providing all three parameters, but it won't matter if they are blank or NULL, matches will still return from the ones that aren't blank.


q: I'm using an SqlCommand object to insert a record into a table with an autogenerated primary key. How can I write the command text so that I get the newly created ID when I use the ExecuteScalar() method?

[A]
```
```
insert into Yourtable()
values()
SELECT SCOPE_IDENTITY()
```
```
I just ran a test and verified that the semi-colons are optional using SQL Server 2005 SP2, and .Net 3.5


q:
I just had some basic php questions to further my understanding as I learn, that I could not find easy answers to

I have a php ajax application that generates a table of mysql rows. I would like to know if there is a way to get php to generate neat html, as it seems neat enough as I echo it out, but when "viewing source" the html is a huge jumbled block with no line breaks or anything. Is there a trick to doing this?

What is the best way to limit table output for a mysql database, so only the first 10 records or so are displayed, and there are automatically generated next and previous links to go between records?

When outputting information with php from a mysql database, what is the best way to handle booleans? What is the easiest way to display the words "yes" or "no" or a tick or a cross? edit: I do not mean should I use words or pictures, but rather how to show either in response to a boolean

[A]
You could use the
PHP Tidy Addon
. Keep in mind, that filtering the HTML with it uses quite some Server CPU. Alternatively you have to print the line breaks yourself (echo "\n";)
However I suggest, that you leave it as it is. Just consider how many people will benefit from reading the source code vs. how many people will benefit from smaller file sizes if you don't format the HTML nicely.
You have to do that manually. There are some helping libraries available on the net. Just
Google it
.
That's up to you to decide and depends on the application. Keep your users needs in mind.


q:
I had created the xml document with xml version="1.0".

In that document I need to use the greater than symbol > and less than symbol <.

How should I include those symbols? It's not working.

&gt; and &lt; are not working for me.

Is there any special encoder for this?

[A]
Use
```
>
```
and
```
<
```
for 'greater-than' and 'less-than' respectively


q:
I wish to display a list of letters from a through z on a form.
Each letter needs to be clickable with that value being passed as a click argument.
Aside from creating 26 letters and using the click event of each letter does anyone know of a quick way to do this?
I know how to load dynamic controls etc and how to do it that way. Just wondering if anyone knew of a clever way to do this?

Cheers

[A]
This is the "dynamic way" I would do it in. I know you asked for other clever ways to do it in but I think this is the most accepted way to do it.
This will produce those buttons and add a click-handler that takes the button as sender. It will also see to that the buttons location wraps if outside of the forms width.
```
```
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim ButtonSize As New Size(20, 20)
    Dim ButtonLocation As New Point(10, 20)

    For p As Integer = Asc("A") To Asc("Z")
        Dim newButton As New Button
        If ButtonLocation.X + ButtonSize.Width > Me.Width Then
            ButtonLocation.X = 10
            ButtonLocation.Y += ButtonSize.Height
        End If
        newButton.Size = ButtonSize
        newButton.Location = ButtonLocation
        newButton.Text = Chr(p)
        ButtonLocation.X += newButton.Width + 5
        AddHandler newButton.Click, AddressOf ButtonClicked
        Me.Controls.Add(newButton)
    Next

    End Sub

    Sub ButtonClicked(ByVal sender As Object, ByVal e As System.EventArgs)
        MsgBox(CType(sender, Button).Text)
    End Sub
End Class
```
```
alt text http://img235.imageshack.us/img235/2267/testoa6.jpg


q:
I tried to write a TransformMesh function. The function accepts a Mesh object and a Matrix object. The idea is to transform the mesh using the matrix. To do this, I locked the vertex buffer, and called Vector3::TransformCoordinate on each vertex. It did not produce expected results. The resulting mesh was unrecognizable.

What am I doing wrong?

// C++/CLI code. My apologies.
int n = verts->Length;
for(int i = 0; i < n; i++){
        verts[i].Position = DX::Vector3::TransformCoordinate(verts[i].Position, matrix);
}

[A]
Without contextual code around what you are doing, it might be hard to know the exact problem. How is the mesh created? How is verts[] read, how is it written? Are you trying to read from a write only vertex buffer?
My recommendation would be to try with a very simple translation matrix first and debug the code and see the vertex input and output. See if you receive good data and if it's transformed correctly. If so, the problem is in vertex stride, stream declaration or something else deeper in the DirectX pipeline.
As I said, more code would be needed to pinpoint the origin of the problem.


q:
I want to initialize a struct element, split in declaration and initialization. This is what I have:

typedef struct MY_TYPE {
  bool flag;
  short int value;
  double stuff;
} MY_TYPE;

void function(void) {
  MY_TYPE a;
  ...
  a = { true, 15, 0.123 }
}

Is this the way to declare and initialize a local variable of MY_TYPE in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?

Update I ended up having a static initialization element where I set every subelement according to my needs.

[A]
```
```
void function(void) {
  MY_TYPE a;
  a.flag = true;
  a.value = 15;
  a.stuff = 0.123;
}
```
```


q:
How do I call the correct overloaded function given a reference to an object based on the actual type of the object. For example...

class Test
{
    object o1 = new object();
    object o2 = new string("ABCD");
    MyToString(o1);
    MyToString(o2);//I want this to call the second overloaded function

    void MyToString(object o)
    {
        Console.WriteLine("MyToString(object) called.");
    }

    void MyToString(string str)
    {
        Console.WriteLine("MyToString(string) called.");
    }
}

what I mean is there a better option than the following?

if(typeof(o) == typeof(string))
{
    MyToString((string)o);
}
else
{
    MyToString(o);
}

May be this can be done using reflection?

[A]
Ok as soon as I hit post I remembered this can indeed be done using reflection...
```
```
var methInfo = typeof(Test).GetMethod("MyToString", new Type[] {o.GetType()});
methInfo.Invoke(this, new object[] {o});
```
```


q:
I have the following requirements:

I need a api that works on CE (x86) + .NET Compact Framework to play videos (Similar to CorePlayer API... Just free)?

Is their anything else available or must I use CorePlayer?

[A]
DirectShow?
Check out
this page
for a starting point.
Provided that DirectShow is present on your CE, which I don't know...
EDIT
: Since you can use DirectShow, I'd like to add a bit.
As
ctacke
notes, it can be a lot of work if you do everything manually, but it's pretty straightforward if you can use
```
IGraphBuilder
```
(see the sample I linked above).
I don't know much about DirectShow versions, but the one included with Windows Mobile 6.0 lacks a splitter for MPEG audio. It means, e.g., that out of the box it won't play .mp3 files unless you wrap them in RIFF headers.


q:
I haven't looked at this in a while, but if I recall correctly both ant and maven still rely on JUnit 3 for unit tests (as of maven 2.09 the default POM file still has JUnit 3.81).

Does it still make sense to stick to JUnit 3 instead of using the latest and greatest? Any good reason I might be missing?

[A] Maven has no explicit binding to Junit 3.81. You can switch to any version of junit you want. If you're running java 5 I think you should switch to at least 4.4 Spring 2.5 is not compatible with 4.5.


q:
Does hibernate HQL queries support using select min, max, count and other sql functions?

like:

select min(p.age) from person p

Thanks

[A]
Some aggregate functions are supported: look in the
manual


q:
I'm learning DI, and made my first project recently.

In this project I've implement the repository pattern. I have the interfaces and the concrete implementations. I wonder if is possible to build the implementation of my interfaces as "plugins", dlls that my program will load dynamically.

So the program could be improved over time without having to rebuild it, you just place the dll on the "plugins" folder, change settings and voilá!

Is this possible? Can Ninject help with this?

[A]
you can easily do it with normal C# reflection, you don't need any extra technology.
There are quite a few examples on the web, e.g.
http://www.codeproject.com/KB/cs/c__plugin_architecture.aspx
In general in your main application, you need to load the assembly implementing the plugin, e.g.:
```
```
ass = Assembly.Load(name);
```
```
and then you need to create an instance of your plugin. If you know the name of the class it would look like this:
```
```
ObjType = ass.GetType(typename);
IPlugin plugin = (IPlugin)Activator.CreateInstance(ObjType);
```
```
and then you just use it.


q: In the Windows Mobile world you can create a so-called Today plugin that adds content to the phone's main screen -- the one where you see the number of missed calls, unread sms and upcoming events.  Is it possible to do something similar on the BlackBerry?  I'd like to show some important info there, so that they are as visible and as easily reachable as possible.

[A]
These things are already displayed on the ribbon depending on the theme.
If you want to create/modify a theme, use the Plazmic CDK.
There are two ways to put individual icons onto the ribbon (similar to icons like mail, calendar, address book, browser, maps, etc):
channel push: easiest if the user is on a BES, now a way to do it for the non-enterprise people on BIS called WebSignals.
write a midp or rimlet j2me application.  Rimlet preferred unless you really need compatibility with other (non-RIM) j2me midp devices.
OK, there is technically a third way, but I really don't think it's serious: MDS Studio.
All the tools are free but you may need a code signing key if you're writing a rimlet using a secure API.
http://na.blackberry.com/eng/support/docs/developers/?userType=21


q: Is there a simple way to remove a leading zero (as in 01 becoming 1)?


q:
Something I do often if I'm storing a bunch of string values and I want to be able to find them in O(1) time later is:

foreach (String value in someStringCollection)
{
    someDictionary.Add(value, String.Empty);
}

This way, I can comfortably perform constant-time lookups on these string values later on, such as:

if (someDictionary.containsKey(someKey))
{
    // etc
}

However, I feel like I'm cheating by making the value String.Empty. Is there a more appropriate .NET Collection I should be using?

[A]
If you're using .Net 3.5, try
HashSet
. If you're not using .Net 3.5, try
C5
. Otherwise your current method is ok (bool as @leppie suggests is better, or not as @JonSkeet suggests, dun dun dun!).
```
```
HashSet<string> stringSet = new HashSet<string>(someStringCollection);

if (stringSet.Contains(someString))
{
    ...
}
```
```


q:
I'm new to ruby and started to create my *nd toy app.
I:

Created controller 'questions'

Created model 'question'

Created controller action 'new'

Added 'New.html.erb' file

in erb file I use form_for helper and and new controller action where I instantiate
@question instance variable.
When I try to run this I get 'undefined method: questions_path for #<ActionView::Base:0x5be5e24>' error.
Below is my new.html.erb:

<%form_for @question do |f| %>
   <%=f.text_field :title %>
<%end%>

Please advise how to fix this and also help me with aliasing this controller action.
What I mean is I would like to type http://mysite/questions/ask, instead of /questions/create

[A]
In
```
config/routes.rb
```
you will need to add:
```
```
map.resources :questions
```
```
to fix the undefined method questions_path problem.
One way to get
```
/questions/ask
```
is to modify
```
routes.rb
```
like so:
```
```
map.ask_question '/questions/ask', :controller => 'questions', :action => 'create'
```
```
which will give you
```
ask_question_path
```
which you can reference in your code.


q:
I need to change the date format from US (mm/dd/YYYY) to UK (dd/mm/YYYY) on a single database on a SQL server machine.

How can this be done?

I've seen statements that do this for the whole system, and ones that do it for the session, but I can't change the code now as it will have to go through QA again, so I need a quick fix to change the date time format.

Update

I realize that the date time has nothing to do with how SQL Server stores the data, but it does have a lot to do with how it parses queries.

I'm chucking raw data from an XML file into a database. The dates in the XML file are in UK date format.

[A]
You do realize that format has nothing to do with how SQL Server stores datetime, right?
You can use
```
set dateformat
```
for each session. There is no setting for database only.
If you use parameters for data insert or update or where filtering you won't have any problems with that.


q: I have a TextBox control on my Form. I use the Leave event on the control to process user input. It works fine if the user clicks on some other control on the form, but the even doesn't get fired when the user goes straight to the main menu. Any ideas which event should I use to get it fired everytime?

[A]
You should use "Validating" and "Validated" events for checking user's input.
Then if user go to another control "A", and the control "A" has property "CausesValidation" set to "true" ( its default value ) the "Validating" and "Validated" event will be fired.
The menu has "CausesValidation" property too.
Edit:
Sorry, I forgot the "CausesValidation" in menu strip is our functionality and not built-in.
But the check for validating is pretty simple:
```
```
private void menuStrip1_MenuActivate( object sender, EventArgs e ) {
    bool ret = this.Validate( false );
    if ( false == ret ) {
        // user's input is wrong
    }
}
```
```
Use any ContainerControl instead of "this", if you want check the validation in another control than the "this" form. For example in MDI Child window.


q:
I have a canvas element defined statically in the html with a width and height. If I attempt to use JavaScript to resize it dynamically (setting a new width and height - either on the attributes of the canvas or via the style properties) I get the following error in Firefox:

uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object"  nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"  location: "JS frame :: file:///home/russh/Desktop/test.html :: onclick :: line 1"  data: no]

Is it possible to resize this element or do I have to destroy it and create a new element on the fly?

[A]
You didn't publish your code, and I suspect you do something wrong. it is possible to change the size by assigning width and height attributes using numbers:
```
```
canvasNode.width  = 200; // in pixels
canvasNode.height = 100; // in pixels
```
```
At least it works for me. Make sure you don't assign strings (e.g., "2cm", "3in", or "2.5px"), and don't mess with styles.
Actually this is a publicly available knowledge — you can read all about it in
the HTML canvas spec
— it is very small and unusually informative. This is the whole DOM interface:
```
```
interface HTMLCanvasElement : HTMLElement {
           attribute unsigned long width;
           attribute unsigned long height;

  DOMString toDataURL();
  DOMString toDataURL(in DOMString type, [Variadic] in any args);

  DOMObject getContext(in DOMString contextId);
};
```
```
As you can see it defines 2 attributes
```
width
```
and
```
height
```
, and both of them are
```
unsigned long
```
.


q:
I have been using anonymous namespaces to store local data and functions and wanted to know when the data is initialized?  Is it when the application starts in the same way as static data or is it compiler dependent?  For example:

// foo.cpp
#include "foo.h"

namespace {

const int SOME_VALUE = 42;

}

void foo::SomeFunc(int n)
{
    if (n == SOME_VALUE)
    {
        ...
    }
}

The question arises out of making some code thread-safe.  In the above example I need to be certain that SOME_VALUE is initialized before SomeFunc is called for the first time.

[A]
In this particular case (a global variable that is const) the variable is "initialized" at compile time.
SOME_VALUE is always equal to 42.
In fact, most (all?) compiler will actually compile this as if it was hardcoded :
```
```
void foo::SomeFunc(int n)
{
    if (n == 42)
    {
        ...
    }
}
```
```


q:
I'm working on an existing j2ee app and am required to remove some vendor specific method calls from the code.

The daos behind a session facade make calls into the ejb container to get the user's id and password - in order to connect to the database.  The user id and password part of the initialContext used to connect to the server.

I am able to get the userid using sessionContext.getCallerPrincipal()

Is there anyway to get to the SECURITY_CREDENTIALS used on the server connection or, is there a way to pass information from the server connection into the ejbs (they are all stateless session beans).

This is a large app with both a rich-client and web front end, and in a perfect world I'd be happy to go back and re-architect the entire solution to use J2EE security etc - but unfortunately, that is not realistic.

[A]
Normally the Java EE security model will not allow the retrieval of the user password, for security reasons. But it depends on the implementation. Some vendors provide methods to retrieve this kind of information, but if you rely on such implementations, be aware that the portability of the application will be compromised.
One common approach is to write a servlet filter to intercept the login request and save a copy of the credentials, to be used later. If your application doesn't use the Java EE security infrastructure, this could be easily implemented. That's because some vendors prevent you from filtering an authentication servlet.


q:
I have a simple model called Party with a corresponding table called parties. There's also a controller with all the usual CRUD actions and so on. This model is used in a website and only one admin user is allowed to edit the parties - everyone else is allowed to call GET actions (index, show). Nothing special so far.

Now I need to do the following: The admin would like to choose a single Party at a time for special presentation (the selected Party is showing up on the start page of the application). The most important thing is, that there's only ONE party at time selected.

How would you solve this problem? Boolean Flag in Party model? Save the selection (id of the party) somewhere outside the database? Implement a new model with a has_one relation to Party (seems like overkill to me)?

I hope my explanation is good enough to understand the issue.

[A]
I would go for the boolean flag and create nested singleton resource (promoted), which I would implement in PartiesController itself (
```
set_promoted_party and get_promoted_party actions
```
). For these I would create two new routes:
```
```
PUT /parties/promoted/:party_id # to set the promoted party
GET /parties/promoted/:party_id # to get the promoted_party
```
```


q: How do you specify the Fill Factor when creating an index in MySql?

[A]
You don't.
http://dev.mysql.com/doc/refman/5.0/en/create-index.html
However, it is an 'accepted' feature request for version 6.x:
http://bugs.mysql.com/bug.php?id=18178
So, don't hold your breath on seeing it any time soon.


q:
What we are looking for is: while compiling the same configuration, say Release|Win32, is there a way to only do the postbuild steps sometimes. Like, if I am on a dev machine do all the post-build steps or if I am on a build server then don't do them. Or is the only way to accomplish this is by implementing a new configuration?

Commenters: Thanks for the ideas, we do not want to use scripts as they would be one more thing to maintain, and going to MSBuild proj files would be a lot of headache at this point as well. Thanks for trying though.

[A]
If you want to crack into MSBuild itself (.*proj files are essentially just MSBuild scripts), you can run machine-specific steps post-build:
http://flimflan.com/blog/MachineSpecificTasksWithMSBuild.aspx
"This takes advantage of the fact that all environment variables are immediately available as properties in an MSBuild script; and that all Windows machines (that I've worked on recently) have the COMPUTERNAME environment variable set."


q:
How do I pass an array I have created on the server side onto the client side for manipulation by Javascript?

Any pseudo code will help

[A]
You'll need to embed it as a javascript array declaration into the page.  There are a number of ways to do this, but it generally means turning the array into text that you write to the page, probably using the ClientScriptManager.
I'm hoping for better javascript integration in a upcoming verison of ASP.Net.  Moving the
value
of a server variable —any server variable— to the client ought to be supported with a simple, one-line function call.  Not the back-flips we need right now.


q:
In C the following horror is valid:

myFunc()
{
  return 42;  // return type defaults to int.
}

But, what about in C++? I can't find a reference to it either way...

My compiler (Codegear C++Builder 2007) currently accepts it without warning, but I've had comments that this is an error in C++.

[A]
It's
ill-formed
in C++. Meaning that it doesn't compile with a standard conforming compiler. Paragraph
7.1.5/4
in Annex C of the Standard explains the change "Banning implicit int".


q: Does SQL Server CheckSum calculate a CRC? If not how can I get SQL Server to calculate a CRC on an arbitrary varchar column?

[A]
I don't think T-SQL gives you the option to specify using a proper CRC as your checksum function. FYI, SQL Server Integration Services (SSIS) does have a "Checksum" transformation that gives you a choice of what checksum algorithm to use, and one of the choices is:
CRC32 - Using a standard 32-bit cyclic
  redundancy check (CRC), this provides
  a more open implementation.
To implement a CRC in SQL, you can either write a pure T-SQL implementation of CRC (fun!), or (if you're using SQL Server 2005 or higher) write / find it in another .NET language and then use that class as a compiled SQL stored procedure.


q:
I have a div tag in the view that I'd like to update with a graph that I generate via Gruff.

I have the following controller action which does this at the end

send_data g.to_blob, :disposition=>'inline', :type=>'image/png', :filename=>'top_n.pdf'

Now if I directly invoke this action, I can see the graph. (More details here if reqd.)

If I add a link_to_remote_tag that calls the above action via AJAX passing in specific input, generates this graph and tries to update a placeholder div tag... I see gibberish.

I think I can write the graph to a png file with g.write(filename.png) how do I embed the graph within the div tag in the view at run-time?

[A]
In your link_to_remote tag just set :complete to something like this:
```
```
:complete => "updateImg(id_of_div, request.responseText)"
```
```
And write a JS function:
```
```
function updateImg(id, img)
{
  $(id).innerHTML = '<img src="' + img + '" />';
}
```
```
Where id_of_div is the id of the div when you want to show de image.
The request.responseText var come from the request of the AJAX call, I mean, when your code writes the png file with the graph, finish the method returning the path to this new png (render :text => path_to_new_image ); then, use this request variable in the :complete.


q: We develop Java Web-aps (Websphere, DB2) which display graphical and databased information. We would also like to offer the same application offline (distribution via CD/DVD) with online data-update. We have tried a number of alternatives in the past, but nothing has been really stable. What are the new best practices to take a Web ap plus data (in a small database) offline?

[A]
I don't know how well it works with the CD/DVD distribution front, but the first thing that comes to mind is
Gears
. On the .NET side of the fence there's
Silverlight 2
. Then there's the
Mozilla Prism
project, although I don't know how far advanced that is.
These are all designed for not just offline access, but mixed offline/online, talking to a server when it's available and working locally when necessary.


q:
Which is the best way to display a custom form for each new document being added to a specific document library?

I want the user to have some control over some actions that adding the document will cause - specifically, tasks created for users in a Task List, which the contributing user will have to OK before committing.

Is the best way to do this via a Workflow or an event handler?

Regards
Moo


q:
I have a piece of code in ANSI C which uses the time.h library and time_h structures to (amongst other date-related calculations) work out the interval between two given dates. This works fine but this limits my code to input between 1970 and 2038. I would now like to make my code more general.

Is there a common C library (ANSI or C99 standard) which implements date calculations on ranges larger than time.h, on a granularity of 1 day (i.e. I need to-the-day resolution but hour resolution is not necessary)?

(I'm adapting the code to deal with historical events hence it would be nice if it could also deal with dates in B.C. ....)

[A]
There's a public domain implementation used in SQLite:
documentation
,
source
I've also found the
Calendar FAQ
useful;
this
page pops up early on Google.


q: Doing a refresh after certain action in asp.net seems to make them happen again even when that action doesn't make sense (think double delete). The web way to deal with this situation is to redirect after a post to get a clean version of the page that can be refreshed without reposting an action to the webserver.  How can I do this with ASP.NET

[A]
I have a feeling there is a deeper problem I'm not getting but here goes. In your postback event:
```
```
// the post handling logic, e.g. the click event code
Response.Redirect(Request.RawUrl);
```
```


q:
I've got some directories that have been moved or renamed. The Linux command line SVN client ignores these directories. The TortoiseSVN plugin for Explorer shows them. If I delete them and update, they come back.

All of the file movement and deletion has been done using the Linux SVN CLI tools. When doing an 'svn update' or even a fresh 'svn co' on a Linux system, these empty directories are not shown.

When doing a fresh checkout using TortoiseSVN, the empty directories are created, even though they don't exist in the HEAD revision anymore.

How can I make them go away?


q:
I've found a answer how to remove diacritic characters on stackoverflow, but could you please tell me if it is possible to change diacritic characters to non-diacritic ones?

Oh.. and I think about .NET (or other if not possible)

[A]
Copying from
my own answer to another question
:
Instead of creating your own table, you could instead convert the text to normalization form D, where the characters are represented as a base character plus the diacritics (for instance, "á" will be replaced by "a" followed by a combining acute accent). You can then strip everything which is not an ASCII letter.
The tables still exist, but are now the ones from the Unicode standard.
You could also try NFKD instead of NFD, to catch even more cases.
References:
http://unicode.org/reports/tr15/
http://www.siao2.com/2005/02/19/376617.aspx
http://www.siao2.com/2007/05/14/2629747.aspx


q:
I'm considering using AMQP (using qpid) to enable a mixture of Python and Java services communicate with each other. Basic text messaging seems simple enough but, as with every other messaging technology I've investigated, that's where it seems to stop. Except for building instant messaging applications, I would have thought sending strings wasn't a particularly useful thing to do yet example after example demonstrates sending unformatted text around.

My instinct then is to use XML (de-)serialization or something similar (JSON, YAML, Protocol Buffers etc.) which has good library support in both languages. Is this a best practice and, if so, which (de-)serialization protocol would people recommend? Or am I missing the point somewhere and should be quite content sending small bits of text?

[A]
XML or JSON are probably the easiest. Protocol buffers is cool but I'd treat it as an optimisation to think of later on if you really need to (as its a bit harder to use being essentially a binary wire format).
BTW you might want to look at Stomp rather than AMQP; its got way more client libraries and supported message brokers. e.g.
Apache ActiveMQ
which is way more popular than qpid or rabbitmq - or indeed any
JMS provider
would work just fine.


q:
Calling through to my Silverlight Enabled WCF-Service in my silverlight application, occasionally users get timeouts. Whats the easiest way to boost the time allowed by the service client for a response?

The exact exception thrown is: System.TimeoutException: [HttpRequestTimedOutWithoutDetail]

Thanks

[A]
Ammount of time connection can be open:
BasicHttpBinding.OpenTimeout
property
Time that a connection can remain inactive, during which no application messages are received, before it is dropped:
BasicHttpBinding.ReceiveTimout
property
This can be set in the  node of the ServiceReference.ClientConfig file in the silverlight app.


q:
I am using NHibernate on a new ASP.NET project, and am running into what I believe to be strange behavior.  I am attempting to manage my session by using an HttpModule to catch the EndRequest event and close the session.  This is working fine, however, after the EndRequest event fires, I am getting an exception in the OnLoad event of one of my custom controls that is attempting to read a Property from my object that is lazy loaded.  I get an exception stating 'failed to lazily initialize a collection, no session or session was closed'.  Turning lazy load off for these properties does fix the problem, and is an acceptable solution.  But this seems to be going against what I always thought to be true.

I would assume that the OnLoad event and all server side processing would be done at the point that EndRequest is fired.  This is also the first time that I have used IIS 7 on a project.  Is this a reason for the behavior? What is the expected behavior?

[A]
If your object is lazy-init and no session is open, resolving the properties will fail.
Remember that lazy exceptions will most probably appear when you have some relationship with another entity that hasn't been initialized.
http://forum.springframework.org/showthread.php?t=13474
I would also recommend using something like the HTTP Module in
Rhino Commons
to manage your NHibernate Sessions.


q: Any list of Testing frameworks for ActionScript 2.0/3.0 around there?

[A]
FlexUnit is the "official" unit testing framework. It's owned by Adobe's Research guys I believe.
http://labs.adobe.com/wiki/index.php/ActionScript_3:resources:apis:libraries
Here's a tutorial on how to use it:
http://langexplr.blogspot.com/2008/10/creating-flex-unit-tests-with-flexunit.html


q:
What is the best way to make one of the branches of a subversion repository the new trunk?

There has been a major rewrite for the entire system: things have been moved around, rewritten, replaces, removed, renamed etc. The rewritten code has been tested and is ready to replace the old trunk.

Basically, the the old mainline (Trunk 5) is tagged and will end here. The rewritten branch (Branch 6) is to become the new mainline (Trunk 7):

Trunk(1) --> Trunk(2) --> Trunk(5) --> ×          +--> new Trunk(7)
  \                             \                 |
  fork                         merge             ???
    \                             \               |
     +--> Branch(3) --> Branch(4) --> Branch(6) --+

All ongoing changes from the old 'Trunk' are already incorporated in the 'Rewritten branch'

How can I do this?

[A]
Use
svn move
to move the contents of the old trunk somewhere else and rename the branch to trunk afterward.
Note that copy and move in svn work like file operations. You can use them to move/copy stuff around in your repository and these changes are versioned as well. Think of "move" as "copy+delete".
[EDIT] Nilbus just notified me that you will get merge conflicts when you use
```
svn move
```
.
I still think that this is the correct approach. It will cause conflicts but if you merge carefully, chances are that you won't lose any data. If that bothers you, use a better VCS like
Mercurial
or
Git
.


q:
I know this is probably on the Internet somewhere but I can't find the answer here on Stackoverflow so I thought I may boost up the knowledge base here a little.

I'm a newbie to Ruby and Rails but my company is getting pretty invested in it so I'm trying to get to know it in a little more detail.

It's been difficult for me to change my mindset to designing an application from the "model" rather the from the database, so I'm trying to figure out how would do all of the design work that I have classically done in the Database in the Rails model instead.

So the most recent task that I have given myself is to figure out how to configure a Rails database model to do cascading deletes? Is there an easy way of doing this? Or would I have to go into the MySql and set this up?

[A]
Yeah you can, if you are using a relationship like has_many you just do this
```
```
has_many :memberships, dependent: :destroy
```
```


q:
I have an http module on a sharepoint site and this module instantiates a custom class and add it to the session and does other initial things for my site.
However, I'm noticing that the http module is being called for all request types (.aspx, .js, .png, .jpg).

Is there any way to have an http module only be called for .net specific page types?


q: When working with WCF services, is it better to create a new instance of the service every time you use it?  Or is it better to create one and re-use it?  Why is either approach better?  Is it the same for asynchronous proxies?

[A]
There is a corollary here to Server Activated Objects in .NET Remoting (one of the technologies that is replaced by WCF), which have two modes, "Single Call" (stateless) and "Singleton" (stateful).
The approach you take in WCF should be based on your performance and scaling requirements in conjunction with the needs of your consumers, as well as server-side design constraints.
If you have to maintain state between calls to the service, then you will obviously want to have a stateful instance, but if you don't you should probably implement it so that it is static, which should scale better (you can more easily load balance, etc).


q: I am getting a " Thread was being aborted  " Exception in an ASP.NET page.I am not at all using any Response.Redirect/Server.Transfer method.Can any one help me to solve this ?

[A]
The
bad
solution is using
```
```
Response.Redirect(URL, False)
```
```
which will cause
not
to Response.End() current page, however be careful this might lead problems because rest of the page will get
executed
and might cause
login bypass
and similar security and performance issues.
Edit : Apparently you are not using Response.Redirect and you can't catch AbortThreadExecution with Try Catch, which means this answer is totally useless now :)
Although to able to get an answer you need to learn how to ask a question. you need to provide information such as :
Exception details
When it, what are the symptoms
What have you tried and didn't work
Have you manage the isolate the problem?


q:
I've got 2 Questions:

1.
I've sarted working around with Linq to XML and i'm wondering if it is possible to change an XML document via Linq. I mean, is there someting like

XDocument xmlDoc = XDocument.Load("sample.xml");

update item in xmlDoc.Descendants("item")
where (int)item .Attribute("id") == id
...

2.
I already know how to create and add a new XMLElement by simply using

xmlDoc.Element("items").Add(new XElement(......);

but how can I remove a single entry?

XML sample data:

<items>
  <item id="1" name="sample1" info="sample1 info" web="" />
  <item id="2" name="sample2" info="sample2 info" web="" />
</itmes>

[A]
Is this what you have in mind?
```
```
using System;
using System.Linq;
using System.Xml.Linq;

static void Main(string[] args)
{
    string xml = @"<data><record id='1'/><record id='2'/><record id='3'/></data>";
    StringReader sr = new StringReader(xml);
    XDocument d = XDocument.Load(sr);

    // the verbose way, if you will be removing many elements (though in
    // this case, we're only removing one)
    var list = from XElement e in d.Descendants("record")
               where e.Attribute("id").Value == "2"
               select e;

    // convert the list to an array so that we're not modifying the
    // collection that we're iterating over
    foreach (XElement e in list.ToArray())
    {
       e.Remove();
    }

    // the concise way, which only works if you're removing a single element
    // (and will blow up if the element isn't found)
    d.Descendants("record").Where(x => x.Attribute("id").Value == "3").Single().Remove();

    XmlWriter xw = XmlWriter.Create(Console.Out);
    d.WriteTo(xw);
    xw.Flush();
    Console.ReadLine();
}
```
```


q:
We have one web application (sharepoint) that collects information from disparate sources. We would like to be able to link users to the main websites of those various sources and have them pre-authenticated. I.E. they enter their credentials for the other sources (which are a number of different types LDAP, AD and home grown!) and we retrieve some information for them, and remember there details (Possibly Single Sign-on to keep em nice and safe). The user can then click a link that will open the full app in another window already authenticated.

Is this even likely to be possible?

[A]
You need to act as a web browser acts to different sites with storing credentials (usually in cookies) locally. Use therefore a  a proper client library with cookie support. This could go probably for most of sites. There are sites using HTTP authentication, which are also easier to access from appropriate client libraries.  The most demanding can be access to SSL websites, but again, most client HTTP libraries cover that nowadays as well.
All you need now is just to prepare your web application to act as a proxy to all those separate web resources. How exactly this is done in Sharepoint, well, I hope others will answer that...


q:
My code is like the following:

URLConnection cnx = address.openConnection();
cnx.setAllowUserInteraction(false);
cnx.setDoOutput(true);
cnx.addRequestProperty("User-Agent",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
InputStream is = cnx.getInputStream();

Is it ok if I set the headers before I get the InputStream? Will my header be sent, or will the server see the default URLConnection's user-agent ( if any ) ?

[A]
The headers
must
be set prior to getting the
```
InputStream
```
to have any affect - an
```
IllegalStateException
```
will be thrown if the connection is already open.
As far as the
```
User-Agent
```
header specifically, it should be sent if it has been set.
See the
URLConnection
JavaDoc.


q:
I have an existing htaccess that works fine:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule (.*) /default.php
DirectoryIndex index.php /default.php

I wish to modify this so that all urls that start with /test/ go to /test/default.php, while keeping all other URLs with the existing /default.php.

Example: http://www.x.com/hello.php -- > http://www.x.com/default.php Example: http://www.x.com/test/hello.php -- > http://www.x.com/test/default.php

[A]
Put the rule for /test/ in before the rule for everything else, but give it an
```
[L]
```
flag to stop the rewrite rule processing there if it matches.


q:
I have a control which the user can resize with the mouse.  When they move the right side, I just change the width, and everything works fine.

However, when they move the left size, I have to change the Left and Width properties.  The right hand side of the control visibly twitches, showing the old width in the new position.

It still twitches if I set both left and width at once using Bounds; whether or not I use SetStyle with any of UserPaint, Opaque, OptimizedDoubleBuffer, AllPaintingInWmPaint or ResizeRedraw; and whether or not it's double buffered.  It still twitches if I call SuspendLayout()/ResumeLayout() on either the control or its parent.

How do I stop controls from twitching when I change their left positions and their widths?

[A]
You might want to try calling
```
Control.SuspendLayout()
```
on the containing form before moving / resizing, then
```
Control.ResumeLayout()
```
.
It sounds like no matter what mode you set the control to, some event that fires when you change the bounds is redrawing it before both values are set.  It may have something to do with the form.
EDIT:
I saw this
similar question
on SO, you mentioned you had already used SetStyle(), but maybe there is some combination of options you can choose that will give you the desired effect.
Hope that helps!


q:
The other day I decided to write an implementation of radix sort in Java. Radix sort is supposed to be O(k*N) but mine ended up being O(k^2*N) because of the process of breaking down each digit to one number. I broke down each digit by modding (%) the preceding digits out and dividing by ten to eliminate the succeeding digits. I asked my professor if there would be a more efficient way of doing this and he said to use bit operators. Now for my questions: Which method would be the fastest at breaking down each number in Java, 1) Method stated above. 2) Convert number to String and use substrings. 3) Use bit operations.

If 3) then how would that work?

[A]
Radix_sort_(Java)
The line of code that does this;
```
```
int key = (a[p] & mask) >> rshift;
```
```
is the bit manipulation part.
```
&
```
is the operator to do a bitwise AND and
```
>>
```
is a right-shift.


q:
Okay I have this RewriteRule which is supposed to redirect any request for the file base.css to {folder of .htacces file}/include/style/base.css, but is just keeps redirecting in an infinite loop, I thought the L parameter would make sure that wouldn't happen.

RewriteRule (.*)/base.css$ include/style/base.css [L,NC,R=301]

Also it redirects to http://localhost/C:/somemaps/include/style/base.css which it isn't really supposed to do either.

Can anyone tell me how to fix this?

Also I would like to have the RewriteRule so it would redirect any file.css to {folder of .htacces file}/include/style/file.css

BTW the .htacces file is in the root of the website (which is not the root of the server!)

[A]
You have Redirect and Rewrite confused.  A redirect is a HTTP status code that tells the browser to go to another URL.  You actually just want to Rewrite the location to another file location.  Try
```
```
RewriteRule (.*)/(.*).css$ /include/style/$2.css [L,NC]
```
```
If this doesn't work try adding the following right after the RewriteEngine On
```
```
RewriteBase /my-virtual-folder-path-where-htaccess-is-stored
```
```


q:
I have the following very simple Javascript-compatible regular expression:

<script type="text/javascript" id="(.+)" src="([^"]+)">

I am trying to match on script tags and gather both the ID and src attributes. I'd like to make the order of the attributes irrelevant, so that the following will still match:

<script id="..." type="text/javascript" src="...">
<script src="..." id="..." type="text/javascript">
<script id="..." src="..." type="text/javascript">

Is it possible to allow the attributes to appear in any order without compromising its ability to collect the matching ID and src?

edit The string to match on is coming from innerHTML, making DOM traversal impossible. Also, I cannot use any third party libraries for this specific application.

[A]
Try the following:
```
```
<script\s*\S*\s*(id="([^"]+)")?\s*\S*\s*(src="([^"]+)")\s*\S*\s*(id="([^"]+)")?[^>]*>
```
```
since you don't care about the type, just remove it because it makes things more complicated.  And then just brute force the rest by adding two optional ID's on either sice of the src.
Alternatively you can do
```
```
<script\s*(([^=]*)="([^"]*)")+\s*>
```
```
To get all the attributes and then pick out the ones you want in code.