Question:
given a matrix of distances between points is there an algorithm for determining a set of n-dimensional points that has these distances? (or at least minimises the error)

sort of like a n-dimensional version of the turnpike problem.

The best I can come up with is using multidimensional scaling.

Answer:
I can't edit the original, because I don't have enough rep, but I've tried to restate the problem here.
The OP has an input NxN matrix of distances. He wants to create an output array, size N, of N-dimensional coordinates representing points, where the distance between each point is stored in the input matrix.
Note that this is not solvable in the general case:
Suppose I have a matrix like this
```
A  B  C
A  x  1  2
B     x  0
C        x
```
A is 1 unit of distance (say 1 metre) away from B, and A is one metre away from C. But B and C are in the same spot.
In this particular case the minimal sum of errors is 1 metre, and there are an infinite variety of solutions which achieve that result


Question:
I am interested to read and understand the 2D mesh algorithms. A search on Google reveals a lot of papers and sources, however most are too academic and not much on beginner's side.

So, would anyone here recommend any reading sources ( suitable for the beginners), or open source implementation that I can learn from the start? Thanks.

Also, compared to triangular mesh generation, I have more interest in quadrilateral mesh and mix mesh( quad and tri combined).

Answer:
The first link on your Google search takes you to
Jonathan Shewchuk's
site. This is not actually a bad place to start. He has a program called
triangle
which you can download for 2D triangulation. On that page there is a
link
to references used in
creating triangle
, including a link to a description of the
triangluation algorithm
.
There are several approaches to mesh generation. One of the most common is to create a
Delaunay triangulation
. Triangulating a set of points is fairly simple and there are several algorithms which do that, including Watson's and
Rupert's
as used in triangle
When you want to create a constrained triangulation, where the edges of the triangulation match the edges of your input shape it is a bit harder, because you need to recover certain edges.
I would start by understanding Delaunay triangulation. Then maybe look at some of the other meshing algorithms.
Some of the common topics that you will find in mesh generation papers are
Robustness - that is how to deal with floating point round off errors.
Mesh quality - ensuring the shapes of the triangles/tetrahedrons are close to equilateral. Whether this is important depends on why you are creating the mesh. For analysis work it is very important,
How to choose where to insert the nodes in the mesh to give a good mesh distribution.
Meshing speed
Quadrilateral/Hexahedral mesh generation. This is harder than using triangles/tetrahedra.
3D mesh generation is much harder than 2D so a lot of the papers are on 3D generation
Mesh generation is a large topic. It would be helpful if you could give some more information on what aspects (eg 2D or 3D) that you are interested in. If you can give some idea of what you ant to do then maybe I can find some better sources of information.


Question: I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.

Answer:
You need to define a Spring Bean which implements
ApplicationListener
.
Then, in your code, do something like this:
```
```
public void onApplicationEvent(ApplicationEvent appEvent)
{
    if (appEvent instanceof AuthenticationSuccessEvent)
    {
        AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
        UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();

        // ....
    }
}
```
```
Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)


Question: Which Template-Engine and Ajax-Framework/-Toolkit is able to load template information from JAR-Files?

Answer:
You need to define a Spring Bean which implements
ApplicationListener
.
Then, in your code, do something like this:
```
```
public void onApplicationEvent(ApplicationEvent appEvent)
{
    if (appEvent instanceof AuthenticationSuccessEvent)
    {
        AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
        UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();

        // ....
    }
}
```
```
Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)


Question:
So Google Analytics does not have an API that we can use to get our data, so is there an efficient way to programaticly fetch the data collected by Google, without logging it locally?

Edit:
I would prefer a Python or PHP solution but anything will work.

Answer:
Well, it depends on what you want to do with the data. If you only want to process part of it, then I don't think it is difficult.
Here's a basic web search with a hit explanations from Google and someone else:
http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55561
http://blogoscoped.com/archive/2008-01-17-n73.html


Question:
I'm trying to call the SQL statement below but get the following error:

System.Data.SqlClient.SqlException: Conversion failed when converting
  the varchar value '+@buildingIDs+' to data type int.

@"SELECT id, startDateTime, endDateTime
    FROM tb_bookings
   WHERE buildingID IN ('+@buildingIDs+')
     AND startDateTime <= @fromDate";

buildingID is an int type column in the db. Will I need to pass the IDs as an array of ints?

Answer:
It's trying to compare an int with the string value '+@buildingsIDs+'
So it tries to convert the string to convert it to an int and fails.
So do the following:
```
buildingsIDs = "1, 5, 6";
@"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (" + buildingIDs + ") AND startDateTime <= @fromDate";
```


Question:
ModRewrite can easily handle stripping the www off the front of my domain.

In .htaccess:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

But with SSL, the certificate check comes before the .htaccess rewrite, causing certificate error.

I would rather not buy an SSL certificate for the www only to redirect it.

Can you offer me a smarter solution?
(btw EV Certificates are not available as wildcards)

Answer:
You can get certificates with multiple domain names in them. Get one with
```
mydomain.com
```
and
```
www.mydomain.com
```
. I think it's also possible to buy "wildcard" certificates that will match any subdomain, but they cost much more.


Question:
I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.

I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :

filepath = r"c:\ttemp\FILEPA~1.EXE"
print os.path.basename(filepath)
'c:\\ttemp\\FILEPA~1.EXE']
print os.path.splitdrive(filepath)
('', 'c:\ttemp\\FILEPA~1.EXE')

WTF ?

It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".

Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.

Answer:
From a
```
os.path
```
documentation:
os.path.splitdrive(path)
Split the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.
If you running this on unix, it doesnt use drive specifications, hence - drive will be empty string.
If you want to solve windows paths on any platform, you can just use a simple regexp:
```
```
import re
(drive, tail) = re.compile('([a-zA-Z]\:){0,1}(.*)').match(filepath).groups()
```
```
```
drive
```
will be a drive letter followed by
```
:
```
(eg.
```
c:
```
,
```
u:
```
) or
```
None
```
, and
```
tail
```
the whole rest :)


Question:
Is OpenID a secure method of authentication users on a website?

And, if not, what are the security risks associated with OpenID?

Answer:
OpenID is inherently insecure. It works by your site redirecting the user to their open ID provider site and then accepting an ID back from that site. This provides insecurities in both directions. You have to trust the ID that comes back (as you have no way of authenticating the user yourself) and it is easy to operate a proxy to the user’s open ID provider, that allows you to steal their username and password.
OpenID is fine for something like Stack Overflow, where it doesn’t really matter if someone impersonates you. Using OpenID for sites with more serious – on a personal level – content is extremely risky. If you use OpenID for your email for example, then anyone stealing your Id can access your email. They could then in turn send password reminder requests to other sites that you use in order to get passwords for those sites. In the worst case, you could use OpenID for a bank account, or have a bank that sends password reminders to your email account...
There are numerous other security problems with OpenID. You can find more information in
"Privacy on the Internet"
.


Question: How can I modify a SharePoint site so that versioning is turned on by default in Document Libraries?

Answer:
Versioning is not done at the site level, but at the list level.
If you want versioning to be turn on on each new library, you'll have to either:
Use your own library template (with versioning turned on)
Use feature + event handler to programmatically activate versioning on each new list
The easiest way is probably to use your own template. To do this, create a new document library, activate versioning, then save this list as template.
When you create a new list, you will then be able to use your template and directly create a list with versioning activated.


Question: I'm looking for an open-source library for editing AAC metadata in M4A files (as appearing in iTunes).  Specifically, I need to be able to add an album art tag.  It should be something similar to id3lib, which works with ID3 tags on MP3 files.

Answer:
Since I hadn't find any open-source library maybe open-source program, that can read and set iTunes-style metadata tags in MPEG-4 files, will help you.
atomicparsley.sourceforge.net
There is also Known iTunes Metadata structure provided:
http://atomicparsley.sourceforge.net/mpeg-4files.html
This discussion may also turn out helpful for you:
www.hydrogenaudio.org/forums/lofiversion/index.php/t31022.html
Good Luck


Question:
I have a template in word (.docx) format and want to replace some placeholders in this template with my own data, do you know where I can find the right classes for this project? It would be nice for me to know the namespace. Are there any newer classes for handling word documents in the docx format (xml) than the com classes? Thank you for all your answers, I hope someone can help me with my problem.

greets

Sebastian

Answer:
The new office formats (docx, xlsx, etc) are zip files that contain a collection of xml files.  With that in mind you have a couple of approaches.
You can use the Open XML SDK located at
http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&displaylang=en
You can unzip the docx file, do a search and replace for your tokens, and zip it back up.
There is a website at
openxmldeveloper.org
that is just for this kind of thing.  Also, bear in mind that they are already shipping a beta version 2 of the SDK.


Question:
Why can't I pass the table name to a prepared PDO statement?

$stmt = $dbh->prepare('SELECT * FROM :table WHERE 1');
if ($stmt->execute(array(':table' => 'users'))) {
    var_dump($stmt->fetchAll());
}

Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do

$sql = "SELECT * FROM $table WHERE 1"

Answer:
Using the former isn't inherently more safe than the latter, you need to sanitize the input whether it's part of a parameter array or a simple variable.  So I don't see anything wrong with using the latter form with
```
$table
```
, provided you make sure that the content of
```
$table
```
is safe (alphanum plus underscores?) before using it.


Question:
My application runs under CF 2.0 locally and i would like to know how to connect and send something to print in the embedded printer of a http://www.milliontech.com/home/content/view/195/95/'>Bluebird BIP-1300 device.

Ideally i would like an example in C#.

Thank you in advance.

Answer:
I'm not familiar with this particular device, but in general, printers in this class require you to send RAW data, as they don't have Windows drivers.
This KB article
outlines how to send data to the device using C#: whether this is useful for you depends on whether the unmanaged APIs used are available in the environment your CF app runs on.
In case the APIs are supported, what you need next are the correct escape codes for the device in order to get the on-paper results you want. These are usually well-documented in the printer manual.
If the Spooler API is not available, or you run into other issues that make this approach more trouble than it's worth, the third-party
PrinterCE.NetCF SDK
may also be worth looking into.


Question:
I'm trying to serialize objects from a database that have been retrieved with Hibernate, and I'm only interested in the objects' actual data in its entirety (cycles included).

Now I've been working with XStream, which seems powerful. The problem with XStream is that it looks all too blindly on the information. It recognizes Hibernate's PersistentCollections as they are, with all the Hibernate metadata included. I don't want to serialize those.

So, is there a reasonable way to extract the original Collection from within a PersistentCollection, and also initialize all referring data the objects might be pointing to. Or can you recommend me to a better approach?

(The results from Simple seem perfect, but it can't cope with such basic util classes as Calendar. It also accepts only one annotated object at a time)

Answer:
I recommend a simpler approach: user dozer:
http://dozer.sf.net
. Dozer is a bean mapper, you can use it to convert, say, a PersonEJB to an object of the same class. Dozer will recursively trigger all proxy fecthes through getter() calls, and will also convert src types to dest types (let's say java.sql.date to java.utilDate).
Here's a snippet:
```
```
MapperIF mapper = DozerBeanMapperSingletonWrapper.getInstance();
PersonEJB serializablePerson = mapper.map(myPersonInstance, PersonEJB.class);
```
```
Bear in mind, as dozer walks through your object tree it will trigger the proxy loading one by one, so if your object graph has many proxies you will see many queries, which can be expensive.


Question:
Is there a way to figure out versions of modules that were loaded into the process' address space when the process crashed from a crash dump that was generated by the process calling the MiniDumpWriteDump function? In other words, is any version information stored inside a dmp file?

Thanks.

Answer:
load your minidump into WinDbg, then there's a Modules item off the Debug menu that shows checksum and timestamp information. That may be enough info for your purposes.
You can get the version from all loaded modules by typing "LM v" in the command window, in WinDBG. The list is long and you get lots, including the Product and File version strings. However, I think it fetches this information from locally-stored modules that it loads, making sure its got the right ones from checksum information it uses to match them to the symbol files.


Question:
What is the easiest way to check if events have been logged in the eventlog during a period of time?

I want to perform a series of automated test steps and then check if any errors were logged to the Application Event Log, ignoring a few sources that I'm not interested in. I can use System.Diagnostics.EventLog and then look at the Entries collection, but it doesn't seem very useable for this scenario. For instance Entries.Count can get smaller over time if the event log is removing old entries. I'd prefer some way to either query the log or monitor it for changes during a period of time. e.g.

DateTime start = DateTime.Now;
// do some stuff...
foreach(EventLogEntry entry in CleverSolution.EventLogEntriesSince(start, "Application"))
{
  // Now I can do stuff with entry, or ignore if its Source is one
  // that I don't care about.
  // ...
}

Answer:
The
System.Diagnostics.EventLog
class really is the right way to do this.
Your main objection seems to be that the log can remove old entries in some cases.  But you say this is in a software testing scenario.  Can't you arrange to configure your test systems such that the logs are large enough to contain all entries and the removal of old entries won't occur during your tests?


Question:
I've got a column in a database table (SQL Server 2005) that contains data like this:

TQ7394
SZ910284
T r1534
su8472

I would like to update this column so that the first two characters are uppercase. I would also like to remove any spaces between the first two characters. So T q1234 would become TQ1234.

The solution should be able to cope with multiple spaces between the first two characters.

Is this possible in T-SQL? How about in ANSI-92? I'm always interested in seeing how this is done in other db's too, so feel free to post answers for PostgreSQL, MySQL, et al.

Answer:
```
```
update Table set Column = case when len(rtrim(substring (Column , 1 , 2))) < 2
            then UPPER(substring (Column , 1 , 1) + substring (Column , 3 , 1)) + substring(Column , 4, len(Column)
            else UPPER(substring (Column , 1 , 2)) + substring(Column , 3, len(Column) end
```
```
This works on the fact that if there is a space then the trim of that part of string would yield length less than 2 so we split the string in three and use upper on the 1st and 3rd char. In all other cases we can split the string in 2 parts and use upper to make the first two chars to upper case.


Question: Internet Explorer (from versions 4 to 7, at least) limits the number of files uploaded using a single 'input type="file"' form field to one. What is the best approach to take if I want to upload more than one file in a single HTTP POST request?

Answer:
You have to include multiple
```
input
```
controls, one per file to be uploaded.
If you don't know how many you want ahead of time, you can use jQuery (or plain javascript) to create them on-the-fly.


Question:
I use XFire to create a webservice wrapper around my application. XFire provides the webservice interface and WSDL at runtime (or creates them at compile time, don't know exactly).

Many of our customers don't know webservices very well and additionally they simply don't read any external documentation like Javadoc. I know that it's possible to add documentation (for parameters and methods) directly to the WSDL file.

I thought about Annotations or Aegis XML files but I don't know how... Do you know a way?

Edit: I just found this JIRA issue but the last activity was 2006. Any ideas?

Answer:
XFire is slowly headed for /dev/null. Use
CXF
instead. In other words, XFire is being deprecated in favor of CXF - it's pretty much the same developers.
Since you use the Java-first approach, I suggest you generate you WSDL once and for all with CXF's
```
java2wsdl
```
tool, then you put your documentation in that and tell CXF to use
that
documented WSDL instead of letting CXF generate its own (undocumented) WSDL at runtime/deploy-time.
This page
has pretty much everything you need to know about creating a web service in CXF.


Question: How do I remove a trailing comma from a string in ColdFusion?

Answer:
Check the rightmost char - if it's a comma, set the string to a substring of the original, with length -1.
Trimming the string ensures that spaces after the trailing comma don't interfere with this method.
```
```
<cfset myStr = "hello, goodbye,">
<cfset myStr = trim(myStr)>

<cfif right(myStr, 1) is ",">
    <cfset myStr = left(myStr, len(myStr)-1)>
</cfif>
```
```


Question:
I would like TortoiseSVN (1.5.3) to ignore certain folders, their contents and certain other files wherever they might appear in my directory hierarchy but I cannot get the global ignore string right.

Whatever I do, it either adds to much or ignores too much

What is the correct 'Global ignore pattern' to ignore....

Folders : bin obj release compile
Files   : *.bak *.user *.suo

Update: To help clarify... yes I am using this on windows.

Answer:
Currently I have the following in my Global Ignore Pattern:
```
```
bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db
```
```
Works really well to ignore several hidden or temp files/folders....
So for your specific requirements:
Folders:
```
bin obj release compile
```
Files:
```
*.bak *.user *.suo
```
I would use:
```
```
bin obj release compile *.bak *.user *.suo
```
```


Question: Please give me the direction of the best guidance on the Entity Framework.

Answer:
Currently I have the following in my Global Ignore Pattern:
```
```
bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db
```
```
Works really well to ignore several hidden or temp files/folders....
So for your specific requirements:
Folders:
```
bin obj release compile
```
Files:
```
*.bak *.user *.suo
```
I would use:
```
```
bin obj release compile *.bak *.user *.suo
```
```


Question:
In applying for jobs via agents I sometimes get blocked by an agent who says do you know software package X. When I reply that I know the similar package Y they might say unless you know X I cannot put you forward.

The problem is that some of these agents don't know what they talking about, they are merely being used by their clients as a screening filter.

It would be useful to be able to say to these agents that because I know Y I can expect to become reasonably proficient in X in a given number of days/months. However not knowing X determining the required time is why I'm asking this question.

Most recently X was Oracle and Y was SQL Server.

Please can those of you who know both, express an opinion on how long is required to become reasonably proficient? NB I'm not talking about becoming a DBA!

Answer:
If you're being hired as a DBA, it will take a while to switch between databases as the management of them differs (I base this on my experience with Oracle and DB2 only).
I DON'T know SQL Server but I can imagine a Microsoft program with its nice GUI management would be vastly different to managing DB2/z, for example (although you can use the fancy DB2 LUW (Linux/UNIX/Window) tools if you're that way inclined).
If you're just cutting code to use the database, the SQL differences are minor (relatively).  That shouldn't take much time at all, assuming you're already proficient with SQL.


Question:
What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.

This is ASP.NET 1.1

Answer:
Preventing XSS is a different issue from validating input.
Regarding XSS: You should not try to check
input
for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.
Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".


Question: Is there a way to automatically apply a theme/template/style to all controls of the targettype, so I don't have to specify Template=..., Style=... on all controls?

Answer:
I thought there was a way to do this by just omitting the x:Key attribute, but that doesn't seem to work anymore. Based on some googling it seems to me like you're best best is to create a custom control library of your own that has a themes/generic.xaml file that defines your custom styles. Then you can use your own elements that are styled properly (MyButton instead of Button). Either that or
stick with the Style property
.
Some example of this
here
and an alternate approach using themes
here
.
Update:
Just found a really good example of this
here
(I think you might have already seen it :).


Question: I need to make a change to an ASP.NET web service written a couple years ago on 2.0.  I call this web service from an old 1.1 web site.  I need to make some changes to the web service, so am thinking, should I rewrite this into a WCF service and if so, will I still be able to use it from my 1.1 web site?

Answer:
You can make a WCF service act and behave just like a traditional 1.1 ASMX web service, but is that what you want?
I think you need to ask yourself what featires of WCF are motivating you to upgrade.
Do you want to also expose the service as a REST-ful service?  Do you need to implement message level security?
If it's just to go to the latest technology for the sake of the latest technology, I'd say stick with ASMX web services if your requirements for message and protocol security aren't that high and you're working with mostly microsoft technologies.
Writing a WCF service is regrettably more difficult than a plain-old asmx web service.


Question:
Sybase db tables do not have a concept of self updating row numbers. However , for one of the modules , I require the presence of rownumber corresponding to each row in the database such that max(Column) would always tell me the number of rows in the table.

I thought I'll introduce an int column and keep updating this column to keep track of the row number. However I'm having problems in updating this column in case of deletes. What sql should I use in delete trigger to update this column?

Answer:
You can easily assign a unique number to each row by using an identity column. The identity can be a numeric or an integer (in ASE12+).
This will
almost
do what you require. There are certain circumstances in which you will get a gap in the identity sequence. (These are called "identity gaps", the best discussion on them is
here
). Also deletes will cause gaps in the sequence as you've identified.
Why do you need to use max(col) to get the number of rows in the table, when you could just use count(*)? If you're trying to get the last row from the table, then you can do
```
```
select * from table where column = (select max(column) from table).
```
```
Regarding the delete trigger to update a manually managed column, I think this would be a potential source of deadlocks, and many performance issues. Imagine you have 1 million rows in your table, and you delete row 1, that's 999999 rows you now have to update to subtract 1 from the id.


Question:
We are developing a considerably big application using Ruby on Rails framework (CRM system) and are considering to rewrite it to use ExtJS so that Rails would just do the data handling, while ExtJS would do all the browser heavylifting in a desktop-like manner.

Anyone has some experience and hints about what would be the best approach? Is ExtJS mature enough to be used in relatively big (and complex) applications? And what about the Rails part - what would be the best approach here?

EDIT:

Just to make it clear. I would prefer to do it in such a way that all the javascript client side application code is loaded at once (at the start up of the application, optimally as one compressed js file) and then just use ajax to send data to and from Rails app. Also, it would be nice to have ERB available for dynamic generation of the Ext apliccation elements.

Answer:
Ext is definitely mature enough to handle this situation. I'm currently working on a Rails project with a lot of Ext, and the hardest part has definitely been working with Rails's
```
to_json
```
to render JSON that Ext can read (for arrays, hashes, models, which failed validation, etc.)
Check out the ext_
```
scaffold
```
plugin for Rails. I started with this and hacked away at its
```
ActiveRecord
```
/
```
ActionView
```
extensions until it did what I needed it to do.


Question:
Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls?  Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control.  Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.

Are these the only two choices?  Is there a right way to do this that I'm missing?

Thanks!
Eric Sipple

Answer:
Setting the value for
```
WebControl.Attributes["onclick"]
```
is okay. If ASP.NET needs a client-side
```
click
```
handler, it will concatenate the values, delimited by semi-colon.


Question: I have a BulletedList in asp.net that is set to DisplayMode="LinkButton". I would like to trigger the first "bullet" from a javascript, can this be done? And if so, how?

Answer:
Say you have the BulletedList as
```
```
<asp:BulletedList runat="server" ID="MyLovelyBulletedList" DisplayMode="LinkButton">
    <asp:ListItem Text="My Lovely Text 1" />
    <asp:ListItem Text="My Lovely Text 2" />
</asp:BulletedList>
```
```
... then you can fire the "onclick" event like this (cross-browser):
```
```
var links = document.getElementById('<%= MyLovelyBulletedList.ClientID %>').getElementsByTagName('a');

var targetLink = links[0];

if (targetLink.fireEvent)
{
    // IE
    targetLink.fireEvent("onclick");
}
else if (targetLink.dispatchEvent)
{
    // W3C
    var evt = document.createEvent("MouseEvents");

    evt.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0, false, false, false, false, 0, null);

    targetLink.dispatchEvent(evt);
}
```
```


Question:
When reading my RSS feed with the Thunderbird feed reader, some entries are duplicated. Google Reader does not have the same problem.

Here is the faulty feed:
http://plcoder.net/rss.php?rss=Blog

There is a problem, but where?

I added a GUID, but the problem remains. Other feeds do not duplicate like mine, so I will do rework on this module and replace this old good code.

Conclusion: I completely reworked the RSS generator code, and it's OK. I think I was using a very old version of RDF.

Answer:
Try adding a
```
<guid>
```
tag to each item, giving it a permalink.  i.e.:
```
```
<item rdf:about="http://plcoder.net/?doc=2134&amp;titre=mon-pc-se-la-pete">
  <link>http://plcoder.net/?doc=2134&amp;titre=mon-pc-se-la-pete</link>
  <guid>http://plcoder.net/?doc=2134&amp;titre=mon-pc-se-la-pete</guid>
  ...
</item>
```
```
Without a GUID, if any of the content in the post changes, your RSS aggregator might think that it is a new post.  With the GUID, even if the content of that item changes, your RSS aggregator
should
just update the post, instead of treating it as a new item.


Question:
This question is similar to my  earlier question.

I have used ASP .Net in Visual Studio 2005 about 4 years ago. How long would it take to get back up to speed with the latest versions?

Answer:
Not very long. The major addition to VS 2008 is support for Linq, but you don't have to use this (or any of the new features).
The IDE is extremely similar to VS 2005.
Essentially, 2005 targets the 3.0 framework, and 2008 target the 3.5 framework, but these are both just expansions of the 2.0 framework, and not new versions (unlike the change from 1.1 to 2.0).


Question:
I am trying to find all matches in a string that begins with | |.

I have tried: if ($line =~ m/^\\\|\s\\\|/) which didn't work.

Any ideas?

Answer:
You are escaping the pipe one time too many, effectively escaping the backslash instead.
```
```
print "YES!" if ($line =~ m/^\|\s\|/);
```
```


Question:
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.

Example:

public class MyGenericClass<T> {
  public void doSomething() {
    // Snip...
    // Call to a 3rd party lib
    T bean = (T)someObject.create(T.class);
    // Snip...
  }
}

Clearly the example above doesn't work  and results in the following error: Illegal class literal for the type parameter T.

My question is: does someone know a good alternative or workaround for this?

Answer:
Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :
```
```
public class MyGenericClass<T> {

    private final Class<T> clazz;

    public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
        return new MyGenericClass<U>(clazz);
    }

    protected MyGenericClass(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void doSomething() {
        T instance = clazz.newInstance();
    }
}
```
```
It's ugly, but it works.


Question:
I am doing .net programming in addition to c and c++ development and want more flexibility on my home machine.  I want to be able to have both Linux (probably Ubuntu) and Windows Vista on my home computer.  Is there a way I can install both and on boot be prompted for which one to start?  Is there a way to set Windows to default?

I have seen this before in CS labs in undergrad.

Also, I assume there would be no problem if I were to use Windows 32-bit along with Ubuntu 64-bit.  Any advise?

Answer:
You can dual boot, but I would recommend using a Virtual Machine for what you want to do.
Look at
VMWare
and
Virtual PC
.
For more information on Virtual PC:
http://en.wikipedia.org/wiki/Microsoft_Virtual_PC
For more information on VMWare:
http://en.wikipedia.org/wiki/VMware_Workstation
You should note that dual booting Windows and Linux can be a little risky and is a bit permanent. Running in a Virtual Machine means that you can run the Linux install in a window and not worry about it affecting your development machine at all. The software will not know the difference, so your testing is not affected.
Consider that the Virtual Machine is like a sandbox, where you can try new and different things out, without fear of consequences.
Virtual machines do run with a bit of overhead, and therefore you should not expect to be playing games or anything through them. I would say it is very much like logging into a machine through Remote Desktop (good LAN connection) as far as performance goes.
EDIT: There is also
VirtualBox
that you could check out. Thanks for the helpers in my comments for that one.


Question: Using JDK1.5 how does one send a binary attachemnt (such as a PDF file) easily using the JavaMail API?

Answer:
If you want to do it easily I'd suggest using
Commons-Email
! It's built on the JavaMail API, but it makes it much simpler.
There is a sample in the
User Guide
on how to send email with attachments... it's much easier than using the standard JavaMail API!


Question: How to unit test the windows workflows?

Answer:
MS dropped the ball on making workflows easily mockable and testable.  If you want to do thorough tests on your custom activities you'll need to purchase a mocking framework that can mock sealed types such as
TypeMock.
Otherwise, you'll have to write your code around the limitations of Workflow.


Question: Specifically MSSQL 2005.

Answer:
Some links to possible answers:
http://www.extremeexperts.com/sql/Tips/DateTrick.aspx
http://www.devx.com/tips/Tip/14405
http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
http://www.sqlservercurry.com/2008/03/find-last-day-of-month-in-sql-server.html


Question:
This is a question for anyone who has the pleasure to work in both Java and C#.

Do you find that you have to make a mental context switch of some kind when you move from one to the other?

I'm working in both at the moment and because the syntax and libraries are so similar and yet subtly different I'm finding it frustrating when i move from one to the other.

This is more so than I've experienced moving between any other programming languages.

Does anyone have any tips for making your brain work differently for languages that are so similar?

Answer:
Yes, I have to make a mental context switch - because LINQ isn't available in Java :(
Beyond that, there are little things like
```
foreach (X x in y)
```
vs
```
for (X x : y)
```
which often trip me up, but not a
huge
amount otherwise.
As for a tip to make your brain work differently: don't give into the temptation to use the naming conventions of the other language. I find that using camel-cased method names in Java is a good nudge to my brain, for example.
EDIT: The differences in terms of generics are important and can occasionally be brain-warping, too.


Question: I need to determine the highest .NET framework version installed on a desktop machine from C\C++ code.  Looks like I can iterate the folders under %systemroot%\Microsoft.NET\Framework, but that seems kind of error prone.  Is there a better way?  Perhaps a registry key I can inspect?  Thanks.

Answer:
Use the
Windows Registry
location
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
```
.


Question:
im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here?

int value = *min_element(v2.begin(), v2.end());
cout << "min value at position " << *find(v2.begin(), v2.end(), value);

Answer:
```
min_element
```
already gives you the iterator, no need to invoke
```
find
```
(additionally, it's inefficient because it's twice the work). Use
```
distance
```
or the
```
-
```
operator:
```
```
cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
```
```


Question:
I have parsed XML using both of the following two methods...

Parsing the XmlDocument using the object model and XPath queries.

XSL/T

But I have never used...

The Linq Xml object model that was new to .Net 3.5

Can anyone tell me the comparative efficiency between the three alternatives?

I realise that the particular usage would be a factor, but I just want a rough idea. For example, is the Linq option massively slower than the others?

Answer:
I haven't actually tested it, but Linq is primarily a compiler code-gen type feature, and so it should be comparable to using an XmlDocument and XPath queries.
The primary value of Linq is that it provides compile-time verification of your query statements, which neither XPath nor XSLT can provide.
I would think that if performance is a concern, your decision would be based on the task at hand.  For example, retrieving a single value from an XML document might be fastest using a single XPath query, but translating XML data into an HTML page would be faster using XSLT.


Question:
Files:

Website\Controls\map.ascx

Website\App_Code\map.cs

I'd like to create a strongly typed instance of map.ascx in map.cs

Normally, in an aspx, you would add a <%Register... tag to be able to instantiate in codebehind. Is this possible in an app_code class?
I'm using .NET 3.5/Visual Studio 2008

Thanks!

Answer:
Normally, I'd do something like this (assuming your type is "Map" and that you have the appropriate "Inherits" declaration in your .ascx file):
```
```
Map map = (Map)LoadControl("~/Controls/map.ascx");
```
```


Question:
I'm working on a free software (bsd license) project with others. We're searching for a system that check out our source code (svn) and build it also as test it (unit tests with Check / other tools).

It should have a webbased interface and generate reports.

I hope we don't have to write such a system from null by ourselves...

Answer:
I don't think that there's a buildsystem that is capable of doing all this tasks - but what about combining them?
SCons
is a nice buildsystem that runs on every machine that has
Python
. It can even build directly from
SVN
. For automatic building you can try
Buildbot
.


Question: I'm making a report in Access 2003 that contains a sub report of related records.  Within the sub report, I want the top two records only.  When I add "TOP 2" to the sub report's query, it seems to select the top two records before it filters on the link fields.  How do I get the top two records of only those records that apply to the corresponding link field?  Thanks.

Answer:
I've got two suggestions:
1) Pass your master field (on the parent form) to the query as a parameter (you could reference a field on the parent form directly as well)
2) You could fake out rownumbers in Access and limit them to only rownum <= 2. E.g.,
```
```
SELECT o1.order_number, o1.order_date,
    (SELECT COUNT(*) FROM orders AS o2
        WHERE o2.order_date <= o1.order_date) AS RowNum
    FROM
        orders AS o1
    ORDER BY o1.order_date
```
```
(from
http://groups.google.com/group/microsoft.public.access.queries/msg/ec562cbc51f03b6e?pli=1
)
However, this kind of query might return an read only record set, so it might not be appropriated if you needed to do the same thing on a Form instead of a Report.


Question:
When i deploy a rails application in production mode, it appends a date-time string as a query param to the end of all the static asset urls. This is to prevent browsers using old-out of date cahed copies of the assets after I redeploy the application.

Is there a way to make rails use the old time stamps for the assets that have not changed (and only the ones that have not changed) since the last deployment. I want to do this to prevent users having to redownload those assets that have not changed.

Answer:
I think you can use ENV['RAILS_ASSET_ID'] to alter the cache-busting asset ID. Unfortunately, this is for all assets.
But if it's not set, it uses the asset's source modification time. If that file hasn't been modified since the last time you used it, it shouldn't be a problem.
If the asset ID is changing when they haven't been changed, it might be because of your deployment process altering the modification time and maybe you could look at tweaking that.
Lastly, you can always
override rails_asset_id with your own custom method
.
Hope this helps.


Question:
Looking into System.Data.DbType there is no SqlVariant type there. SqlDataReader, for example, provides the GetString method for reading into string variable. What is the appropriate way to retrieve data from the database field of type sql_variant, presumably into object?

The aim is to read data stored as sql_variant type in database. Not to assign the value into variable of object type. I mentioned object type variable because I thing the sql_variant, if possible, would go into such type.

Answer:
If you want to put the data into a variable of type object then (simplified):
```
```
object result = null;
result = reader["columnNameGoesHere"];
```
```
Should do the trick.
There's also a good explanation of the various different methods of retrieving the contents of a given columns current record in
this DevHood tutorial
. The summary table of data type mappings at the end may come in handy too!


Question:
I have an internal web app with an image at the top of the page, currently containing some english text with drop shadows. I now need to provide localized versions of this page for various languages. My main choices are:

Have a different graphic per supported language, containing the localized text.

Use CSS to position localized text over a plain image, with a complex CSS technique to get drop shadows in most current browsers.

Are there other options? This is for an educational environment, I don't get to control the browser used by the students.

I did try both removing the drop shadows from the graphic, and also moving the text into in a header in the HTML, but neither was appealing. People said it looked like a cheap knockoff of the current page, which wounds my pride.

Answer:
Personally I'm a big fan of CSS techniques for visual effects like this. The big benefit is that you are offloading the processing of the effect to the client side, saving you bandwith and content creation time (custom text images for each locale is a big order!), and making the page download faster for the user.
The only reason to avoid it is if you absolutely MUST have the drop shadows on very old (IE5) browsers with next to no CSS support.
Edit: Just thought of something - I a few cases like this where I need a specific font or some exact text effect I've used PHP to render the text, with effects, to an image and cache it server side. That way you avoid the content creation process and gain wider browser support in exchange for bandwidth and server CPU time. It's your call if the tradeoff is acceptable.


Question:
I have a strange bug with WPF Interop and an Excel Addin. I'm using .Net 3.5 SP1.

I'm using Add-in Express to create a Custom Task Pane for Excel 2003. Within that taskpane I'm using ElementHost to host a WPF UserControl. The UserControl simply contains a Grid with a TextBox and ComboBox. My problem is that whilst everything displays properly, the ComboBox won't stay dropped-down unless I hold the mouse down over the down-arrow.

I don't believe this is necessarily related to Add-in Express because I've had a similar problem when I tried displaying a WPF window modelessly in Excel.

A second problem is that the ComboBox seems reluctant to give up focus. If I click it, the text area goes grey to indicate that it has focus, but I can't move focus anywhere else in the window. The only way to wrest focus away is to move the mousewheel.

Anybody else had a similar problem, and managed to fix it?

Answer:
Add-in Express looked into this for me, and it turns out to have something to do with the Window style of the Task Pane that gets added to Excel. If you turn off the WS_CHILD flag in the Windows CreateParams then Combo Boxes and other popups work as expected.
They gave me this snippet of code to add to my ADXExcelTaskPane:
```
```
private const uint WS_CHILD = 0x40000000;
private const uint WS_CLIPCHILDREN = 0x02000000;
private const uint WS_CLIPSIBLINGS = 0x04000000;

private CreateParams _CreateParams = new CreateParams();
protected override CreateParams CreateParams
{
    get
    {
        _CreateParams = base.CreateParams;
        if (!DesignMode)
            _CreateParams.Style = (int)(WS_CLIPCHILDREN | WS_CLIPSIBLINGS); //| WS_CHILD

        return _CreateParams;
    }
}
```
```


Question: Is there a way to define a column (primary key) as a UUID in SQLAlchemy if using PostgreSQL (Postgres)?

Answer:
You could try writing a
custom type
, for instance:
```
```
import sqlalchemy.types as types

class UUID(types.TypeEngine):
    def get_col_spec(self):
        return "uuid"

    def bind_processor(self, dialect):
        def process(value):
            return value
        return process

    def result_processor(self, dialect):
        def process(value):
            return value
        return process

table = Table('foo', meta,
    Column('id', UUID(), primary_key=True),
)
```
```


Question:
I would like to add a BuildListener to my headless build process, which is building an Eclipse product. The docs on how to do this are, shall we say, a bit scanty. I think I need to put my custom jar in a plugin and then use the org.eclipse.ant.core.extraClasspathEntries extension point to make that jar visible to Ant. But everything I have tried results in
 [myClass] which was specified to be a build listener is not an instance of org.apache.tools.ant.BuildListener.

My class implements the BuildListener interface. Various  postings seem to indicate that this means my class is visible-to/loaded-by the Plugin classloader rather than the Ant classloader. But I thought the whole point of the extension point was to make jars visible to Ant...

Can anyone shed light on what I'm doing wrong?
Additional info: I am trying to run this build from the Eclipse IDE at the moment using the AntRunner application.

Answer:
I had this problem when I had two plugins providing an
```
ant.jar
```
.
Make sure you use the
```
org.apache.ant
```
plugin and that there is no other plugin providing another
```
ant.jar
```
.
Another thing I just stumbled upon: The jar containing your contribution must not be in the plugins classpath (Runtime -> Classpath).
See
Eclipse Bug 34466
.


Question: I'm a big fan of Capistrano but I need to develop an automated deployment script for a Java-only shop.  I've looked at Ant and Maven and they don't seem to be well geared towards remote administration the way Capistrano is - they seem much more focused on simply building and packaging applications.  Is there a better tool out there?

Answer:
I don't think there is a Capistrano-like application for Java Web Applications, but that shouldn't really keep you from using it (or alternatives like Fabric) to deploy your applications. As you've already said, Ant is more a replacement for GNU Make while Maven is primary a buildout/dependency-management application.
Since Java Web Applications are thanks to the .war container less dependent on external libraries, you can (depending on your application server) make deploying an application as easy as running a simple HTTP PUT-request.
But if you require additional steps,
Fabric
has worked very well for me so far and I assume that Capistrano also offers generic shell-command, put and get operations. So I wouldn't look for too long for an alternative if what you already have already works :-)


Question:
I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types.

Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?

Answer:
Usually, yes.
All the compiler really knows is that your program can create at least one instance of each class.  But it doesn't know what you will do with those instances.  So the code will almost certain be generated.
That said, if the methods in question are
not
virtual, and are never called, the
linker
can remove them with its normal dead code removal features.  So the generated (and compiled) code won't be in the final EXE.
Also this will largely depend on the C++ compiler being used because they're not all the same.


Question:
I need to generate multiple random values under SQL Server 2005 and somehow this simply wont work

with Random(Value) as
(
    select rand() Value
        union all
    select rand() from Random

)select top 10 * from Random

Whats the preffered workaround?

Answer:
I'm currently using this:
```
```
with Random(Value) as
(
    select rand(checksum(newid())) Value
        union all
    select rand(checksum(newid())) from Random
)select top 10 * from Random
```
```
but that seems overly hackish :S
Why doesnt rand get reevaluated in the first version?


Question:
We are using Visual Studio 2008 as our primary development IDE.  Our security team has set up McAfee to scan files in our \Local Settings\Temp folder.  Unfortunately VS uses this directory during code builds which is slowing the developers down.  We've reached an impasse with the security team on this, and wonder if anyone knows of a configuration setting in VS where we could change the folder to where those temporary files are written.

Thanks

Answer:
Maybe complain a lot that you need faster computers since the added security slows you down so much? Have hard facts ready (like "slower compile time costs me 60 minutes every day")
Usually when it comes around to spending money most businesses find other ways around a problem.


Question:
What's the best way to break from nested loops in Javascript?

//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
   for (var Heading in Navigation.Headings)
   {
      for (var Item in Navigation.Headings[Heading])
      {
         if (Args[x] == Navigation.Headings[Heading][Item].Name)
         {
            document.write("<a href=\""
               + Navigation.Headings[Heading][Item].URL + "\">"
               + Navigation.Headings[Heading][Item].Name + "</a> : ");
            break; // <---HERE, I need to break out of two loops.
         }
      }
   }
}

Answer:
Wrap that up in a function and then just
```
return
```
.


Question:
Is it possible to make hibernate do "the right thing" for some value of "right" in this situation?

from ClassA a, ClassB b
where a.prop = b.prop

The thing is that prop is a UserType with different representation in the joined tables. In table A it is represented as an integer and in table B it is represented as a char. So the eq test translates to see if 1 == 'a' more or less, which is false but the object represented by 1 or 'a' should is the same so they should compare true.

Answer:
(1) Change data-type of columns which map to "prop" to be the same. This will require "Making DBA your friend" but will result in consitent "prop" UserType usage.
(2) Handle the type differences in equals() method
```
```
public boolean equals(Object x, Object y) throws HibernateException {
    boolean retValue = false;
    if (x == y) retValue = true;

    if (x!=null && y!=null){
        Character xChar = new Character(x);
        Character yChar = new Character(y);
        if (xChar.equals(ychar)){
            retValue = true;
        }
    }

    return retValue;
}
```
```


Question:
I have one question maybe someone here can help me. If i do "ps aux --sort user" on linux console I have one list of users and their processes runing on the machine. My question is how do I remove the users name and print that list like this in a C program:

for example:

(…)
--------------------------------------------------------------------------
user: APACHE
--------------------------------------------------------------------------
3169 0.0 1.2 39752 12352 ? S 04:10 0:00 /usr/sbin/httpd
--------------------------------------------------------------------------
user: VASCO
--------------------------------------------------------------------------
23030 0.0 0.1 4648 1536 pts/1 Ss 20:02 0:00 –bash

(…)

I print the user name then I print his processes... any ideas ?

thx

Answer:
```
```
ps aux --sort user | perl -npe 's/^(\w+)//g; if ($user ne $1) {$user=$1; print "user: " . uc($user) . "\n";}'
```
```


Question:
I have unmanaged C++ calling a managed delegate via the function pointer provided by Marshal::GetFunctionPointerForDelegate.  This delegate has the potential to throw an exception.  I need to be able to properly handle this exception in my unmanaged C++ to ensure things like pointer cleanup, and potentially rethrow the exception up into more managed code.  The call stack is similar to this:

Managed Code -> Unmanaged C++ -> callback to Managed Code via delegate (exception can be thrown here).

Anyone have pointers for properly handling this situation so that the resources in unmanaged code can be cleaned up and a usable exception can be thrown out to the managed code which initiated the whole call stack?

Answer:
Catching from managed code with
```
```
try
{
  throw gcnew InvalidOperationException();
}
catch(InvalidOperationException^ e)
{
  // Process e
  throw;
}
```
```
And an
```
```
[assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)];
```
```
on your assembly catches managed and unmanaged exceptions


Question:
I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.

function foo(id) {
    this.dom = document.getElementById(id);
    this.bar = 5;
    var self = this;
    this.dom.addEventListener("click", self.onclick, false);
}

foo.prototype = {
    onclick : function() {
        this.bar = 7;
    }
};

Now when I create a new object (after the DOM has loaded, with a span#test)

var x = new foo('test');

The 'this' inside the onclick function points to the span#test and not the foo object.

How do I get a reference to my foo object inside the onclick function?

Answer:
```
```
this.dom.addEventListener("click", function(event) {
    self.onclick(event)
}, false);
```
```


Question: Passing an undimensioned array to the VB6's Ubound function will cause an error, so I want to check if it has been dimensioned yet before attempting to check its upper bound.  How do I do this?

Answer:
I found this:
```
```
Dim someArray() As Integer

If ((Not someArray) = -1) Then
  Debug.Print "this array is NOT initialized"
End If
```
```
Edit
: RS Conley pointed out in his
answer
that (Not someArray) will sometimes return 0, so you have to use ((Not someArray) = -1).


Question:
I have a SEAM app with some JPA/Hibernate entities. And I now wonder where to put my query, persistence methods.

The default choice seems to put them in a session bean layer with injected

@PersistenceContext(...) @Inject EntityManager entityManager;

But I think I would rather have the methods on the entities themselves. What are the pro's/con's?

Testablity?

Niceness?

Performance?

And does anyone have links to best practices for interacting with the EntityManager etc. from methods on the Entities rather than session beans?

Best,
Anders

Answer:
I have no experience with SEAM, but from my experience with Java projects, I found it easiest to keep beans clear of persist methods. What we usually do:
Have beans for business objects (like "User" and "Setting" for example)
Have a DAO layer which can persist and retrieve these beans (simple CRUD)
Have a Service Layer which nows how to handle the beans, and maybe even how to build an aggregate of beans
This way, everything is pretty separated, and is easy to unittest. Performance is usually not an issue with this setup.


Question:
Does Mono .NET support and compile C++ / CLI?

If not, do you know if they have any plans of supporting it?

Answer:
go
here
and look under "Missing Languages".  But just because you cant compile does not mean that you cant
run
.  You can compile your C++ code using the framework sdk and try running it using mono.  Worth trying anyway.


Question:
How can I add a line break to text when it is being set as an attribute i.e.:

<TextBlock Text="Stuff on line1 \n Stuff on line2" />

Breaking it out into the exploded format isn't an option for my particular situation.  What I need is some way to emulate the following:

<TextBlock>
  <TextBlock.Text>
    Stuff on line1 <LineBreak/>
    Stuff on line2
  </TextBlock.Text>
<TextBlock/>

Answer:
```
```
<TextBlock Text="Stuff on line1
Stuff on line 2"/>
```
```
You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic"
```
vbCrLf
```
, then you can use
```

```
By the way, note the syntax: It's the ampersand, a pound, the letter
x
, then the hex value of the character you want, and then finally a semi-colon.
ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.


Question:
I have an extremely simple routes.rb in my Rails app:

ActionController::Routing::Routes.draw do |map|
  map.resources :tags
end

Starting up my app with script/server and pointing my browser to localhost:3000/tags/ yields:

ActionController::MethodNotAllowed

Only get and post requests are allowed.

...

Starting up my app with script/server webrick, however, solves the problem.

Later: in case it matters, I'm running Mongrel 1.1.5 on OSX 10.5.5.

Answer:
I have seen this happen with older versions of mongrel, but 1.1.5 is not old. I have also seen some similar problems when the browser double-posts a request to a URL. Is that happening here?
I'd need some more information to be able to help you: What browser are you using? Are you using the firebug plugin on Firefox? What does the server log say about the request, other than the MethodNotAllowed exception?


Question:
How do I fix that error once and for all?  I just want to be able to do unions in MySQL.

(I'm looking for a shortcut, like an option to make MySQL ignore that issue or take it's best guess, not looking to change collations on 100s of tables ... at least not today)

Answer:
Not sure about mySQL but in MSSQL you can change the collation in the query so for example if you have 2 tables with different collation and you want to join them or as in you situation crate UNION you can do
```
```
select column1 from tableWithProperCollation
union all
select column1 COLLATE SQL_Latin1_General_CP1_CI_AS from tableWithDifferentCollation
```
```
Of course SQL_Latin1_General_CP1_CI_AS is just an example of collation you want to "convert" to


Question:
Is there any way to determine a removable drive speed in Windows without actually reading in a file.  And if I do have to read in a file, how much needs to be read to get a semi accurate speed (e.g. determine whether a device is USB2 or USB1)?

EDIT: Just to clarify, USB2 and USB1 were an example.  These could be Compact Flash, could be SSD, could be a removable drive.  And I am trying to determine this as fast as possible as it has a real effect on the responsiveness of the application.

EDIT:  Should also clarify, this has to be done programatically.  It will probably be done in C++.

EDIT: Boost answer is kind of what I was looking for (though I haven't written any WMI in C++).  But I need to know what properties I have to check to determine relative speed.  I don't need exact speed (like I said about the difference in speed between USB1 and USB2), but I need to know if it is going to be SLLOOOOWWW.

Answer:
Several megabytes, I'd say. Transfer speeds can start out slow, and then speed up as the transfer progresses. There are also variations because of file sizes (a single 1GB file will transfer much faster than 1GB of smaller files).
Best way to do that would be to copy a file to/from the device, and time how long it takes with your code. USB1 speed is 11Mb/s (I think), and USB2 is 480Mb/s (note those are numbers for the whole bus, not each port, so multiple devices on the same bus will change the actual numbers).


Question:
What is an efficient way to shrink a two dimensional array to a smaller size in C#?

For example:

var bigArray = new object[100, 100];
var smallArray = new object[10, 10];

bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;

startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;

smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);

How will you write SomeShrinkingMethod() ?

Thanks!

EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.

Answer:
You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.
The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.
Edit:
In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.


Question:
We are doing some performance tests on our website and we are getting the following error a lot:

*** 'C:\inetpub\foo.plex' log message at: 2008/10/07 13:19:58
DBD::ODBC::st execute failed: [Microsoft][SQL Native Client]String data, right truncation (SQL-22001) at C:\inetpub\foo.plex line 25.

Line 25 is the following:

SELECT DISTINCT top 20 ZIP_CODE, CITY, STATE FROM Zipcodes WHERE (ZIP_CODE like ?) OR (CITY like ?) ORDER BY ZIP_CODE

And lastly, this is perl code.

Any ideas?

EDIT: the issue here was that I was searching in the zip file with the string "74523%" which is too long.  I ended up just not adding the % if they give five digits.

Answer:
Either the parameter supplied for
```
ZIP_CODE
```
is larger (in length) than
```
ZIP_CODE
```
s column width or the parameter supplied for
```
CITY
```
is larger (in length) than
```
CITY
```
s column width.
It would be interesting to know the values supplied for the two
```
?
```
placeholders.


Question:
I've got a UI front end which talks to and manipulates a SQL Server database, and one of the things it can do is run reports on the data in the database.

This UI can be installed on multiple computers, and so far I've just been keeping the reports in a folder with the install, but this means that any time a new report is added is has to manually be copied to every single UI install out there.

I was thinking of storing the .rpt files in the database itself (As Blobs) and having some mechanism for the UI to fetch them when needed as a way to centralize the reports and eliminate this issue.

Has anybody tried this, and did it work well? Or if you haven't, can you think of anything I should take into account before moving forward with this? Are the any tips, tricks, or caveats you can think of that might be helpful to me?

Answer:
Here's great podcast with Paul Randal (he wrote parts of DBCC!) where they talk about the new filestream feature in sql server 2008  for handling blobs, but they also go into the sizes of files that do and don't work well
as blobs as part of the talk. I think it would help you.
http://www.runasradio.com/default.aspx?showNum=74
I just found out that the 25-page FILESTREAM whitepaper Paul wrote has has been published on MSDN.
http://msdn.microsoft.com/en-us/library/cc949109.aspx
.
Based on the research cited later in this white paper, BLOBs smaller than 256 kilobytes (KB) (such as widget icons) are better stored inside a database, and BLOBs larger than 1 megabyte (MB) are best stored outside the database. For those sized between 256 KB and 1 MB, the more efficient storage solution depends on the read vs. write ratio of the data, and the rate of “overwrite”. Storing BLOB data solely within the database (e.g., using the varbinary(max) data type) is limited to 2 gigabytes (GB) per BLOB.


Question:
So, I have a nice domain model built.  Repositories handle the data access and what not.  A new requirements has popped up that indicates that reasons need to be logged with deletes.  Up until now, deletes have been fairly simple => Entity.Children.Remove(child).  No internal change tracking was happening as my ORM tool was handling state management.  However, I'm not sure exactyl how to handle this.

1) I could keep a deleted children collection in the parent entity and pull the change tracking out of nHibernate and handle it myself.

2) ??????

Answer:
Could you implement the
IInterceptor interface
and override the onDelete functionality to pull the information you need from the entity and send it to logger before you delete (using NHibernate of course)?
example


Question: I would like to ask for some simple examples showing the uses of <div> and <span>. I've seen them both used to mark a section of a page with an id or class, but I'm interested in knowing if there are times when one is preferred over the other.

Answer:
```
<div>
```
is a block-level element and
```
<span>
```
is an inline element.
If you wanted to do something with some inline text,
```
<span>
```
is the way to go since it will not introduce line breaks that a
```
<div>
```
would.
As noted by others, there are some semantics implied with each of these, most significantly the fact that a
```
<div>
```
implies a logical division in the document, akin to maybe a section of a document or something, a la:
```
```

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis congue vehicula purus.

Nam eget magna nec sapien fringilla euismod. Donec hendrerit.

```
```


Question:
I am trying to install newgem on my linux box (sudo gem install newgem) and i am getting the following error:

Building native extensions.  This could take a while...
ERROR:  Error installing newgem:
ERROR: Failed to build gem native extension.

/usr/bin/ruby1.8 extconf.rb install newgem
extconf.rb:1:in `require': no such file to load -- mkmf (LoadError)
from extconf.rb:1

Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4/ext/redcloth_scan/gem_make.out

What could the problem be?

Answer:
```
mkmf
```
is a Ruby module which generates Makefiles.  It is supposed to be part of the standard Ruby install, but Debian (and derivatives) split it out into the
```
ruby1.8-dev
```
package.
If you can't find
```
mkmf.rb
```
in any of the directories outputted by
```
ruby -e'print $:.join("\n")'
```
, then you should figure out what you need to install.


Question: What tool is there for generating C# classes from NHibernate mappings files?

Answer:
On the
NHibernate resources page
under 'Helpful tools', there are a few code generators listed:
http://nhibernate.info/doc/nh/en/index.html


Question:
Why does Visual studio take so long to delete a file from the solution tree?  The app freezes and sits there for what feels like an eternity.

If I delete the file from the file system first, then delete it in the solution it happens instantly.

Is there an option I can set somewhere to avoid this?

Answer: I've found that this is sometimes a symptom of project size. Deleting a file from a project with hundreds of files can take 30 seconds on my (admittedly slow) work computer. But deleting one of two files in a project is usually instant.


Question:
Is there a way to select manually a node in virtualizing TreeView and then bring it into view?

The data model I'm using with my TreeView is implemented based on the VM-M-V model. Each TreeViewItem's IsSelected property is binded to a corresponing property in ViewModel. I've also created a listener for TreeView's ItemSelected event where I call BringIntoView() for the selected TreeViewItem.

The problem with this approach seems to be that the ItemSelected event won't be raised until the actual TreeViewItem is created. So with the virtualization enabled node selection won't do anything until the TreeView is scrolled enough and then it jumps "magically" to the selected node when the event is finally raised.

I'd really like to use virtualization because I have thousands of nodes in my tree and I've already seen quite impressive performance improvements when the virtualization has been enabled.

Answer:
Here is an example taken from an
MSDN Question
public void ScrollToItem(int index)
```
```
{

        Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background,

            (System.Windows.Threading.DispatcherOperationCallback)delegate(object arg)

            {

                int N = fileList.Items.Count;

                if (N == 0)

                    return null;

                if (index < 0)

                {

                    fileList.ScrollIntoView(fileList.Items[0]); // scroll to first

                }

                else

                {

                    if (index < N)

                    {

                        fileList.ScrollIntoView(fileList.Items[index]); // scroll to item

                    }

                    else

                    {

                        fileList.ScrollIntoView(fileList.Items[N - 1]); // scroll to last

                    }

                }

                return null;

            }, null);

    }
```
```


Question:
I have this code that performs an ajax call and loads the results into two duplicate divs every time a dropdown is changed. I want the results to be faded into the div, to give a more obvious indication that something has changed, as its so seamless its sometimes hard to notice the change!

print("$('.ajaxdropdown').change(function(){

        $.ajax({
            type: "GET",
            url: "/includes/html/gsm-tariff.php",
            data: "c_name="+escape($(this).val()),
            success: function(html){
                $("#charges-gsm").html(html);
                                    //i want to fade result into these 2 divs...
                $("#charges-gsm-faq").html(html);
                $("#charges-gsm-prices").html(html);
            }
        });
    });");

I've tried appending the fadein method and a few other things, but no joy.

Answer:
You'll have to
```
hide()
```
it before you can use
```
fadeIn()
```
.
UPDATE:
Here's how you'd do this by chaining:
```
```
$("#charges-gsm-faq").hide().html(html).fadeIn();
$("#charges-gsm-prices").hide().html(html).fadeIn();
```
```


Question:
select distinct constraint_type from user_constraints;

C
-
C
P
R
U

Seems P means primary key and R means foreign key, correct?  What are U and C?

Answer:
```
```
Code Description                Acts On Level
---------------------------------------------
C    Check on a table           Column
O    Read Only on a view        Object
P    Primary Key                Object
R    Referential (Foreign Key)  Column
U    Unique Key                 Column
V    Check Option on a view     Object
```
```


Question:
my goal is to write a stored proc that can collect all field values from multiple rows into one single output variable (maybe varchar(some_length)). It may seem strange solution but i've quite positive its the only one i can use at that situation im in. I have not used Firebird before and stored procs look way different than in other well-known  db systems.
My Firebird is 1.5 and dialect 3 (not sure what it means).
So maybe someone could help me with a algorithm example.

Answer:
The following procedure does what you describe:
```
```
SET TERM !!;
CREATE PROCEDURE concat_names
  RETURNS (concat VARCHAR(2000))
AS
DECLARE VARIABLE name VARCHAR(100);
BEGIN
  concat = '';
  FOR SELECT first_name || ' ' || last_name FROM employee INTO :name
  DO BEGIN
    concat = concat || name || ', ';
  END
END!!
SET TERM ;!!
EXECUTE PROCEDURE concat_names;
```
```
But I question the wisdom of this solution.  How do you know the VARCHAR is long enough for all the rows in your desired dataset?
It's far easier and safer to run a query to return the result to an application row by row.  Every application programming language has methods to concatenate strings, but more importantly they have more flexible methods to manage the growth of data.
By the way, "dialect" in Firebird and InterBase refers to a compatibility mode that was introduced so that applications developed for InterBase 5.x can work with later versions of InterBase and Firebird.  That was almost ten years ago, and AFAIK there's no need today to use anything lower than dialect 3.


Question: Does anyone know if there is a good equivalent to Java's Set collection in C#? I know that you can somewhat mimic a set using a Dictionary or a HashTable by populating but ignoring the values, but that's not a very elegant way.

Answer:
Try
HashSet
:
The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...
The capacity of a HashSet(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object.
The HashSet(Of T) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the
Dictionary(Of TKey, TValue)
or
Hashtable
collections. In simple terms, the HashSet(Of T) class can be thought of as a
Dictionary(Of TKey, TValue)
collection without values.
A HashSet(Of T) collection is not sorted and cannot contain duplicate elements...


Question: I am building a blog type page, and I want to load items into the page as the user scrolls down, much like Google Reader, or Soup.io. How would you go about achieving this effect? I've seen some examples which read the height of the page, and have an onScroll even attached to the window so that as the user scrolls down we can test to see if they've scrolled down far enough to warrant loading more items. Soup.io's implementation seems to remove the old items as you scroll down so that the browser isn't dealing with an ever-increasingly large DOM tree. Which javascript libraries would be best suited to this task?

Answer:
Unspace had an article demonstrating this functionality:
Endless Pageless: No More Next Page
.  Their demonstration page is
here
(dead, for reference).
This particular example uses RoR and
Prototype.


Question:
I have two collections which have property Email in both collections. I need to get a list of the items in the first list where Email does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?

So far I have a join, like...

var matches = from item1 in list1
join item2 in list2 on item1.Email equals item2.Email
select new { Email = list1.Email };

But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.

Answer:
I don't know if this will help you but..
```
```
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;

var query =
    from c in dc.Customers
    where !(from o in dc.Orders
            select o.CustomerID)
           .Contains(c.CustomerID)
    select c;

foreach (var c in query) Console.WriteLine( c );
```
```
from
The NOT IN clause in LINQ to SQL
by
Marco Russo


Question:
Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:

>>> 6/3
2
>>> 6//3
2

Answer:
```
//
```
is floor division. It will always give you the integer floor of the result.  The other is 'regular' division.


Question:
Is there any way to clean up this type of loop using LINQ?

  List<Car> result;
  List<string> makes;
  List<string> models;

  for (int i = 0; i < makes.Count() && i < models.Count(); i++)
  {
    result.Add(new Car() { Make = makes[i], Model = models[i] });
  }

Basically I'm looking for some way to collate multiple arrays of individual fields into a single array of objects made up of those fields.

Answer:
You could use
```
Enumerable.Range
```
, like so:
```
```
List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count))
    .Select(i => new Car { Make = makes[i], Model = models[i] }).ToList();
```
```
If
```
makes
```
and
```
models
```
always contain the same number of items, you can use more compact syntax:
```
```
List<Car> result = makes.Select((make, i) => new Car { Make = make, Model = models[i] }).ToList();
```
```


Question:
I'm working on a home project that involves comparing images to a database of images (using a quadrant - or so - histogram approach).  I wanted to know what my options are in regards to web cams or other image capture devices that:

Are easy to work with with the
Windows SDK (particularly
DirectShow, which I plan to use
with C#)

Have drivers for both
64-bit and 32-bit Windows Vista (and
Server 2008)

I'm asking primarily so I can avoid pitfalls that other people may have experienced with web cams and to see if there are other image capture devices (or C# usable APIs) available that I should look at.  I suspect that any old web cam will do but I'd rather be safe than sorry.

Answer:
As per
ScottGu
,
One tip to take advantage of is the relative path fix-up support provided by the head runat="server" control.  You can use this within Master Pages to easily reference a .CSS stylesheet that is re-used across the entire project (regardless of whether the project is root referenced or a sub-application):
The path fix-up feature of the head control will then take the relative .CSS stylesheet path and correctly output the absolute path to the stylesheet at runtime regardless of whether it is a root referenced web-site or part of a sub-application.


Question:
How do I do forward referencing / declaration in C++ to avoid circular header file references?

I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how.

Answer:
You predeclare the class without including it.  For example:
```
```
//#include "Foo.h" // including Foo.h causes circular reference
class Foo;

class Bar
{
...
};
```
```


Question:
In the following code below:

Image img = new Image();
img.Source = new BitmapImage(new Uri("http://someURL/somefilename.jpg", UriKind.Absolute));

how can I determine if the image successfully loaded (when there's a valid URI)? i.e., The URI is a valid format, but the file may not exist.

Answer:
```
Image
```
has an
```
ImageFailed
```
event.
```
BitmapSource
```
(base for
```
BitmapImage
```
) has an
```
IsDownloading
```
property, as well as
```
DownloadProgress
```
,
```
DownloadCompleted
```
, and
```
DownloadFailed
```
events.


Question:
Say you've loaded a text file into a string, and you'd like to convert all Unicode escapes into actual Unicode characters inside of the string.

Example:

"The following is the top half of an integral character in Unicode '\u2320', and this is the lower half '\U2321'."

Answer:
The answer is simple and works well with strings up to at least several thousand characters.
Example 1:
```
```
Regex  rx = new Regex( @"\\[uU]([0-9A-F]{4})" );
result = rx.Replace( result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString() );
```
```
Example 2:
```
```
Regex  rx = new Regex( @"\\[uU]([0-9A-F]{4})" );
result = rx.Replace( result, delegate (Match match) { return ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); } );
```
```
The first example shows the replacement being made using a lambda expression (C# 3.0) and the second uses a delegate which should work with C# 2.0.
To break down what's going on here, first we create a regular expression:
```
```
new Regex( @"\\[uU]([0-9A-F]{4})" );
```
```
Then we call Replace() with the string 'result' and an anonymous method (lambda expression in the first example and the delegate in the second - the delegate could also be a regular method) that converts each regular expression that is found in the string.
The Unicode escape is processed like this:
```
```
((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); });
```
```
Get the string representing the number part of the escape (skip the first two characters).
```
```
match.Value.Substring(2)
```
```
Parse that string using Int32.Parse() which takes the string and the number format that the Parse() function should expect which in this case is a hex number.
```
```
NumberStyles.HexNumber
```
```
Then we cast the resulting number to a Unicode character:
```
```
(char)
```
```
And finally we call ToString() on the Unicode character which gives us its string representation which is the value passed back to Replace():
```
```
.ToString()
```
```
Note: Instead of grabbing the text to be converted with a Substring call you could use the match parameter's GroupCollection, and a subexpressions in the regular expression to capture just the number ('2320'), but that's more complicated and less readable.


Question:
echo $_POST["name"]; //returns the value a user typed into the "name" field

I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this?

Answer:
```
```
array_keys($_POST)
```
```
Manual


Question:
I'd like all queries like

http://mysite.com/something/otherthing?foo=bar&x=y

to be rewritten as

http://mysite.com/something/otherthing.php?foo=bar&x=y

In other words, just make the .php extension optional, universally.

Answer:
Something like...
```
```
RewriteRule /something/(.+)?(.+) /something/$1.php?$2
```
```
would probably work.


Question:
How do I create subdomain like http://user.mywebsite.example? Do I have to access .htaccess somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?

To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?

Answer:
In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records.  So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration.  If they don't offer some sort of API, this might get tricky.
Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case).  I've never explored this option before but I suspect most of the consumer registrars do not.  I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.


Question:
I can't find this anywhere in the Domino Designer help. It seems so straightforward!

All I need to do is find the position of a character in a string.

Answer:
(edited) Please see the answer from charles ross instead.
https://stackoverflow.com/a/19437044/11293
My less efficient method is below.
If you really need the character position though you could do this:
```
```
REM {
    S  Source string
    F  Character to find
    R  Location of character in string or 0
};

S := "My string";
F := "t";
LEN_S := @Length(S);
R := 0;

@For(I := 1; I < LEN_S; I := I + 1;
    @If(@Middle(S; I; 1) = F;
        @Do(R := I; I := LEN_S);
        @Nothing
    )
);
```
```


Question:
Can an XML attribute be the empty string?

In other words, is

<element att="" />

valid XML?

Answer:
Yes, this is well-formed XML.
An easy way to test this (on Windows) is to save the sample in a
```
test.xml
```
file and open it with Internet Explorer. IE will display an error message if the document is not well-formed.


Question:
When I debug locally in fire fox 2.0x many times my page won't have the styles added properly or the page will not completely render (the end is seemingly cut off). Sometimes it takes multiple refreshes or shift-refreshes to fix this. Is this a common issue or is it just me? Any solutions?

I want to add that this is happening in fire fox 3.x to me as well. I add my javascript to the pages dynamically and this might be part of the issue. This is when I am working locally with Visual Studio.

Update: This does happen in IE but it happens much more often in Fire Fox. The issue seems to be only javascript and CSS files not loading. For example I get jQuery is not defined, $ is not defined etc. I don't think I have local IIS to test this on but from the server it always works perfectly. Fire Bug shows all my css and javascript files to be requested and received.

Answer: One thing to do would be to check the source of the page(s) in question. My guess would be that the local server that VS runs is not giving you the entire source of the page. One way to verify this would be to run exactly the same code in the debug environment, as well as from a "real" server like IIS 6. If the same behavior is seen on loading the page from both servers, as well as insuring that the full page source is being recieved by the browser(s), then it is a bug in Firefox and should be reported. This is especially true if other browsers, ie. IE, Chrome, Safari, Opera, render the page fully.


Question:
Possible Duplicate:

  What is the correct way to create a single instance application?

How to force C# .net app to run only one instance in Windows?

Answer:
I prefer a mutex solution similar to the following.  As this way it re-focuses on the app if it is already loaded
```
```
using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}
```
```


Question:
Suppose there is a fully populated array of data String[n][3] myData.

I want to do this:

for (String[] row : myData)
{
   SQL = "update mytable set col3 = row[2]
   where col1 = row[0] and col2=row[1];"
}

Obviously I've left a lot out, but I want to express the idea as succinctly as possible.

Is there a simple way of doing this in a single DB command?
How about a not so simple way?

EDITS:
Data is not coming from another table (it's a web form submission - Multiple Choice exam)

Seeing as the app is web facing, It's got to be injection proof.  Parameterized Queries are my preferred way of going.

I'm using MS-SQL Server 2005

EDIT:Closing, and re-asking as Multiple DB Updates:

EDIT: Re-opened, as this appears to be a popular question

Answer:
You can make a big string like:
```
```
for (String[] row : myData)
{
   SQL += "update mytable set col3 = row[2]
   where col1 = row[0] and col2=row[1];"
}

sqlDriver.doInsertQuery(SQL); // change this to your way of inserting into the db
```
```
And just commit it all at once. I'm not very good with SQL so that's how i would do it.
The sql engine will just split it by the ';' and do separate inserts on its own. It's ok to add it all in a string though. It's kind the same as if u copy a big string with multiple updates/inserts into the sql prompt


Question:
I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time.

public function registerButtonCallback(function:Function):void
{
  clearButtonCallback();

  button.addEventListener(MouseEvent.CLICK, function, false, 0, true);
}

public function clearButtonCallback():void
{
  if (button.hasEventListener(MouseEvent.CLICK) == true)
  {
    // do something to remove that listener
  }
}

I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback - for example, I might want to be able to click the button twice.

Suggestions?

Answer:
I am presuming that you want only one callback function at any given time.  If that's teh case then why not have a single callback function associated with the click event on the button which itself called a function and have that function be settable...
```
```
<mx:Button click="doCallback()" .../>

public var onClickFunction:Function = null;
private function doCallback():void
{
    if (onClickFunction != null)
    {
        onClickFunction(); // optionally you can pass some parameters in here if you match the signature of your callback
    }
}
```
```
A consumer of your control which houses your button would set the onClickFunction with the appropriate function.  In fact you could set it as often as you liked.
If you wanted to go one step further you could subclass the AS3 Button class and wrap all of this inside it.


Question: One problem I have with open-source is not often the product or documentation, but the level of community involvement and support. Response time for some questions on official forums can take more than a week, which can honestly make a big difference when choosing a platform for commercial services use. However, I find that evaluating the community beforehand is very difficult. How do I know what are the most common issues, and whether or not people are getting support for them? How do I know what problems I personally might encounter based upon my project, which would require some level of community support? Do you have a formula for performing this evaluation?

Answer:
If your question is posed because you don't want to pay for support, then I think your best bet is to ask questions about a specific project on neutral forums like this and see what others have experienced in terms of support and timeliness of resolution to issues.
If you are willing to pay for support, there are companies that provide commercial support for open source projects, like
OpenLogic
as an example that could factor into your formula.


Question:
I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field.

Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it.

Net::HTTP doesn't look like the best idea. curb is looking good.

Answer:
Ok, here's a simple example using curb.
```
```
require 'yaml'
require 'curb'

# prepare post data
post_data = fields_hash.map { |k, v| Curl::PostField.content(k, v.to_s) }
post_data << Curl::PostField.file('file', '/path/to/file'),

# post
c = Curl::Easy.new('http://localhost:3000/foo')
c.multipart_form_post = true
c.http_post(post_data)

# print response
y [c.response_code, c.body_str]
```
```


Question: I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.

Answer:
Here's what I came up with:
```
```
import os

def CreateNewChangeList(description):
    "Create a new changelist and returns the changelist number as a string"
    p4in, p4out = os.popen2("p4 changelist -i")
    p4in.write("change: new\n")
    p4in.write("description: " + description)
    p4in.close()
    changelist = p4out.readline().split()[1]
    return changelist

def OpenFileForEdit(file, changelist = ""):
    "Open a file for edit, if a changelist is passed in then open it in that list"
    cmd = "p4 edit "
    if changelist:
        cmd += " -c " + changelist + " "
    ret = os.popen(cmd + file).readline().strip()
    if not ret.endswith("opened for edit"):
        print "Couldn't open", file, "for edit:"
        print ret
        raise ValueError
```
```


Question:
Using the SharePoint API, how can I modify an extended webapp web.config file?

I have to do some changes in this file to specify the connection string, membershipprovider, etc... for using Forms Authentication.

Currently, I can change the "master" webapplication web.config file, but not the extended one.

Edited

I'm using Sp 2007. I'm already using SPWebConfigModification class to modify the parent webapp. Thoses modifications are propagated to the extended webapp. I have to change ONLY the extended one. But I don't find the way to do it.

What I'm trying to achieve, is to program a little wizard that:

Shows a WebApp list so the user can select one

Extend that selected webapp to a different zone

Configure that extended zone to use Forms Authentication

Thanks

Answer:
Quick answer: look into the SPWebConfigModification class. I am assuming you're using SharePoint 2007. The best way to learn about this is to dig into open source projects:
Google code search:
http://www.google.com/codesearch?q=spwebconfigmodification&hl=en&btnG=Search+Code
This project on CodePlex looks like it's one big SPWebConfigModification:
http://www.codeplex.com/ajaxifymoss/Release/ProjectReleases.aspx?ReleaseId=13360


Question:
We may start converting an old VS2003 MFC project to use the fancy new features provided by the MFC Feature Pack and VS2008. Several of the new UI controls would be very nice except for one thing - they automatically save their information to the registry. I don't have a problem with the registry, but for the multiple environments the users use out program from, it's much easier to save user data to the database.

So, I'm hoping that there is one main "access the registry" function that could be overloaded to point the database. But brief investigation hasn't turned up anything. Has anyone else had any success doing something similar?

Answer:
The MFC feature pack uses code supplied by BCGSoft and they added this feature (so you can save state to an XML file, database, etc.) way back in 2001.  I don't have the feature pack on this PC but try looking for a class called something like
```
CMFCRegistrySP
```
.
I will check myself tomorrow.
Does the
```
StateCollection
```
sample do this?
http://msdn.microsoft.com/en-us/library/bb983406.aspx


Question:
What exactly does the word patch mean when referring to 'submitting a patch'?

I've seen this used a lot, especially in the open source world. What what does it mean and what exactly is involved in submitting a patch?

Answer:
It's a file with a list of differences between the code files that have changed.  It's usually in the format generated by doing a
diff -u
on the two files.  Most version control systems allow the easy creation of patches but it's generally in that same format.
This allows the code change to be easily applied to someone else's copy of the source code using the
patch
command.
For example:
Let's say I have the following code:
```
```
<?php
  $foo = 0;
?>
```
```
and I change it to this:
```
```
<?php
  $bar = 0;
?>
```
```
The patch file might look like this:
```
```
Index: test.php
===================================================================
--- test.php    (revision 40)
+++ test.php    (working copy)
@@ -3,7 +3,7 @@
         <?php
-            $foo = 0;
+            $bar= 0;
         ?>
```
```