Question:
I have a local mercurial repository with some site-specific changes in it.  What I would like to do is set a couple files to be un-commitable so that they aren't automatically committed when I do an hg commit with no arguments.

Right now, I'm doing complicated things with mq and guards to achieve this, pushing and popping and selecting guards to prevent my changes (which are checked into an mq patch) from getting committed.

Is there an easier way to do this?  I'm sick of reading the help for all the mq commands every time I want to commit a change that doesn't include my site-specific changes.

Answer:
I would put those files in
```
.hgignore
```
and commit a "sample" form of those files so that they could be easily recreated for a new site when someone checks out your code.


Question:
Our clients will be uploading images to be printed on their documents and we have been asked to come up with a way to get the resolution of the image in order to warn them if the image has too low of a resolution and will look pixalated in the end-product

If it comes to it we could also go with the dimensions if anyone knows how to get those but the resolution would be preferred

Thank you

Answer:
System.Drawing.Image
```
```
Image newImage = Image.FromFile("SampImag.jpg");
newImage.HorizontalResolution
```
```


Question:
What are the best places to find out everything there is to know about Domain-Driven Design, from beginner to advanced.

Books

Websites

Mailing lists

User groups

Conferences

etc

Answer:
Maybe read the book
Domain Driven Design
?


Question:
I've seen a few sites that list related searches when you perform a search, namely they suggest other search queries you may be interested in.

I'm wondering the best way to model this in a medium-sized site (not enough traffic to rely on visitor stats to infer relationships). My initial thought is to store the top 10 results for each unique query, then when a new search is performed to find all the historical searches that match some amount of the top 10 results but ideally not matching all of them (matching all of them might suggest an equivalent search and hence not that useful as a suggestion).

I imagine that some people have done this functionality before and may be able to provide some ideas of different ways to do this. I'm not necessarily looking for one winning idea since the solution will no doubt vary substantially depending on the size and nature of the site.

Answer:
Maybe read the book
Domain Driven Design
?


Question:
I'm writing by own blogging engine in PHP with a MYSQL backend database. MY question is: How would you go about making user comments and blog posts include newlines wherever they are appropriate?

For example, if a user hits the return key in the message/comments box how would this translate into a new line that would show in the browser when the comment is viewed?

Answer:
PHP has a function: nl2br which turns new lines into
```
<br />
```
www.php.net/nl2br


Question:
I'm writing a setup program to install an application to a USB drive. The application is meant to be used only from USB drives, so it would save an extra step for the user by automatically selecting USB drive to install to.

I might explore using Nullsoft or MSI for install, but since I'm mostly familiar with .NET I initially plan to try either custom .NET installer or setup component on .NET.

Is it possible to determine the drive letter of a USB flash drive on Windows using .NET? How?

Answer:
You could use:
```
```
from driveInfo in DriveInfo.GetDrives()
where driveInfo.DriveType == DriveType.Removable && driveInfo.IsReady
select driveInfo.RootDirectory.FullName
```
```


Question:
In python is it possible to get or set a logical directory (as opposed to an absolute one).

For example if I have:

/real/path/to/dir

and I have

/linked/path/to/dir

linked to the same directory.

using os.getcwd and os.chdir will always use the absolute path

>>> import os
>>> os.chdir('/linked/path/to/dir')
>>> print os.getcwd()
/real/path/to/dir

The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.

Answer:
The underlying operational system / shell reports real paths to python.
So, there really is no way around it, since
```
os.getcwd()
```
is a wrapped call to C Library
```
getcwd()
```
function.
There are some workarounds in the spirit of the one that you already know which is launching
```
pwd
```
.
Another one would involve using
```
os.environ['PWD']
```
. If that environmnent variable is set you can make some
```
getcwd
```
function that respects it.
The solution below combines both:
```
```
import os
from subprocess import Popen, PIPE

class CwdKeeper(object):
    def __init__(self):
        self._cwd = os.environ.get("PWD")
        if self._cwd is None: # no environment. fall back to calling pwd on shell
           self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip()
        self._os_getcwd = os.getcwd
        self._os_chdir = os.chdir

    def chdir(self, path):
        if not self._cwd:
            return self._os_chdir(path)
        p = os.path.normpath(os.path.join(self._cwd, path))
        result = self._os_chdir(p)
        self._cwd = p
        os.environ["PWD"] = p
        return result

    def getcwd(self):
        if not self._cwd:
            return self._os_getcwd()
        return self._cwd

cwd = CwdKeeper()
print cwd.getcwd()
# use only cwd.chdir and cwd.getcwd from now on.
# monkeypatch os if you want:
os.chdir = cwd.chdir
os.getcwd = cwd.getcwd
# now you can use os.chdir and os.getcwd as normal.
```
```


Question: What is the best way to encrypt an URL with parameters in Java?

Answer:
Are you sure you don't mean URL
encode
?
Encoding is available through
```
java.net.URLEncoder.encode
```
.


Question:
I have created a bunch of movie clips which all have similar names and then after some other event I have built up a string like:

var clipName = "barLeft42"

which is held inside another movie clip called 'thing'.

I have been able to get hold of a reference using:

var movieClip = Eval( "_root.thing." + clipName )

But that feels bad - is there a better way?

Answer:
Movie clips are collections in actionscript (like most and similar to javascript, everything is basically key-value pairs). You can index into the collection using square brackets and a string for the key name like:
```
```
_root.thing[ "barLeft42" ]
```
```
That should do the trick for you...


Question:
Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport)?

(The question refers to Firefox.)

Answer:
Update:
Time marches on and so have our browsers.
This technique is no longer recommended
and you should use
Dan's solution
if you do not need to support version of Internet Explorer before 7.
Original solution (now outdated):
This will check if the element is entirely visible in the current viewport:
```
```
function elementInViewport(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top >= window.pageYOffset &&
    left >= window.pageXOffset &&
    (top + height) <= (window.pageYOffset + window.innerHeight) &&
    (left + width) <= (window.pageXOffset + window.innerWidth)
  );
}
```
```
You could modify this simply to determine if any part of the element is visible in the viewport:
```
```
function elementInViewport2(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top < (window.pageYOffset + window.innerHeight) &&
    left < (window.pageXOffset + window.innerWidth) &&
    (top + height) > window.pageYOffset &&
    (left + width) > window.pageXOffset
  );
}
```
```


Question:
While most operating systems and web browsers have very good support for bidirectional text such as Hebrew and Arabic, most commercial and open-source software does not:

Most text editors, besides the original notepad and the visual studio editor, does a very poor job. (And I tried dozens of them).

I could not find any file compare tool doing a decent job - No even Beyond-Compare.

Same thing for software and packages dealing with charting and reporting.

Some questions I have:

Do you share the same pain I do?

Is the software you write bidirectional compliant? Do you have bug reports about it?

Do you even know what are the issues involved? Do you test for them?

Any suggestions on how to make the software world a better place for bidirectional language speakers?

Answer:
Do you share the same pain I do?
No.  And that's probably the answer: most people have no idea how bidirectional languages work.  I for example have some troubles working with that.  Because I'm interested in that topic quite a bit I was reading pango sources a while back, and that's probably the second reason why the support sucks: it's damn hard to get right.
I think the GNOME project has one of the best support for bidirectional user interfaces thanks to Pango (of course I can't verify that because I wouldn't be able to spot the problems).
But because you said "open source": I think the globalization support in open source projects is generally outstanding.  Linux sucks are pretty much everything, but internationalization is something they get right.
gettext is still one of the few translation systems that has a (I know half baked but) working pluralization system.
Is the software you write bidirectional compliant? Do you have bug reports about it?
Probably not.  I'm working on a web publishing software currently and that's one of the things I haven't tested at all so far :-(
Do you even know what are the issues involved? Do you test for them?
Bi-directional support is not no the direct roadmap.  So no tests for them, where the issues are I know from the translation interface I wrote for Plurk.
Any suggestions on how to make the software world a better place for bidirectional language speakers?
For an open source project: ask guys to help you that know where the issues are.  For closed source?  Hire someone who knows.


Question:
I have an SSIS package that copies the data in a table from one SQL Server 2005 to another SQL Server 2005.  I do this with a "Data Flow" task.  In the package config file I expose the destination table name.

Problem is when I change the destination table name in the config file (via notepad) I get the following error "vs_needsnewmetadata".  I think I understand the problem... the destination table column mapping is fixed when I first set up the package.

Question:  what's the easiest way to do the above with an ssis package?

I've read online about setting up the metadata programmatically and all but I'd like to avoid this.  Also I wrote a C# console app that does everything just fine... all tables etc are specified in the app.config ... but apparently this solution isn't good enough.

Answer:
If all you are doing is copying data from one SQL2005 server to another I would just create a Linked Server and use a stored proc to copy the data. An SSIS package is overkill.
How to Create  linked server
Once the linked server is created you would just program something like...
```
```
INSERT INTO server1.dbo.database1.table1(id,name)
SELECT id, name FROM server2.dbo.database1.table1
```
```
As far the SSIS package I have always had to reopen and rebuild the package so that the meta data gets updated when modifying the tables column properties.


Question:
Using MS SQL Server Management Studio 2005 - To Restore a Database:

Restore Database

(*) From Device:

Click "..."  Button

Backup media:  File

Click "Add" Button

Popup Window: "Locate Backup File"

That window Defaults to C:\Program Files\Microsoft SQL Server\MSSQL.1\Backup

How do I configure MS SQL Server Management Studio to look in D:\data\databases\

instead of looking in  C:\Program Files\Microsoft SQL Server\MSSQL.1\Backup ?

Answer:
In the registry, edit the
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer\BackupDirectory
```
value to point to
```
d:\data\databases
```


Question:
I recently converted a ruby library to a gem, which seemed to break the command line usability

Worked fine as a library

  $ ruby -r foobar -e 'p FooBar.question' # => "answer"

And as a gem, irb knows how to require a gem from command-line switches

  $ irb -rubygems -r foobar
  irb(main):001:0> FooBar.question # => "answer"

But the same fails for ruby itself:

  $ ruby -rubygems -r foobar -e 'p FooBar.question'
  ruby: no such file to load -- foobar (LoadError)

must I now do this, which seems ugly:

  ruby -rubygems -e 'require "foobar"; p FooBar.question' # => "answer"

Or is there a way to make the 2 switches work?

Note: I know the gem could add a bin/program for every useful method but I don't like to pollute the command line namespace unnecessarily

Answer:
-rubygems is actually the same as -r ubygems.
It doesn't mess with your search path, as far as I understand, but I think it doesn't add anything to your -r search path either. I was able to do something like this:
```
```
ruby -rubygems -r /usr/lib/ruby/gems/myhelpfulclass-0.0.1/lib/MyHelpfulClass -e "puts MyHelpfulClass"
```
```
MyHelpfulClass.rb exists in the lib directory specified above.
That kind of sucks, but it at least demonstrates that you can have multiple -r equire directives.
As a slightly less ugly workaround, you can add additional items to the ruby library search path (colon delimited in *nix, semicolon delimited in windows).
```
```
export RUBYLIB=/usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib
ruby -rubygems -r MyHelpfulClass -e "puts MyHelpfulClass"
```
```
If you don't want to mess with the environment variable, you can add something to the load path yourself:
```
```
ruby -I /usr/lib/ruby/gems/1.8/gems/myhelpfulclass-0.0.1/lib \
   -rubygems -r MyHelpfulClass -e "puts MyHelpfulClass"
```
```


Question:
I have a website (ASP.NET) and some winforms(.Net 2.0) for a project (written in C#). I use the webservice (IIS6) for task that both require like sending email inside the business.

I think Webservice is nice but I would like from your experience what should and what should not be in a webservice?

Answer:
Well it sounds like you have a limited Service Oriented Architecture (at least, that's what I think you're getting at), which according to Gartner means you'll be rich soon.  :)
I find that the benefit of SOA for me really comes down to the heterogeneity of the systems involved (sounds like yours doesn't qualify there because it's all .NET), and the negative of SOA is primarily because of the verbose nature of XML.  True, you don't
need
XML for SOA, but it's the current majority, IMHO.
But if you're not concerned about the bandwidth/parsing penalties, who cares?  Maybe you're not piping through 10,000 service calls a minute.  With this style of implementation, you're following
DRY
, just with a WS instead of a sub, and you're adhering to a standard that is by nature compatible with multiple systems.
There's worse approaches.


Question:
In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time.  In said languages, there are library classes to reduce this cost such as C# System.Text.StringBuilder and Java java.lang.StringBuilder.

Does php (4 or 5; I'm interested in both) share this limitation?  If so, are there similar solutions to the problem available?

Answer:
no such limitation in php,
php can concatenate strng with the dot(.) operator
```
```
$a="hello ";
$b="world";
echo $a.$b;
```
```
outputs "hello world"


Question:
When I use traceroute, I often see abbreviations in the hostnames along the route, such as "ge", "so", "ic", "gw", "bb" etc. I can guess "bb" means backbone.

Does anyone know what any these strings abbreviate, or know any other common abbreviations?

Answer:
These are ISO-3166-1 Alpha2 geographical domain id's converted to lower case.
ge - Georgia
gw - Guinea-Bisseau
so - Somalia
bb - Barbados
ic - old code for Iceland?
Just look for ISO-3166 for the complete list of country codes. And RFC 1700 for the geo domain list.
Can you please provide the output from one of your traceroutes?
Hostnames using components such as bb for backbone and gw for gateway tend to put those towards the start of a hostname, e.g. bb1.toto.com.au or gw2.wtf.co.uk.
This follows a naming convention of more specfic to less specific elements in the name as you traverse from left to right.
Geographical domains are, almost always, at the end of the hostname.


Question:
I'd like to slice and dice large datafiles, up to a gig, in a fairly quick and efficient manner.  If I use something like UNIX's "CUT", it's extremely fast, even in a CYGWIN environment.

I've tried developing and benchmarking various Ruby scripts to process these files, and always end up with glacial results.

What would you do in Ruby to make this not so dog slow?

Answer:
This question reminds me of Tim Bray's
Wide Finder project
. The fastest way he could read an Apache logfile using Ruby and figure out which articles have been fetched the most was with this script:
```
```
counts = {}
counts.default = 0

ARGF.each_line do |line|
   if line =~ %r{GET /ongoing/When/\d\d\dx/(\d\d\d\d/\d\d/\d\d/[^ .]+) }
     counts[$1] += 1
   end
end

keys_by_count = counts.keys.sort { |a, b| counts[b] <=> counts[a] }
keys_by_count[0 .. 9].each do |key|
    puts "#{counts[key]}: #{key}"
end
```
```
It took this code 7½ seconds of CPU, 13½ seconds elapsed, to process a million and change records, a quarter-gig or so, on last year’s 1.67Ghz PowerBook.


Question:
I tend to implement UI functionality using fairly self-documenting void doSomething() methods, i.e. if the user presses this button then perform this action then enable this list box, disable that button, etc. Is this the best approach? Is there a better pattern for general UI management i.e. how to control when controls are enabled/disabled/etc. etc. depending on user input?

Often I feel like I'm veering towards the 'big class that does everything' anti-pattern as so much seems to interact with the 'main' form class. Often, even if I'm including private state variables in the class that have been implemented using a relatively modular design, I'm still finding it grows so quickly it's ridiculous.

So could people give me some good advice towards producing quality, testable, decoupled WinForms design without falling into these traps?

Answer:
I would only put UI logic in the Form class and put any application logic in its own class:
```
```
class Form1 : Form
 {
    void Button1_Click
     {
       Program.DoCommand1();
     }
 }

static class Program
{
  internal static void DoCommand1() {/* ... */}
}
```
```


Question:
I am trying to mock-up an API and am using separate apps within Django to represent different web services. I would like App A to take in a link that corresponds to App B and parse the json response.

Is there a way to dynamically construct the url to App B so that I can test the code in development and not change to much before going into production? The problem is that I can't use localhost as part of a link.

I am currently using urllib, but eventually I would like to do something less hacky and better fitting with the web services REST paradigm.

Answer:
I would only put UI logic in the Form class and put any application logic in its own class:
```
```
class Form1 : Form
 {
    void Button1_Click
     {
       Program.DoCommand1();
     }
 }

static class Program
{
  internal static void DoCommand1() {/* ... */}
}
```
```


Question: We want to switch a web server from Windows 2003 to Windows 2003 Enterprise (64 bits) to use 8GB of RAM. Will IIS 6.0 and an ASPNET 1.1 application be able to benefit from the change?

Answer:
My understanding is that there was a virtual address space limitation of 3 GB in ASP.NET 1.1, and that it was never made 64 bit compatible, though 2.0 was.
You can get IIS 6.0 to run 32 bit (i.e. ASP.NET 1.1) on the 64 OS, but it will be in a 32 bit mode (along with anything else hosted, including ASP.NET 2.0 sites).
Microsoft article on switching between 32 bit and 64 bit


Question:
Imagine I have the folling XML file:

<a>before<b>middle</b>after</a>

I want to convert it into something like this:

<a>beforemiddleafter</a>

In other words I want to get all the child nodes of a certain node, and move them to the parent node in order. This is like doing this command: "mv ./directory/* .", but for xml nodes.

I'd like to do this in using unix command line tools. I've been trying with xmlstarlet, which is a powerful command line XML manipulator. I tried doing something like this, but it doesn't work

echo "<a>before<b>middle</b>after</a>" | xmlstarlet ed -m "//b/*" ".."

Update: XSLT templates are fine, since they can be called from the command line.

My goal here is 'remove the links from an XHTML page', in other words replace where the link was, with the contents of the link tag.

Answer:
In XSLT, you could just write:
```
```
<xsl:template match="a"><xsl:apply-templates /></xsl:template>

<xsl:template match="a/b"><xsl:value-of select="."/></xsl:template>
```
```
And you'd get:
```
```
beforemiddleafter
```
```
So if you wanted to do this the easy way you could just create an XSL stylesheet and run your XML file through that.
I realise this isn't what you said you'd like to do (using Unix command line), however. I don't know anything about Unix, so maybe someone else can fill in the blanks, eg. some sort of command line calls that can execute the above.


Question:
I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions.

What is the main reason of the difference between Java and C# in throwing exceptions?

In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.

Answer:
The basic design philosophy of C# is that actually catching exceptions is rarely useful, whereas cleaning up resources in exceptional situations is quite important. I think it's fair to say that
```
using
```
(the IDisposable pattern) is their answer to checked exceptions. See [1] for more.
http://www.artima.com/intv/handcuffs.html


Question:
Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue:

int i = 4;
...
if (i == 10)
  doStuff();

Later on you figure that you want the variable i to be either defined or undefined, so you change the above instantiation to:

Integer i = null;

Now the equality check fails.

Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?

Answer:
Firstly, switching from using a primitive to using an object just to get the ability to set it to null is probably a bad design decision.  I often have arguments with my coworkers about whether or not null is a sentinel value, and my opinion is usually that it is not (and thus shouldn't be prohibited like sentinel values should be), but in this particular case you're going out of your way to use it as a sentinel value.  Please don't.  Create a boolean that indicates whether or not your integer is valid, or create a new type that wraps the boolean and integer together.
Usually, when using newer versions of Java, I find I don't need to explicitly create or cast to the object versions of primitives because of the auto-boxing support that was added some time in 1.5 (maybe 1.5 itself).


Question:
I'm doing a sitemap producer in Object Pascal and need a good function or lib to emulate the parse_url function on PHP.

Does anyone know of any good ones?

Answer:
The
URI RFC
lists this regular expression for URI parsing:
```
```
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
   12            3  4          5       6  7        8 9
```
```
Where the numbers are these groups:
```
```
$1 = http:
  $2 = http
  $3 = //www.ics.uci.edu
  $4 = www.ics.uci.edu
  $5 = /pub/ietf/uri/
  $6 = <undefined>
  $7 = <undefined>
  $8 = #Related
  $9 = Related
```
```
For this URI:
```
```
http://www.ics.uci.edu/pub/ietf/uri/#Related
```
```
The regular expression is pretty simple and uses no special features the regular expression lib has to provide, so grab one that is compatible with your pascal implementation and there you go.


Question:
I'd be very grateful if you could compare the winning O’Rourke's Perl solution to Lundh's Python solution, as I don't know Perl good enough to understand what's going on there. More specifically I'd like to know what gave Perl version 3x advantage: algorithmic superiority, quality of C extensions, other factors?

Wide Finder: Results

Answer:
Perl is heavily optimized for text processing.  There are so many factors that it's hard to say what's the exact difference.  Text is represented completely differently internally (utf-8 versus utf-16/utf-32) and the regular expression engines are completely different too.  Python's regular expression engine is a custom one and not as much used as the perl one.  There are very few developers working on it (I think it's largely unmaintained) in contrast to the Perl one which is basically the "core of the language".
After all Perl is
the
text processing language.


Question:
I would like to do a lookup of tables in my SQL Server 2005 Express database based on table name. In MySQL I would use SHOW TABLES LIKE "Datasheet%", but in T-SQL this throws an error (it tries to look for a SHOW stored procedure and fails).

Is this possible, and if so, how?

Answer:
Try this :
```
```
select * from information_schema.columns
where table_name = 'yourTableName'
```
```
also look for other
```
information_schema
```
views.


Question: Been using PHP/MySQL for a little while now, and I'm wondering if there are any specific advantages (performance or otherwise) to using mysql_fetch_object() vs mysql_fetch_assoc() / mysql_fetch_array().

Answer:
Fetching an array with
```
mysql_fetch_array()
```
lets you loop through the result set via either a foreach loop or a for loop.
```
mysql_fetch_object()
```
cannot be traversed by a for loop.
Not sure if that even matters much, just thought I'd mention it.


Question:
What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this.

$sortedObjectArary = sort($unsortedObjectArray, $Object->weight);

Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might be something useful there, but I don't see anything elegant or obvious.

Answer:
Almost verbatim from the manual:
```
```
function compare_weights($a, $b) {
    if($a->weight == $b->weight) {
        return 0;
    }
    return ($a->weight < $b->weight) ? -1 : 1;
}

usort($unsortedObjectArray, 'compare_weights');
```
```
If you want objects to be able to sort themselves, see example 3 here:
http://php.net/usort


Question:
What is the simplest SOAP example using Javascript?

To be as useful as possible, the answer should:

Be functional (in other words actually work)

Send at least one parameter that can be set elsewhere in the code

Process at least one result value that can be read elsewhere in the code

Work with most modern browser versions

Be as clear and as short as possible, without using an external library

Answer:
Simplest example would consist of:
Getting user input.
Composing XML SOAP message similar to this
```
```
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema"
               xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetInfoByZIP xmlns="http://www.webserviceX.NET">
      <USZip>string</USZip>
    </GetInfoByZIP>
  </soap:Body>
</soap:Envelope>
```
```
POSTing message to webservice url using XHR
Parsing webservice's XML SOAP response similar to this
```
```
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
  <GetInfoByZIPResponse xmlns="http://www.webserviceX.NET">
   <GetInfoByZIPResult>
    <NewDataSet xmlns="">
     <Table>
      <CITY>...</CITY>
      <STATE>...</STATE>
      <ZIP>...</ZIP>
      <AREA_CODE>...</AREA_CODE>
      <TIME_ZONE>...</TIME_ZONE>
     </Table>
    </NewDataSet>
   </GetInfoByZIPResult>
  </GetInfoByZIPResponse>
 </soap:Body>
</soap:Envelope>
```
```
Presenting results to user.
But it's a lot of hassle without external JavaScript libraries.


Question:
I need to do some simple timezone calculation in mod_perl.  DateTime isn't an option.  What I need to do is easily accomplished by setting $ENV{TZ} and using localtime and POSIX::mktime, but under a threaded MPM, I'd need to make sure only one thread at a time was mucking with the environment.  (I'm not concerned about other uses of localtime, etc.)

How can I use a mutex or other locking strategy to serialize (in the non-marshalling sense) access to the environment?  The docs I've looked at don't explain well enough how I would create a mutex for just this use.  Maybe there's something I'm just not getting about how you create mutexes in general.

Update: yes, I am aware of the need for using Env::C to set TZ.

Answer:
If you're using apache 1.3, then you shouldn't need to resort to mutexes.  Apache 1.3 spawns of a number of worker processes, and each worker executes a single thread.  In this case, you can write:
```
```
{
    local $ENV{TZ} = whatever_I_need_it_to_be();

    # Do calculations here.
}
```
```
Changing the variable with
```
local
```
means that it reverts back to the previous value at the end of the block, but is still passed into any subroutine calls made from within that block.  It's almost certainly what you want.  Since each process has its own independent environment, you won't be changing the environment of other processes using this technique.
For apache 2, I don't know what model it uses with regards to forks and threads.  If it keeps the same approach of forking off processes and having a single thread each, you're fine.
If apache 2 uses honest to goodness real threads, then that's outside my area of detailed knowledge, but I hope another lovely stackoverflow person can provide assistance.
All the very best,
```
```
Paul
```
```


Question: Everything I have read says that when making a managed stored procedure, to right click in Visual Studio and choose deploy. That works fine, but what if I want to deploy it outside of Visual Studio to a number of different locations? I tried creating the assembly with the dll the project built in SQL, and while it did add the assembly, it did not create the procedures out of the assembly. Has anyone figured out how to do this in SQL directly, without using Visual Studio?

Answer:
Copy your assembly DLL file to the local drive on your various servers.  Then register your assembly with the database:
```
```
create assembly [YOUR_ASSEMBLY]
from '(PATH_TO_DLL)'
```
```
...then you create a function referencing the appropriate public method in the DLL:
```
```
create proc [YOUR_FUNCTION]
as
external name [YOUR_ASSEMBLY].[NAME_SPACE].[YOUR_METHOD]
```
```
Be sure to use the [ brackets, especially around the NAME_SPACE.  Namespaces can have any number of dots in them, but SQL identifiers can't, unless the parts are explicitly set apart by square brackets.  This was a source of many headaches when I was first using SQL CLR.
To be clear, [YOUR_ASSEMBLY] is the name you defined in SQL; [NAME_SPACE] is the .NET namespace inside the DLL where your method can be found; and [YOUR_METHOD] is simply the name of the method within that namespace.


Question:
So I'm using hibernate and working with an application that manages time.
What is the best way to deal with times in a 24 hour clock?

I do not need to worry about TimeZone issues at the beginning of this application but it would be best to ensure that this functionality is built in at the beginning.

I'm using hibernate as well, just as an fyi

Answer:
Store them as long ts = System.currentTimeMillis().
That format is actually TimeZone-safe as it return time in UTC.
If you only need time part, well, I'm not aware of built-in type in Hib, but writing your own type Time24 is trivial -- just implement either org.hibernate.UserType  or org.hibernate.CompositeUserType (load=nullSafeGet and store=nullSafeSet methods in them).
See
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-types-custom
But I'd still save absolute time anyway. May help in future.
P.S. That's all presuming storing Date is out of question for some reason. TimeZone in Date sometimes gets in the way, really. ;)


Question:
JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function.  How do you do the reverse, and add a function to an "object"?

This works:

var foo = function() { return 1; };
foo.baz = "qqqq";

At this point, foo() calls the function, and foo.baz has the value "qqqq".

However, if you do the property assignment part first, how do you subsequently assign a function to the variable?

var bar = { baz: "qqqq" };

What can I do now to arrange for bar.baz to have the value "qqqq" and bar() to call the function?

Answer:
JavaScript allows functions to be
  treated as objects--you can add a
  property to a function. How do you do
  the reverse, and add a function to an
  object?
You appear to be a bit confused. Functions, in JavaScript,
are
objects. And
variables
are
variable
. You wouldn't expect this to work:
```
```
var three = 3;
three = 4;
assert(three === 3);
```
```
...so why would you expect that assigning a function to your variable would somehow preserve its previous value? Perhaps some annotations will clarify things for you:
```
```
// assigns an anonymous function to the variable "foo"
var foo = function() { return 1; };
// assigns a string to the property "baz" on the object
// referenced by "foo" (which, in this case, happens to be a function)
foo.baz = "qqqq";
```
```


Question:
Although my question might seem abstract I hope it's not. Suppose I develop an application, an ASP.NET MVC site and later I am tasked to build an Winforms client for this application how much and how can I reuse from the existing application?

I defined the models, I defined controllers and views. They all work well.

Now the boss comes asking for a Winforms client and I am hoping I can reuse the models and the controllers (provided I put them in different assemblies) and not reuse just the views (ASPX views).

Can this be done? How?

Answer:
I have done this previously, not with asp.net MVC but with pure asp.net web forms.  I used a home-grown MVP (Model-View-Presenter) pattern, and the absolute most important thing to allow the Presenter (== Controller in your case) to be used in a WinForms app was to not reference
anything
to do with system.web
So the first thing you need to do is introduce interface(s) to wrap any request, response, web etc stuff, and have every Presenter accept these interfaces via Dependency Injection (or make them available to the Presenters by some other technique), then if the Presenter uses those rather than the actual system.web stuff.
Example:
Imagine you want to transfer control from Page A to Page B (which in your winforms app you might want to close form A then open form B).
Interface:
```
```
public interface IRuntimeContext
{
  void TransferTo(string destination);
}
```
```
web implementation:
```
```
public class AspNetRuntimeContext
{
  public void TransferTo(string destination)
  {
    Response.Redirect(destination);
  }
}
```
```
winforms implementation:
```
```
public class WinformsRuntimeContext
{
  public void TransferTo(string destination)
  {
    var r = GetFormByName(destination);
    r.Show();
  }
}
```
```
Now the Presenter (Controller in your case):
```
```
public class SomePresenter
{
  private readonly runtimeContext;
  public SomePresenter(IRuntimeContext runtimeContext)
  {
    this.runtimeContext = runtimeContext;
  }

  public void SomeAction()
  {
    // do some work

    // then transfer control to another page/form
    runtimeContext.TransferTo("somewhereElse");
  }
}
```
```
I haven't looked at the asp.net MVC implementation in detail but I hope this gives you some indication that it will probably be a lot of work to enable the scenario you are after.
You may instead want to consider accepting that you will have to re-code the View and Controller for the different platforms, and instead concentrate on keeping your controllers extremely thin and putting the bulk of your code in a service layer that can be shared.
Good Luck!


Question: Is it the case that the entire restful verb is under a single all encompassing transaction? That is to say, if I raise a Error in the validation or callbacks at any point in the handling of a UPDATE, DELETE, or CREATE operation, is every database operation that I may have performed in previous callbacks also rolled back? Succinctly, does raising a Error on any callback or validation make it such that no change at all occurs in the database for that verb action?

Answer:
Some methods (create, destroy) go to the database immediately. Transactions occur by using the transaction method on classes derived from ActiveRecord as follows:
```
```
Student.transaction do
  Course.transaction do
    course.enroll(student)
    student.units += course.units
  end
end
```
```
(This example is for multiple databases. For a single database, you only need one transaction.)
You can then rollback on these transactions, and exceptions thrown within the transaction are propagated after the rollback.
This depends upon the database having transactions.
NB: save and destroy are wrapped in transactions.


Question:
But here's an example:

Dim desiredType as Type
if IsNumeric(desiredType) then ...

EDIT: I only know the Type, not the Value as a string.

Ok, so unfortunately I have to cycle through the TypeCode.

But this is a nice way to do it:

 if ((desiredType.IsArray))
      return 0;

 switch (Type.GetTypeCode(desiredType))
 {
      case 3:
      case 6:
      case 7:
      case 9:
      case 11:
      case 13:
      case 14:
      case 15:
          return 1;
 }
 ;return 0;

Answer:
You can find out if a variable is numeric using the
```
Type.GetTypeCode()
```
method:
```
```
TypeCode typeCode = Type.GetTypeCode(desiredType);

if (typeCode == TypeCode.Double || typeCode == TypeCode.Integer || ...)
     return true;
```
```
You'll need to complete all the available numeric types in the "..." part ;)
More details here:
TypeCode Enumeration


Question:
I want to write a query like this:

SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o

But this isn't how the MAX function works, right?  It is an aggregate function so it expects a single parameter and then returns the MAX of all rows.

Does anyone know how to do it my way?

Answer:
I don't think so. I wanted this the other day. The closest I got was:
```
```
SELECT
  o.OrderId,
  CASE WHEN o.NegotiatedPrice > o.SuggestedPrice THEN o.NegotiatedPrice
     ELSE o.SuggestedPrice
  END
FROM Order o
```
```


Question:
I've got a Lua program that seems to be slower than it ought to be.  I suspect the issue is that I'm adding values to an associative array one at a time and the table has to allocate new memory each time.

There did seem to be a table.setn function, but it fails under Lua 5.1.3:

stdin:1: 'setn' is obsolete
stack traceback:
        [C]: in function 'setn'
        stdin:1: in main chunk
        [C]: ?

I gather from the Google searching I've done that this function was depreciated in Lua 5.1, but I can't find what (if anything) replaced the functionality.

Do you know how to pre-size a table in Lua?

Alternatively, is there some other way to avoid memory allocation when you add an object to a table?

Answer:
I don't think you can - it's not an array, it's an associative array, like a perl hash or an awk array.
http://www.lua.org/manual/5.1/manual.html#2.5.5
I don't think you can preset its size meaningfully from the Lua side.
If you're allocating the array on the C side, though, the
```
```
void lua_createtable (lua_State *L, int narr, int nrec);
```
```
may be what you need.
Creates a new empty table and pushes
  it onto the stack. The new table has
  space pre-allocated for narr array
  elements and nrec non-array elements.
  This pre-allocation is useful when you
  know exactly how many elements the
  table will have. Otherwise you can use
  the function lua_newtable.


Question:
I need a short code snippet to get a directory listing from an HTTP server.

Thanks

Answer:
Basic understanding:
Directory listings are just HTML pages generated by a web server.
Each web server generates these HTML pages in its own way because there is no standard way for a web server to list these directories.
The best way to get a directory listing, is to simply do an HTTP request to the URL you'd like the directory listing for and to try to parse and extract all of the links from the HTML returned to you.
To parse the HTML links please try to use the
HTML Agility Pack
.
Directory Browsing:
The web server you'd like to list directories from must have directory browsing turned on to get this HTML representation of the files in its directories.  So you can only get the directory listing if the HTTP server wants you to be able to.
A quick example of the HTML Agility Pack:
```
```
HtmlDocument doc = new HtmlDocument();
doc.Load(strURL);
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a@href")
{
HtmlAttribute att = link"href";
//do something with att.Value;
}
```
```
Cleaner alternative:
If it is possible in your situation, a cleaner method is to use an intended protocol for directory listings, like the File Transfer Protocol (FTP), SFTP (FTP like over SSH) or FTPS (FTP over SSL).
What if directory browsing is not turned on:
If the web server does not have directory browsing turned on, then there is no easy way to get the directory listing.
The best you could do in this case is to start at a given URL, follow all HTML links on the same page, and try to build a virtual listing of directories yourself based on the relative paths of the resources on these HTML pages.  This will not give you a complete listing of what files are actually on the web server though.


Question: Coming from a Perl 5 background, what are the advantages of moving to Perl 6 or Python?

Answer:
Perl is generally better than python for quick one liners, especially involve text/regular expressions
http://novosial.org/perl/one-liner/


Question: Lets say I have a class that stores user information complete with getters and setters, and it is populated with data from an XML file.  How would I iterate over all of the instances of that class like you would do with java beans and tag libraries?

Answer:
This assumes you can acquire all instances of your class and add them to a Generic List.
```
```
List<YourClass> myObjects = SomeMagicMethodThatGetsAllInstancesOfThatClassAndAddsThemtoTheCollection();
foreach (YourClass instance in myObjects)
{
Response.Write(instance.PropertyName.ToString();
}
```
```
If you don't want to specify each property name you could use Reflection, (see PropertyInfo) and do it that way. Again, not sure if this is what your intent was.


Question:
I'm currently turning an array of pixel values (originally created with a java.awt.image.PixelGrabber object) into an Image object using the following code:

public Image getImageFromArray(int[] pixels, int width, int height) {
    MemoryImageSource mis = new MemoryImageSource(width, height, pixels, 0, width);
    Toolkit tk = Toolkit.getDefaultToolkit();
    return tk.createImage(mis);
}

Is it possible to achieve the same result using classes from the ImageIO package(s) so I don't have to use the AWT Toolkit?

Toolkit.getDefaultToolkit() does not seem to be 100% reliable and will sometimes throw an AWTError, whereas the ImageIO classes should always be available, which is why I'm interested in changing my method.

Answer:
I've had good success using java.awt.Robot to grab a screen shot (or a segment of the screen), but to work with ImageIO, you'll need to store it in a BufferedImage instead of the memory image source.  Then you can call one static method of ImageIO and save the file.  Try something like:
```
```
// Capture whole screen
Rectangle region = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capturedImage = new Robot().createScreenCapture(region);

// Save as PNG
File imageFile = new File("capturedImage.png");
ImageIO.write(capturedImage, "png", imageFile);
```
```


Question:
I found an article on getting active tcp/udp connections on a machine.

http://www.codeproject.com/KB/IP/iphlpapi.aspx

My issue however is I need to be able to determine active connections remotely - to see if a particular port is running or listening without tampering with the machine.

Is this possible?

Doesn't seem like it natively, otherwise it could pose a security issue. The alternative would be to query a remoting service which could then make the necessary calls on the local machine.

Any thoughts?

Answer:
There is no way to know which ports are open without the remote computer knowing it.  But you can determine the information without the program running on the port knowing it (i.e. without interfering with the program).
Use SYN scanning:
To establish a connection, TCP uses a three-way handshake.  This can be exploited to find out if a port is open or not without the program knowing.
The handshake works as follows:
The client performs an active open by sending a SYN to the server.
The server replies with a SYN-ACK.
Normally, the client sends an ACK back to the server.  But this step is skipped.
SYN scan is the most popular form of
  TCP scanning. Rather than use the
  operating system's network functions,
  the port scanner generates raw IP
  packets itself, and monitors for
  responses. This scan type is also
  known as "half-open scanning", because
  it never actually opens a full TCP
  connection. The port scanner generates
  a SYN packet. If the target port is
  open, it will respond with a SYN-ACK
  packet. The scanner host responds with
  a RST packet, closing the connection
  before the handshake is completed.
The use of raw networking has several
  advantages, giving the scanner full
  control of the packets sent and the
  timeout for responses, and allowing
  detailed reporting of the responses.
  There is debate over which scan is
  less intrusive on the target host. SYN
  scan has the advantage that the
  individual services never actually
  receive a connection while some
  services can be crashed with a connect
  scan. However, the RST during the
  handshake can cause problems for some
  network stacks, particularly simple
  devices like printers. There are no
  conclusive arguments either way.
Source Wikipedia
As is mentioned below, I think
nmap
can do SYN scanning.
Using sockets for TCP port scanning:
One way to determine which ports are open is to open a socket to that port.  Or to a different port which finds out the information for you like you mentioned.
For example from command prompt or a terminal:
```
```
telnet google.com 80
```
```
UDP Port scanning:
if a UDP packet is sent to a port that is not open, the system will respond with an ICMP port unreachable message. You can use this method to determine if a port is open or close.  But the receiving program will know.


Question:
Say I have an array that represents a set of points:

x = [2, 5, 8, 33, 58]

How do I generate an array of all the pairwise distances?

Answer:
```
```
x = [2, 5, 8, 33, 58]
print x.collect {|n| x.collect {|i| (n-i).abs}}.flatten
```
```
I think that would do it.


Question:
How do I pick a random element from a set?
I'm particularly interested in picking a random element from a
HashSet or a LinkedHashSet, in Java.
Solutions for other languages are also welcome.

Answer:
Since you said "Solutions for other languages are also welcome", here's the version for Python:
```
```
>>> import random
>>> random.choice([1,2,3,4,5,6])
3
>>> random.choice([1,2,3,4,5,6])
4
```
```


Question:
Can you have custom client-side javascript Validation for standard ASP.NET Web Form Validators?

For instance use a asp:RequiredFieldValidator leave the server side code alone but implement your own client notification using jQuery to highlight the field or background color for example.

Answer:
What you can do is hook into the validator and assign a new evaluate method, like this:
```
```
<script type="text/javascript">
        rfv.evaluationfunction = validator;

        function validator(sender, e) {
            alert('rawr');
        }
    </script>
```
```
rfv is the ID of my required field validator.  You have to do this at the bottom of your page so that it assigns it after the javascript for the validator is registered.
Its much easier just to use the CustomFieldValidator and assign its client side validation property.
```
```
<asp:CustomValidator ControlToValidate="txtBox" ClientValidationFunction="onValidate" />

<script type='text/javascript'>
function onValidate(sender, e)
 {
     alert('do validation');
 }
</script>
```
```
Check out the documentation
here
and
here
.


Question:
I have seen this link: Implementing Mutual Exclusion in JavaScript.
On the other hand, I have read that there are no threads in javascript, but what exactly does that mean?

When events occur, where in the code can they interrupt?

And if there are no threads in JS, do I need to use mutexes in JS or not?

Specifically, I am wondering about the effects of using functions called by setTimeout() and XmlHttpRequest's onreadystatechange on globally accessible variables.

Answer:
JavaScript is single threaded... though Chrome may be a new beast (I think it is also single threaded, but each tab has it's own JavaScript thread... I haven't looked into it in detail, so don't quote me there).
However, one thing you DO need to worry about is how your JavaScript will handle multiple ajax requests coming back in not the same order you send them.  So, all you really need to worry about is make sure your ajax calls are handled in a way that they won't step on eachother's feet if the results come back in a different order than you sent them.
This goes for timeouts too...
When JavaScript grows multithreading, then maybe worry about mutexes and the like....


Question:
We're looking to automate our deployment of Web Applications, particularly when going from local development to a remote server.

Our current stack is LAMP remotely, MAMP locally, but I'm interested in general what people are using for this task regardless of their environment?

I'm not just talking about moving files around, I also meant considering other tasks such as:

Setting up Database schema

Managing configurations

Misc tasks required for deployment (creating log files etc.)

Answer:
rsync->great tool
But, the answer depends on your enviro.  What do you use for source control?  What do you use for a build system? Etc.
Deployment for a web server is nothing more than a "cp" command depending on which files changed.  You need to build a process that tracks the files that change, pull those files from source control and then pushes those changes.  When you are dealing with PHP files, how do you know which files to push? That's the problem.  You solve that, you'll be fine.  The tool to cp the files and "deploy" them is the easy part.


Question:
I have an <img> in an HTML document that I would like to highlight as though the user had highlighted it using the mouse. Is there a way to do that using JavaScript?

I only need it to work in Mozilla, but any and all information is welcome.

EDIT: The reason I want to select the image is actually not so that it appears highlighted, but so that I can then copy the selected image to the clipboard using XPCOM. So the img actually has to be selected for this to work.

Answer:
You can swap the source of the image, as in img.src = "otherimage.png";
I actually did this at one point, and there are things you can do to pre-load the images.
I even set up special attributes on the image elements such as swap-image="otherimage.png", then searched for any elements that had it, and set up handlers to automatically swap the images... you can do some fun stuff.
Sorry I misunderstood the question!  but anyways, for those of you interested in doing what I am talking about, here is an example of what I mean (crude implementation, I would suggest using frameworks like jQuery to improve it, but just something to get you going):
```
```
<html>
<body>
<script language="javascript">
function swap(name) {
  document.getElementById("image").src = name;
}
</script>
<img id="image" src="test1.png"
     onmouseover="javascript:swap('test0.png');"
     onmouseout="javascript:swap('test1.png');">
</body>
</html>
```
```


Question:
I'd like to ensure my RAII class is always allocated on the stack.

How do I prevent a class from being allocated via the 'new' operator?

Answer:
All you need to do is declare the class' new operator private:
```
```
class X
{
    private:
      // Prevent heap allocation
      void * operator new   (size_t);
      void * operator new[] (size_t);
      void   operator delete   (void *);
      void   operator delete[] (void*);

    // ...
    // The rest of the implementation for X
    // ...
};
```
```
Making 'operator new' private effectively prevents code outside the class from using 'new' to create an instance of X.
To complete things, you should hide 'operator delete' and the array versions of both operators.
Since C++11 you can also explicitly delete the functions:
```
```
class X
{
// public, protected, private ... does not matter
    static void *operator new     (size_t) = delete;
    static void *operator new[]   (size_t) = delete;
    static void  operator delete  (void*)  = delete;
    static void  operator delete[](void*)  = delete;
};
```
```
Related Question:
Is it possible to prevent stack allocation of an object and only allow it to be instiated with ‘new’?


Question:
I'm a long-time Windows developer, having cut my teeth on win32 and early COM.  I've been working with .NET since 2001, so I'm pretty fluent in C# and the CLR.  I'd never heard of Castle Windsor until I started participating in Stack Overflow.  I've read the Castle Windsor "Getting Started" guide, but it's not clicking.

Teach this old dog new tricks, and tell me why I should be integrating Castle Windsor into my enterprise apps.

Answer:
Castle Windsor is an inversion of control tool.  There are others like it.
It can give you objects with pre-built and pre-wired dependencies right in there.
An entire object graph created via reflection and configuration rather than the "new" operator.
Start here:
http://tech.groups.yahoo.com/group/altdotnet/message/10434
Imagine you have an email sending class.  EmailSender. Imagine you have another class WorkflowStepper.  Inside WorkflowStepper you need to use EmailSender.
You could always say
```
new EmailSender().Send(emailMessage);
```
but that - the use of
```
new
```
- creates a TIGHT COUPLING that is hard to change.  (this is a tiny contrived example after all)
So what if, instead of newing this bad boy up inside WorkflowStepper, you just passed it into the constructor?
So then whoever called it had to new up the EmailSender.
```
new WorkflowStepper(emailSender).Step()
```
Imagine you have hundreds of these little classes that only have one responsibility (google SRP).. and you use a few of them in WorkflowStepper:
```
new WorkflowStepper(emailSender, alertRegistry, databaseConnection).Step()
```
Imagine not worrying about the details of
```
EmailSender
```
when you are writing
```
WorkflowStepper
```
or
```
AlertRegistry
```
You just worry about the concern you are working with.
Imagine this whole graph (tree) of objects and dependencies gets wired up at RUN TIME, so that when you do this:
```
WorkflowStepper stepper = Container.Get<WorkflowStepper>();
```
you get a real deal
```
WorkflowStepper
```
with all the dependencies automatically filled in where you need them.
There is no
```
new
```
It just
happens
- because it knows what needs what.
And you can write fewer defects with better designed, DRY code in a testable and repeatable way.


Question: Is it possible to prevent stack allocation of an object and only allow it to be instiated with 'new' on the heap?

Answer:
You could make the constructor
```
private
```
, then provide a
```
public
```
static factory method to create the objects.


Question:
I need to change the functionality of an application based on the executable name. Nothing huge, just changing strings that are displayed and some internal identifiers. The application is written in a mixture of native and .Net C++-CLI code.

Two ways that I have looked at are to parse the GetCommandLine() function in Win32 and stuffing around with the AppDomain and other things in .Net. However using GetCommandLine won't always work as when run from the debugger the command line is empty. And the .Net AppDomain stuff seems to require a lot of stuffing around.

So what is the nicest/simplest/most efficient way of determining the executable name in C++/CLI? (I'm kind of hoping that I've just missed something simple that is available in .Net.)

Edit: One thing that I should mention is that this is a Windows GUI application using C++/CLI, therefore there's no access to the traditional C style main function, it uses the Windows WinMain() function.

Answer:
Call
GetModuleFileName()
using 0 as a module handle.
Note:
you
can
also use the
```
argv[0]
```
parameter to main or call
```
GetCommandLine()
```
if there is no main. However, keep in mind that these methods will not necessarily give you the complete path to the executable file. They will give back the same string of characters that was used to start the program. Calling
```
GetModuleFileName()
```
, instead, will always give you a complete path and file name.


Question:
I'm trying to display an array of files in order of date (last modified).

I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?

Answer:
Warning
```
create_function()
```
has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.
For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is:
```
```
<?php

$myarray = glob("*.*");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));

?>
```
```
Tested this on my system and verified it does sort by file mtime as desired. I used a similar approach (written in Python) for determining the last updated files on my website as well.


Question:
I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too.

Does anyone know of a premade component that could do this?

Answer:
Take a look at the
SharpDevelop
C# compiler/IDE source code. They have a sophisticated text box with line numbers. You could look at the source, figure out what they're doing, and then implement it yourself.
Here's a sample of what I'm referencing:
alt text http://community.sharpdevelop.net/photos/mattward/images/original/FeatureTourQuickClassBrowser.aspx


Question:
...or are they the same thing? I notice that each has its own Wikipedia entry: Polymorphism, Multiple Dispatch, but I'm having trouble seeing how the concepts differ.

Edit: And how does Overloading fit into all this?

Answer:
Multiple Dispatch is a kind of polymorphism.  In Java/C#/C++, there is polymorphism through inheritance and overriding, but that is not multiple dispatch, which is based on two or more arguments (not just
```
this
```
, like in Java/C#/C++)


Question:
Most importantly, why did it fail?

What I'm looking for here is pathologies that anyone, whether new to the team or just waking up one day,can spot.

Answer:
A project that had no end. No one knew when it was finished. All we knew was that we had to keep doing whatever that we were doing. And yes sadly it was just as vague as I explained it.
Did it fail. In my opinion it did since we never saw what happened to it at the end, we were moved on to another project, and you can say it faded into the night.
Why? Everything opposite of the 7 project management body of knowledge.


Question:
I have a 2D character array:

char nm[MAX1][MAX2] = { "john", "bob", "david" };

I want to swap two of these elements (without std::swap) by simply writing

swapPointers(nm[0], nm[1]);

where swapPointers looks like this

void swapPointers(char *&a, char *&b)
{
    char *temp = a;
    a = b;
    b = a;
}

However, this does not compile (and while adding casts makes it compile, the pointers end up pointing to wrong/weird locations).

Can anybody help?

Thanks!

Answer:
```
```
void swapPointers(char** ppa, char** ppb)
{
    char* ptemp = *ppa;
    *ppb = *ppa;
    *ppa = ptemp;
}

swapPointers(&nm[0], &nm[1]);
```
```


Question:
I have an app that has impersonation used throughout.  But when a user is logged in as an admin, a few operation require them to write to the server itself.  Now if these users do not have rights on the actual server (some don't) it will not let them write.

What I want to do is turn off impersonation for just a couple commands.

Is there a way to do something like this?

using(HostingEnvironment.Impersonate.Off())
  //I know this isn't a command, but you get the idea?

Thank you.

Answer:
I am not sure if this is the preferred approach but when I wanted to do this I new'd up an instance of a
WindowsIdentity
and called the
Impersonate
method.  This allows subsequent code to impersonate a different Windows user. It returns a
WindowsImpersonationContext
that has an
Undo
method which reverts the impersonation context back again.


Question:
Say I have the following string:

"I am the most foo h4ck3r ever!!"

I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:

"I am the most <span class="special">foo></span> h4ck3r ever!!"

BeautifulSoup seemed like the way to go, but I haven't been able to make it work.

I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.

Some advice for this would be really useful, especially in python.

Answer:
How about this:
```
```
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def makeSpecial(mystring, special_substr):
...     return mystring.replace(special_substr, '%s
' % special_substr)
...
>>> makeSpecial("I am the most foo h4ck3r ever!!", "foo")
'I am the most foo h4ck3r ever!!'
>>>
```
```


Question:
I'm trying to bind a List<T> to a DataGridView control, and I'm not having any luck creating custom bindings.

I have tried:

gvProgramCode.DataBindings.Add(new Binding("Opcode",code,"Opcode"));

It throws an exception, saying that nothing was found by that property name.

The name of the column in question is "Opcode". The name of the property in the List<T> is Opcode.

ANSWER EDIT: the problem was that I did not have the bindable fields in my class as properties, just public fields...Apparently it doesn't reflect on fields, just properties.

Answer:
Is the property on the grid you are binding to Opcode as well?.. if you want to bind directly to List you would just DataSource = list.  The databindings allows custom binding. are you trying to do something other than the datasource?
You are getting a bunch of empty rows? do the auto generated columns have names? Have you verified data is in the object (not just string.empty) ?
```
```
class MyObject
    {
        public string Something { get; set; }
        public string Text { get; set; }
        public string Other { get; set; }
    }

    public Form1()
    {
        InitializeComponent();

        List<MyObject> myList = new List<MyObject>();

        for (int i = 0; i < 200; i++)
        {
            string num = i.ToString();
            myList.Add(new MyObject { Something = "Something " + num , Text = "Some Row " + num , Other = "Other " + num  });
        }

        dataGridView1.DataSource = myList;
    }
```
```
this should work fine...


Question:
I am developing a forms app (not web) for Windows Mobile, using .NET CF 3.5.  I need an HTML editor control.  I'm looking for something along the lines of a simple FCKEditor, but for using in a forms app (EXE).

Any suggestions?

Answer:
I'm not sure if it is supported by the compact framework but you can try setting designmode on the WebBrowser control through reflection and wrapping it up to make a simple WYSIWYG editor.. think this is the code..
```
```
webBrowser1.Document.GetType().GetProperty("designmode").SetValue(webBrowser1.Document, true, null);
```
```


Question:
I'm trying to write an app using Ruby on Rails and I'm trying to achieve the following:

The app needs to receive UDP messages coming in on a specific port (possibly 1 or more per second) and store them in the database so that the rest of my Rails app can access it.

I was thinking of writing a separate daemon that would receive these messages and shell out to a ruby script on my rails app that will store the message in the database using the right model.  The problem with this approach is that the ruby script will be run very often.  It would be better performance-wise if I could just have a long-running ruby process that can constantly receive the UDP messages store them in the database.

Is this the right way to do it?  Is there something in the Rails framework that can help with this?

Answer:
You definitely don't want to load the Rails stack for each incoming request -- that would be way too slow; you'll want to use something lower-level to handle the incoming connections. You might look at the internals of Webrick to see a simple server daemon coded in ruby -- or, if you want something more performant, look at Mongrel or Thin.
In general, the whole Rails stack isn't gonna help you a lot here -- most of it is geared towards serving web apps, not saving stuff straight off the wire.
The part of Rails that will probably help you the most is ActiveRecord -- there's a pretty good chance you'll want to use that to store your Model data in the database. In fact, you should be able to
```
include
```
your actual Rails models and use them in your UDP-monitoring process. Check the
ActiveRecord docs
for examples in connecting to a database outside your Rails project.


Question:
Is it possible to specify a relative path reference in connectionstring, attachDbFileName property in a web.config?

For example, In my database is located in the App_data folder, I can easily specify the AttachDBFilename as|DataDirectory|\mydb.mdf and the |Datadirectory| will automatically resolve to the correct path.

Now, suppose that web.config file is located in A folder, but the database is located in B\App_data folder, where A and B folder is located in the same folder. Is there anyway to use relative path reference to resolve to the correct path?

Answer:
It depends on where your '|DataDirectory|' is located.  If the resolved value of '|DataDirectory|' is in folder A (where the web.config is), then no - you can't specify a relative path that is not a subfolder of the resolved value of '|DataDirectory|'.
What you
can
do is set the value of '|DataDirectory|' to be wherever you would like, by calling the
AppDomain.SetData
method.
From the MSDN online documentation:
When DataDirectory is used, the resulting file path cannot be higher in the directory structure than the directory pointed to by the substitution string. For example, if the fully expanded DataDirectory is C:\AppDirectory\app_data, then the sample connection string shown above works because it is below c:\AppDirectory. However, attempting to specify DataDirectory as |DataDirectory|..\data will result in an error because \data is not a subdirectory of \AppDirectory.
Hope this helps.


Question:
I need to pass a regex substitution as a variable:

sub proc {
    my $pattern = shift;
    my $txt = "foo baz";

    $txt =~ $pattern;
}

my $pattern = 's/foo/bar/';
proc($pattern);

This, of course, doesn't work. I tried eval'ing the substitution:

eval("$txt =~ $pattern;");

but that didn't work either. What horribly obvious thing am I missing here?

Answer:
Well, you can precompile the regular expression using the
qr//
operator.  But you can't pass an operator (s///).
```
```
$pattern = qr/foo/;

print "match!\n" if $text =~ $pattern;
```
```
But if you have to pass the substitution operator, you are down to passing either code or strings:
```
```
proc('$text =~ s/foo/bar');

sub proc {
   my $code = shift;

   ...

   eval $code;
}
```
```
or, code:
```
```
proc(sub {my $text = shift;  $text =~ s/foo/bar});

sub proc {
   my $code = shift;

   ...

   $code->("some text");
}
```
```


Question:
A common pattern with STL containers is this:

map<Key, Value> map;
for(map<Key, Value>::iterator iter = map.begin(); iter != map.end(); ++iter)
{
  ...
}

So in order to avoid writing the declaration of the template parameters we can do this somewhere:

typedef map<Key, Value> TNiceNameForAMap;

But if this map is only used in a single function or for a single iteration this is an annoying overhead.

Is there any way around this typedef?

Answer:
Not sure what you mean by "overhead". If it simplifies the way you write your code, use it, otherwise stick with the longhand.
If it's only used in a restricted scope, put the typedef in that same scope. Then it doesn't need to be published, or documented, or appear on any UML diagrams. For example (and I don't claim this is the best code ever in other respects):
```
```
int totalSize() {
    typedef std::map<Key, Value> DeDuplicator;
    DeDuplicator everything;

    // Run around the universe finding everything. If we encounter a key
    // more than once it's only added once.

    // now compute the total
    int total = 0;
    for(DeDuplicator::iterator i = everything.begin(); i <= everything.end(); ++i) {
        total += i->second.size(); // yeah, yeah, overflow. Whatever.
    }
    return total;
}
```
```
Combining with Ferruccio's suggestion (if you're using boost), the loop becomes:
```
```
BOOST_FOREACH(DeDuplicator::pair p, everything) {
    total += p.second.size();
}
```
```
And combining with bk1e's suggestion (if you're using C++0x or have features from it), and assuming that BOOST_FOREACH interacts with auto in the way I think it should based on the fact that it can normally handle implicit casts to compatible types:
```
```
std::map<Key, Value> everything;
// snipped code to run around...
int total = 0;
BOOST_FOREACH(auto p, everything) {
    total += p.second.size();
}
```
```
Not bad.


Question:
What MySQL query will do a text search and replace in one particular field in a table?

I.e. search for foo and replace with bar so a record with a field with the value hello foo becomes hello bar.

Answer:
The
Replace
string function will do that.


Question:
In reading about Perl 6, I see a feature being trumpeted about, where you no longer have to do:

return "0 but true";

...but can instead do:

return 0 but True;

If that's the case, how does truth work in Perl 6? In Perl 5, it was pretty simple: 0, "", and undef are false, everything else is true.

What are the rules in Perl 6 when it comes to boolean context?

Answer:
According to O'Reilly's
Perl 6 and Parrot Essentials
,
false
is 0, undef, the empty string, and values flagged as
false
.
true
is everything else.
Also, Perl 6 has both a primitive boolean type and by having True and False
roles
that any value can mix in (so you can have a "0 but True" value or a "1 but False" one for example, or a false list containing elements, or a true list that's empty).
See
http://www.mail-archive.com/macosx@perl.org/msg09930.html


Question:
Selenium Remote Control has a method of "get_html_source", which returns the source of the current page as a string.

AFAIK, this method works in all cases in Firefox and Safari. But when it's invoked in Internet Explorer, it returns an incorrect source.

Does anyone know if this is a bug with Selenium or Internet Explorer, and if there's a fix?

Answer:
I'm 99% sure get_html_source uses the browser's innerHTML property. InnerHTML returns the browser's internal representation of a document, and has always been inconsistent and "wonky" between platforms.
You can test this by temporarily adding the following onload attribute to the body tag of your page.
```
```
onload="var oArea = document.createElement('textarea');oArea.rows=80;oArea.cols=80;oArea.value = document.getElementsByTagName('html')[0].innerHTML;document.getElementsByTagName('body')[0].appendChild(oArea)"
```
```
This will add a text area to the bottom of your page with the document's innerHTML.  If you see the same "incorrect" HTML source you know IE's the culprit here.
Possible workarounds would be running the source through HTML Tidy or some other cleaner if you're after valid markup.  I don't know of anything that will give you a consistent rendering between browsers.


Question:
I have been running StyleCop over some C# code, and it keeps reporting that my using directives should be inside the namespace.

Is there a technical reason for putting the using directives inside instead of outside the namespace?

Answer:
Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multiple namespaces in the file) but if you only have one namespace per file then it doesn't make much of a difference whether they go outside or inside the namespace.
```
```
using ThisNamespace.IsImported.InAllNamespaces.Here;

namespace Namespace1
{
   using ThisNamespace.IsImported.InNamespace1.AndNamespace2;

   namespace Namespace2
   {
      using ThisNamespace.IsImported.InJustNamespace2;
   }
}

namespace Namespace3
{
   using ThisNamespace.IsImported.InJustNamespace3;
}
```
```


Question:
Is there a simple out of the box way to impersonate a user in .NET?

So far I've been using this class from code project for all my impersonation requirements.

Is there a better way to do it by using .NET Framework?

I have a user credential set, (username, password, domain name) which represents the identity I need to impersonate.

Answer:
Here is some good overview of .NET impersonation concepts.
Michiel van Otegem: WindowsImpersonationContext made easy
WindowsIdentity.Impersonate Method (check out the code samples)
Basically you will be leveraging these classes that are out of the box in the .NET framework:
WindowsImpersonationContext
WindowsIdentity
The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.


Question:
What are the advantages and limitations of dynamic type languages compared to static type languages?

See also: whats with the love of dynamic languages (a far more argumentative thread...)

Answer:
The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time).
A good take on the issue is from
Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages
by Erik Meijer and Peter Drayton at Microsoft:
Advocates of static typing argue that
  the advantages of static typing
  include earlier detection of
  programming mistakes (e.g. preventing
  adding an integer to a boolean),
  better documentation in the form of
  type signatures (e.g. incorporating
  number and types of arguments when
  resolving names), more opportunities
  for compiler optimizations (e.g.
  replacing virtual calls by direct
  calls when the exact type of the
  receiver is known statically),
  increased runtime efficiency (e.g. not
  all values need to carry a dynamic
  type), and a better design time
  developer experience (e.g. knowing the
  type of the receiver, the IDE can
  present a drop-down menu of all
  applicable members). Static typing
  fanatics try to make us believe that
  “well-typed programs cannot go wrong”.
  While this certainly sounds
  impressive, it is a rather vacuous
  statement. Static type checking is a
  compile-time abstraction of the
  runtime behavior of your program, and
  hence it is necessarily only partially
  sound and incomplete. This means that
  programs can still go wrong because of
  properties that are not tracked by the
  type-checker, and that there are
  programs that while they cannot go
  wrong cannot be type-checked. The
  impulse for making static typing less
  partial and more complete causes type
  systems to become overly complicated
  and exotic as witnessed by concepts
  such as “phantom types” [11] and
  “wobbly types” [10]. This is like
  trying to run a marathon with a ball
  and chain tied to your leg and
  triumphantly shouting that you nearly
  made it even though you bailed out
  after the first mile.
Advocates of dynamically typed
  languages argue that static typing is
  too rigid, and that the softness of
  dynamically languages makes them
  ideally suited for prototyping systems
  with changing or unknown requirements,
  or that interact with other systems
  that change unpredictably (data and
  application integration). Of course,
  dynamically typed languages are
  indispensable for dealing with truly
  dynamic program behavior such as
  method interception, dynamic loading,
  mobile code, runtime reflection, etc.
  In the mother of all papers on
  scripting [16], John Ousterhout argues
  that statically typed systems
  programming languages make code less
  reusable, more verbose, not more safe,
  and less expressive than dynamically
  typed scripting languages. This
  argument is parroted literally by many
  proponents of dynamically typed
  scripting languages. We argue that
  this is a fallacy and falls into the
  same category as arguing that the
  essence of declarative programming is
  eliminating assignment. Or as John
  Hughes says [8], it is a logical
  impossibility to make a language more
  powerful by omitting features.
  Defending the fact that delaying all
  type-checking to runtime is a good
  thing, is playing ostrich tactics with
  the fact that errors should be caught
  as early in the development process as
  possible.


Question:
I've tried this, but get a ClassNotFoundException when calling:

Class.forName("com.AClass", false, mySpecialLoader)

Answer:
The ClassLoader will have to call defineClass to get the Class.  According to the JavaDoc for defineClass:
If name is not null, it must be equal
  to the binary name of the class
  specified by the byte array.
If the name is null, it will get it from the bytecode. So you can return any class you want as long as it's called com.AClass. In other words, you could have multiple versions of com.AClass.  You could even use something like JavaAssist to create a class on the fly.
But that doesn't explain the ClassNotFoundException - it sounds like your class loader isn't returning anything.


Question:
I am writing a custom maven2 MOJO. I need to access the runtime configuration of another plugin, from this MOJO.

What is the best way to do this?

Answer:
I'm not sure how you would do that exactly, but it seems to me that this might not be the best design decision.  If at all possible you should aim to decouple your Mojo from any other plugins out there.
Instead I would recommend using custom properties to factor out any duplication in the configuration of separate plugins.
You can set a custom property "foo" in your pom by using the properties section:
```
```
<project>
  ...
  <properties>
    <foo>value</foo>
  </properties>
  ...
</project>
```
```
The property foo is now accessible anywhere in the pom by using the dollar sign + curly brace notation:
```
```
<somePluginProperty>${foo}</somePluginProperty>
```
```


Question:
We've got a Java server application that runs on a number of computers, all connected to the Internet, some behind firewalls. We need to remotely update the JAR files and startup scripts from a central site, with no noticeable interruption to the app itself.

The process has to be unattended and foolproof (i.e. we can't afford to break the app due to untimely internet outages).

In the past we've used a variety of external scripts and utilities to handle similar tasks, but because they have their own dependencies, the result is harder to maintain and less portable. Before making something new, I want to get some input from the community.

Has anyone found a good solution for this already? Got any ideas or suggestions?

Just to clarify: This app is a server, but not for web applications (no webapp containers or WAR files here). It's just an autonomous Java program.

Answer:
I'd recommend Capistrano for multi-server deployment. While it is built for deploying Rails apps, I've seen it used successfully to deploy Java applications.
Link:
Capistrano 2.0 Not Just for Rails


Question: I am using Excel where certain fields are allowed for user input and other cells are to be protected. I have used Tools Protect sheet, however after doing this I am not able to change the values in the VBA script. I need to restrict the sheet to stop user input, at the same time allow the VBA code to change the cell values based on certain computations.

Answer:
I don't think you can set any part of the sheet to be editable only by VBA
, but you can do something that has basically the same effect -- you can unprotect the worksheet in VBA before you need to make changes:
```
```
wksht.Unprotect()
```
```
and re-protect it after you're done:
```
```
wksht.Protect()
```
```
Edit: Looks like this workaround may have solved Dheer's immediate problem, but for anyone who comes across this question/answer later, I was wrong about the first part of my answer, as Joe points out below.  You
can
protect a sheet to be editable by VBA-only, but it appears the "UserInterfaceOnly" option can only be set when calling "Worksheet.Protect" in code.


Question:
I'm looking for some insight into XNA on Xbox 360, mainly if its possible to run vector-based float mathematics on its GPU?

If there's a way, can you point me into the right direction?

Answer:
I don't claim to be an expert on this, but hopefully this can point you in a helpful direction.
Is it possible? Yes. You probably already know that the GPU is good at such calculations (hence the question) and you can indeed control the GPU using XNA. Whether or not it will suit your needs is a different matter.
To make use of the GPU, you'll presumably want to write shaders using HLSL. There's a decent introduction to HLSL in the context of XNA at
Reimers
which you might want to run through. Notably, that tutorial focuses on making the GPU do graphics-related crunching, but what you write in the shaders is up to you. If your vector-based float math is for the purpose of rendering (and thus can stay in the GPU domain), you're in luck and can stop here.
Likely rendering onscreen is not what you're after. Now, you have a fair amount of flexibility in HLSL as far as doing your math goes. Getting the results out to the CPU, however, is not how the system was designed. This is getting fuzzy for me, but Shawn Hargreaves (an XNA dev) states on
more
than
one occasion
that getting output from the GPU (other than rendered onscreen) is non-trivial and has performance implications. Retrieving data involves a call to GetData which will
cause a pipeline stall
.
So it can be done. The XNA framework will let you write shaders for the 360 (which supports Shader Model 3.0 plus a few extensions) and it
is
possible to get those results out, though it may not be efficient enough for your needs.


Question:
I have a repository of files which are unrelated to each other but are common to multiple projects. Each project might only need a subset of these files. For example:

/myRepo:
    /jquery.js
    /jquery.form.js
    /jquery.ui.js

Project A requires jquery.js and jquery.form.js, whereas Project B requires jquery.js and jquery.ui.js

I could just do a checkout of myRepo into both projects, but that'd add a lot of unnecessary files into both. What I'd like is some sort of way for each Project to only get the files it needs. One way I thought it might be possible is if I put just the required files into each project and then run an svn update on it, but somehow stop SVN from adding new files to each directory. They'd still get the modifications to the existing files, but no unnecessary files would be added.

Is this possible at all?

Answer:
If I understood your question correctly, you want to share code across projects? If so, look at the svn:externals property.
Externals explained in Subversion Red Book
svn:externals in Windows


Question: When userA uploads a file, his files will be uploaded to folderA, when userB, to folderB, and so on. Roles/Profiles in ASP.NET. Folders will be pre-existing. Anyone?

Answer: You'll probably want to hand-code that. There's nothing intrinsic to ASP.NET for managing user files. However, the code to do so should be relatively easy. Assuming the username is unique and never changes, you can combine the username with a path (use Path.Combine) and upload to that location. I would also lock down that location so that nobody else can access it.


Question:
Is it possible to use an attribute of a child to group a query?

Post.find(:all, :include => [ :authors, :comments ], :group=>'authors.city')

does not work.

However, I am able to use author.city as part of the conditions.

Answer:
If that's what you're using, then the syntax is wrong for the :group argument, it should be:
```
```
Post.find(:all, :include => [ :author, :comments ], :group=>'authors.city')
```
```
Make sure your :author and :comments associations are correct.  If 'authors' is the actual table name, then you'll need a 'has_one :author' association in you Post model, and an  Author model.
Associations need to be correct, too:
```
```
class Post < AR:Base
   belongs_to :author
   has_many :comments
 end

 class Author < AR:Base
   has_many :posts
 end

 class Comment < AR:Base
   belongs_to :post
 end
```
```
And the db schema:
```
```
posts
   id
   author_id
 authors
   id
 comments
   id
   post_id
```
```
This will let the query run correctly, however, now
I'm
getting an error with the results... the :group clause doesn't seem to be applied when :include is used.


Question:
I decided to teach myself assembly language.

I have realized that my program will not compile if I attempt to change the value of any segment register.

Every article that I have found says that I can indeed change the value of at least 4 segment registers, so what gives?

I am really only interested in the why at this point, I don't have any real purpose in changing these addresses.

Answer:
Are you writing windows executables?
In protected-mode (Win32), segment registers are not used any more.
Reference
:
Memory model is also drastically
  different from the old days of the
  16-bit world. Under Win32, we need not
  be concerned with memory model or
  segment anymore! There's only one
  memory model: Flat memory model.
  There's no more 64K segments. The
  memory is a large continuous space of
  4 GB. That also means you don't have
  to play with segment registers. You
  can use any segment register to
  address any point in the memory space.
  That's a GREAT help to programmers.
  This is what makes Win32 assembly
  programming as easy as C.


Question: I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any error in execution. On exception i also return proper error code. But i am not aware of where i can check for this error code.

Answer:
This is what I could find, maybe it solves your problem:
SP to get the current job activiity.
```
```
exec msdb.dbo.sp_help_jobactivity  @job_id = (your job_id here)
```
```
You can execute this SP and place the result in a temp table and get the required result from there.
Otherwise have a look at these tables:
msdb.dbo.sysjobactivity
msdb.dbo.sysjobhistory
Run the following to see the association between these tables.
exec sp_helptext sp_help_jobactivity


Question:
I open a connection like this:

Using conn as New OdbcConnection(connectionString)
    conn.Open()
    //do stuff
End Using

If connection pooling is enabled, the connection is not physically closed but released to the pool and will get reused. If it is disabled, it will be physically closed.

Is there any way of knowing programmatically if connection pooling is enabled or not? and the number of used and unused connections currently open in the pool?

EDIT: I need to get this information from within the program, I can't go and check it manually on every single PC where the program will be deployed.

Answer:
MSDN as
in-depth guidelines on this
Configuring Connection Pooling from
the Data Source Administrator
[snip]
Alternatively, you can start the ODBC
Data Source Administrator at the Run
prompt. On the taskbar,
click Start,
click Run, and then type Odbcad32.
The tab for managing connection
pooling is found in the ODBC Data
Source Administrator dialog box in
version ODBC 3.5 and later.
Configuring Connection Pooling from
the Registry
For versions prior to version 3.5 of
the ODBC core components, you need to
modify the registry directly to
control the connection pooling
CPTimeout value.
Pooling is always handled by data server software. The whole point being is that in .NET you shouldn't have to worry about it (for example, this is why you should always use the SqlConnection when working with SQL Server - part of it is that it enables the connection pooling).
Update
On Vista, just type "ODBC" in the Start menu and it will find the app for you.
Update Following Clarification from OP
In terms of determining if connection pooling is enabled on each machine, looking at the
MSDN guidelines
I whould say you would best best if you check the registry values (See
this article
for pointers on registry access).
TBH though, unless the client machines are really crappy, I would possibly not even bother.. AFAIK it is enabled by default, and opening connections on a client machine (in my experience) has never been a big deal. It only really becomes a big deal when
lots
are being opened.


Question:
Ok, my web application is at C:\inetpub\wwwroot\website

The files I want to link to are in S:\someFolder

Can I make a link in the webapp that will direct to the file in someFolder?

Answer:
If its on a different drive on the server, you will need to make a
virtual directory
in IIS. You would then link to "
```
/virtdirect/somefolder/
```
"


Question:
I'm working on an app that requires no user input, but I don't want the iPhone to enter the power saving mode.

Is it possible to disable power saving from an app?

Answer:
Objective-C
```
```
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
```
```
Swift
```
```
UIApplication.shared.isIdleTimerDisabled = true
```
```


Question:
I want to call a web service, but I won't know the url till runtime.

Whats the best way to get the web reference in, without actually committing to a url.

What about having 1 client hit the same web service on say 10 different domains?

Answer:
Create the web reference, and convert the web service to a dynamic web service. A dynamic web service allows you to modify the Url.
You need to create the web reference now to ensure your application understands the interfaces available. By switching to a dynamic web service you can then modify the .Url property after you have initialised the web reference in your code.
```
```
service = new MyWebService.MyWebService();
service.Url = myWebServiceUrl;
```
```


Question:
When providing a link to a PDF file on a website, is it possible to include information in the URL (request parameters) which will make the PDF browser plugin (if used) jump to a particular bookmark instead of just opening at the beginning?

Something like: http://www.somehost.com/user-guide.pdf?bookmark=chapter3 ?

If not a bookmark, would it be possible to go to a particular page?

I'm assuming that if there is an answer it may be specific to Adobe's PDF reader plugin or something, and may have version limitations, but I'm mostly interested in whether the technique exists at all.

Answer:
Yes, you can link to specific pages by number or named locations and that will always work
if the user's browser uses Adobe Reader as plugin for viewing PDF files
.
For a specific page by number:
```
```
Link text
```
```
For a named location (destination):
```
```
Link text
```
```
To create destinations within a PDF with Acrobat:
Manually navigate through the PDF for the desired location
Go to View > Navigation Tabs > Destinations
Under Options, choose Scan Document
Once this is completed, select New Destination from the Options menu and enter an appropriate name


Question: How do I write a program that tells when my other program ends?

Answer:
This is called the "halting problem" and is not solvable.
See
http://en.wikipedia.org/wiki/Halting_problem


Question:
So I'm writing a framework on which I want to base a few apps that I'm working on (the framework is there so I have an environment to work with, and a system that will let me, for example, use a single sign-on)

I want to make this framework, and the apps it has use a Resource Oriented Architecture.

Now, I want to create a URL routing class that is expandable by APP writers (and possibly also by CMS App users, but that's WAYYYY ahead in the future) and I'm trying to figure out the best way to do it by looking at how other apps do it.

Answer:
Use a list of Regexs to match which object I should be using
For example
```
```
^/users/[\w-]+/bookmarks/(.+)/$
^/users/[\w-]+/bookmarks/$
^/users/[\w-]+/$
```
```
Pros: Nice and simple, lets me define routes directly
Cons: Would have to be ordered, not making it easy to add new things in (very error prone)
This is, afaik, how Django does it


Question: I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?

Answer:
Depends on what you want to do.  To append you can open it with "a":
```
```
with open("foo.txt", "a") as f:
     f.write("new line\n")
```
```
If you want to preprend something you have to read from the file first:
```
```
with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before
```
```


Question: I would like to know your experience when you need to take over somebody else's software project - more so when the original software developer has already resigned.

Answer: The most success that we've had with that is to "wiki" everything. During the notice period ask the leaving developer to help you document everything in the team/company wiki and see if you can do code reviews with him/her and add comments to the code while doing the reviews that explain sections. Best for the "taking over" developer to write the comments in the code under the supervision of the leaver.


Question: Is there any way to edit column names in a DataGridView?

Answer:
I don't think there is a way to do it without writing custom code.
I'd implement a ColumnHeaderDoubleClick event handler, and create a TextBox control right on top of the column header.


Question:
I'm wondering, and in need, of strategies that can be applied to reducing low-level locking.
However the catch here is that this is not new code (with tens of thousands of lines of C++ code) for a server application, so I can't just rewrite the whole thing.

I fear there might not be a solution to this problem by now (too late). However I'd like to hear about good patterns others have used.

Right now there are too many lock and not as many conflicts, so it's a paranoia induced hardware performance issue.
The best way to describe the code is as single threaded code suddenly getting peppered with locks.

Answer:
The threading model of your program has to be decided before a single line is written. Any module, if inconsistent with the rest of the program, can crash, corrupt of deadlock the application.
If you have the luxury of starting fresh, try to identify large functions of your program that can be done in parallel and use a thread pool to schedule the tasks. The trick to efficiency is to avoid mutexes wherever possible and (re)code your app to avoid contention for resources at a high level.


Question: I'm looking for a way to set the default language for visitors comming to a site built in EPiServer for the first time. Not just administrators/editors in the backend, people comming to the public site.

Answer:
Depends on your setup.
If the site languages is to change under different domains you can do this.
Add to configuration -> configSections nodes in web.config:
```
```
<sectionGroup name="episerver">
  <section name="domainLanguageMappings" allowDefinition="MachineToApplication" allowLocation="false" type="EPiServer.Util.DomainLanguageConfigurationHandler,EPiServer" />
```
```
..and add this to episerver node in web.config:
```
```
<domainLanguageMappings>
    <map domain="site.com" language="EN" />
    <map domain="site.se" language="SV" />
  </domainLanguageMappings>
```
```
Otherwhise you can do something like this.
Add to appSettings in web.config:
```
```
<add name="EPsDefaultLanguageBranch" key="EN"/>
```
```