Question:
Is there a fast and clean way of returning a JSON hash back from any node in a Ruby on Rails' acts_as_nested_set without using recursion?

Here's the recursive solution for reference:

class Node < ActiveRecord::Base
  has_many :products
  def json_hash
    if children.size > 0
      children.collect { |node| { node.name => node.json_hash }.to_json
    else
      { node.name => node.products.find(:all).collect(&:name) }.to_json
    end
  end
end

Answer:
There is a
wikipedia article
on tree traversal which shows different alternatives to the recursive solution you are using.  It may be tricky to use them in your specific case, but it should be possible.
However, my question to you is, is there a specific reason you want to use iteration instead of recursion?  I don't think any of the iterative solutions will be nearly as clean.  Are your trees so big that you are running out of stack space (they would have to be pretty big)?  Otherwise, I'm not so sure an iterative solution will really be faster.
I see one potential for improvement though, if you are seeing performance issues... but I don't know rails, so I'm not sure if it is accurate:
Does the find method return a new array?  If so, you probably want to invoke .collect! instead of .collect, because if find creates an array, you are just creating an array and then throwing it away to the call to collect (which also creates an array), which surely is not going to be very efficient and may slow you down a lot if you have a big tree there.
So
```
```
{ node.name => node.products.find(:all).collect(&:name) }.to_json
```
```
might become
```
```
{ node.name => node.products.find(:all).collect!(&:name) }.to_json
```
```
EDIT: Also, it may be more efficient to create your hash of hashes, and then convert the whole thing to json in 1 fell swoop, rather than converting it piecemail like you are doing.
So
```
```
class Node < ActiveRecord::Base
  has_many :products
  def json_hash
    if children.size > 0
      children.collect { |node| { node.name => node.json_hash }.to_json
    else
      { node.name => node.products.find(:all).collect!(&:name) }.to_json
    end
  end
end
```
```
might become
```
```
class Node < ActiveRecord::Base
  has_many :products
  def json_hash
    to_hash.to_json
  end

  def to_hash
    if children.size > 0
      children.collect { |node| { node.name => node.to_hash }
    else
      { node.name => node.products.find(:all).collect!(&:name) }
    end
  end
end
```
```
Whether this works and is more efficient I leave as an exercise for you ;-)


Question:
I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I could configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer.

Thanks

Answer:
There doesn't seem to be an easier way,
unless you're willing to buy MAMP Pro
.
As far as I know, the only way to use SSL with MAMP is to
configure mod_ssl for Apache
. mod_ssl is bundled with MAMP, and I found configuration to be pretty straightforward. Note that you'll probably have to start Apache from the command line to use it:
```
```
/Applications/MAMP/bin/apache2/bin$ ./apachectl stop
/Applications/MAMP/bin/apache2/bin$ sudo ./apachectl startssl
```
```


Question: I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable<T>. Is there any way to get this functionality on IEnumerable<T>?

Answer:
I guess it would work to use reflection to get whatever property you want to sort on:
```
```
IEnumerable<T> myEnumerables
var query=from enumerable in myenumerables
          where some criteria
          orderby GetPropertyValue(enumerable,"SomeProperty")
          select enumerable

private static object GetPropertyValue(object obj, string property)
{
    System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);
    return propertyInfo.GetValue(obj, null);
}
```
```
Note that using reflection is considerably slower than accessing the property directly, so the performance would have to be investigated.


Question:
I assumed there were only bug fixes/(no new types) in .NET 2.0 SP1 until I came across few posts which were mentioning DateTimeOffset structure, that was added in .NET 2.0 SP1.

Is there a full listing of the newly added types in .NET 2.0 SP1?

Answer:
Here's what you're looking for:
Full Article:
http://www.hanselman.com/blog/CatchingRedBitsDifferencesInNET20AndNET20SP1.aspx
This may also be helpful:
Full Article:
http://www.hanselman.com/blog/ChangesInTheNETBCLBetween20And35.aspx


Question:
How do you run Emacs in Windows?

What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the .emacs file located?

Answer:
Well, I personally really like what I have been using since I started with Emacs, which is GNU Emacs.  It looks like it is built for
windows too
.  That link also answers your
.emacs file question
.
Here is a place you can download it
.  You should probably get version 22.2 (the latest).
If this is your first time, I hope you enjoy it!  I know I absolutely love emacs!


Question:
Has anybody got any kind of experience with dynamic programming using WCF. By dynamic programming I mean runtime consumption of WSDL's.
I have found one blog entry/tool:
http://blogs.msdn.com/vipulmodi/archive/2006/11/16/dynamic-programming-with-wcf.aspx

Has anybody here found good tools for this?

Answer:
I have done this a long time ago with SOAP web services. There was a tool on GotDotNet which I think has become
Web Services Studio Express
, that had code which inspected/parsed a WSDL file and allowed you to call it.
I think the assumption is that the WSDL is known at the time of client creation, and you don't need to be hooked up at runtime. If you inspect the WSDL at runtime you still need to have some sort of logic to decide how to generate the proxy. Why would can you not consume the WSDL before runtime? Web Services are supposed to be fairly static with an interface that doesn't change once published.
You can use .NET CodeDom to generate code to execute and use the web service described by the WSDL. The WSDL can be parsed using the standard .NET XML classes.


Question: What do search engine bots use as a starting point? Is it DNS look-up or do they start with some fixed list of well-know sites? Any guesses or suggestions?

Answer:
You can submit your site to search engines using their
site submission forms
- this will get you into their system. When you actually get crawled after that is impossible to say - from experience it's usually about a week or so for an initial crawl (homepage, couple of other pages 1-link deep from there). You can increase how many of your pages get crawled and indexed using clear semantic link structure and submitting a
sitemap
- these allow you to list all of your pages, and weight them relative to one another, which helps the search engines understand how important you view each part of site relative to the others.
If your site is linked from other crawled websites, then your site will also be crawled, starting with the page linked, and eventually spreading to the rest of your site. This can take a long time, and depends on the crawl frequency of the linking sites, so the url submission is the quickest way to let google know about you!
One tool I can't recommend highly enough is the
Google Webmaster Tool
. It allows you to see how often you've been crawled, any errors the googlebot has stumbled across (broken links, etc) and has a host of other useful tools in there.


Question:
I'm looking for a tool to generate a JavaScript stub from a WSDL.

Although I usually prefer to use REST services with JSON or XML, there are some tools I am currently integrating that works only using SOAP.

I already created a first version of the client in JavaScript but I'm parsing the SOAP envelope by hand and I doubt that my code can survive a service upgrade for example, seeing how complex the SOAP envelope specification is.

So is there any tool to automatically generate fully SOAP compliant stubs for JavaScript from the WSDL so I can be more confident on the future of my client code.

More: The web service I try to use is RPC encoded, not document literal.

Answer:
I had to do this myself in the past and I found this
CodeProject article
.  I changed it up some, but it gave me a good foundation to implement everything I needed.  One of the main features it already has is generating the SOAP client based off the WSDL.  It also has built in caching of the WSDL for multiple calls.
This article also has a custom implementation of XmlHttpRequest for Ajax calls.  This is the part that I didn't use.  During that time, I think I was using
Prototype
javascript library and modified the code in this article to use it's Ajax functions instead.  I just felt more comfortable using Prototype for the ajax calls, because it was widely used and had been tested on all the browsers.


Question:
I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality:

The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database.

Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible.

Answer:
I haven't tried it, but take a look at
isbndb
API Description: Introduction
ISBNdb.com's remote access application programming interface (API) is designed to allow other websites and standalone applications use the vast collection of data collected by ISBNdb.com since 2003. As of this writing, in July 2005, the data includes nearly 1,800,000 books; almost 3,000,000 million library records; close to a million subjects; hundreds of thousands of author and publisher records parsed out of library data; more than 10,000,000 records of actual and historic prices.
Some ideas of how the API can be used include:
```
```
- Cataloguing home book collections
- Building and verifying bookstores' inventories
- Empowering forums and online communities with more useful book references
- Automated cross-merchant price lookups over messaging devices or phones
```
```
Using the API you can look up information by keywords, by ISBN, by authors or publishers, etc. In most situations the API is fast enough to be used in interactive applications.
The data is heavily cross-linked -- starting at a book you can retrieve information about its authors, then other books of these authors, then their publishers, etc.
The API is primarily intended for use by programmers. The interface strives to be platform and programming language independent by employing open standard protocols and message formats.


Question:
Is it possible to determine which property of an ActiveX control is the default property? For example, what is the default property of the VB6 control CommandButton and how would I found out any other controls default!

/EDIT: Without having source to the object itself

Answer:
I don't use VB, but here it goes.
I found
Using the Value of a Control
, but it's not a programmatic solution.
If you have access to the code, look for
```
```
Attribute Value.VB_UserMemId = 0
```
```
using Notepad.


Question:
In Java, static and transient fields are not serialized. However, I found out that initialization of static fields causes the generated serialVersionUID to be changed. For example, static int MYINT = 3; causes the serialVersionUID to change. In this example, it makes sense because different versions of the class would get different initial values. Why does any initialization change the serialVersionUID? For example, static String MYSTRING = System.getProperty("foo"); also causes the serialVersionUID to change.

To be specific, my question is why does initialization with a method cause the serialVersionUID to change. The problem I hit is that I added a new static field that was initialized with a system property value (getProperty). That change caused a serialization exception on a remote call.

Answer:
If I read the spec correctly the automatic
```
serialVersionUID
```
shouldn't change if you change the value of a static of transient field. Take a look at
Chapter 5.6
of the Spec.
However
, if you think about this a bit - you start by serializing an object that has
```
static int MYINT = 3
```
, when you then deserialize the class you expect to get the same object back, that is, with
```
MYINT = 3
```
. So, if you change the static initialization you would expect the
```
serialVersionUID
```
to change because you can't get the same object back again.
Anyways
, keep this in all your serializable classes and you can control the
```
serialVersionUID
```
:
```
```
private static final long serialVersionUID = 7526472295622776147L;
```
```


Question:
Is there any way to use this kind of format in .Net (C#)?
I want to use the same skin format that uTorrent uses in my app, but i can't get the transparent background.
Any ideas?
Thanks for your time.

Answer:
The PixelFormat enumeration lists the formats of 'bitmaps' you can create in .Net, so you'd want PixelFormat.Format32bppArgb:
http://msdn.microsoft.com/en-us/library/system.drawing.imaging.pixelformat.aspx
http://msdn.microsoft.com/en-us/library/3z132tat.aspx
However I'm not entirely sure that the BMP file format supports transparency - so you would have to save the file as perhaps a PNG file instead.


Question: I am going to be using Subversion for source control on a new J2EE web application. What directory structure will you recommend for organizing code, tests and documentation?

Answer:
I usually have
```
Project Directory
  src - actual source
  doc - documentation
  lib - libraries referenced from source
  dep - installation files for dependencies that don't fit in lib
  db  - database installation script
```
In work with Visual Studio, I'm not sure if this works the same in the java world. But i usually put stuff in different project folders in src. For each source project there's a separate test project. Build files go in the main project directory. I usually put a README there too documenting how to setup the project if it needs more than just checking out.
EDIT: This is the structure for a single working checkout of the project. It will be duplicated for each branch/tag in your revision control system (remember, in most SVN system, copies are cheap). The above example under Subversion would look like:
```
```
/project
    /trunk
        /src
        /doc
        /...
    /branches
        /feature1
            /src
            /doc
            /...
        /feature2
            /src
            /doc
            /...
```
```


Question:
If not, what are the significant differences?

Edit: Daren Thomas asks:

which ones?

I use gvim on Windows and MacVim on the mac. Seem similar enough to be the same to me...

By which ones, I'm guessing that you mean a specific implementation of vi and emacs for Windows. I'm not sure as I thought there were only one or two. I'm looking for the ones that are closest to the Unix counterparts.

Answer:
which ones?
I use
```
gvim
```
on Windows and
```
MacVim
```
on the mac. Seem similar enough to be the same to me...


Question:
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests.

In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation?

Or will I have to make my own custom shortcuts to setup the context properly?

Answer:
If you can hook your authentication into the
Django authentication scheme
you'll be able to use
```
request.user
```
.
I think this should just be a case of calling
```
authenticate()
```
and
```
login()
```
based on the contents of your Cookie.
Edit: @Staale - I always use the
```
locals()
```
trick
for my context so all my templates can see
```
request
```
and so
```
request.user
```
.  If you're not then I guess it wouldn't be so straightforward.


Question: I'm trying to understand how namespaces work in XML. When I have an element like foo:bar, the attributes will often not have namespaces on them. But sometimes they will. Are the attribute in the namespace of the element, even when the default namespace has been declared? Looking over the xsd for xhtml it seems the attributes are part of the schema and should be in the namespace for xhtml, but they are never presented that way...

Answer:
Read up at
6.1 Namespace Scoping
and
6.2 Namespace Defaulting
on w3c.
Basically:
The scope of a namespace declaration declaring a prefix extends from the beginning of the start-tag in which it appears to the end of the corresponding end-tag
However, the text here doesn't seem to explain if  means a is foo:a or the default namespace in the context. I would assume that it does not refer to foo:a, but rather the documents default namespace a. Considering this quote at least:
Such a namespace declaration applies to all element and attribute names within its scope whose prefix matches that specified in the declaration.
Ie. the namespace "foo:" only applies to elements prefixed with foo:


Question:
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.

How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?

Answer:
Namespaces are packages essentially. They can be used like this:
```
```
namespace MyNamespace
{
  class MyClass
  {
  };
}
```
```
Then in code:
```
```
MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
```
```
Or, if you want to always use a specific namespace, you can do this:
```
```
using namespace MyNamespace;

MyClass* pClass = new MyClass();
```
```
Edit:
Following what
bernhardrusch
has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).
And as you asked
below
, you can use as many namespaces as you like.


Question:
I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.

I know that's possible by using keyword system like that :

#!/usr/bin/env ruby
directory = '/home/paulgreg/'
system 'ls ' + directory

but is that possible by using the "backquotes or backticks syntax" ?
(I mean by using that syntax : ls)

Answer:
No, that will just concatenate the output from
```
ls
```
and the contents of
```
directory
```
.
But you can do this:
```
```
#!/usr/bin/env ruby
directory = '/home/paulgreg/'
`ls #{directory}`
```
```


Question: Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?

Answer:
You can try:
```
```
Bitmap.InterpolationMode = InterpolationMode.HighQualityBicubic;
```
```
and
```
```
Bitmap.CompositingQuality = CompositingQuality.HighQuality;
```
```
Which does keep the quality fairly high, but not the highest possible.


Question:
In Visual Studio you can create a template XML document from an existing schema. The new XML Schema Explorer in VS2008 SP1 takes this a stage further and can create a sample XML document complete with data.
Is there a class library in .NET to do this automatically without having to use Visual Studio? I found the XmlSampleGenerator  article on MSDN but it was written in 2004 so maybe there is something already included in .NET to do this now?

Answer:
Directly, none that I can think of, other than third party add-ons. You could utilize the
xsd schema definition tool
to take your XSD and create a .NET object/class, once you have that, you could, to quote the linked page:
XSD to Classes: Generates runtime classes from an XSD schema file. The generated classes can be used in conjunction with
System.Xml.Serialization.XmlSerializer
to read and write XML code that follows the schema.


Question:
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username)

For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this:
(jobId, label, username) = job

I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this?

Here are my two best guesses:
(jobId, label, username) = (job[0], job[1], job[2])
...but that doesn't scale nicely when you have 15...20 fields

or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)

Answer:
I'd say that a dictionary is definitely the best way to do it.  It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries.  If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.
For example:
```
```
job={}
job['jobid'], job['label'], job['username']=<querycode>
```
```


Question:
As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC?

I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site.

Answer:
Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence.
So start with MVC, and you will easily be able to move in to WebForms if needed.


Question:
I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen Ayende's blog posts and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider.

If you've got some background using these things, any chance you could put it in real laymans terms:

What exactly building DSLs means?

What languages are you using?

Where using a DSL makes sense?

What is the benefit of using DSLs?

Answer:
DSL
stands for
Domain Specific Language
i.e. language designed specifically for solving problems in given area.
For example, Markdown (markup language used to edit posts on SO) can be considered as a DSL.
Personally I find a place for DSL almost in every large project I'm working on. Most often I need some kind of SQL-like query language. Another common usage is rule-based systems, you need some kind of language to specify rules\conditions.
DSL makes sense in context where it's difficult to describe\solve problem by traditional means.


Question: What is the best way to calculate Age using Flex?

Answer:
I found an answer at
the bottom of this page in comments section (which is now offline)
.
jpwrunyan said on Apr 30, 2007 at 10:10 PM :
By the way, here is how to calculate age in years (only) from DOB without needing to account for leap years:
With a slight correction by
Fine-Wei Lin
, the code reads
```
```
private function getYearsOld(dob:Date):uint {
    var now:Date = new Date();
    var yearsOld:uint = Number(now.fullYear) - Number(dob.fullYear);
    if (dob.month > now.month || (dob.month == now.month && dob.date > now.date))
    {
       yearsOld--;
    }
    return yearsOld;
}
```
```
This handles most situations where you need to calculate age.


Question:
I am re-factoring some code and am wondering about the use of a lock in the instance constructor.

public class MyClass {

    private static Int32 counter = 0;
    private Int32 myCount;

    public MyClass() {

        lock(this) {
            counter++;
            myCount = counter;
        }
    }
}

Please confirm

Instance constructors are thread-safe.

The lock statement prevents access to that code block, not to the static 'counter' member.

If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a MyClass and changing the count before this one sets its count?

FYI - This class is not a singleton. Instances must simply be aware of their number.

Answer:
I'm guessing this is for a singleton pattern or something like it. What you want to do is not lock your object, but lock the counter while your are modifying it.
```
```
private static int counter = 0;
private static object counterLock = new Object();

lock(counterLock) {
    counter++;
    myCounter = counter;
}
```
```
Because your current code is sort of redundant. Especially being in the constructor where there is only one thread that can call a constructor, unlike with methods where it could be shared across threads and be accessed from any thread that is shared.
From the little I can tell from you code, you are trying to give the object the current count at the time of it being created. So with the above code the counter will be locked while the counter is updated and set locally. So all other constructors will have to wait for the counter to be released.


Question:
I'm using Microsoft AjaxControlToolkit for modal popup window.

And on a modal popup window, when a postback occurred, the window was closing. How do I prevent from the closing action of the modal popup?

Answer:
You can call
```
Show()
```
method during postback to prevent the modal popup window from closing
```
```
MyModalPopoupExtender.Show()
```
```


Question:
When should I include PDB files for a production release? Should I use the Optimize code flag and how would that affect the information I get from an exception?

If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app?

Answer:
When you want to see source filenames and line numbers in your stacktraces, generate PDBs using the pdb-only option. Optimization is separate from PDB generation, i.e. you can optimize
and
generate PDBs without a performance hit.
From
the C# Language Reference
If you use /debug:full, be aware that there is some impact on the speed and size of JIT optimized code and a small impact on code quality with /debug:full. We recommend /debug:pdbonly or no PDB for generating release code.


Question:
I'm about to start testing an intranet web application. Specifically, I've to determine the application's performance.

Please could someone suggest formal/informal standards for how I can judge the application's performance.

Answer:
To test the front-end then YSlow is great for getting statistics for how long your pages take to load from a user perspective. It breaks down into stats for each specfic HTTP request, the time it took, etc. Get it at
http://developer.yahoo.com/yslow/
Firebug, of course, also is essential. You can profile your JS explicitly or in real time by hitting the profile button. Making optimisations where necessary and seeing how long all your functions take to run. This changed the way I measure the performance of my JS code.
http://getfirebug.com/js.html


Question: I am using the ODBC connector to access a MySQL db from Visual Studio 2008 and I'm facing performance problems when dealing with crystal reports and to solve this I need a native connector to visual studio. If someone has had a similar problem and knows a solution or tools (freeware preferable), I would be really grateful.

Answer:
You want
Connector/Net
Update:
This link should take you to a more recent version:
http://dev.mysql.com/downloads/connector/net/5.2.html


Question: Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.

Answer:
Try this:
```
```
StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
    StackTraceElement main = stack[stack.length - 1];
    String mainClass = main.getClassName ();
```
```
Of course, this only works if you're running from the main thread.  Unfortunately I don't think there's a system property you can query to find this out.
Edit:
Pulling in @John Meagher's comment, which is a great idea:
To expand on @jodonnell you can also
  get all stack traces in the system
  using Thread.getAllStackTraces(). From
  this you can search all the stack
  traces for the "main" Thread to
  determine what the main class is. This
  will work even if your class is not
  running in the main thread.


Question: I'm a software engineer, not a lawyer, and my university doesn't offer any courses geared toward licensing software. In fact, their law-related courses are lacking (but slowly growing in number). Where can I go to learn about open-source licenses and how to choose them?

Answer:
There are lots described here:
http://www.gnu.org/licenses/license-list.html#SoftwareLicenses
The decision of which one to use can be political, but should ultimately be determined by your plans/desires for the software. If you want to ensure it is always free then choose GPL or another "Copyleft" license.  If you don't mind some commercial use, choose another one that's compatible with that.


Question: I'm creating an application which lets you define events with a time frame.  I want to automatically fill in the end date when the user selects or changes the start date.  I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.

Answer:
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the
```
getTime()
```
method
or
just using the date in a numeric expression.
So to get the difference, just subtract the two dates.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
```
```
var oldBegin = ...
var oldEnd = ...
var newBegin = ...

var newEnd = new Date(newBegin + oldEnd - oldBegin);
```
```
This should just work
EDIT
: Fixed bug pointed by @bdukes
EDIT
:
For an explanation of the behavior,
```
oldBegin
```
,
```
oldEnd
```
, and
```
newBegin
```
are
```
Date
```
instances. Calling operators
```
+
```
and
```
-
```
will trigger Javascript auto casting and will automatically call the
```
valueOf()
```
prototype method of those objects. It happens that the
```
valueOf()
```
method is implemented in the
```
Date
```
object as a call to
```
getTime()
```
.
So basically:
```
date.getTime() === date.valueOf() === (0 + date) === (+date)
```


Question: What is the fastest method of parsing an XML file in C#? I'm using .Net 2.0

Answer:
If you're using .Net 2 then the XmlReader and XmlDocument are about it.
If you can use .Net 3.5 then the new Linq to Xml methods are a big improvement.


Question: As per this comment in a related thread, I'd like to know why Levenshtein distance based methods are better than Soundex.

Answer:
Soundex is rather primitive - it was originally developed to be hand calculated. It results in a key that can be compared.
Soundex works well with western names, as it was originally developed for US census data. It's intended for phonetic comparison.
Levenshtein distance looks at two values and produces a value based on their similarity. It's looking for missing or substituted letters.
Basically Soundex is better for finding that "Schmidt" and "Smith" might be the same surname.
Levenshtein distance is better for spotting that the user has mistyped "Levnshtein" ;-)


Question: I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net.  Does anybody has experience with this?

Answer:
I like
Atalasoft's DotImage Photo
, but its a closed source solution and costs about 600 per dev license.
You can also check out
DTools at Codeplex
, which is an open source framework designed to supplement the standard Fx.  It includes some Exif related classes.


Question:
I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:

var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');

This gives me an error:

unterminated string literal

With JSON.parse(data), I see similar error messages: "Unexpected token ↵" in Chrome, and "unterminated string literal" in Firefox and IE.

When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail.

Answer:
This is what you want:
```
```
var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
```
```
You need to escape the
```
\
```
in your string (turning it into a double-
```
\
```
), otherwise it will become a newline in the JSON source, not the JSON data.


Question:
Following my question regarding a .NET YAML Library... as there doesn't seem to be great support for YAML in .NET, are there and good open source really simple .NET XML libraries.  I just want something where I can pass it a section name and a key and it gives me the value as well as being able to give me a list of all the current sections and keys.

Also, preferably something with a license that allows it to be used commercially.

Answer: Can you use the 3.5 framework? Linq to XML is fantastic, and simple.


Question:
I have a library I created,

File mylib.c:

#include <mylib.h>

int
testlib() {
    printf("Hello, World!\n");
    return (0);
}

File mylib.h:

#include <stdio.h>
extern int testlib();

In my program, I've attempted to call this library function:

File myprogram.c:

#include <mylib.h>

int
main (int argc, char *argv[]) {
    testlib();
    return (0);
}

When I attempt to compile this program I get the following error:

In file included from myprogram.c:1
mylib.h:2 warning: function declaration isn't a prototype

I'm using: gcc (GCC) 3.4.5 20051201 (Red Hat 3.4.5-2)

What is the proper way to declare a function prototype?

Answer:
Try:
```
```
extern int testlib(void);
```
```


Question:
.NET Framework: 2.0
Preferred Language: C#

I am new to TDD (Test Driven Development).

First of all, is it even possible to unit test Windows Service?

Windows service class is derived from ServiceBase, which has overridable methods,

OnStart

OnStop

How can I trigger those methods to be called as if unit test is an actual service that calls those methods in proper order?

At this point, am I even doing a Unit testing? or an Integration test?

I have looked at WCF service question but it didn't make any sense to me since I have never dealt with WCF service.

Answer:
I would start
here
.  It shows how to start and stop services in C#
A sample to start is is
```
```
public static void StartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
    // ...
  }
}
```
```
I have also tested services mostly through console app, simulating what the service would do.  That way my unit test is completely automated.


Question:
The company I work for makes hardware that communicates to the computer though a serial port. Third party companies write software that communicates with our hardware.

There are times when I need to diagnose our hardware. However, a third party software app connects to the serial port when Windows starts up, blocking any other connection. I don't know the name of this application/service and it's not always the same one.

Is there any way to either:

Find the name/pid of the app/service that is currently using a given serial port or

Steal the serial port connection from another app.

vb.net preferably, but I'll take a language agnostic answer as well.

Answer:
Sysinternals
has a slew of utilities I find very useful and educational for tracking down what processes are doing to the system.
They have a utility that does exactly what you need called
Portmon
, and give some information on how it works near the bottom of the page.  That info and a few well-asked questions will probably give you everything you need to implement it yourself if the utility isn't enough.
-Adam


Question:
I'm looking to use SQL to format a number with commas in the thousands, but no decimal (so can't use Money) - any suggestions?

I'm using SQL Server 2005, but feel free to answer for others as well (like MySQL)

Answer:
In MySQL, the
```
FORMAT()
```
function will do the trick.


Question:
We're doing an "Amazing Race" kind of event, and thought it would be cool to have CDs that could only play once... like a "this message will self destruct in 5 seconds..."

Any thoughts on how to do this?  I was thinking it could be a compiled HTML website that would write a cookie and only play once.  I don't want to write to the registry (don't want to depend on windows, don't want to install anything, etc).

I also don't care if it's hackable... This is a one-time fun event, and I don't really care too much if people could remove the cookie or something.

Any other ideas?

Answer:
If the content is HTML and run inside a normal browser window, then a cookie may work but there are caveats:
User runs the CD once when IE is the default browser. User runs at a later time, when Firefox is the default browser so cookie cannot be checked.
The browser's security settings may be locked down to prevent use of script so the cookie cannot be set (more of an IE problem).
An alternative might be Flash's equivalent of cookies, but if script was locked down then the same may be true for Flash.


Question:
The following code illustrates an object literal being assigned, but with no semicolon afterwards:

var literal = {
    say: function(msg) { alert(msg); }
}
literal.say("hello world!");

This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?

I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.

Answer:
Not technically, JavaScript has semicolons as optional in many situations.
But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.
Automatic semicolon insertion is performed by the interpreter, so you
can
leave them out if you so choose. In the comments, someone claimed that
Semicolons are not optional with statements like break/continue/throw
but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference.
Here is the rest of the standard on semicolon insertion:
For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.


Question:
I would like to flash a success message on my page.

I am using the jQuery fadeOut method to fade and then remove the element. I can increase the duration to make it last longer, however this looks strange.

What I would like to happen is have the element be displayed for five seconds, then fade quickly, and finally be removed.

How can you animate this using jQuery?

Answer:
use
```
setTimeout(function(){$elem.hide();}, 5000);
```
Where
```
$elem
```
is the element you wish to hide, and
```
5000
```
is the delay in milliseconds. You can actually use any function within the call to
```
setTimeout()
```
, that code just defines a small anonymous function for simplicity.


Question:
It seems that IE6 ignores any form of cache invalidation sent via http headers, I've tried setting Pragma to No Cache and setting Cache Expiration to the current time, yet in IE6, hitting back will always pull up a cached version of a page I am working on.

Is there a specific HTTP Header that IE6 does listen too?

Answer:
Have you tried setting an ETag in the header?  They're a pretty reliable way to indicate that content has changed
w3c Spec
&
Wikipedia
Beyond that, a little more crude way is to append a random query string parameter to the request, such as the current unix timestamp.  As I said, crude, but then IE6 is not the most subtle of beasts


Question: I have a simple 2-column layout with a footer that clears both the right and left div in my markup.  My problem is that I can't get the footer to stay at the bottom of the page in all browsers.  It works if the content pushes the footer down, but that's not always the case.

Answer:
To get a sticky footer:
Have a
```
<div>
```
with
```
class="wrapper"
```
for your content.
Right
before
the closing
```
</div>
```
of the
```
wrapper
```
place the
```
<div class="push"></div>
```
.
Right
after
the closing
```
</div>
```
of the
```
wrapper
```
place the
```
<div class="footer"></div>
```
.
```
```
* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */
}
.footer, .push {
    height: 142px; /* .push must be the same height as .footer */
}
```
```


Question: Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly.

Answer:
For a heavy weight solution, you should check out
doxygen
.  It scans through your code base and comes up with a website, effectively, that documents your code.  One of the many things it shows is include trees.
If you were looking to be able to plug the output of this tool into some other process, then this may not work for you (although doxygen does output to other formats, I'm not real familiar with that feature).  If you simply want to eyeball the dependencies, though, it should work great.


Question:
I have the next function:

function setImagesWidth(id,width) {
    var images = document.getElementById(id).getElementsByTagName("img");
    for(var i = 0; i < images.length;i++) {
        // If the real width is bigger than width parameter
            images[i].style.width=width;
        //}
    }
}

I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework.

images[i].offsetWidth returns 111 for an image of 109px width. Is this because 1px each side border?

Answer:
Here is, hopefully, enough sample code to give you what you want:
```
```
var myImage = document.getElementById("myImagesId");
var imageWidth = myImage.offsetWidth;
var imageHeight = myImage.offsetHeight;
```
```
That should give you the numbers you need to derive the solution you want. I think you can write the rest of the code yourself. :)
EDIT: Here, I couldn't help myself - is this what you are after?
```
```
function setImagesWidth(id,width) {
   var images = document.getElementById(id).getElementsByTagName("img");
   for(var i = 0; i < images.length;i++) {
      if(images[i].offsetWidth > width) {
         images[i].style.width= (width + "px");
      }
   }
}
```
```


Question:
Sometimes IE6 will render the text of a <ul> list the same color as the background color. If you select it, they show back up, or if you scroll the page up and back down.

It is obviously a rendering bug, but I was wondering if anyone knows of a workaround to make it reliable?

Answer:
Have you tried explicitly setting a line-height? For some reason this seems to be the solution to a great many IE6 rendering bugs!
e.g.
```
```
.mylist {
    line-height: 1.6em;
}
```
```


Question:
How can I determine if a string is an IP address? Either IPv4 or IPv6?

What is the least and most number of characters?

I assume this would be a regex answer.

Answer:
For IPv4 you can use this regular expression.
```
```
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
```
```
It looks quite complex but it works by limiting each quad to the numbers 0-255.


Question: We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE.  We aren't sure what the EXE file is used for because we are able to install without the EXE.

Answer:
It's a bootstrapper that checks to make sure that the .NET Framework is installed, before launching the MSI. It's pretty handy.
I suggest using something like SFX Compiler to package the two together into one self-extracting .exe and then launch the extracted setup.exe. This way you retain the benefits of the bootstrapper, but your users only download a single thing.
Edit
: also see
The official line:
MSDN documentation
Some bootstrapper customization:
some guy's blog post about what he did


Question:
Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?

//pseudo-codeish
string s = Coalesce(string1, string2, string3);

or, more generally,

object obj = Coalesce(obj1, obj2, obj3, ...objx);

Answer:
the
??
operator.
```
```
string a = nullstring ?? "empty!";
```
```


Question:
Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong.  Will it cause a memory leak.

EG:

try

dim mySQL as new sqlcommand(sSQL, cnInput)

// do a sql execute and read the data

mySQL = new sqlcommand(sSQLdifferent, cnInput)

// do sql execute and read the data
catch ...

finally

if mysql isnot nothing then
   mysql.dispose
   mysql = nothing
end if

EDIT: put try catch in to avoid the comments about not using them

Answer:
Garbage collection will gather up the first new when it is run.
Only the second one you purposely dispose in the Finally block.  The first one will be disposed of the next time the garbage collection is run.
I do not think this is a good idea.  If the first command is not closed correctly it is possible you would have an open connection to the database and it will not be disposed.
A better way would be to dispose the first command after you are done using it, and then to reuse it.


Question:
X Windows has special processes called Window Managers that manage the layout of windows and decorations like their title bar, control buttons etc. Such processes use an X Windows API to detect events related to windows sizes and positions.

Are there any consistent ways for writing such processes for Microsoft Windows or Mac OS/X?

I know that in general these systems are less flexible but I'm looking for something that will use public APIs and not undocumented hacks.

Answer:
Garbage collection will gather up the first new when it is run.
Only the second one you purposely dispose in the Finally block.  The first one will be disposed of the next time the garbage collection is run.
I do not think this is a good idea.  If the first command is not closed correctly it is possible you would have an open connection to the database and it will not be disposed.
A better way would be to dispose the first command after you are done using it, and then to reuse it.


Question:
I'm writing a C# POS (point of sale) system that takes input from a keyboard wedge magcard reader. This means that any data it reads off of a mag stripe is entered as if it were typed on the keyboard very quickly. Currently I'm handling this by attaching to the KeyPress event and looking for a series of very fast key presses that contain the card swipe sentinel characters.

Is there a better way to deal with this sort of input?

Edit: The device does simply present the data as keystrokes and doesn't interface through some other driver. Also We use a wide range of these types of devices so ideally a method should work independent of the specific model of wedge being used. However if there is no other option I'll have to make do.

Answer:
One thing you can do is that you should be able to configure your wedge reader so that it presents one or many escape characters before or after the string.  You would use these escape characters to know that you are about to have (or just had) a magcard input.
This same technique is used by barcode reader devices so you application knows to get focus or handle the data input from the device.
The negative to this approach is that you have to properly configure your external devices.  This can be a deployment issue.
This assumes that your devices simply present the data as keystrokes and don't interface through some other driver.


Question:
I have some code that uses SMO to populate a list of available SQL Servers and databases.  While we no longer support SQL Server 2000, it's possible that the code could get run on a machine that SQL Server 2000 and not have the SMO library installed.  I would perfer to check for SMO first and degrade the functionality gracefully instead of blowing up in the user's face.  What is best way to detect whether or not SMO is available on a machine?

Every example that I have seen through a quick Google scan was a variation of "look for C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies\Microsoft.SqlServer.Smo.dll".  The problem with that approach is that it only works with SQL Server 2005.  If SQL Server 2008 is the only SQL Server installed then the path will be different.

Answer:
This is kind of clunky, but a quick check of the registry seems to work.  Under HKEY_CLASSES_ROOT, a large number of classes from the SMO assemblies will be registered.  All I needed to do was to pick one of the SMO classes and check for the existence of the key with the same name.  The following function will return true if SMO has been installed, false if otherwise.
```
```
private bool CheckForSmo()
{
    string RegKeyName = @"Microsoft.SqlServer.Management.Smo.Database";
    bool result = false;
    Microsoft.Win32.RegistryKey hkcr = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(RegKeyName);
    result = hkcr != null;

    if (hkcr != null)
    {
        hkcr.Close();
    }

    return result;
}
```
```


Question:
class Foo
{
   static bool Bar(Stream^ stream);
};

class FooWrapper
{
   bool Bar(LPCWSTR szUnicodeString)
   {
       return Foo::Bar(??);
   }
};

MemoryStream will take a byte[] but I'd like to do this without copying the data if possible.

Answer:
If I had to copy the memory, I think the following would work:
```
```
static Stream^ UnicodeStringToStream(LPCWSTR szUnicodeString)
{
   //validate the input parameter
   if (szUnicodeString == NULL)
   {
      return nullptr;
   }

   //get the length of the string
   size_t lengthInWChars = wcslen(szUnicodeString);
   size_t lengthInBytes = lengthInWChars * sizeof(wchar_t);

   //allocate the .Net byte array
   array^ byteArray = gcnew array(lengthInBytes);

   //copy the unmanaged memory into the byte array
   Marshal::Copy((IntPtr)(void*)szUnicodeString, byteArray, 0, lengthInBytes);

   //create a memory stream from the byte array
   return gcnew MemoryStream(byteArray);
}
```
```


Question:
We have a client that has Oracle Standard, and a project that would be ten times easier addressed using OLAP. However, Oracle only supports OLAP in the Enterprise version.

Migration to enterprise is not possible

I'm thinking of doing some manual simulation of OLAP, creating relational tables to simulate the technology.

Do you know of some other way I could do this? Maybe an open-source tool for OLAP? Any ideas?

Answer:
I find that it's the schema that causes most of the issues people have with querying a database.  OLAP forces you to either a flat table or a Star/snowflake schema which is easy to query and comparably faster to the source oltp tables.   So if you ETL your source to a flat table or star schema you should get 80% of what you get from OLAP, the 20% being MDX and analytic functions and performance.
Note that you should get a perf boost with a star schema in relational database as well and Oracle probably has analytic functions in PL/SQL anyways.


Question:
I've started working with ASP.net AJAX (finally ☺). and I've got an update panel together with a asp:UpdateProgress. My Problem: The UpdateProgress always forces a line-break, because it renders out as a div-tag.

Is there any way to force it being a span instead? I want to display it on the same line as some other controls without having to use a table or even shudders absolute positioning in CSS.

I'm stuck with ASP.net AJAX 1.0 and .net 3.0 if that makes a difference.

Answer:
You can make a div inline like this:
```
```

stuff

```
```
I'm skeptical of it rendering the div for you though...  I don't remember having this problem on my pages...


Question:
I have a C# singleton class that multiple classes use. Is access through Instance to the Toggle() method thread-safe? If yes, by what assumptions, rules, etc. If no, why and how can I fix it?

public class MyClass
{
    private static readonly MyClass instance = new MyClass();

    public static MyClass Instance
    {
        get { return instance; }
    }

    private int value = 0;

    public int Toggle()
    {
        if(value == 0)
        {
            value = 1;
        }
        else if(value == 1)
        {
            value = 0;
        }

        return value;
    }
}

Answer:
Quote:
```
```
if(value == 0) { value = 1; }
if(value == 1) { value = 0; }
return value;
```
```
```
value
```
will always be 0...


Question:
Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.

[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]

Becomes:

[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]

Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?

Answer:
Here it is in C#
```
```
int[,] array = new int[4,4] {
    { 1,2,3,4 },
    { 5,6,7,8 },
    { 9,0,1,2 },
    { 3,4,5,6 }
};

int[,] rotated = RotateMatrix(array, 4);

static int[,] RotateMatrix(int[,] matrix, int n) {
    int[,] ret = new int[n, n];

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            ret[i, j] = matrix[n - j - 1, i];
        }
    }

    return ret;
}
```
```


Question:
Looking for an example that:

Launches an EXE

Waits for the EXE to finish.

Properly closes all the handles when the executable finishes.

Answer:
There is an example at
http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx
Just replace the
```
argv[1]
```
with your constant or variable containing the program.
```
```
#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }

    // Start the child process.
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    )
    {
        printf( "CreateProcess failed (%d).\n", GetLastError() );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles.
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}
```
```


Question:
I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?

Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):

The [below] code does NOT make a
  connection or send any packets (to
  64.233.187.99 which is google). Since UDP is a stateless protocol connect()
  merely makes a system call which
  figures out how to route the packets
  based on the address and what
  interface (and therefore IP address)
  it should bind to. addr() returns an
  array containing the family (AF_INET),
  local port, and local address (which
  is what we want) of the socket.

Answer:
try:
Request.remote_ip
remote_ip()
Determine originating IP address. REMOTE_ADDR is the standard but will
  fail if the user is behind a proxy. HTTP_CLIENT_IP and/or
  HTTP_X_FORWARDED_FOR are set by proxies so check for these if
  REMOTE_ADDR is a proxy. HTTP_X_FORWARDED_FOR may be a comma- delimited
  list in the case of multiple chained proxies; the last address which
  is not trusted is the originating IP.
Update:
Oops, sorry I misread the documentation.


Question:
The Python docs say:

re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string...

So what's going on when I get the following unexpected result?

>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'

Answer:
Look at the definition of
```
re.sub
```
:
```
```
re.sub(pattern, repl, string[, count, flags])
```
```
The 4th argument is the count, you are using
```
re.MULTILINE
```
(which is 8) as the count, not as a flag.
Either use a named argument:
```
```
re.sub('^//', '', s, flags=re.MULTILINE)
```
```
Or compile the regex first:
```
```
re.sub(re.compile('^//', re.MULTILINE), '', s)
```
```


Question:
I know you can use several different view engines with ASP.NET MVC:

ASPX, obviously

NVelocity

Brail

NHaml

et al...

The default ASPX view engine seems to make the most sense to me, coming from an ASP.NET WebForms background.

But, I wanted to get an idea of the pros and cons of each and see what most people are using.

Which does StackOverflow use?

Answer:
Most people on the planet will just use ASPX because that's what they know.  Another excellent benefit is the compiled-nature... so you not only get type-safety and intellisense, but you can get the perf benefit as well.
The drawback that I see is that it's so flippin' verbose.  I converted an app to NVelocity and was astounded at how clean it looked.  The problem is that there were a lot of things that didn't work with NVelocity (like your own custom view helpers) and there was a severe lack of documentation.
I added a feature to MvcContrib where you can register your own HtmlExtension types to it, but it's more of a bandaid until a better solution comes out.


Question:
I have heard/read the term but don't quite understand what it means.

When should I use this technique and how would I use it? Can anyone provide a good code sample?

Answer:
The visitor pattern is a way of doing double-dispatch in an object-oriented way.
It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time.
Double dispatch is a special case of
multiple dispatch
.
When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object.
For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time.
In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.
Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters.
To do double-dispatch in C#
, you can declare a method with a sole object argument and then specific methods with specific types:
```
```
using System.Linq;

class DoubleDispatch
{
    public T Foo<T>(object arg)
    {
        var method = from m in GetType().GetMethods()
                   where    m.Name == "Foo"
                         && m.GetParameters().Length==1
                         && arg.GetType().IsAssignableFrom
                                           (m.GetParameters()[0].GetType())
                         && m.ReturnType == typeof(T)
                   select m;

        return (T) method.Single().Invoke(this,new object[]{arg});
    }

    public int Foo(int arg) { /* ... */ }

    static void Test()
    {
        object x = 5;
        Foo<int>(x); //should call Foo(int) via Foo<T>(object).
    }
}
```
```


Question:
How am I supposed to get the IDENTITY of an inserted row?

I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY, but don't understand the implications or impacts attached to each.

Can someone please explain the differences and when I would be using each?

Answer:
From MSDN
@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.
@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.
IDENT_CURRENT is a function which takes a table as a argument.
@@IDENTITY may return confusing result when you have an trigger on the table
SCOPE_IDENTITY is your hero most of the time.


Question: Generally the database server is the biggest, most expensive box we have to buy as scaling vertically is the only option.  Are there any databases that scale well horizontally (i.e. across multiple commodity machines) and what are the limitations in this approach?

Answer:
There are storage techniques such as JavaSpaces (or a commercial implementation such as Gigaspaces) which provide highly scalable, fast & secure access to objects.
There are also distributed cacheing systems such as memcached, which offer a similar approach.
Of course, neither of these are true databases, but they are things that can work in conjunction with databases to offer a large amount of horizontal scalability, given a suitable architecture.  The real problem is that if you want all of the ACID goodness that comes with a database, there are certain unavoidable performance penalties. The only way out is to figure out the bits where you don't need ACID, and use other technologies to service those bits.


Question:
What would be the best way to do an scp or sftp copy in a Unix environment using C?

I'm interested in knowing the best library to use and an example if at all possible. I'm working on a Solaris server with the Sun tools installed.

Answer:
In the past, I've simply called a shell script that contained the file transfer code.
```
```
int transferFile()
{
  // Declare the transfer command
  char transferCommand[50] = "/home/tyler/transferFile.shl";
  // Execute the command
  return system(transferCommand);
}
```
```
This will return 1 if the transfer command returns successfully.


Question:
What's the best way to get user input in a C program where the choices are of a limited number?

Say for example the choices are:

A) Print the list.
B) Add 99 to the end of the list.
C) Delete all duplicates.
5) Reset 5 times.

Entering "A" and then Enter is OK.
Or, just a single keystroke would work as well.

Answer:
I have used something simple like the following:
```
```
int intput()
{
    char input = 0;
    int ret_val = 0;

    read(0, &input, 1);

    switch(input) {
        case 'c':
            // Do c
            break;

        case 'p':
            // Do p
            break;

        case 'd':
            // Do d
            break;

        case 'q':
            quit = 1;
            break;

        case '?':
            PRINT(ENABLE, "c - connect\n");
            PRINT(ENABLE, "p - ping\n");
            PRINT(ENABLE, "d - disconnect\n");
            PRINT(ENABLE, "q - quit\n");
            PRINT(ENABLE, "? - this message\n");
            break;
    }

    return 0;
}
```
```


Question:
Here is some code I could not get to format properly in markdown, this is straight C code, pasted into the text box with the '4 spaces' format to denote code:

#define PRINT(x, format, ...) \
if ( x ) { \
    if ( debug_fd != NULL ) { \
        fprintf(debug_fd, format, ##__VA_ARGS__); \
    } \
    else { \
        fprintf(stdout, format, ##__VA_ARGS__); \
    } \
}

It seems as though the '\' causes the newlines to be ignored.  Ok fine, I am used to this in bash, but if I put '\' the second one doesn't show up.  As if the second one is absorbed.   Am I missing something?

Answer:
Add at least four spaces or a hard tab before each line of the code. Like this:
```
```
#define PRINT(x, format, ...) \
if ( x ) { \
    if ( debug_fd != NULL ) { \
        fprintf(debug_fd, format, ##VA_ARGS); \
} \
else { \
    fprintf(stdout, format, ##VA_ARGS); \
} \
}
```
```


Question: Does anyone know how many options a drop down list can have? Is it unlimited?  How many before performance degrades?

Answer:
Does anyone know how many options a drop down list can have? Is it unlimited?
I imagine it is unlimited in theory, obviously not in practice as a computer's RAM and the specific browser's limitations come into play.
How many before performance degrades?
Again, this would depend on a few factors, at the least the specific browser, the computer's memory and processing power.
EDIT: From experience, I have had drop down lists with thousands of options. It wasn't ideal though because who wants to scroll through all of those? This is why an auto-complete of some type is more desirable for numerous reasons, especially the end user's experience.


Question: I'm using Ctrl+Left / Ctrl+Right in a GreaseMonkey script as a hotkey to turn back / forward pages. It seems to works fine, but I want to disable this behavior if I'm in a text edit area. I'm trying to use document.activeElement to get the page active element and test if it's an editable area, but it always returns "undefined".

Answer:
document.activeElement works for me in FF3 but the following also works
```
```
(function() {

var myActiveElement;
document.onkeypress = function(event) {
    if ((myActiveElement || document.activeElement || {}).tagName != 'INPUT')
        // do your magic
};
if (!document.activeElement) {
    var elements = document.getElementsByTagName('input');
    for(var i=0; i<elements.length; i++) {
        elements[i].addEventListener('focus',function() {
            myActiveElement = this;
        },false);
        elements[i].addEventListener('blur',function() {
            myActiveElement = null;
        },false);
    }
}

})();
```
```


Question: Do you have any strategies for retrofitting unit tests onto a code base that currently has no unit tests ?

Answer:
Read
Working Effectively With Legacy Code by Feathers
.
Jimmy Bogard has a
good blog series on SOC
.


Question: How can I get the MAC Address using only the compact framework?

Answer:
Add a reference to System.Management.dll and use something like:
```
```
Dim mc As System.Management.ManagementClass
Dim mo As ManagementObject
mc = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim moc As ManagementObjectCollection = mc.GetInstances()
For Each mo In moc
    If mo.Item("IPEnabled") = True Then
        ListBox1.Items.Add("MAC address " & mo.Item("MacAddress").ToString())
    End If
Next
```
```


Question: Anyone know a good book or post about how to start in EF? I have seen the DnrTV any other place?

Answer:
Mike Taulty's Blog:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/category/1024.aspx
A great EF intro deck:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/03/13/10235.aspx
And these ADO.NET Data Services screencasts are nice too:
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/01/25/10152.aspx
ADO.NET Entity Framework MSDN:
http://msdn.microsoft.com/en-us/library/bb399572.aspx
ADO.NET Entity Framework forums:
http://forums.microsoft.com/msdn/ShowForum.aspx?ForumID=533&SiteID=1
ADO.NET team blog:
http://blogs.msdn.com/adonet/archive/tags/Entity+Framework/default.aspx
Programming LINQ and the ADO.NET Entity Framework Webcast:
http://blogs.msdn.com/adonet/archive/2008/01/28/programming-linq-and-the-ado-net-entity-framework-webcast.aspx


Question:
I'm using the AutoComplete control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox.

I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work.  If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click.

Is there a special place I need to set the focus or something else I need to do to make this work?  Thanks.

Answer:
We had exactly the same problem.  What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox.  You can have a look at the (terribly hacky) solution here:
http://www.drive.com.au
The textbox id is
```
MainSearchBox_SearchTextBox
```
.  Have a look at about line 586 & you can see where I'm wiring up all the events (I'm actually using prototype for this bit.
Basically on the focus event of the textbox I set a global var called
```
textBoxHasFocus
```
to true and on the blur event I set it to false.  The on the load event of the page I call this script:
```
```
if (textBoxHasFocus) {
    $get("MainSearchBox_SearchTextBox").blur();
    $get("MainSearchBox_SearchTextBox").focus();
}
```
```
This resets the textbox.  It's really dodgy, but it's the only solution I could find


Question:
Of course the best metric would be a happiness of your users.

But what metrics do you know for GUI usability measurements?

For example, one of the common metrics is a average click count to perform action.
What other metrics do you know?

Answer:
Jakob Nielsen has several articles regarding usability metrics, including one that is entitled, well,
Usability Metrics
:
The most basic measures are based on the definition of usability as a quality metric:
success rate (whether users can perform the task at all),
the time a task requires,
the error rate, and
users' subjective satisfaction.


Question:
Is there any benefit in using a <blockquote> element over a <div>? I was looking at a website's markup to learn CSS and I couldn't figure out why the <blockquote> was being used.

EDIT: Yeah sorry I didn't clarify, it was used to hold the <div> tag with username as 'text' and an input tag. There was clearly no quote.

Answer:
Semantically, a
```
blockquote
```
tag makes sense when you're quoting something.  Sure, a stylized div can do the same thing, but why not use the right tag for the job?
Additionally, the blockquote tag allows you to include a citation with the
```
cite
```
attribute.


Question:
What database should a beginner use in the C language?

Can I use MySQL?

Thanks

Answer:
You can use SQLite, MySQL, PostgreSQL, or any other DBMS with a C language binding.
SQLite In 5 Minutes Or Less
MySQL C API
PostgreSQL C API


Question:
In one of my applications I have a 1gb database table that is used for reference data. It has a huge amounts of reads coming off that table but there are no writes ever. I was wondering if there's any way that data could be loaded into RAM so that it doesn't have to be accessed from disk?

I'm using SQL Server 2005

Answer:
You're going to want to take a look at memcached. It's what a lot of huge (and well-scaled) sites used to handle problems just like this. If you have a few spare servers, you can easily set them up to keep most of your data in memory.
http://en.wikipedia.org/wiki/Memcached
http://www.danga.com/memcached/
http://www.socialtext.net/memcached/


Question:
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn't support that, does the dateutil package support this?

Answer:
EDIT: See @Blair Conrad's answer for a cleaner solution
```
```
>>> import datetime
>>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
datetime.date(2000, 1, 31)
```
```


Question: What would be the best way to develop a text box that remembers the last x number of entries that were put into it.  This is a standalone app written with C#.

Answer:
This is actually fairly easy, especially in terms of showing the "AutoComplete" part of it.  In terms of remembering the last x number of entries, you are just going to have to decide on a particular event (or events) that you consider as an entry being completed and write that entry off to a list... an AutoCompleteStringCollection to be precise.
The TextBox class has the 3 following properties that you will need:
AutoCompleteCustomSource
AutoCompleteMode
AutoCompleteSource
Set AutoCompleteMode to SuggestAppend and AutoCompleteSource to CustomSource.
Then at runtime, every time a new entry is made, use the Add() method of AutoCompleteStringCollection to add that entry to the list (and pop off any old ones if you want).  You can actually do this operation directly on the AutoCompleteCustomSource property of the TextBox as long as you've already initialized it.
Now, every time you type in the TextBox it will suggest previous entries :)
See this article for a more complete example:
http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx
AutoComplete also has some built in features like FileSystem and URLs (though it only does stuff that was typed into IE...)


Question: Does anyone know how to setup Mercurial to use p4merge as the merge/diff tool on OS X 10.5?

Answer:
I'm guessing there's a CLI tool for p4merge (which I know nothing about).
I wrote a blog post about using Changes.app, and some other GUI tools with Mercurial:
Using Mercurial with GUI Tools.
Basically, you need to know the calling expectations of the CLI tool that loads up the diff tool.  IE, how to make it load data from a particular file, and how to make it wait for exit.  There should be enough info on the post to give you some ideas.


Question:
I'm behind a firewall at work at the moment and I was testing something that I had deployed to my website, and the work proxy seems to be blocking it somewhat.

Basically I am getting a message of:

Operation is not valid due to the current state of the object

I've got it down to my proxy interferring, but I can't see any advanced settings or anything I can set up to go through my proxy to get to my service.

I did a quick google for it, but no joy.

Anyone found a quick way to get around it?

Answer:
Edit, I forgot to write this part in the answer: You may need to add the web reference url to the safe list for your proxy.  I am not sure what proxy you are using or if you have control of it, but this should solve your problem.  If you don't have access to change the proxy, then I put a quick work around right below.
Here's a quick work around, just use the browser to navigate to the WSDL.  Grab the xml and save it as a .wsdl file on your computer you would like to generate the client on.  Then use the
wsdl.exe
to generate the client pointing it to the path you saved the wsdl file.


Question:
I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.

Example:

// Updated to be correct, thanks @Apocalisp
^foo.*(?<!bar)$

Should match anything that starts with "foo" and doesn't end with "bar".  I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters.

I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too.

Thanks to @Kibbee for verifying that this works in C# as well.

Answer:
I'm not familiar with Java regex but documentation for the
Pattern Class
would suggest you could use (?!X) for a non-capturing zero-width negative lookahead (it looks for something that is not X at that postision, without capturing it as a backreference). So you could do:
```
```
foo.*(?!bar) // not correct
```
```
Update
: Apocalisp's right, you want negative lookbehind. (you're checking that what the .* matches doesn't end with bar)


Question:
Starting a new project and would like to use one of the MVC framworks.  ASP.NET MVC is still in preview but Spring.net is in production and has a history with Java.  I'd like to know the general lowdown between the two.

Current questions..

What are the major feature differences?

What about deployment/hosting issues?

Future support? Do you think Spring.net will fade once ASP.NET MVC is in production.

Current Support?  I saw the Jeff twitting about a breaking change in the next preview.

Thanks!

Answer:
I am a little confused by the question.  Spring.Net is a dependency injection framework that you can use in ASP.NET MVC.  I kind of based my answer off what you are actually asking though.  The difference between ASP.NET MVC and another MVC framework that runs in ASP.NET.
If you are worried about using ASP.NET MVC in production since it is not even in beta yet, then you may want to check out
MonoRail
as an alternate.  There are some differences in features, but the two are pretty close in terminology and how MVC is implemented.  To learn differences,
here is a question
that was posted, that you might want to monitor.  I think once ASP.NET hits release, that most Microsoft shops will switch to it.  With ASP.NET MVC still being developed, you will run into breaking changes that you will have to change when you upgrade to the next release.  That goes with the territory of living on the edge.  You just need to read the release notes before jumping to the latest release.


Question:
I have upgraded a MS Visual Studio Application from VS 2003 to VS 2008 (Targeting .NET 2.0). As part of the conversion process the wizard said I needed to take the additional step of Converting my Project to a Website by Right-Clicking and blah blah blah...

I didn't follow directions and the web application seems to be working fine.

My question is, should I be concerned about pushing this to a production system? What exactly is going on here?

Answer:
There are two types of web applications in ASP.NET: The Web Site and Web Application Project. The difference between the two are discussed here:
Difference between web site and web applications in Visual Studio 2005
Convert to Website allows you to convert a Web Application Project to a Web Site.
Visual Studio 2003 used the Web Application Project style, but initially VS2005 only supported web sites. VS2005 SP1 brought back Web Applications.
If you don't want to convert your project to a web site, apply SP1 if you're using VS2005. VS2008 can support either.


Question:
I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc.

I've found solutions to this problem but they rely on alternative color palettes than RGB.
I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors.

Any ideas would be great.

Answer:
you could have them be within a certain brightness. that would control the ammount of "neon" colors a bit. for instance, if the "brightness"
```
```
brightness = sqrt(R^2+G^2+B^2)
```
```
was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black.


Question:
I have a self referencing Categories table. Each Category has a CategoryID, ParentCategoryID, CategoryName, etc. And each category can have any number of sub categories, and each of those sub categories can have any number of sub categories, and so and and so forth. So basically the tree can be X levels deep.

Then Products are associated to leaf (sub) Categories. Is there a way to get all the Products for any given Category (which would be all the products associated to all its leaf descendants) using LINQ to SQL?

This feels like a recursive problem. Is it better to used a Stored Procedure instead?

Answer:
Well here is a terrible rushed implementation using LINQ.
Don't use this :-)
```
```
public IQueryable GetCategories(Category parent)
{
    var cats = (parent.Categories);
    foreach (Category c in cats )
    {
        cats  = cats .Concat(GetCategories(c));
    }
    return a;
}
```
```


Question:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

Answer:
I think
```
```
var castList = list.Cast<typeof(T)>();
```
```
should be
```
```
var castList = list.Cast<T>();
```
```
@Jon Limjap The most glaring error I can see is
  that an
```
IList
```
is definitely different from an
```
IList<T>
```
. An
```
IList
```
is non-generic
  (e.g.,
```
ArrayList
```
).
The original question was already using an
```
IList<T>
```
. It was removed when someone edited the formatting. Probably a problem with Markdown.
Fixed now.


Question:
Simple question, but one that I've been curious about...is there a functional difference between the following two commands?

String::class
String.class

They both do what I expect -- that is to say they return Class -- but what is the difference between using the :: and the .?

I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after :: but not after ., but I don't know what the reason for this is...

Answer:
The
```
.
```
operator basically says "send this message to the object". In your example it is calling that particular member. The
```
::
```
operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator.
When you use
```
::
```
you have to be referencing members that are defined. When using
```
.
```
you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for
```
.
```
while it does for
```
::
```
.


Question:
I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer).

So, given an InputStream in and an OutputStream out, is there a simpler way to write the following?

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
}

Answer:
I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.
```
```
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}
```
```


Question:
I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.

However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.

Does anybody have any ideas for resolving this?

Answer:
If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work.
You could also do this in your Page_Load (In your masterpage):
```
```
Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js"))
```
```


Question: Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)

Answer:
OK, here's my best pseudo math:
The equation for your line is:
Y = a + bX
Where:
b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n)
a = sum(y)/n - b(sum(x)/n)
Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :)
... and now with added Sigma
b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n)
a = (Σy)/n - b((Σx)/n)
Where Σ(xy) is the sum of all x*y etc. and n is the number of points


Question:
Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure?

For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it.

SQL Server 2005 is my only applicable limitation I think.

create procedure getDepartments
  @DepartmentIds varchar(max)
as
  declare @Sql varchar(max)
  select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')'
  exec(@Sql)

Answer:
Yeah, your current solution is prone to SQL injection attacks.
The best solution that I've found is to use a function that splits text into words (there are a few posted here, or you can use
this one from my blog
) and then join that to your table. Something like:
```
```
SELECT d.[Name]
FROM Department d
    JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId
```
```


Question: Can we have the database and transaction logs on the same drive? What will be its consequences if it is not recommended?

Answer:
The only downside is that it causes more thrashing on the disk, so worse performance.
A single write will require 2 seeks (between: write transaction log, write data, commit log). Having the transaction log on a separate disk means as few as zero seeks, because the drive heads can remain on the transaction log and the data.


Question:
How can I do this fast?

Sure I can do this:

static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
    if (a1.Length != a2.Length)
        return false;

    for (int i=0; i<a1.Length; i++)
        if (a1[i]!=a2[i])
            return false;

    return true;
}

But I'm looking for either a BCL function or some highly optimized proven way to do this.

java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2);

works nicely, but it doesn't look like that would work for x64.

Note my super-fast answer here.

Answer:
I would use unsafe code and run the
```
for
```
loop comparing Int32 pointers.
Maybe you should also consider checking the arrays to be non-null.


Question:
In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code?

What I need is to create a list of menu items where each item has name, URL, and an active flag  (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language.

Answer:
If you need to use something similar to the
```
{% url %}
```
template tag in your code, Django provides the
```
django.core.urlresolvers.reverse()
```
. The
```
reverse
```
function has the following signature:
```
```
reverse(viewname, urlconf=None, args=None, kwargs=None)
```
```
https://docs.djangoproject.com/en/dev/ref/urlresolvers/
At the time of this edit the import is
```
django.urls import reverse
```


Question:
I know that I can do something like

$int = (int)99; //(int) has a maximum or 99

To set the variable $int to an integer and give it a value of 99.

Is there a way to set the type to something like LongBlob in MySQL for LARGE Integers in PHP?

Answer:
No. PHP does what is called automatic type conversion.
In your example
```
```
$int = (int)123;
```
```
the "(int)" just assures that at that exact moment 123 will be handled as an int.
I think your best bet would be to use a class to provide some sort of type safety.


Question: Using PyObjC, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?

Answer:
Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift.
There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term.
That said, Objective-C and Swift really are not too scary...
2016 edit
Javascript with NativeScript framework is available to use now.


Question:
I know that default cron's behavior is to send normal and error output to cron's owner local email box.

Is there other ways to get theses results (for example to send it by email to a bunch of people, to store them somewhere, and so on) ?

Answer:
The cron line is just like any other unix command line so you can redirect output to another program. Ie.
```
```
* * * * * /path/my/command > /my/email/script 2&>1
```
```


Question: For example, I issued an ALTER TABLE statement to create an index on a MEDIUMTEXT field in an InnoDB table that has 134k rows where the size of the index was 255 bytes and the average size of the data in the field is 30k.  This command has been running for the last 15 minutes or so (and is the only thing running on the database).  Is there any way for me to determine if it is going to finish in closer to 5 minutes, 5 hours, or 5 days?

Answer:
This is a pretty common request apparently - requested as far back as 2005 on
bugs.mysql.com
.
It exists in Oracle already, and is listed as useful, but
"it is not a simple thing to do, so don't expect it to be
implemented soon."
. Although that was 2005 :)
That said, the chap who asked the original question later released a
patch
for MySQL 5.0, backported to 4.1, which might help you out.


Question:
Say I have a site on http://example.com. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words

http://example.com & http://example.com/ should be allowed, but
http://example.com/anything and http://example.com/someendpoint.aspx should be blocked.

Further it would be great if I can allow certain query strings to passthrough to the home page:
http://example.com?okparam=true

but not
http://example.com?anythingbutokparam=true

Answer:
Basic robots.txt:
```
```
Disallow: /subdir/
```
```
I don't think that you can create an expression saying 'everything but the root', you have to fill in all sub directories.
The query string limitation is also not possible from robots.txt. You have to do it in the background code (the processing part), or maybe with server rewrite-rules.


Question:
I know 'best' is subjective, so according to you, what is the best solution for the following problem:

Given a string of length n (say "abc"), generate all proper subsets of the string. So, for our example, the output would be {}, {a}, {b}, {c}, {ab}, {bc}, {ac}. {abc}.

What do you think?

Answer:
```
```
def subsets(s):
    r = []
    a = [False] * len(s)
    while True:
        r.append("".join([s[i] for i in range(len(s)) if a[i]]))
        j = 0
        while a[j]:
            a[j] = False
            j += 1
            if j >= len(s):
                return r
        a[j] = True

print subsets("abc")
```
```


Question:
When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during wm_close - is DestroyHandle the .net equivalent?

I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg:

void Dispose(bool disposing) {
    otherObject.Event -= myEventHandler;
}

Answer:
Normally
```
DestroyHandle
```
is being called in
```
Dispose
```
method. So you need to make sure that all controls are disposed to avoid resource leaks.


Question:
Is there a way to detect if a flash movie contains any sound or is playing any music?

It would be nice if this could be done inside a webbrowser (actionscript from another flash object, javascript,..) and could be done before the flash movie starts playing.

However, I have my doubts this will be possible altogether, so any other (programmable) solution is also appreciated

Answer:
Yes, on the server side for sure.  Client side?  I don't know.  (I'm a serverside kind of guy.)
On the server side, one would have to parse the file, read the header and/or look for audio frames.  (I've ported a haskel FLV parser to Java for indexing purposes myself, and there are other parsing utilities out there.  It is possible.)
osflash.org's FLV page
has the gory details.  Check out the FLV Format sections's FLV Header table.
```
```
FIELD       DATA TYPE      EXAMPLE                  DESCRIPTION
 Signature   byte[3]        “FLV”                    Always “FLV”
 Version     uint8          “\x01” (1)               Currently 1 for known FLV files
 Flags       uint8 bitmask  “\x05” (5, audio+video)  Bitmask: 4 is audio, 1 is video
 Offset      uint32-be      “\x00\x00\x00\x09” (9)   Total size of header (always 9 for known FLV files)
```
```
EDIT: My client side coding with Flash is non-existent, but I believe there is an onMetaDataLoad event that your code could catch.  That might be happening a bit late for you, but maybe it is good enough?


Question:
In the business I work for we are discussion methods to reduce the read load on our primary database.

One option that has been suggested is to have live one-way replication from our primary database to a slave database. Applications would then read from the slave database and write directly to the primary database. So...

Application Reads From Slave

Application Writes to Primary

Primary Updates Slave Automatically

What are the major pros and cons for this method?

Answer:
A few cons:
2 points of failure
Application logic will have to take into account the delay between writing something and then reading it, since it won't be available immediately from the secondary database
A strategy I have used is to send key reporting data to a secondary database nightly, de-normalizing it on the way, so that beefy queries can run on that database instead of locking up tables and stealing resources from the OLTP server.  I'm not using any formal data warehousing or replication tools, rather I identify problem queries that are Ok without up-to-the-minute data and create data structures on the secondary server specifically for those queries.
There are definitely pros to the "replicate everything" approach:
You can run any ad-hoc query on the secondary, since it has all of your data
If your primary server dies, you can re-purpose the secondary quickly to take over


Question: Older versions of the .Net Framework used to install "Microsoft .NET Framework v1.0 / v1.1 / v2.0 Configuration" in the Control Panel, under Administrative Tools. I just noticed that there isn't a v3.0 or v3.5 version of this. Is this functionality now hiding somewhere else, or do I have to use the command-line tools instead?

Answer:
Both 3 and 3.5 still use the
Common Language Runtime of .NET Framework 2.0
. So no control panel is needed, as you can still use the 2.0 control panel.