Question:
My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying.  We'd also like to make sure it can't be copied and distributed to our customers' customers.

One model we've seen is tying a license to a MAC address so the software will only work on one machine.

What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions?

Answer:
I'd suggest you take the pieces of information you want in the key, and hash it with md5, and then just take the first X characters (where X is a key length you think is manageable).
Cryptographically, it's far from perfect, but this is the sort of area where you want to put in the minimum amount of effort which will stop a casual attacker - anything more quickly becomes a black hole.
Oh, I should also point out, you will want to provide the expiration date (and any other information you might want to read out yourself) in plain text (or slightly obfuscated) as part of the key as well if you go down this path - The md5 is just to stop the end user from changing he expiration date to extend the license.
The easiest thing would be a key file like this...
```
```
# License key for XYZZY
expiry-date=2009-01-01
other-info=blah
key=[md5 has of MAC address, expiry date, other-info]
```
```


Question: Most of the work I do is with what could be considered enterprise Web applications. These projects have large budgets, longer timelines (from 3-12 months), and heavy customizations. Because as developers we have been touting the idea of the Web as the next desktop OS, customers are coming to expect the software running on this "new OS" to react the same as on the desktop. That includes easy to manage automatic upgrades. In other words, "An update is available. Do you want to upgrade?" Is this even a realistic expectation? Can anyone speak from experience on trying to implement this feature?

Answer:
One of the primary reasons to implement an application as a web application is that you get automatic upgrades for free.  Why would users be getting prompted for upgrades on a web app?
For Windows applications, the "update is available, do you want to upgrade?" functionality is provided by Microsoft using ClickOnce, which I have used in an enterprise environment successfully -- there are a few gotchas but for the most part it is a good way to manage automatic deployment and upgrade of Windows apps.
For mobile apps, you can also implement auto-upgrades, although it is a little trickier.
In any case, to answer your question in a broad sense, I don't know if it is expected that all enterprise apps should make upgrading easy, but it certainly is worth the money from an IT support standpoint to architect them to allow for easy upgrading.


Question: Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?

Answer:
I think this pair of articles by Philip J. Eby does a great job discussing the differences between the two languages (mostly about philosophy/mentality rather than specific language features).
Python is Not Java
Java is Not Python, either


Question:
Say I have this given XML file:

<root>
    <node>x</node>
    <node>y</node>
    <node>a</node>
</root>

And I want the following to be displayed:

ayx

Using something similar to:

<xsl:template match="/">
    <xsl:apply-templates select="root/node"/>
</xsl:template>
<xsl:template match="node">
    <xsl:value-of select="."/>
</xsl:template>

Answer:
You can do this, using
```
xsl:sort
```
. It is important to set the
```
data-type="number"
```
because else, the position will be sorted as a string, end therefor, the 10th node would ge considered before the 2nd one.
```
```
<xsl:template match="/">
    <xsl:apply-templates select="root/node">
        <xsl:sort
            select="position()"
            order="descending"
            data-type="number"/>
    </xsl:apply-templates>
</xsl:template>
<xsl:template match="node">
    <xsl:value-of select="."/>
</xsl:template>
```
```


Question:
We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case).  However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.

The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property.  Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name?  In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.

Answer:
It is generally considered a bad idea to version control your binaries and I do not recommend doing so. But if you absolutely have to, you can use antcall combined with param to pass parameters and call a target.
```
```
<antcall target="reusable">
    <param name="some.variable" value="var1"/>
</antcall>

<target name="reusable">
    <!-- Do something with ${some.variable} -->
</target>
```
```
You can find more information about the
antcall task here
.


Question:
I know I've seen this in the past, but I can't seem to find it now.

Basically I want to create a page that I can host on a dasBlog instance that contains the layout from my theme, but the content of the page I control.

Ideally the content is a user control or ASPX that I write.  Anybody know how I can accomplish this?

Answer:
I did something similar setting up a handler to stream video files from the blog on my home server.  I ended up ditching it because it killed my bandwidth whenever someone would view a video, but I did have it up and working for a while.
To get it to work I had to check dasBlog out from source control and open it in visual studio.  I had VS2008 and it was built using VS2005, so it took some work to get everything to build.  Once I could get the unaltered solution to build I added a new class library project to hold my code.  This is to make sure my code stays separate across dasBlog updates.
I don't have access to the code here at work so I can't tell you exact names right now, but if you want your pages to be able to use the themes then they need to inherit from a class in the newtelligence.dasBlog.Web namespace, and I believe also implement an interface.  A good place to look is in FormatPage and FormatControl.


Question: What is the difference between UNION and UNION ALL?

Answer:
The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result set but union all returns all rows after joining.
from
http://zengin.wordpress.com/2007/07/31/union-vs-union-all/


Question:
What is Dynamic Code Analysis?

How is it different from Static Code Analysis (ie, what can it catch that can't be caught in static)?

I've heard of bounds checking and memory analysis - what are these?

What other things are checked using dynamic analysis?

-Adam

Answer:
Basically you instrument your code to analyze your software as it is running (dynamic) rather than just analyzing the software without running (static). Also see this
JavaOne presentation comparing the two
.
Valgrind
is one example dynamic analysis tool for C. You could also use code coverage tools like
Cobertura
or
EMMA
for Java analysis.
From Wikipedia's
definition of dynamic program analysis
:
Dynamic program analysis is the
  analysis of computer software that is
  performed with executing programs
  built from that software on a real or
  virtual processor (analysis performed
  without executing programs is known as
  static code analysis). Dynamic program
  analysis tools may require loading of
  special libraries or even
  recompilation of program code.


Question: Is it necessary to set large objects to null when implementing a Dispose() method?

Answer:
If a class has a Dispose method the best practice is to call it. the reason
behind that is that Dispose runs when called, whereas setting the object to
null simply adds a entry to the Finalize queue in GC, and we cannot
determine when GC will run.
There is no performance benefit in implementing the Dispose method on types that use only managed resources (such as arrays) because they are automatically reclaimed by the garbage collector. Use the Dispose method primarily on managed objects that use native resources and on COM objects that are exposed to the .NET Framework. Managed objects that use native resources (such as the FileStream class) implement the IDisposable interface.
An elegant means of inoking Dispose that have adopted is using the "using" construct. For those of you who may not be familiar with the construct, it provide a means to implicity invoke Dispose() on an instance that implements IDisposable even if an exception is thrown durring the operation. The following is an example of the using construct:
```
```
using(DisposableClass dc = new DisposableClass())
{
   dc.PerformActionOnUmanagedResources();
   dc.PerformAnotherActionOnUmanagedResources();
}
```
```
In the previous example, if an exception was thrown in the PerformActionOnUmanagedResources() method, although the PerformAnotherActionOnUmanagedResources() method would not be processed, the using block will still implicity invoke the Dispose method on dc ensuring the realese of any unmanaged resources.


Question:
Each cell contains some text and a background color. So I have some cells that are blue and some that are red. What function do I use to count the number of red cells?

I have tried =COUNTIF(D3:D9,CELL("color",D3)) with no success (Where D3 is red).

Answer:
Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:
http://www.cpearson.com/excel/colors.aspx
Example form the site:
The SumColor function is a color-based
  analog of both the SUM and SUMIF
  function. It allows you to specify
  separate ranges for the range whose
  color indexes are to be examined and
  the range of cells whose values are to
  be summed. If these two ranges are the
  same, the function sums the cells
  whose color matches the specified
  value. For example, the following
  formula sums the values in B11:B17
  whose fill color is red.
```
=SUMCOLOR(B11:B17,B11:B17,3,FALSE)
```


Question:
When I turn an image (<img>) into a hyperlink (by wrapping it in <a>), Firefox adds a black border around the image.  Safari does not display the same border.

What CSS declaration would be best to eliminate the border?

Answer:
```
```
a img {
    border-width: 0;
}
```
```


Question:
I know that the .NET framework looks for referenced DLLs in several locations

Global assembly cache (GAC)

Any private paths added to the AppDomain

The current directory of the executing assembly

What order are those locations searched? Is the search for a DLL ceased if a match is found or does it continue through all locations (and if so, how are conflicts resolved)?

Also, please confirm or deny those locations and provide any other locations I have failed to mention.

Answer:
No longer is the current directory searched first when loading DLLs! This change was also made in Windows XP SP1. The default behavior now is to look in all the system locations first, then the current directory, and finally any user-defined paths.
(ref.
http://weblogs.asp.net/pwilson/archive/2003/06/24/9214.aspx
)
The default search order, which can be changed by the application, is also described on MSDN:
Dynamic-Link Library Search Order
.


Question:
The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially).

Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line.

For more information on the bug, read it here.

This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0.

Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.

Answer:
For this particular issue, the reason is because javascript generated by
ASP.NET 2.0 has some IE only notation: event.srcElement is not availabe in
FireFox (use event.target instead):
```
```
function WebForm_FireDefaultButton(event, target) {
if (!__defaultFired && event.keyCode == 13 && !(event.srcElement &&
(event.srcElement.tagName.toLowerCase() == "textarea"))) {
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof(defaultButton.click) !=
"undefined") {
__defaultFired = true;
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
return true;
}
```
```
If we change the first 2 lines into:
```
```
function WebForm_FireDefaultButton(event, target) {
var element = event.target || event.srcElement;
if (!__defaultFired && event.keyCode == 13 && !(element &&
(element.tagName.toLowerCase() == "textarea"))) {
```
```
Put the changed code in a file and then do
```
```
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptInclude("js1", "JScript.js");
}
```
```
Then it will work for both IE and FireFox.
Source:
http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html


Question:
Pretty much what the title says really.

We have some code that is .NET 1.1 based and no real desire to up-convert it.  However, we are looking to add developers to the team and they will need copies of Visual Studio.

My understanding is that they will need VS 2003 - as this is the only IDE that supports .NET 1.1 but I am wondering if we are still able to purchase it!

Answer:
You can build 1.1 projects in Visual Studio 2005:
http://www.hanselman.com/blog/BuildingNET11ProjectsUsingVisualStudio2005.aspx
The MSBuild Everett Environment (MSBEE) has been announced, and soon this will be a (reasonably) supported scenario and we'll all be able to build both 1.1 and 2.0 versions of .NET code on Visual Studio 2005.
Also read this post about this issue:
http://blogs.msdn.com/clichten/archive/2005/11/08/490541.aspx
And also:
MSBuild Extras
– Toolkit for .NET 1.1 “MSBee” is an addition to MSBuild that allows developers to build managed applications using Visual Studio 2005 projects that target .NET 1.1.


Question:
This is pretty simple, I come from a swing/awt background.

I'm just wondering what the proper way to set the background color for a SWT widget is?

I've been trying:

widget.setBackground( );

Except I have no idea how to create the color Object in SWT?

Answer:
To create a color, try this:
```
```
Device device = Display.getCurrent ();
Color red = new Color (device, 255, 0, 0);
```
```


Question:
exact code will be helpful. I assume the DirectoryServices namespace does it but I can't find the method that does it.

I need actual C# code. All the samples I found so far are VB or VBScript. The C# examples I found are for reading/setting ADSI properties. A command like backup seems to have a certain .NET syntax which I am not clear how to use. In VB there's a straightforward backup command. Need an equivalent in .NET.

Answer:
You'll need to use ADSI objects. The
IIsComputer.Backup
method is what you want.
As far as how to access ADSI objects from C#, check out this
MSDN page
.
EDIT:
Here's a
sample implementation in C#
.


Question:
What options exist for accessing different databases from C++?
Put differently, what alternatives are there to ADO?
What are the pros and cons?

Answer:
Microsoft ODBC
.
The MFC ODBC classes such as
CDatabase
.
OleDB
(via COM).
And you can always go through the per-RDBMS native libraries (for example, the
SQL Server native library
)
DAO
(don't).
3rd party ORM providers.
I would recommend going through ODBC or OleDB by default. Native libraries really restrict you, DAO is no fun, there aren't a lot of great 3rd-party ORM for C++/Windows.


Question:
How would you describe and promote WCF as a technology to a non-technical client/manager/CEO/etc?

What are competing solutions or ideas that they might bring up(such as those they read about in their magazines touting new technology)?

What is WCF not good for that you've seen people try to shoehorn it into?

-Adam

Answer:
In a single sentence, I'd say that WCF is "software that lets you set up and manage communication between systems a lot more efficiently than in the past".
I can see them bringing up BizTalk as a competitor, but of course you could say that WCF works with it and is in fact used as base technology for it in the more recent versions.
I'm not sure if I can think of any inappropriate shoe-horning of WCF that I have seen, although there are plenty of legacy apps that will probably be "upgraded" to WCF that don't really need to be for any real business reason.


Question: I know that it does in PHP, and I'm pretty sure it does in Java. I haven't used the latest versions of .NET, so I won't speak for them. It seems very awkward, but I was wondering if there was an underlying reason for this.

Answer:
One reason is compatibility - anyone who has done 'check for existence' knows to exclude directories; changing that behaviour may confuse those who rely on that behaviour.
Secondly, the underlying code often does a check on the operating system for existence in a catlog of filesystem entries - to the OS, a directory is the same as a file. In other words, it's looking for an entry of 'xyz' in the catalog not a file with name 'xyz' in the catalog.
Backwards compatability is the main reason, I suspect.


Question: I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this?

Answer:
to learn what libraries a binary uses, use ldd
```
```
ldd path/to/the/tool
```
```
You'd have to write a little shell script to get to your system-wide breakdown.


Question: What kind of multi-threading issues do you have to be careful for in asp.net?

Answer:
Programmatic Caching is one area which immediately comes to my mind. It is a great feature which needs to be used carefully. Since it is shared across requests, you have to put locks around it before updating it.
Another place I would check is any code accessing filesystem like writing to log files. If one request has a read-write lock on a file, other concurrent requests will error out if not handled properly.


Question:
We're using Mercurial where I work and I want to have a setup similar to how I used SVN:

Trunk

Tags

Production

Branches

Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'.

Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial?

Answer:
Something like
```
hg transplant
```
? That's what we use on our dev and prod branches.


Question: Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect.  In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control.

Answer:
I recently discovered that you can use SetWindowPos to accomplish this.  Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this:
```
```
SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
```
```
This changes the z-order of controls which, in turn, establishes the tab order.


Question:
This is the text from MSDN comment: "According to the book ATL Internals (2ed) the use of attributes is deprecated and should not be used in new ATL projects."

But WHY?!!

Answer:
In ATL these attributes were a compiler trick. They were not a core part of the platform like attributes in C#. They were also more confusing to debug than macros's and the method of dumping generated attribute code was a hassle.
I suspect another issue is likely to have been C++ compiler compatibility and standards-adherence. Attributes didn't make for more beautiful C++ code, and perhaps this syntax may be used in a future version of a real C++ standard.


Question: It's really quite annoying as they are not part of the project.

Answer:
The Visual Studio Web Deployment addin lets you exclude folders and more.
VS2005
VS2008
Also a decent writeup on the
Web Deployment addin


Question:
I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:

Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))

The ItemDrag handler (where the exception takes place), looks like:

private void treeView_ItemDrag(object sender,
        System.Windows.Forms.ItemDragEventArgs e)
{

        this.DoDragDrop(e.Item, DragDropEffects.Move);
}

Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2)

Answer:
```
FORMATETC
```
is a type of application clipboard, for lack of a better term.  In order to pull off some of the visual tricks of draging around the tree node, it has to be copied into this clipboard with its source description.  The source control loads its info into the
```
FORMATETC
```
clipboard and sends it to the target object.  It looks like the error occurs on the drop and not on the drag. The
```
DV
```
in
```
DV_E_FORMATETC
```
typically indicates the error occurrs on the drop step.
The destination doesn't look like it likes what you are droping on it. The clipboard may be corrupt or the drop destination may not be configured to understand it.
I recommend you try one of two things.
Remove the original tree structure and destination. Dump your dlls.  Close everything.  Open up and put the treeview and destination back on the form.  It may have just been poorly formed and not fully populating the
```
FORMATETC
```
structure.
Try putting another treeview and droping to that.  If you are droping to another tree and it works you know your oranges to oranges work and it isn't the treeview.  It may be the destination if it is a grid or listview.  You may need to change those structures to be able to receive the drop.
Not that it helps but the structure is something like this:
```
```
typedef struct tagFORMATETC
{
  CLIPFORMAT      cfFormat;
  DVTARGETDEVICE  *ptd;
  DWORD           dwAspect;
  LONG            lindex;
  DWORD           tymed;
} FORMATETC, *LPFORMATETC;
```
```


Question: One of my co-workers claims that even though the execution path is cached, there is no way parameterized SQL generated from an ORM is as quick as a stored procedure. Any help with this stubborn developer?

Answer:
I would start by reading this article:
http://decipherinfosys.wordpress.com/2007/03/27/using-stored-procedures-vs-dynamic-sql-generated-by-orm/
Here is a speed test between the two:
http://www.blackwasp.co.uk/SpeedTestSqlSproc.aspx


Question:
I'm using WScript to automate some tasks, by using WScript.Shell to call external programs.

However, right now it does not wait for the external program to finish, and instead moves on. This causes issues because I have some tasks dependent on others finishing first.

I am using code like:

ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir

Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.run ZipCommand

Is there a way to do this so it blocks until the shell executed program returns?

Answer:
If you use the "Exec" method, it returns a reference, so you can poll the "Status" property to determine when it is complete.  Here is a sample from
msdn
:
```
```
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec(ZipCommand)

Do While oExec.Status = 0
    WScript.Sleep 100
Loop
```
```


Question: I'm currently working on putting together a fairly simple ORM tool to serve as a framework for various web projects for a client.  Most of the projects are internal and will not require massive amounts of concurrency and all will go against SQL Server.  I've suggested that they go with ORM tools like SubSonic, NHibernate, and a number of other open source projects out there, but for maintainability and flexibility reasons they want to create something custom.  So my question is this: What are some features that I should make sure to include in this ORM tool?  BTW, I'll be using MyGeneration to do the code generation templates.

Answer:
You need to go the nHibernate style, in my experience, and have it so that you have some kind of map, between your objects and the database. This allows your objects to have some things that are hard to represent in a database but are easier represented in POCOs.
Generation gets you started, by giving you classes that meet your schema, but if you plan on maintaining anything or testing anything, mapping is pain now for pleasure later.
Subsonic is a great model, and its open source, if you must go generation, use their templates in myGeneration to get a leg up.
BTW: I've done what you are doing, and I ended up with something very similar to subsonic, and now advise my clients to take the subsonic source, and fork it for themselves.


Question:
I know this isn't strictly speaking a programming question but something I always hear from pseudo-techies is that having a lot of entries in your registry slows down your Windows-based PC. I think this notion comes from people who are trying to troubleshoot their PC and why it's running so slow and they open up the registry at some point and see leftover entries from programs they uninstalled ages ago.

But is there any truth to this idea? I would not think so since the registry is essentially just a database and drilling down to an entry wouldn't take significantly longer on a larger registry. But does it?

EDIT: To be clear, I'm not looking for advice on how to make a PC run faster, or asking why my PC in particular is slow (it's not), I'm just curious if people who say "bigger registry means slower PC" are accurate or not.

Answer:
In short, not really.
In the old days when machines were slower the answer was yes; but having a modern processor rip through even a 60MB registry is not a problem.
Typically, the real reason a modern machine starts running slow is due to everything from malware to virus scanners: Mcafee, Norton's, etc are prime targets in my mind.
Also, the WinSXS folder tends to grow as service packs and applications are installed.  This seems to have a negative impact on system performance.  There are only two possible solutions in this scenario.  First, if possible, reinstall the OS with the latest service pack already slipstreamed into the install.  Second, if that isn't possible AND you are running Vista with SP1, you can run the vsp1cln.exe tool (see
technet
) which will clean up a lot of the older versions of components.  Note that this tool can only be executed once and it does not allow you to roll back.


Question:
As far as I can tell, this is isn't possible, so I'm really just hoping for a left field undocumented allocation hook function.

I want a way to track allocations like in _CrtSetAllocHook, but for C#/.NET.

The only visibility to the garbage collector/allocation appears to be GC.CollectionCount.

Anyone have any other .NET memory mojo?

Answer:
The CLR has a 'profiling API' that hooks into pretty much everything - it is what the commercial .NET memory profiling products use, I believe. Here is an MSDN link to the top level of the documentation:
.NET Framework General Reference: About the Profiling API
See this MSDN magazine article for an introduction to the memory piece:
Inspect and Optimize Your Program's Memory Usage with the .NET Profiler API


Question:
Does anyone have a good solution for integrating some C# code into a java application?

The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc.

Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stuff in there, so I would rather keep it tightly integrated if possible.

Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant.

Answer: If it's short, I think you're better off re-writing the code in java.  Downloading one 50Mb runtime is bad enough.


Question: When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows)

Answer:
From
Joe Grossberg
's blog (no longer available):
But if you're using GNU Emacs 21.2
  (the latest version, which includes
  this as part of the standard distro),
  you can just put the following lines
  into your .emacs file
```
```
;; recentf stuff
(require 'recentf)
(recentf-mode 1)
(setq recentf-max-menu-items 25)
(global-set-key "\C-x\ \C-r" 'recentf-open-files)
```
```
Then, when you launch emacs, hit
CTRL
-
X
CTRL
-
R
. It will show a list of
  the recently-opened files in a buffer.
  Move the cursor to a line and press
ENTER
. That will open the file in
  question, and move it to the top of
  your recent-file list.
(Note: Emacs records file names.
  Therefore, if you move or rename a
  file outside of Emacs, it won't
  automatically update the list. You'll
  have to open the renamed file with the
  normal
CTRL
-
X
CTRL
-
F
method.)
Jayakrishnan Varnam has a
page
  including screenshots
of how this
  package works.
Note:
You don't need the
```
(require 'recentf)
```
line.


Question: Does anyone know if silverlight plugs into chrome, or when they plan to support it?

Answer:
This guy have had partial success with silverlight in chrome, but it does not seem to be supported:
http://wildermuth.com/2008/09/02/Silverlight_2_and_Google_Chrome
From The Microsoft Silverlight Team in the
silverlight forum
:
Hello, currently we don't have plans
  to support Chrome. We will support it
  in the future if it gains enough
  market share. Please understand, each
  browser implements the plug-in model
  differently, so it'll be a lot of
  effort to officially support a browser
  100%... By the way, IE 8 also runs
  each tab in its own process. If a tab
  crashes, other tabs will still work
  fine.
UPDATE:
Jon Galloway has just posted instructions on how to get silverlight successfully running on Chrome here:
http://weblogs.asp.net/jgalloway/archive/2008/09/17/silverlight-on-chrome.aspx


Question:
This has been driving me crazy for a few days.  Why doesn't the following work?

    Dim arr(3, 3) As Integer

    For y As Integer = 0 To arr.GetLength(0) - 1
        For x As Integer = 0 To arr.GetLength(y) - 1
            arr(y, x) = y + x
        Next
    Next

Also, what if the array looked like this instead?

{ {1, 2, 3},
  {4, 5, 6, 7, 8, 9, 9, 9},
  {5, 4, 3, 2}
}

Answer:
```
arr.GetLength(y)
```
should be
```
arr.GetLength(1)
```


Question:
Is there a good way to adjust the size of a UITextView to conform to its content? Say for instance I have a UITextView that contains one line of text:

"Hello world"

I then add another line of text:

"Goodbye world"

Is there a good way in Cocoa Touch to get the rect that will hold all of the lines in the text view so that I can adjust the parent view accordingly?

As another example, look at the notes' field for events in the Calendar application - note how the cell (and the UITextView it contains) expands to hold all lines of text in the notes' string.

Answer:
Did you try
```
[textView sizeThatFits:textView.bounds]
```
?
Edit: sizeThatFits returns the size but does not actually resize the component. I'm not sure if that's what you want, or if
```
[textView sizeToFit]
```
is more what you were looking for. In either case, I do not know if it will perfectly fit the content like you want, but it's the first thing to try.


Question:
I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

For example, let's say I have three files. Using execfile:

script_1.py calls script_2.py.

In turn, script_2.py calls script_3.py.

How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py?

(Executing os.getcwd() returns the original starting script's filepath not the current file's.)

Answer:
It's not entirely clear what you mean by "the filepath of the file that is currently running within the process".
```
sys.argv[0]
```
usually contains the location of the script that was invoked by the Python interpreter.
Check the
sys documentation
for more details.
As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to
the file from which the module was
  loaded, if it was loaded from a file


Question:
I'm working on moving a client/server application created with C# and WinForms into the SOA/WPF/Silverlight world. One of the big hurdles is the design of the UI. My current UI is MDI driven and users rely heavily on child windows, having many open at the same time and toggling back and forth between them.

What might be the best way to recreate the UI functionality in an MDI-less environment? (I've no desire to create MDI functionality on my own in WPF). Tabs? A list panel that toggles different controls?

Answer:
I think the answer is really going to be up to your users -- I'd set up some prototypes with multiple paradigms and let them provide some input.  The last thing you want to do is introduce a new UI paradigm without having any end-user input.
Tabs are really popular now, but don't allow side-by-side viewing, so if that is a requirement you may want to go with more of an outlook-style setup, with multiple panels that can be activated, hidden and resized.
One thing that you might want to do is to code your app as a composite UI, where each view is built independently from its container (be it a child window, tab or accordion, etc.), and is just "dropped in" in the designer.  That will protect you from when the users change their minds about the navigation paradigm in the future.


Question:
How do I format a number in Java?

What are the "Best Practices"?

Will I need to round a number before I format it?

32.302342342342343 => 32.30

.7323 => 0.73

etc.

Answer:
From
this thread
, there are different ways to do this:
```
```
double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12
```
```
```
```
f = (float) (Math.round(n*100.0f)/100.0f);
```
```
```
```
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24
```
```
The
DecimalFormat()
seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.


Question:
One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover

does anyone have any ideas or have created such a thing before

we have a couple ideas but they involve to much database usage

We prefer that it be FREE!!!

Answer:
From
this thread
, there are different ways to do this:
```
```
double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12
```
```
```
```
f = (float) (Math.round(n*100.0f)/100.0f);
```
```
```
```
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24
```
```
The
DecimalFormat()
seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.


Question:
I have a two dimensional array that I need to load data into.  I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable).

I have it declared as follows:

float[,] _calibrationSet;
    ....
int calibrationRow = 0;
While (recordsToRead)
{
  for (int i = 0; i < SensorCount; i++)
   {
     _calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat();
   }
   calibrationRow++;
}

This causes a NullReferenceException, so when I try to initialize it like this:

_calibrationSet = new float[,];

I get an "Array creation must have array size or array initializer."

Thank you,
Keith

Answer:
You can't use an array.
Or rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...)
Generally, you would go with one of the collection classes - ArrayList, List<>, LinkedList<>, etc. - which one depends a lot on what you're looking for; List will give you the closest thing to what i described initially, while LinkedList<> will avoid the problem of frequent re-allocations (at the cost of slower access and greater memory usage).
Example:
```
```
List<float[]> _calibrationSet = new List<float[]>();

// ...

while (recordsToRead)
{
    float[] record = new float[SensorCount];
    for (int i = 0; i < SensorCount; i++)
    {
        record[i] = calibrationArrayView.ReadFloat();
    }
    _calibrationSet.Add(record);
}

// access later: _calibrationSet[record][sensor]
```
```
Oh, and it's worth noting (as
Grauenwolf
did), that what i'm doing here doesn't give you the same memory structure as a single, multi-dimensional array would - under the hood, it's an array of references to other arrays that actually hold the data. This speeds up building the array a good deal by making reallocation cheaper, but can have an impact on access speed (and, of course, memory usage). Whether this is an issue for you depends a lot on what you'll be doing with the data after it's loaded... and whether there are two hundred records or two million records.


Question: Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?

Answer:
You can only tell whether the current thread holds a normal lock (
```
Thread.holdsLock(Object)
```
). You can't get a reference to the thread that has the lock without native code.
However, if you're doing anything complicated with threading, you probably want to familiarize yourself with the java.util.concurrent packages. The
```
ReentrantLock
```
does allow you to get its owner (but its a protected method, so you'd have to extend this). Depending on your application, it may well be that by using the concurrency packages, you'll find that you don't need to get the lock's owner after all.
There are non-programmatic methods to find the lock owners, such as signaling the JVM to issue a thread dump to stderr, that are useful to determine the cause of deadlocks.


Question: I'm looking at sessions in Django, and by default they are stored in the database.  What are the benefits of filesystem and cache sessions and when should I use them?

Answer:
The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.
The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.
If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.


Question:
I'm looking at developing a device which will need to support Ethernet over USB (hosted in Linux, XP, and Vista). As I understand it, Vista and Linux support the industry standard USB CDC. However, in classic Windows style, XP only supports it's own Remote NDIS. So, now I'm thinking of just bowing down and doing it over RNDIS, as opposed to rolling my own CDC driver for XP.

I've been reading some older documentation that says even XP is pretty buggy with NDIS (suprise!). Does anyone have experience with XP's RNDIS drivers? Are they safe for product development? Any insight would be much appreciated.

Answer:
The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.
The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.
If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.


Question:
I'm having a strange problem.

I have to use GetPostBackEventRefence to force a Postback, but it works the first time, after the first postback, the .NET function is not rendered... any ideas?

This is what I'm missing after the postback:

<script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
    var theform;
    if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
        theform = document.Main;
    }
    else {
        theform = document.forms["Main"];
    }
    theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
    theform.__EVENTARGUMENT.value = eventArgument;
    theform.submit();
}
// -->
</script>

Answer:
The first thing I would look at is whether you have any asp controls (such as linkbutton, comboboxes,that don't normally generate a submit but requre a postback) being displayed on the page.
The __doPostback function will only be put into the page if ASP thinks that one of your controls requires it.
If you aren't using one of those you can use:
```
```
Page.ClientScript.GetPostBackClientHyperlink(controlName, "")
```
```
to add the function to your page


Question:
Suppose I have the following C code.

unsigned int u = 1234;
int i = -5678;

unsigned int result = u + i;

What implicit conversions are going on here, and is this code safe for all values of u and i? (Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.)

Answer:
Short Answer
Your
```
i
```
will be
converted
to an unsigned integer by adding
```
UINT_MAX + 1
```
, then the addition will be carried out with the unsigned values, resulting in a large
```
result
```
(depending on the values of
```
u
```
and
```
i
```
).
Long Answer
According to the C99 Standard:
6.3.1.8 Usual arithmetic conversions
If both operands have the same type, then no further conversion is needed.
Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
In your case, we have one unsigned int (
```
u
```
) and signed int (
```
i
```
). Referring to (3) above, since both operands have the same rank, your
```
i
```
will need to be
converted
to an unsigned integer.
6.3.1.3 Signed and unsigned integers
When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
Now we need to refer to (2) above. Your
```
i
```
will be converted to an unsigned value by adding
```
UINT_MAX + 1
```
. So the result will depend on how
```
UINT_MAX
```
is defined on your implementation. It will be large, but it will not overflow, because:
6.2.5 (9)
A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
Bonus: Arithmetic Conversion Semi-WTF
```
```
#include <stdio.h>

int main(void)
{
  unsigned int plus_one = 1;
  int minus_one = -1;

  if(plus_one < minus_one)
    printf("1 < -1");
  else
    printf("boring");

  return 0;
}
```
```
You can use this link to try this online:
https://repl.it/repls/QuickWhimsicalBytes
Bonus: Arithmetic Conversion Side Effect
Arithmetic conversion rules can be used to get the value of
```
UINT_MAX
```
by initializing an unsigned value to
```
-1
```
, ie:
```
```
unsigned int umax = -1; // umax set to UINT_MAX
```
```
This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information:
Is it safe to use -1 to set all bits to true?


Question:
If I have 2 query sources how do I find ones that are in one that are not in the other?

example of join to find items in both:

var results = from item1 in qs1.Items
   join item2 in qs2 on item1.field1 equals item2.field2
   select item1;

So what would the linq code be to return the items in qs1 that are not in qs2?

Answer:
From
Marco Russo
```
```
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 );
```
```


Question:
I was browsing this thread, which has good recommendation but a bit too general for me.

So, if anyone has a collection of nice game programming feeds,please share them. :)

(both general and specific topics are welcome)

Answer:
If you are catpuring logging information for future searching and anaylsis perhaps a database would be a better answer.
As for your solution.  Flat files do not scale well at all where as a database scale much better.  I wouldn't split the files either, that just compounds the scalability issue.  If you have to use a flat file I would probably try keeping the meta data in a csv (less over head) and the data in a series of files indexed by the csv file.  That way all the data doesn't impact your index file.  Just my thoughts.


Question:
How does unix handle full path name with space and arguments ?

In windows we quote the path and add the command-line arguments after, how is it in unix?

 "c:\foo folder with space\foo.exe" -help

update:

I meant how do I recognize a path from the command line arguments.

Answer:
You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.
```
```
/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"
```
```
All refer to the same executable under Mac OS X.
I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.


Question: My drupal site (internal) will not display the TinyMCE editor when using Google Chrome browser. Has anyone gotten TinyMCE to work with Chrome in Drupal 5?

Answer:
There are a number of known incompatibilities between TinyMCE and WebKit (the rendering engine used by Chrome).  If you're using TinyMCE 2.x, you might want to try the
Safari plug-in to TinyMCE
; Safari also uses WebKit.  I gather also that
TinyMCE 3.x has better support for Safari/WebKit
than TinyMCE 2.x, so you might want to try upgrading to the latest 3.x version.
HTH
Alastair


Question:
How would you find the fractional part of a floating point number in PHP?

For example, if I have the value 1.25, I want to return 0.25.

Answer:
```
```
$x = $x - floor($x)
```
```


Question:
Do any editors honer C #line directives with regards to goto line features?

Context:
I'm working on a code generator and need to jump to a line of the output but the line is specified relative to the the #line directives I'm adding.
I can drop them but then finding the input line is even a worse pain

Answer:
```
#line
```
directives are normally inserted by the precompiler, not into source code, so editors won't usually honor that if the file extension is
```
.c
```
.
However, the normal file extension for post-compiled files is
```
.i
```
or
```
.gch
```
, so you might try using that and see what happens.


Question:
Any ideas what the average user's download speed is? I'm working on a site that streams video and am trying to figure out what an average download speed as to determine quality.

I know i might be comparing apples with oranges but I'm just looking for something to get a basis for where to start.

Answer:
You could try looking at the lower tier offerings from AT&T and Comcast.  Probably 1.5 Mbps for the basic level (which I imagine most people get).
The "test your bandwidth" sites may have some stats on this, too.


Question: I have a scenario wherein, for example, I need to repeat a list of US states and display a table of cities and city populations after the name of each state. The design requirement dictates that every outer repetition must be the name of a state followed by a table of cities, and that requirement cannot be changed at this time. Are there disadvantages to nesting a GridView within a Repeater and then binding each repeated GridView during the Repeater's ItemDataBound event? What are some alternative solutions?

Answer:
If it were me, I'd reverse the question and ask why
I should
use a GridView,  If you need a bunch of built-in features like paging and sorting, then the GridView might be a good fit.  If you just want tabular data, I'd reconsider.  Why?  Because with GridView you're getting a whole bunch of stuff you won't use, your ViewState will be potentially huge, and your page performance will be slower.
I'm not a bigot when it comes to GridView, but I only use them when there is a damn good reason.


Question:
So I have about 10 short css files that I use with mvc app.
There are like
error.css
login.css
etc...
Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this

if(Debug.Mode){

<link rel="stylesheet" type="text/css" href="error.css" />
<link rel="stylesheet" type="text/css" href="login.css" />
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="page.css" />
} else {
<link rel="stylesheet" type="text/css" href="site.css" />
}

I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits.

Answer:
I should had used google.
```
```
#if DEBUG
    Console.WriteLine("Debug mode.")
#else
    Console.WriteLine("Release mode.")
#endif
```
```
Make sure that the option "Configuration settings" -> "Build" "Define DEBUG
constant" in the project properties is checked.


Question:
I'm using Helicon's ISAPI Rewrite 3, which basically enables .htaccess in IIS.  I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com.  I used the following rule from the examples but it affects subdomains:

RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]

This works for most part, but is also redirect sub.example.com to www.sub.example.com.  How can I rewrite the above rule so that subdomains do not get redirected?

Answer:
Can't you adjust the RewriteCond to only operate on example.com?
```
```
RewriteCond %{HTTP:Host} ^example\.com(.*) [NC]
```
```


Question:
One of the things I miss the most in ActionScript is the lack of operator overloading, in particular ==. I kind of work around this issue by adding a "Compare" method to my classes, but that doesn't help in many cases, like when you want to use things like the built in Dictionary.

Is there a good way to work around this problem?

Answer:
Nope.
But it doesn't hurt to add
```
equals
```
methods to your own classes. I try to never use
```
==
```
when comparing objects (the same goes for
```
===
```
, which is the same thing for objects) since it only checks
identity
.
Sadly all the collections in Flash and Flex assume that identity is the only measure of equality that is needed.
There are hints in Flex that someone wanted to alleviate this problem at one time, but it seems like it was abandoned: there is an interface called
IUID
, and it is mentioned in the
Flex Developer's Guide
, but it is not used anywhere. Not even the collections in Flex use it to determine equality. And since you are asking for a solution for Flash, it may not have helped you anyway.
I've written some more about this (in the context of Flex) on my blog:
Is there no equality?
.


Question:
I have some HTML that is generated via a Rich Text Editor outside of my Flex application but would like to display it inside Flex.

The HTML is simple HTML tags, things like styles, anchors, and possibly image tags, is there a control that would let me render this HTML in flex or am I going to have to roll up my sleeves and roll my own?

Any ideas appreciated...Thanks.

Answer:
If the HTML is
really
simple, you can display it in a normal label or textarea component, If it is more complex, I'll quote what I answered
in this question
. The discussion there also has a little more info.
If it is complex HTML and Javascript, one possible way is
HTMLComponent
, a method that uses an iframe over your flash to make it appear like the HTML is in your app. There are a few downsides to this method however - most of them described in detail
at Deitte.com
.
If this can move offline, you could use Air (it has an mx:HTML component built in).
Deitte.com
has a detail of this technique as well.


Question:
What does it mean when a PostgreSQL process is "idle in transaction"?

On a server that I'm looking at, the output of "ps ax | grep postgres" I see 9 PostgreSQL processes that look like the following:

postgres: user db 127.0.0.1(55658) idle in transaction

Does this mean that some of the processes are hung, waiting for a transaction to be committed?  Any pointers to relevant documentation are appreciated.

Answer:
The
PostgreSQL manual
indicates that this means the transaction is open (inside BEGIN) and idle.  It's most likely a user connected using the monitor who is thinking or typing.  I have plenty of those on my system, too.
If you're using Slony for replication, however, the
Slony-I FAQ
suggests
```
idle in transaction
```
may mean that the network connection was terminated abruptly.  Check out the discussion in that FAQ for more details.


Question:
Ruby has two different exceptions mechanisms: Throw/Catch and Raise/Rescue.

Why do we have two?

When should you use one and not the other?

Answer:
I think
http://hasno.info/ruby-gotchas-and-caveats
has a decent explanation of the difference:
catch/throw are not the same as raise/rescue. catch/throw allows you to quickly exit blocks back to a point where a catch is defined for a specific symbol, raise rescue is the real exception handling stuff involving the Exception object.


Question:
I am looking for a way to delete all files older than 7 days in a batch file.  I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task.

Similar things can be done in BASH in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either.

Answer:
Enjoy:
```
```
forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"
```
```
See
```
forfiles
```
documentation
for more details.
For more goodies, refer to
An A-Z Index of the Windows XP command line
.
If you don't have
```
forfiles
```
installed on your machine, copy it from any
Windows Server 2003
to your Windows XP machine at
```
%WinDir%\system32\
```
. This is possible since the EXE is fully compatible between Windows Server 2003 and Windows XP.
Later versions of Windows and Windows Server have it installed by default.
For Windows 7 and newer (including Windows 10):
The syntax has changed a little. Therefore the updated command is:
```
```
forfiles /p "C:\what\ever" /s /m *.* /D -<number of days> /C "cmd /c del @path"
```
```


Question: See here http://www.hanselman.com/blog/InSearchOfThePerfectMonospacedProgrammersFontInconsolata.aspx - for want of a better description - the statement block highlighting - eg in the pics on the link the "statement blocks" are grouped with a vertical line. I understand this is a feature of CodeRush - does R# have either anything similar, or a plugin to do the same?

Answer:
R# has a feature called Highlight current line, which you have to enable in the ReSharper options.  This looks like crap on dark background, high contrast themes, so if you use one I'd suggest going into the Visual Studio options, under Fonts & Colors and going to "ReSharper - current Line" and making the background color a darker shade that doesn't have as much contrast with the background.
R# also has matching brace highlighting, which is color-configurable as well under the same VS option dialog.
Does that answer you question?


Question:
Consider the Oracle emp table. I'd like to get the employees with the top salary with department = 20 and job = clerk. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with:

select * from scott.emp
where deptno = 20 and job = 'CLERK'
and sal =  (select max(sal) from scott.emp
            where deptno = 20 and job = 'CLERK')

This works, but I have to duplicate the test deptno = 20 and job = 'CLERK', which I would like to avoid. Is there a more elegant way to write this, maybe using a group by? BTW, if this matters, I am using Oracle.

Answer:
The following is slightly over-engineered, but is a good SQL pattern for "top x" queries.
```
```
SELECT
 *
FROM
 scott.emp
WHERE
 (deptno,job,sal) IN
 (SELECT
   deptno,
   job,
   max(sal)
  FROM
   scott.emp
  WHERE
   deptno = 20
   and job = 'CLERK'
  GROUP BY
   deptno,
   job
  )
```
```
Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question
SQL Query to get latest price


Question:
Jeff covered this a while back on his blog in terms of 32 bit Vista.

Does the same 32 bit 4 GB memory cap that applies in 32 bit Vista apply to 32 bit Ubuntu? Are there any 32 bit operating systems that have creatively solved this problem?

Answer:
In theory, all 32-bit OSes have that problem. You have 32 bits to do addressing.
```
```
2^32 bits / 2^10 (bits per kb) / 2^10 (kb per mb) / 2^10 (mb per gb) = 2^2 = 4gb.
```
```
Although there are some ways around it. (Look up the jump from 16-bit computing to 32-bit computing. They hit the same problem.)


Question:
I have two spreadsheets... when one gets modified in a certain way I want to have a macro run that modifies the second in an appropriate manner.  I've already isolated the event I need to act on (the modification of any cell in a particular column), I just can't seem to find any concrete information on accessing and modifying another spreadsheet (this spreadsheet is located on a different LAN share also... the user has access to both, though).

Any help would be great.  References on how to do this or something similar are just as good as concrete code samples.

Answer:
In Excel, you would likely just write code to open the other worksheet, modify it and then save the data.
See
this tutorial
for more info.
I'll have to edit my VBA later, so pretend this is pseudocode, but it should look something like:
```
```
Dim xl: Set xl = CreateObject("Excel.Application")
xl.Open "\\the\share\file.xls"

Dim ws: Set ws = xl.Worksheets(1)
ws.Cells(0,1).Value = "New Value"
ws.Save

xl.Quit constSilent
```
```


Question: It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.)  So how do you tell if it has no records without just wrapping it in a try/catch?

Answer:
```
```
if(dr.Read())
{
   //do stuff
}
else
{
 //it's empty
}
```
```
usually you'll do this though:
```
```
while(dr.Read())
{
}
```
```


Question:
I'm trying to create an SSIS package that takes data from an XML data source and for each row inserts another row with some preset values.  Any ideas?  I'm thinking I could use a DataReader source to generate the preset values by doing the following:

SELECT 'foo' as 'attribute1', 'bar' as 'attribute2'

The question is, how would I insert one row of this type for every row in the XML data source?

Answer:
I've never tried it, but it looks like you might be able to use a
Derived Column transformation
to do it: set the expression for attribute1 to
```
"foo"
```
and the expression for attribute2 to
```
"bar"
```
.
You'd then transform the original data source, then only use the derived columns in your destination.  If you still need the original source, you can Multicast it to create a duplicate.
At least I think this will work, based on the documentation.  YMMV.


Question:
Say I have a list as follows:

item1

item2

item3

Is there a CSS selector that will allow me to directly select the last item of a list? In this case item 3.

Cheers!

Answer:
Not that i'm aware of.  The traditional solution is to tag the first & last items with class="first" & class="last" so you can identify them.
The CSS psudo-class
first-child
will get you the first item but not all browsers support it. CSS3 will have
last-child too
(this is currently supported by Firefox, Safari but not IE 6/7/beta 8)


Question:
I have a list of objects I wish to sort based on a field attr of type string. I tried using -

list.sort(function (a, b) {
    return a.attr - b.attr
})

but found that - doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string?

Answer:
Use
```
String.prototype.localeCompare
```
a per your example:
```
```
list.sort(function (a, b) {
    return ('' + a.attr).localeCompare(b.attr);
})
```
```
We force a.attr to be a string to avoid exceptions.
```
localeCompare
```
has been supported
since Internet Explorer 6
and Firefox 1. You may also see the following code used that doesn't respect a locale:
```
```
if (item1.attr < item2.attr)
  return -1;
if ( item1.attr > item2.attr)
  return 1;
return 0;
```
```


Question: I'm tearing my hair out with this one. If I start a block comment /* in VS.NET 2005+ then carriage return, Visual Studio insists that I have another asterisk *. I know there's an option to turn this off but I just can't find it. Anyone know how to turn this feature off?

Answer:
Update: this setting was changed in VS 2015 update 2. See
this answer
.
This post
addresses your question. The gist of it is:
```
```
Text Editor > C# > Advanced > Generate XML documentation comments for ///
```
```


Question: When a template is added using the add-template stsadm command, it becomes available to everyone when creating a subsite. Is there any way to make it only available when a site collection is being created?

Answer:
go to site actions -> Site Settings -> view all site settings -> site templates and page layouts and remove the site template from the list of allowed items.
Gary Lapointe may also have made an stsadm extenstion for it; check
stsadm.blogspot.com
Mauro Masucci
http://www.brantas.co.uk


Question:
I work for a company whose primary business is not software related. Most documentation for using source control is written with a development team writing for commercial or open source projects in mind. As someone who writes in house software I can say that work is done differently then it would be in a commercial or open source setting. In addition there are stored procedures and database scripts that need to be kept in sync with the code.

In particular I am looking to get suggestions on how best to structure the repository with in house software in mind. Most documentation suggests trunk, branches, tags etc. And procedures for keeping production, test and development environments in sync with their respective sections in the repository etc.

Answer:
You could use a service like www.unfuddle.com to set up a free SVN or GIT repository.
We use Unfuddle and it's really great. There are free and paid versions (depending on your needs).
Or, you could of course set up a local copy. There are plenty of tutorials to be found via Google for that:
http://www.google.com/search?rlz=1C1GGLS_enUS291&aq=f&sourceid=chrome&ie=UTF-8&q=set+up+svn


Question: How can I retrieve the page title of a webpage (title html tag) using Python?

Answer:
I'll always use
lxml
for such tasks. You could use
beautifulsoup
as well.
```
```
import lxml.html
t = lxml.html.parse(url)
print(t.find(".//title").text)
```
```
EDIT based on comment:
```
```
from urllib2 import urlopen
from lxml.html import parse

url = "https://www.google.com"
page = urlopen(url)
p = parse(page)
print(p.find(".//title").text)
```
```


Question:
I have a table in a MySql database that stores user accounts. One of the columns, expires, stores an expiration date but defaults to NULL. I need to be able to remove an expiration date and set it back to the default value.

Currently, all of my CRUD routines are written using MySqlCommand with parameters. Can this be done directly with a MySqlParameter, or do I have to create an alternate command object to handle this eventuality?

Answer:
It's not clear what conditions you're talking about. If you want to set column to default value, you can use
DbNull.Value
;
```
```
command.AddWithValue("@param", DbNull.Value);

or

command.Parameters.Add("@param", <data type>).Value = DBNull.Value;
```
```


Question: How can you find out what are the long running queries are on Informix database server? I have a query that is using up the CPU and want to find out what the query is.

Answer:
```
```
SELECT ELAPSED_TIME_MIN,SUBSTR(AUTHID,1,10) AS AUTH_ID,
AGENT_ID, APPL_STATUS,SUBSTR(STMT_TEXT,1,20) AS SQL_TEXT
FROM SYSIBMADM.LONG_RUNNING_SQL
WHERE ELAPSED_TIME_MIN > 0
ORDER BY ELAPSED_TIME_MIN DESC
```
```
Credit:
SQL to View Long Running Queries


Question: What object do you query against to select all the table names in a schema in Oracle?

Answer:
You may use:
```
```
select tabname from tabs
```
```
to get the name of tables present in schema.


Question: Is there any performance to be gained these days from compiling java to native code, or do modern hotspot compilers end up doing this over time anyway?

Answer:
Memory performance or CPU performance? Or are they the same these days?
My only evidence is anecdotal and on a different platform: after porting a bunch of CPU-hungry apps to C# (.NET 2.0), I did not notice substantial loss in performance (I do not consider 10% substantial). Well written code seems to perform well on a variety of architectures.
Most apps spend/waste time with:
IO operations that will not benefit from static (compile-time) analysis.
Bad Algorithms that will not benefit from static analysis.
Bad Memory layouts in critical CPU inner loops. While it is technically possible that compilers help us here, I have yet to see a real compiler do anything interesting.
So based upon my experience, unless you are writing a video codec, there is no benefit to compiling Java apps vs. just relying upon the hotspot compilers.


Question:
I'm wondering what strategies people use for reduced sign on with legacy applications and how effective they have found them?

We have an ASP.Net based intranet and own a lot of the legacy applications, but not all.  We also have BizTalk and are considering the use of it's SSO engine too.

Answer:
A good compromise between effort/rework and the convenience of single sign on is to continue to maintain a list of users, privileges, roles etc in the legacy app.  Make the changes necessary to automatically log the user into your application based on their user account (usually their Windows or network account).
I'm currently running a couple of applications that use this method of sign on, and it makes them seem more integrated even though they aren't.
Another advantage we've found is that it stops people from sharing passwords to legacy applications.  They're much less likely to hand out an admin password that also gives others access to their email or payroll details!


Question: How do you get around this Ajax cross site scripting problem on FireFox 3?

Answer:
If you're using jQuery it has a callback function to overcome this:
http://docs.jquery.com/Ajax/jQuery.ajax#options
As of jQuery 1.2, you can load JSON
  data located on another domain if you
  specify a JSONP callback, which can be
  done like so: "myurl?callback=?".
  jQuery automatically replaces the ?
  with the correct method name to call,
  calling your specified callback. Or,
  if you set the dataType to "jsonp" a
  callback will be automatically added
  to your Ajax request.
Alternatively you could make your ajax request to a server-side script which does the cross-domain call for you, then passes the data back to your script


Question:
So I'm running PPP under linux with a cellular modem.  The program I'm writing needs to know if the link is active before sending any data.

What are my options to check

if the link is available

if it routes to a server I control (it doesn't go to the internet as I said earlier)

Also, what is the best way to restart it - I'd like to have program control over when it starts and stops, so I assume an init.d isn't appropriate.  Using system() doesn't seem to give a PID, are there other options besides fork() and the gaggle of exec??() calls?

C on Linux on ARM (custom distribution using buildroot).

Answer:
You could parse
```
/proc/net/route
```
.


Question:
For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows.

I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it).

Any help?

EDIT: I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically.

Answer:
Of course there is a
```
PATH
```
environment variable
in Windows
.
```
%PATH%
```
This variable contains a semicolon-delimited list of directories in which the command interpreter will search for executable files. Equivalent to the UNIX $PATH variable.


Question:
I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL:

SELECT f.*
FROM Foo f
WHERE f.FooId IN (
    SELECT fb.FooId
    FROM FooBar fb
    WHERE fb.BarId = 1000
)

Any help would be gratefully received.

Answer:
Try using two separate steps:
```
```
// create a Dictionary / Set / Collection fids first
var fids = (from fb in FooBar
            where fb.BarID = 1000
            select new { fooID = fb.FooID, barID = fb.BarID })
            .ToDictionary(x => x.fooID, x => x.barID);

from f in Foo
where fids.HasKey(f.FooId)
select f
```
```


Question:
The Sun Documentation for DataInput.skipBytes states that it "makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes. However, it may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility."

Other than reaching end of file, why might skipBytes() not skip the right number of bytes? (The DataInputStream I am using will either be wrapping a FileInputStream or a PipedInputStream.)

If I definitely want to skip n bytes and throw an EOFException if this causes me to go to the end of the file, should I use readFully() and ignore the resulting byte array? Or is there a better way?

Answer:
1) There might not be that much data available to read (the other end of the pipe might not have sent that much data yet), and the implementing class might be non-blocking (i.e. it will just return what it can, rather than waiting for enough data to fulfil the request).
I don't know if any implementations actually behave in this way, however, but the interface is designed to permit it.
Another option is simply that the file gets closed part-way through the read.
2) Either readFully() (which will always wait for enough input or else fail) or call skipBytes() in a loop.  I think the former is probably better, unless the array is truly vast.


Question:
I want to get the base 10 logarithm of a Fixnum using Ruby, but found that n.log or n.log10 are not defined. Math::log is defined but uses a different base than 10.

What is the easiest way to get the base 10 logarithm of a Fixnum?

Answer:
Reading the documentation for module Math the answer is really obvious:
```
```
Math::log10(n)
```
```
This gives the base 10 logarithm of n.


Question:
How do you get a Media Type (MIME type) from a file using Java?  So far I've tried JMimeMagic & Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly.

How would you probe the file to determine its actual type (not merely based on the extension)?

Answer:
Unfortunately,
```
```
mimeType = file.toURL().openConnection().getContentType();
```
```
does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.
However, you have this:
```
```
mimeType= URLConnection.guessContentTypeFromName(file.getName());
```
```
and also the following, which has the advantage of going beyond mere use of file extension, and takes  a peek at content
```
```
InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 //...close stream
```
```
However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).


Question:
what is the best method for inter process communication in a multithreaded java app.

It should be performant (so no JMS please) easy to implement and reliable,so that
objects & data can be bound to one thread only?

Any ideas welcome!

Answer:
Could you clarify a bit?  Do you mean IPC in a single JVM? (Multiple threads, yes, but at an OS-level only one process.)  Or do you mean multiple JVMs?  (And truly OS-level inter process communications.)
If it is the first, then maybe something out of
java.util.concurrent
, like
ConcurrentLinkedQueue
would do the trick.  (I pass message around inbetween my threads with classes from java.util.concurrent with success.)
If the later, then I'm going to just guess and suggest taking a look at
RMI
, although I don' think it qualifies as fully reliable--you'd have to manage that a bit more 'hands on' like.


Question:
In PostgreSQL, I can do something like this:

ALTER SEQUENCE serial RESTART WITH 0;

Is there an Oracle equivalent?

Answer:
A true restart is not possible
AFAIK
. (Please correct me if I'm wrong!).
However, if you want to set it to 0, you can just delete and recreate it.
If you want to set it to a specific value, you can set the INCREMENT to a negative value and get the next value.
That is, if your sequence is at 500, you can set it to 100 via
```
```
ALTER SEQUENCE serial INCREMENT BY -400;
SELECT serial.NEXTVAL FROM dual;
ALTER SEQUENCE serial INCREMENT BY 1;
```
```


Question:
Given a path such as "mydir/myfile.txt", how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:

"C:/example/cwd/mydir/myfile.txt"

Answer:
```
```
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
```
```
Also works if it is already an absolute path:
```
```
>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
```
```


Question:
I have a list of structs and I want to change one element. For example :

MyList.Add(new MyStruct("john");
MyList.Add(new MyStruct("peter");

Now I want to change one element:

MyList[1].Name = "bob"

However, whenever I try and do this I get the following error:

Cannot modify the return value of
  System.Collections.Generic.List.this[int]‘ because it is not
  a variable

If I use a list of classes, the problem doesn't occur.

I guess the answer has to do with structs being a value type.

So, if I have a list of structs should I treat them as read-only? If I need to change elements in a list then I should use classes and not structs?

Answer:
```
```
MyList[1] = new MyStruct("bob");
```
```
structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).
In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field.


Question:
Typically when writing new code you discover that you are missing a #include because the file doesn't compile. Simple enough, you add the required #include. But later you refactor the code somehow and now a couple of #include directives are no longer needed. How do I discover which ones are no longer needed?

Of course I can manually remove some or all #include lines and add them back until the file compiles again, but this isn't really feasible in a large project with thousands of files. Are there any tools available that will help automating task?

Answer:
You can use
PC-Lint/FlexeLint
to do that.
Unusually there isn't a free OS version of the tool available.
You can remove #includes by passing by reference instead of passing by value and forward declaring. This is because the compiler doesn't need to know the size of the object at compile time. This will require a large amount of manual work on your behalf however. The good thing is it will reduce your compile times.


Question: How can i format currency related data in a manner that is culture aware in JavaScript?

Answer:
Dojo has a
currency formatter
that's locale aware.
If you don't want to include Dojo in your project just for this function, then perhaps you can localize the currency in your back-end?


Question:
Has anyone had good experiences with any Java libraries for Graph algorithms. I've tried JGraph and found it ok, and there are a lot of different ones in google. Are there any that people are actually using successfully in production code or would recommend?

To clarify, I'm not looking for a library that produces graphs/charts, I'm looking for one that helps with Graph algorithms, eg minimum spanning tree, Kruskal's algorithm Nodes, Edges, etc. Ideally one with some good algorithms/data structures in a nice Java OO API.

Answer:
For visualization our group had some success with
prefuse
.  We extended it to handle architectural floorplates and bubble diagraming, and it didn't complain too much.  They have a new Flex toolkit out too called Flare that uses a very similar API.
UPDATE:
I'd have to agree with the comment, we ended up writing a lot of custom functionality/working around prefuse limitations.  I  can't say that starting from scratch would have been better though as we were able to demonstrate progress from day 1 by using prefuse.  On the other hand if we were doing a second implementation of the same stuff, I might skip prefuse since we'd understand the requirements a lot better.


Question:
Let's say I have the following class:

public class Test<E> {
    public boolean sameClassAs(Object o) {
        // TODO help!
    }
}

How would I check that o is the same class as E?

Test<String> test = new Test<String>();
test.sameClassAs("a string"); // returns true;
test.sameClassAs(4); // returns false;

I can't change the method signature from (Object o) as I'm overridding a superclass and so don't get to choose my method signature.

I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.

Answer:
I could only make it working like this:
```
```
public class Test<E> {

    private E e;

    public void setE(E e) {
        this.e = e;
    }

    public boolean sameClassAs(Object o) {

        return (o.getClass().equals(e.getClass()));
    }

    public boolean sameClassAs2(Object o) {
        return e.getClass().isInstance(o);
    }
}
```
```


Question: I assume that char* = "string" is the same to char* = new char[6]. I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves?

Answer:
You don't know where the string literals are stored. It may even be read-only memory, so your code should read:
```
```
const char* c = "string";
```
```
And a
new
char array should be
delete
d just like any other dynamically allocated memory area.


Question: What is the easiest way to extract the original exception from an exception returned via Apache's implementation of XML-RPC?

Answer:
According to the
XML-RPC Spec
it returns the "fault" in the xml.
Is this the "Exception" you are referring to or are you refering to a Java Exception generated while making the XML-RPC call?
Fault example
```
```
HTTP/1.1 200 OK
Connection: close
Content-Length: 426
Content-Type: text/xml
Date: Fri, 17 Jul 1998 19:55:02 GMT
Server: UserLand Frontier/5.1.2-WinNT

<?xml version="1.0"?>
<methodResponse>
  <fault>
    <value>
      <struct>
      <member>
        <name>faultCode</name>
        <value><int>4</int></value>
      </member>
      <member>
        <name>faultString</name>
        <value>
          <string>Too many parameters.</string>
        </value>
      </member>
      </struct>
    </value>
  </fault>
</methodResponse>
```
```


Question:
The rich presentational capabilities of WPF and Silverlight mean developers like me will be working closely with graphic designers more often these days, as is the case in my next project.

Does anyone out there have any tips and experience (from both points of view) on making this go more smoothly?

For example, when I mentioned source control to a designer recently, I was quickly told you can't source control graphics, images etc, so it is a waste of time.  So I responded: ok but, what about XAML files in WPF/Silverlight?

Scott Hanselman spoke about this topic in a podcast, but he focused more on the tools, while I'm more interested in the communication issues/aspects.

Answer:
This may be a bit off topic (I'm replying specifically to your question about source control and graphics), but you
can
put binary data (images etc.) into source control (and in my opinion in a lot of cases should) -- they just take up more disk space and you can't use a diff view to analyze what has changed in any meaningful way, but what you do gain is a history of commit messages documenting each revision, rollback ability and the ability to easily archive (
tagging a revision
in SVN terms) all files (be they visual assets, documentation, source code, whatever) belonging to a specific release/version together. It's also easier for your build system to just fetch everything required for building a specific version of your software from the source control.


Question:
How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0).

I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive.

Answer:
this is VB.NET code to check for any removable drives or CDRom drives attached to the computer:
```
```
Me.lstDrives.Items.Clear()
For Each item As DriveInfo In My.Computer.FileSystem.Drives
    If item.DriveType = DriveType.Removable Or item.DriveType = DriveType.CDRom Then
        Me.lstDrives.Items.Add(item.Name)
    End If
Next
```
```
it won't be that hard to modify this code into a c# equivalent, and more
driveType
's are available.
From MSDN:
Unknown:
The type of drive is unknown.
NoRootDirectory:
The drive does not have a root directory.
Removable:
The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
Fixed:
The drive is a fixed disk.
Network:
The drive is a network drive.
CDRom:
The drive is an optical disc device, such as a CD or DVD-ROM.
Ram:
The drive is a RAM disk.


Question:
This is not specific to any language, it´s just about best practices. I am using JPA/Hibernate (but it could be any other ORM solution) and I would like to know how do you guys deal with this situation:
Let´s suppose that you have a query returning something that is not represented by any of your domain classes.
Do you create a specific class to represent that specific query?
Do you return the query in some other kind of object (array, map...)
Some other solutions?
I would like to know about your experiences and best practices.

P.S.
Actually I am creating specific objetcs for specific queries.

Answer:
I typically write a function that performs a query using SQL and then puts the results into either a list or dictionary (in Java, I'd use either an ArrayList or a HashMap).
If I found myself doing this a lot, I'd probably create a new file to hold all of these queries.  Otherwise I'd just make them functions in whatever file they were needed/used.
Since we're talking Java specifically, I would certainly not create a new class in a separate file.  However, for queries needed in only one class, you could create a private static inner class with only the function(s) needed to generate the query(s) needed by that class.


Question:
The source database is quite large. The target database doesn't grow automatically. They are on different machines.

I'm coming from a MS SQL Server, MySQL background and IDS11 seems overly complex (I am sure, with good reason).

Answer:
have you used the export tool ?  There used to be a way if you first put the db's into quiescent mode and then you could actually copy the DBSpaces across (dbspaces tool I think... its been a few years now).
Because with informix you used to be able to specify the DBSpaces(s) to used for the table (maybe even in the alter table ?).
Check - dbaccess tool - there is an export command.
Put the DB's into quiesent mode or shut down, copy the dbspaces and then attach table telling it to point to the new dbspaces file.  (the dbspaces tool could be worth while looking at.. I have manuals around here.  they are 9.2, but it shouldn't have changed too much).


Question:
Is it possible to deploy a native Delphi application with ClickOnce without a stub C# exe that would be used to launch the Delphi application?

The same question applies to VB6, C++ and other native Windows applications.

Answer:
I'm not 100% sure if this can be accomplished without the stub, but this article may provide some insight:
How To: ClickOnce deployment for unmanaged app with COM component in managed assembly


Question:
I have a ASP.Net website that is failing on AJAX postbacks (both with ASP.Net AJAX and a 3rd part control) in IE.    FireFox works fine.  If I install the website on another machine without .Net 3.5 SP1, it works as expected.

When it fails, Fiddler shows that I'm getting a 405 "Method Not Allowed".  The form seems to be posting to pages other than page I'm viewing.

The form's action is "#" for the page on the broken website (with SP1).  The form's action is "Default.aspx" for the same page on a website without SP1.

Any ideas?

Answer:
These are my observations rather than a full answer:
My guess (without trying to re-produce it myself) is that a couple of things may be happening as the DataSet tries to 'flatten' a hierarchical structure to a relational data structure.
1) thinking about the data from a relational database perspective; there is no obvious primary key field for identifying each of the Foo elements in the collection so the DataSet has automatically used the ordinal position in the file as an auto-generated field called Foo-Id.
2) There are actually two elements called 'Foo' so that probably explains the generation of a strange name for the column 'Foo-Id-0' (it has auto-generated a unique name for the column - I guess you could think of this as a fault-tolerant behaviour in the DataSet).


Question:
I have a variable of type Dynamic and I know for sure one of its fields, lets call it a, actually is an array. But when I'm writing

var d : Dynamic = getDynamic();
for (t in d.a) {
}

I get a compilation error on line two:

You can't iterate on a Dynamic value, please specify Iterator or Iterable

How can I make this compilable?

Answer:
Haxe can't iterate over
```
Dynamic
```
variables (as the compiler says).
You can make it work in several ways, where this one is probably easiest (depending on your situation):
```
```
var d : {a:Array<Dynamic>} = getDynamic();
for (t in d.a) { ... }
```
```
You could also change
```
Dynamic
```
to the type of the contents of the array.


Question:
Flat files and relational databases give us a mechanism to serialize structured data. XML is superb for serializing un-structured tree-like data.

But many problems are best represented by graphs. A thermal simulation program will, for instance, work with temperature nodes connected to each others through resistive edges.

So what is the best way to serialize a graph structure? I know XML can, to some extent, do it---in the same way that a relational database can serialize a complex web of objects: it usually works but can easily get ugly.

I know about the dot language used by the graphviz program, but I'm not sure this is the best way to do it. This question is probably the sort of thing academia might be working on and I'd love to have references to any papers discussing this.

Answer:
XML is very verbose.  Whenever I do it, I roll my own.  Here's an example of a 3 node directed acyclic graph.  It's pretty compact and does everything I need it to do:
```
```
0: foo
1: bar
2: bat
----
0 1
0 2
1 2
```
```


Question: How can I generate UML diagrams (especially sequence diagrams) from existing Java code?

Answer:
What is your codebase? Java or C++?
eUML2 for Java is a powerful UML modeler designed for Java developper
  in Eclipse. The free edition can be used for commercial use. It
  supports the following features:
CVS and Team Support
Designed for large project with multiple and customizable model views
Helios Compliant
Real-time code/model synchronization
UML2.1 compliant and support of OMG XMI
JDK 1.4 and 1.5 support
The commercial edition provides:
Advanced reversed engineering
Powerful true dependency analyze tools
UML Profile and MDD
Database tools
Customizable template support


Question:
When you send an email using C# and the System.Net.Mail namespace, you can set the "From" and "Sender" properties on the MailMessage object, but neither of these allows you to make the MAIL FROM and the from address that goes into the DATA section different from each other.  MAIL FROM gets set to the "From" property value, and if you set "Sender" it only adds another header field in the DATA section.  This results in "From X@Y.COM on behalf of A@B.COM", which is not what you want.  Am I missing something?

The use case is controlling the NDR destination for newsletters, etc., that are sent on behalf of someone else.

I am currently using aspNetEmail instead of System.Net.Mail, since it allows me to do this properly (like most other SMTP libraries).  With aspNetEmail, this is accomplished using the EmailMessage.ReversePath property.

Answer:
Do you mean this?:
```
```
//create the mail message
 MailMessage mail = new MailMessage();

 //set the addresses
 mail.From = new MailAddress("me@mycompany.com");
 mail.To.Add("you@yourcompany.com");

 //set the content
 mail.Subject = "This is an email";
 mail.Body = "this is a sample body with html in it. This is bold This is blue";
 mail.IsBodyHtml = true;

 //send the message
 SmtpClient smtp = new SmtpClient("127.0.0.1");
 smtp.Send(mail);
```
```
From
http://www.systemnetmail.com/faq/3.1.2.aspx


Question:
Is the edit control I'm typing in now, with all its buttons and rules freely available for use?

My web project is also .Net based.

Answer:
It's the
WMD
Markdown editor which is free and seems to be pretty easy to use.  Just include the javascript for it and (in the easiest case), it just attaches to the first textarea it finds.
Here's some info about the
Perl implementation of Markdown
which, according to the site, WMD is 100% compatible with.
@Chris Upchurch
Technically the current release isn't open-source, just free to use.  The next version is supposed to be released with an MIT license though.
"now completely free to use. The next release will be open source under an MIT-style license."


Question: Is it any compilator option of flag?

Answer:
You can if you setup an external tool pointing to MsBuild to build the solution with the multiple process flag /m.
Scott Hanselman wrote a
nice post
on how to accomplish this, so I won't repeat what he has already done.


Question:
In a C# Windows Forms application I want to detect if another instance of the application is already running.
If so, activate the main form of the running instance and exit this instance.

What is the best way to achieve this?

Answer:
Here is what I'm currently doing in the application's Program.cs file.
```
```
// Sets the window to be foreground
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);

// Activate or minimize a window
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;

static void Main()
{
    try
    {
        // If another instance is already running, activate it and exit
        Process currentProc = Process.GetCurrentProcess();
        foreach (Process proc in Process.GetProcessesByName(currentProc.ProcessName))
        {
            if (proc.Id != currentProc.Id)
            {
                ShowWindow(proc.MainWindowHandle, SW_RESTORE);
                SetForegroundWindow(proc.MainWindowHandle);
                return;   // Exit application
            }
        }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
    catch (Exception ex)
    {
    }
}
```
```


Question:
How do I figure out if an array contains an element?
I thought there might be something like [1, 2, 3].includes(1) which would evaluate as true.

Answer:
For lists, use
```
contains
```
:
```
```
[1,2,3].contains(1) == true
```
```


Question:
I'm having a problem running a T4 template using TextTransform.exe on my build server. On my dev machine the template works perfectly. The error message is as follows.

error : Running transformation: System.TypeLoadException: Could not instantiate type System.Xml.Linq.XDocument

The build server has the windows 2008 SDK on it, my machine has VS 2008. I thought mayve it couldn't find System.Data.Xml so I ensure the dll was present in the same directory, but no luck. Any ideas?

Answer:
For lists, use
```
contains
```
:
```
```
[1,2,3].contains(1) == true
```
```


Question:
Given a string "filename.conf", how to I verify the extension part?

I need a cross platform solution.

Answer:
```
```
_splitpath, _wsplitpath, _splitpath_s, _wsplitpath_w
```
```
This is Windows (Platform SDK) only


Question: I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ?

Answer:
InternalsVisibleTo
attribute to the rescue!
Just add:
```
```
[assembly:InternalsVisibleToAttribute("UnitTestAssemblyName")]
```
```
to your Core classes AssemblyInfo.cs file
See
Friend Assemblies (C# Programming Guide)
for best practices.


Question:
In my base page I need to remove an item from the query string and redirect. I can't use

Request.QueryString.Remove("foo")

because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it?

Answer:
```
```
Response.Redirect(String.Format("nextpage.aspx?{0}", Request.QueryString.ToString().Replace("foo", "mangledfoo")));
```
```
I quick hack, saves you little. But foo will not be present for the code awaiting it in nextpge.aspx :)