Question:
I am trying to remotely run a DTSX package from a bat file with this command:

DTEXEC /DTS "\File System\MY_PACKAGE_NAME" /SERVER MY_SERVER_NAME /MAXCONCURRENT " -1 " /CHECKPOINTING OFF  /REPORTING V

This is working fine locally but failing remotely (I do have admin rights on the machine I am pointing to and I have SQL permissions as well) I am getting a timeout error (Login timeout expired).

Answer:
After a bit of research it looks like it is impossible to run DTEXEC remotely (it needs to be run locally - remote execution is not supported).
To overcome this limitation the following method seems to be broadly implemented:
set up a SQL job to run the DTSX package
set up a Stored Procedure to run the job
use isql command line in a BAT file (remotely executed) to run the stored procedure on the relevant SQL instance (with SQL credentials and not machine credentials)


Question: Is it possible to use oracle instant client for application that use oraoledb driver for connecting to oracle 9i DB.

Answer:
I don't believe so.  The
Instant Client FAQ
states
What can Instant Client be used for?
  Instant Client can be used to run your OCI, OCCI, Pro
C, JDBC, and ODBC applications without installing a full Oracle Client. In addition, Instant Client supports SQL
Plus. As of Instant Client 10.2, it is also possible to develop applications for OCI and OCCI using the Instant Client SDK download.
OLE DB is conspicuously absent from that list.  Now, potentially, you could use the Microsoft OLE DB to ODBC provider along with the Instant Client and ODBC, but adding additional layers to software is never very fun.


Question:
Is it possible to create a SQL query which will return one column which contains the dates from a given date range (e.g. all dates from last year till today). E.g.

dat
----
2007-10-01
2007-10-02
2007-10-03
2007-10-04
...

I am wondering if this is possible as an alternative to creating a table which holds all those dates precalculated.

Updated: I need a solution for MYSQL. I am not interested in any other DBs in this case.

Answer:
AFAIK you cannot do that with a single SQL query. However the following block of code will do the job.
Currently in Transact-SQL (for SQL Server). I do not know how this translates to MySQL.
```
```
DECLARE @start datetime
DECLARE @end datetime
DECLARE @results TABLE
(
   val datetime not null
)
set @start = '2008-10-01'
set @end = getdate()
while @start < @end
begin
    insert into @results values(@start)
    SELECT @start = DATEADD (d, 1, @start)
end
select val from @results
```
```
This outputs:
```
```
2008-10-01 00:00:00.000
2008-10-02 00:00:00.000
2008-10-03 00:00:00.000
```
```


Question:
what is the best way of displaying/using the revision number in a java webapp?

we just use ant to build our .war archive, no buildserver or such. i'd hope there was some kind if $ref that i could write in a resource file, but this is only updated when the file in question is committed. i need it globally.

what would you recommend? post-commit triggers that update certain files?
custom ant scripts? is there a more non-hacky way of doing this?
or it it better to have my own version number independent of svn.

edit: great suggestions! thanks a lot for the answers!

Answer:
See
this thread
.
My favourite from that thread is just dumping
```
$Id:$
```
in your code where you want the revision ID. SVN will populate that with the real data when you do an export.


Question:
I noticed last night that the WCF extensions for Visual Studio 2005 aren't available on their site any longer.  I've read that they want people to use Visual Studio 2008 for WCF/WF/WPF.

Have they made an official statement regarding this?

edit:

I already have the CTP3 for VS2005.  I want to know what Microsoft's official stance is.  Yes, I've read the threads and the blogs.  If a blog post is all that is needed to make it official then so be it.

Answer:
There was never anything but CTP released for MS Visual Studio 2008
According to
this
thread MS wants you to move to Visual Studio 2008.
This
blog
post confirms that.
You could still download the
CTP3 for Visual Studio 2005
from a third-party server


Question:
Since content of web applications is dynamically generated it would appear that AdSense is not going to produce relevant ads.

Is there a way to increase relevancy of the AdSense ads for the web application?

Is it possible to achieve Gmail-like ad functionality at all for third-party applications?

Is there a better ad provider for web apps than Google?

Answer:
No, it's not really suitable. As you know, AdSense is based on page content and that's rarely going to target the correct ads unless your site is very focused on one advertising niche.
If you run a huge web-app that gets many millions of pageviews, then you might be able to get something worked out with Google privately. Otherwise, you're left to see what the best of the rest has to offer.
Chitika
does have the power to let you specify what niches you want to display adverts from... But their rates and even their quality of adverts aren't up there with Googles. Have a look around. There are thousands of advertising providers and I'm sure you'll find one that fits your model.
... But it's not Google at the moment.


Question:
I have some simple shell scripting tasks that I want to do

For example: Selecting a file in the working directory from a list of the files matching some regular expression.

I know that I can do this sort of thing using standard bash and grep but I would be nice to be able to hack quick scripts that will work in windows and linux without me having to memorize a heap of command line programs and flags etc.

I tried to get this going but ended up getting confused about where I should be getting information such as a reference to the current directory

So the question is what parts of the Ruby libraries do I need to know to write ruby shell scripts?

Answer:
"How do I write ruby" is a little beyond the scope of SO.
But to turn these ruby scripts into executable scripts, put this as the first line of your ruby script:
```
```
#!/path/to/ruby
```
```
Then make the file executable:
```
```
chmod a+x myscript.rb
```
```
and away you go.


Question:
The ASP.NET application that I am currently responsible for at my day job has hit its limit in terms of its ability to scale inside a single server. Obviously we are working toward moving session out of process and the test and hopefully deploy date draws near. I would like to draw on the experiencies of people using the built in load balancing in Windows vs. an appliance solution such as one by Baracudda, Coyote Point, F5 etc. Did you start with one and move to the other and why ?

thoughts and advice appreciated in advance...

Answer:
some thoughts
WLBS is often "good enough" to get you started with NLB.  However like any great engineer - you need to "measure to know"
its not just about scale-up its about soft or hard redundancy too.  We often NLB between VMs just to give us soft redundancy.
NLB applies just as much to back-edge as well as front-edge networks
stepping up to hardware acceleration brings you a new degree of ops costs.  New training specialized support, escalation etc.
look for hardware acceleration to give you a lot more than NLB e.g. DDoS protection, SSL, Compression, Caching, Content Switching, Connection Aggregation, Buffering.
educate both Devs & Ops SE's about hardware acceleration benefits,a great design can merge the line between network operations and application development.
hardware buffering on it's own made our ASP.NET around 30% quicker just by reducing our GC time.
content switching can enable you to transparently merge or migrate disparate systems.  We merged MSDN & MSDN2 platforms into a single url space using this technique.
session stickyness is a dual edged sword - use sparingly - again no substitute for good engineering - measure and test
everything
We use both WLBS and NLB within our network - cost often drives the conversation.  Treat both as tools in the toolbox, learn their nuances, cost models etc.


Question:
I wonder what's the best deployment directory for Rails apps? Some developers use directories such as /u/apps/#{appname}. Are there any advantages when using /u/apps/#{appname} instead of /var/www/#{appname} or other OS default directories?

Obviously I want to pick the directory with the best security properties and the least friction for setting up the server environment.

How do you deploy your Rails apps? Why are you using a specific directory? Do you think it really matters anyway?

Answer:
I tend to create a dedicated user for each rails app I run and install, and add that user to the
```
www-data
```
group. So, I tend to have
```
/home/mephisto/www
```
,
```
/home/warehouse/www
```
and so on.
I do this purely for organization, and I don't think it matters much.


Question:
I was wondering if it would be possible to retrieve the complete list of security roles defined in a web.xml file in the java code? And if so how to do it?

I am aware of the 'isUserInRole' method but I also want to handle cases where a role is requested but not defined (or spelled differently) in the web.xml file.

Answer:
As far as I know, there's no way do do this within the Servlet API.  However, you can parse web.xml directly and extract the values yourself.  I used dom4j below, but you can use whatever XML processing stuff you like:
```
```
protected List<String> getSecurityRoles() {
    List<String> roles = new ArrayList<String>();
    ServletContext sc = this.getServletContext();
    InputStream is = sc.getResourceAsStream("/WEB-INF/web.xml");

    try {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(is);

        Element webApp = doc.getRootElement();

        // Type safety warning:  dom4j doesn't use generics
        List<Element> roleElements = webApp.elements("security-role");
        for (Element roleEl : roleElements) {
            roles.add(roleEl.element("role-name").getText());
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    return roles;
}
```
```


Question: I have a web application that generates a long report and I need to print it. If I just print the page it will break at the end of the physical page. How can I calculate where to make a break in the web page so that the page breaks line up with the physical pages when they print?

Answer:
Paged media
Print Reference
page-break-after
(
MDN
)
page-break-before
(
MDN
)
page-break-inside
(
MDN
)


Question:
I find it annoying that I can't clear a list. In this example:

a = []
a.append(1)
a.append(2)

a = []

The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.

The only way I can see of retaining the same pointer is doing something like the following:

for i in range(len(a)):
    a.pop()

This seems pretty long-winded though, is there a better way of solving this?

Answer:
You are looking for:
```
```
del L[:]
```
```


Question:
I have never quite understood how/why I would use Maven modules (reactor builds).

We have tens of libraries that we share (as dependencies) among our products, and between libraries as well.  If we were to switch to making them Maven modules, how would we set it up, both in SVN and in our working copies?

Do Maven modules really need to be subfolders? Do they need to be subfolders in the SVN repo too?

Assuming you just need subfolders in the working copy, I suppose svn:externals would work to make, say, a "util" library be a module of multiple projects at the same time.  But I've read many bad things about using svn:externals because there is nothing to stop you from modifying the code in the external, but its not tracked.

Any suggestions?  Am I missing the boat on modules?

Answer:
No ... a modular project should only be used when the child project is integrated into the parent to create a larger artifact, so an example might be an Enterprise project, where your modules contain the EJB (server and client), the WAR, and then those are combined into an EAR file.  This modularity is only for convenience and can be skipped if preferred.
In the case of reusable libraries, make them independent projects and deploy them to a shared repository.  Then they must be referenced as dependencies in the project using them.


Question:
In a C++ file, I have a code like this:

#if ACTIVATE
#   pragma message( "Activated" )
#else
#   pragma message( "Not Activated")
#endif

I want to set this ACTIVE define to 1 with the msbuild command line.

It tried this but it doesn't work:

msbuild /p:DefineConstants="ACTIVATE=1"

Any idea?

Answer:
I think you want:
```
```
/p:DefineConstants=ACTIVATE
```
```


Question: I have a .bat and inside the .bat i would like to execute a special code if there's some modification inside the svn repository (for example, compile).

Answer:
Are you wanting this to be reactive? Or, on-demand?
For reactive, see
hooks
. The script will have to be named according to it's purpose:
pre-commit.bat
,
post-commit.bat
. The scripts are called as:
[script] [repos-path] [revision-number]
For, on-demand:
Working Copy
svn log
svn st
svn diff
svn proplist
Repository
svnlook author
svnlook changed
svnlook date
svnlook diff
svnlook history
Example:
```
```
svn st "C:\path\to\working\directory\" >> C:\path\to\working\project.log
```
```
Every time you run the BAT, it'll add the
st
output to
project.log
. Adjust as needed.


Question:
How do I set the code page to UTF-8 in a C Windows program?

I have a third party library that uses fopen to open files. I can use wcstombs to convert my Unicode filenames to the current code page, however if the user has a filename with a character outside the code page then this breaks.

Ideally I would just call _setmbcp(65001) to set the code page to UTF-8, however the MSDN documentation for _setmbcp states that UTF-8 is not supported.

How can I get around this?

Answer:
All Windows APIs think in UTF-16, so you're better off writing a wrapper around your library that converts at the boundaries.
Oddly enough, Windows thinks UTF-8 is a codepage for the purposes of conversion, so you use the same APIs as you would to convert between codepages:
```
```
std::wstring Utf8ToUtf16(const char* u8string)
{
    int wcharcount = strlen(u8string);
    wchar_t *tempWstr = new wchar_t[wcharcount];
    MultiByteToWideChar(CP_UTF8, 0, u8string, -1, tempWstr, wcharcount);
    wstring w(tempWstr);
    delete [] tempWstr;
    return w;
}
```
```
And something of similar form to convert back.


Question: How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?

Answer:
```
```
import socket
socket.gethostbyname(socket.gethostname())
```
```
This won't work always (returns
```
127.0.0.1
```
on machines having the hostname in
```
/etc/hosts
```
as
```
127.0.0.1
```
), a paliative would be what gimel shows, use
```
socket.getfqdn()
```
instead. Of course your machine needs a resolvable hostname.


Question: Is there any way so that i can echo password when asked for in unix shell without use of external binaries ? Something like simple function triggered when password prompt is displayed

Answer:
```
```
import socket
socket.gethostbyname(socket.gethostname())
```
```
This won't work always (returns
```
127.0.0.1
```
on machines having the hostname in
```
/etc/hosts
```
as
```
127.0.0.1
```
), a paliative would be what gimel shows, use
```
socket.getfqdn()
```
instead. Of course your machine needs a resolvable hostname.


Question:
Sorry for the long question title.

I guess I'm on to a loser on this one but on the off chance.

Is it possible to make the calculation of a calculated field in a table the result of an aggregate function applied to a field in another table.

i.e.

You have a table called 'mug', this has a child called 'color' (which makes my UK head hurt but the vendor is from the US, what you going to do?) and this, in turn, has a child called 'size'. Each table has a field called sold.

The size.sold increments by 1 for every mug of a particular colour and size sold.

You want color.sold to be an aggregate of SUM size.sold WHERE size.colorid = color.colorid

You want mug.sold to be an aggregate of SUM color.sold WHERE color.mugid = mug.mugid

Is there anyway to make mug.sold and color.sold just work themselves out or am I going to have to go mucking about with triggers?

Answer:
No, it is not possible to do this.  A computed column can only be derived from the values of other fields on the same row.  To calculate an aggregate off another table you need to create a view.
If your application needs to show the statistics ask the following questions:
Is it really necessary to show this in real time?  If so, why?  If it is really necesary to do this, then you would have to use triggers to update a table.
This
links to a short wikipedia article on denormalisation.  Triggers will affect write performance on table updates and relies on the triggers being active.
If it is only necessary for reporting purposes, you could do the calculation in a view or a report.
If it is necessary to support frequent ad-hoc reports you may be into the realms of a data mart and overnight ETL process.


Question:
Does NetworkStream.DataAvailable know whether the sender's send buffer is empty? Or does it simply indicate whether the receiver's read buffer has data? My assumption is the latter...

Specifically, for some socket work involving an ongoing conversation, I currently use a length-prefix so the the receiver knows exactly how much data is in the current batch; however, I've been sent a .patch suggesting I use NetworkStream.DataAvailable instead. My concern is that this will just tell me what the receiver has got - not what the sender originally sent - but I'm not a sockets expert.

Am I wrong? Or is length-prefix the way to go?

(note I can't simply Read() until the stream is closed, since multiple batches are sent on the same connection, and it is vital that I treat each batch as separate; if I read too much in one batch (even if it gets buffered and discarded) then the conversation will break).

Answer:
One side of a connection is not going to know whether the other side's send buffer is empty.
```
DataAvailable
```
only indicates whether there is incoming data to be read. You could use that prior to
```
Read()
```
, but it alone doesn't give you the information you want. It doesn't tell you the beginning and ending of each batch.
I've coded back-and-forth conversation before, and I used length-prefixes in the data. What I did was write helper functions that read an exact number of bytes (chunks at a time) and no more.
The only alternative to length-of-batch values in the stream is some way of examining the incoming data and recognizing the beginnings and endings of batches.


Question: How can I find the public facing IP for my net work in Python?

Answer:
This will fetch your remote IP address
```
```
import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
```
```
If you don't want to rely on someone else, then just upload something like this PHP script:
```
```
<?php echo $_SERVER['REMOTE_ADDR']; ?>
```
```
and change the URL in the Python or if you prefer ASP:
```
```
<%
Dim UserIPAddress
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
%>
```
```
Note: I don't know ASP, but I figured it might be useful to have here so I googled.


Question: I'm trying to handle this possible exploit and wondering what is the best way to do it? should i use apache's common-validator and create a list of known allowed symbols and use that?

Answer:
From the
wikipedia article
:
The generic solution is to URL-encode strings before inclusion into HTTP headers such as Location or Set-Cookie.
Typical examples of sanitization include casting to integer, or aggressive regular expression replacement. It is worth noting that although this is not a PHP specific problem, the PHP interpreter contains protection against this attack since version 4.4.2 and 5.1.2.
Edit
im tied into using jsp's with java actions!
There don't appear to be any JSP-based protections for this attack vector - many descriptions on the web assume asp or php, but
this link
describes a fairly platform-neutral way to approach the problem (jsp used as an incidental example in it).
Basically your first step is to indentify the potentially hazardous characters (CRs, LFs, etc) and then to remove them. I'm afraid this about as robust a solution as you can hope for!
Solution
Validate input. Remove CRs and LFs (and all other hazardous characters) before embedding data into any HTTP response headers, particularly when setting cookies and redirecting. It is possible to use third party products to defend against CR/LF injection, and to test for existence of such security holes before application deployment.


Question:
In java, when using SimpleDateFormat with the pattern:

yyyy-MM-dd'T'HH:mm:ss.SSSZ

the date is outputted as:

"2002-02-01T18:18:42.703-0700"

In xquery, when using the xs:dateTime function, it gives the error:

"Invalid lexical value [err:FORG0001]"

with the above date. In order for xquery to parse properly, the date needs to look like:

"2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string

which is based on the ISO 8601, whereas Java date is based on the RFC 822 standard.

I would like to be able to easily specify the timezone in Java so that it will output the way that xquery wants.

Thanks!

Answer:
Try this:
```
```
static public String formatISO8601(Calendar cal) {
MessageFormat format = new MessageFormat("{0,time}{1,number,+00;-00}:{2,number,00}");

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
df.setTimeZone(cal.getTimeZone());
format.setFormat(0, df);

long zoneOff = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) / 60000L;
int zoneHrs = (int) (zoneOff / 60L);
int zoneMins = (int) (zoneOff % 60L);
if (zoneMins < 0)
    zoneMins = -zoneMins;

return (format.format(new Object[] { cal.getTime(), new Integer(zoneHrs), new Integer(zoneMins) }));
}
```
```


Question:
I need to either find a file in which the version is encoded or a way of polling it across the web so it reveals its version. The server is running at a host who will not provide me command line access, although I can browse the install location via FTP.

I have tried HEAD and do not get a version number reported.

If I try a missing page to get a 404 it is intercepted, and a stock page is returned which has no server information on it. I guess that points to the server being hardened.

Still no closer...

I put a PHP file up as suggested, but I can't browse to it and can't quite figure out the URL path that would load it. In any case I am getting plenty of access denied messages and the same stock 404 page. I am taking some comfort from knowing that the server is quite robustly protected.

Answer:
The method
Connect to port 80 on the host and send it
```
```
HEAD / HTTP/1.0
```
```
This needs to be followed by carriage-return + line-feed twice
You'll get back something like this
```
```
HTTP/1.1 200 OK
Date: Fri, 03 Oct 2008 12:39:43 GMT
Server: Apache/2.2.9 (Ubuntu) DAV/2 SVN/1.5.0 PHP/5.2.6-1ubuntu4 with Suhosin-Patch mod_perl/2.0.4 Perl/v5.10.0
Last-Modified: Thu, 02 Aug 2007 20:50:09 GMT
ETag: "438118-197-436bd96872240"
Accept-Ranges: bytes
Content-Length: 407
Connection: close
Content-Type: text/html; charset=UTF-8
```
```
You can then extract the apache version from the Server: header
Typical tools you can use
You could use the HEAD utility which comes with a full install of Perl's
LWP
library, e.g.
```
```
HEAD http://your.webserver.com/
```
```
Or, use the
curl
utility, e.g.
```
```
curl --head http://your.webserver.com/
```
```
You could also use a browser extension which lets you view server headers, such as
Live HTTP Headers
or
Firebug
for Firefox, or
Fiddler
for IE
Stuck with Windows?
Finally. if you're on Windows, and have nothing else at your disposal, open a command prompt (Start Menu->Run, type "cmd" and press return), and then type this
```
```
telnet your.webserver.com 80
```
```
Then type (carefully, your characters won't be echoed back)
```
```
HEAD / HTTP/1.0
```
```
Press return twice and you'll see the server headers.
Other methods
As mentioned by cfeduke and Veynom, the server may be set to return limited information in the Server: header. Try and upload a PHP script to your host with this in it
```
```
<?php phpinfo() ?>
```
```
Request the page with a web browser and you should see the Apache version reported there.
You could also try and use
PHPShell
to have a poke around, try a command like
```
```
/usr/sbin/apache2 -V
```
```


Question:
I am currently plowing my way through IBM's tutorial on CakePHP

At one point I run into this snippet of code:

<?php
class Dealer extends AppModel {
    var $name = 'Dealer';
    var $hasMany = array (
        'Product' => array(
            'className' => 'Product',
            'conditions'=>, // is this allowed?
            'order'=>, // same thing here
            'foreignKey'=>'dealer_id'
        )
    );
}
?>

When I run it I get the following error-message: "Parse error: syntax error, unexpected ',' in /Applications/MAMP/htdocs/cakephp/app/models/product.php on line 7"

I'm a n00b at PHP so my question is: is it allowed to make an array with keys without assigned values? Has anybody played around with this tut and know what is up?

Answer:
It is legal, though as far as I'm aware, you have to explicitly say it's 'empty' by assigning null to it,
```
```
$hasMany = array ('Product' => array(
'className' => 'Product',
'conditions'=> null, // is this allowed?
'order'=> null, // same thing here
'foreignKey'=>'dealer_id'));
```
```
The example you've given sounds very wrong, and probably shouldn't work, as it isn't.


Question:
I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there a direct way to do this using either std::strings or char* strings?

E.g., in Python you could simply do

>>> "." * 5 + "lolcat"
'.....lolcat'

Answer:
In the particular case of repeating a single character, you can use
```
std::string(size_type count, CharT ch)
```
:
```
```
std::string(5, '.') + "lolcat"
```
```
This can't be used to repeat multi-character strings.


Question:
Currently, I'm in the process of hiring a web developer who will be working on a site that processes credit cards. While he won't have the credentials to log into the payment gateway's UI he will have access to the API login and transaction key since it's embedded in the application's code.

I'd like to be aware of all the "what if" scenarios pertaining to the type of damage one could do with that information. Obviously, he can process credit cards but the money goes into the site owner's bank account so I'm not sure how much damage that could cause. Can anyone think of any other possible scenarios?

UPDATE: The payment gateway being used is Authorize.net.

Answer:
If the developer gets access to the raw credit card numbers that can become a bigger problem as your site can be associated with fraudulent activity, assuming the developer is a bad apple.  (They could redirect account numbers, CCV, expiration date to another site, though this should be spottable through network tools and a comprehensive code review.)
Does the API perform the "$1.00" charge (or "$X.XX") to verify that a credit card can be charged a certain amount (and thus returning the result to the caller, such as "yes" or "no")?  If so, it could be used to automate the validation of credit card account numbers traded on the Internet and abuse of such a system could lead back to you.


Question:
In the following example should I expect that values.size() will be called every time around the loop? In which case it might make sense to introduce a temporary vectorSize variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change.

double sumVector(const std::vector<double>& values) {
    double sum = 0.0;
    for (size_t ii = 0; ii < values.size(); ++ii) {
        sum += values.at(ii);
    }
}

Note that I don't care if there are more efficient methods to sum the contents of a vector, this question is just about the use of size() in a for construct.

Answer:
It all depends on what the vector's size implementation is, how aggressive the compiler is and if it listen/uses to inline directives.
I would be more defensive and introduce the temporary as you don't have any guarantees about how efficient your compiler will be.
Of course, if this routine is called once or twice and the vector is small, it really doesn't matter.
If it will be called thousands of times, then I would use the temporary.
Some might call this premature optimization, but I would tend to disagree with that assessment.
While you are trying to optimize the code, you are not investing time or obfuscating the code in the name of performance.
I have a hard time considering what is a refactoring to be an optimization.  But in the end, this is along the lines of "you say tomato, I say tomato"...


Question: I am using MailLogger to send a message about a failed/successful release. I would like to make the mail body simple and easy to read. How can I suppress output for some particular tasks?

Answer:
It all depends on what the vector's size implementation is, how aggressive the compiler is and if it listen/uses to inline directives.
I would be more defensive and introduce the temporary as you don't have any guarantees about how efficient your compiler will be.
Of course, if this routine is called once or twice and the vector is small, it really doesn't matter.
If it will be called thousands of times, then I would use the temporary.
Some might call this premature optimization, but I would tend to disagree with that assessment.
While you are trying to optimize the code, you are not investing time or obfuscating the code in the name of performance.
I have a hard time considering what is a refactoring to be an optimization.  But in the end, this is along the lines of "you say tomato, I say tomato"...


Question:
I would like to know what kind of toolkits, languages, libraries exist for agent-based modeling and what are the pros/cons of them?

Some examples of what I am thinking of are
Swarm, Repast, and MASS.

Answer:
I got introduced to
Dramatis
at OSCON 2008, it is an Agent based framework for Ruby and Python.  The author (Steven Parkes) has some references in his blog and is working at running a language agnostic
Actors discussion list
.
This page
at erights.org has a great set of references to, what I think are, the core papers that introduce and explore the Actors message passing model.


Question: I know I can cycle through my tabs using cmd+{ or cmd+}, but is it possible to select a specific tab (i.e. cmd+3 for the third tab in iTerm) in Leopards' Terminal.app?

Answer:
Yes it is, you use Command-1, Command-2 etc.
Have a look under the
Window
menu, and you'll see the windows listed with their shortcut equivalent. (The 'clover-leaf' is the symbol for the Command key - also known as the Apple key.)
My apologies - missed the fact you were referring to Tabs first time around. I don't believe there is any other keyboard shortcut to switch between Tabs beyond Cmd-{ and }. Perhaps if that's important, don't group them in the first place? Leave them as separate windows?


Question: I have noticed that some apps like Safari and Mail show a loading indicator in the status bar (the bar at the very top of the phone) when they are accessing the network. Is there a way to do the same thing in SDK apps, or is this an Apple only thing?

Answer:
It's in UIApplication:
For Objective C:
Start:
```
```
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
```
```
End:
```
```
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
```
```
For swift :
Start
```
```
UIApplication.shared.isNetworkActivityIndicatorVisible = true
```
```
End
```
```
UIApplication.shared.isNetworkActivityIndicatorVisible = false
```
```


Question:
I've got a byte() array returned as result of directx sound capture, but for other parts of my program I want to treat the results as single(). Is trundling down the array item by item the fastest way of doing it or is there a clever way to do it ?

The code that gets it is

CType(Me._applicationBuffer.Read(Me._nextCaptureOffset, GetType(Byte), LockFlag.None, LockSize), Byte())

which creates the byte array, can Ctype handle single ? (note, I can't figure out a way to  do it!)

Answer:
Try
```
```
float f = BitConverter.ToSingle(bytearray, 0);
```
```
In VB (I think):
```
```
Dim single s;
s = BitConverter.ToSingle(bytearray, 0);
```
```


Question:
Does anyone know the full list of C# compiler number literal modifiers?

By default declaring '0' makes it an Int32 and '0.0' makes it a 'Double'. I can use the literal modifier 'f' at the end to ensure something is treated as a 'Single' instead. For example like this...

var x = 0;    // x is Int32
var y = 0f;   // y is Single

What are the other modifiers I can use? Is there one for forcing to Double, Decimal, UInt32? I tried googling for this but could not find anything. Maybe my terminology is wrong and so that explains why I am coming up blank. Any help much appreciated.

Answer:
```
```
var y = 0f; // y is single
var z = 0d; // z is double
var r = 0m; // r is decimal
var i = 0U; // i is unsigned int
var j = 0L; // j is long (note capital L for clarity)
var k = 0UL; // k is unsigned long (note capital L for clarity)
```
```
From the
C# specification
2.4.4.2 Integer literals and 2.4.4.3 Real literals. Take note that L and UL are preferred as opposed to their lowercase variants for clarity as recommended by
Jon Skeet
.


Question:
Suppose I have a base class B, and a derived class D.  I wish to have a method foo() within my base class that returns a new object of whatever type the instance is.  So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation resides solely in the base class B.

Is this possible?

Answer:
As long as each class has a default constructor:
```
```
public B instance() throws Exception {
        return getClass().newInstance();
    }
```
```


Question:
I wonder, why the hell... did the VS team consider that NOT finding a project reference as a non crucial thing?

The referenced component 'X' could not be found. should be considered an error... and nothing else.

Is there a way (without turning 'Treat all warnings as errors' on) to get this warning as an error in VS2008?

Answer:
That warning comes from the project system, not the compiler.  The project system doesn't know whether or not the reference will actually be needed when the code is compiled.  I've run into several cases (all involving multiple platforms and conditional compilation) where this features allows you to maintain a single project file when you might otherwise have to split into one file per configuration.
There is an option to "treat warnings as errors" -- you should be able to find it in the project configuration screen.


Question:
I'm working on an integration testing project in .NET. The testing framework executable starts a service and then needs to wait for the service to complete an operation.

What is the best approach for the exe to wait on the service to complete its task (the service itself will not exit upon task completion)?

Both processes have access to the same database, so my first thought was a simple table that records the service's status. Once it's signaled that it's done, the exe can stop waiting and complete its task. Other approaches?

Let me reiterate that the service, once it has completed its task, will remain in a running/in-memory state, so waiting for it to exit won't work. ;-)

Also, this is purely for integration testing purposes, and will never go into production, so "simple" is the operative word.

Answer:
You could use IPC Channels:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6143016.html
Or maybe two way remoting:
http://www.codeproject.com/KB/IP/TwoWayRemoting.aspx
The database route would be
simple
, but not necessarily the best.


Question:
What is the PHP preg_replace in C#?

I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do something like that in C# without using .Replace("old","new").

$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';

$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);

Answer:
You are looking for
```
System.Text.RegularExpressions
```
;
```
```
using System.Text.RegularExpressions;

Regex r = new Regex("=C0");
string output = r.Replace(text);
```
```
To get PHP's array behaviour the way you have you need multiple instances of `Regex
However, in your example, you'd be much better served by .Replace(old, new), it's much faster than compiling state machines.


Question:
Possible Duplicate:

  VS2008 Setup Project: Shared (By All Users) Application Data Files?

Please can someone advice what is the best place (path) to put some application data which should be accessible and editable by all users.

This is considering both Windows XP and Windows Vista and i expect that change in any file of above path does NOT trigger UAC!

Answer:
```
```
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
```
```
Should resolve to C:\Documents and Settings\All Users\Application Data\
From there, make subfolders such as MyCompany\MyApp


Question:
Is it possible to have a different set of dependencies in a maven pom.xml file for different profiles?

e.g.

mvn -P debug
mvn -P release

I'd like to pick up a different dependency jar file in one profile that has the same class names and different implementations of the same interfaces.

Answer:
To quote the
Maven documentation on this
:
A profile element contains both an optional activation (a profile trigger) and the set of changes to be made to the POM if that profile has been activated. For example, a project built for a test environment may point to a different database than that of the final deployment.
Or dependencies may be pulled from different repositories based upon the JDK version used
.
(Emphasis is mine)
Just put the dependency for the
```
release
```
profile inside the profile declaration itself and do the same for
```
debug
```
.
```
<profiles>
    <profile>
        <id>debug</id>
        …
        <dependencies>
            <dependency>…</dependency>
        </dependencies>
        …
    </profile>
    <profile>
        <id>release</id>
        …
        <dependencies>
            <dependency>…</dependency>
        </dependencies>
        …
    </profile>
</profiles>
```


Question:
I have a problem similar to the one found here : JSF selectItem label formatting.

What I want to do is to accept a double as a value for my  and display it with two decimals. Can this be done in an easy way?

I've tried using  but that seems to be applied on the value from the inputText that is sent to the server and not on the initial value in the input field.

My code so far:

<h:inputText id="december" value="#{budgetMB.december}" onchange="setDirty()" styleClass="StandardBlack">
    <f:convertNumber maxFractionDigits="2" groupingUsed="false" />
</h:inputText>

EDIT: The above code actually works. I was fooled by JDeveloper that didn't update the jsp page even when I did a explicit rebuild of my project and restarted the embedded OC4J server. However, after a reboot of my computer everything was fine.

Answer:
If I'm not misunderstanding your requirement, I was able to achieve formatting of the value in the input box during the rendering of the view with:
```
```
<h:inputText id="text1" value="#{...}">
    <f:convertNumber pattern="#,###,##0.00"/>
</h:inputText>
```
```
I was using the Standard Faces Components in my vendor-branded Eclipse so I'm assuming the
```
pattern
```
attribute is part of standard JSF.


Question:
I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.

I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP to call the Python script.

Any better ideas? Thanks in advance!

Answer:
Depending on what you are doing,
system()
or
popen()
may be perfect.  Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser.  Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard output in php.  popen() will only let you read or write, but not both.  If you want both, check out
proc_open()
, but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something.
If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection.  If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will.
escapeshellarg()
and
escapeshellcmd()
can help with this, but personally I like to remove everything that isn't a known good character, using something like
```
```
preg_replace('/[^a-zA-Z0-9]/', '', $str)
```
```


Question:
I generally stay away from regular expressions because I seldom find a good use for them. But in this case, I don't think I have choice.

I need a regex for the following situation.  I will be looking at three character strings. It will be a match if the first character is 1-9 or the letters o,n,d (lower or upper)  AND the second character is 1,2 or 3 and the third character is 0-9.

Can anybody help me out?

Answer:
```
```
[1-9ondOND][123][0-9]
```
```
I omitted the
```
^
```
and
```
$
```
(beginning and end of string markers) because you said you'd have three-character strings, but there's no harm in including them, and they may improve speed, not that that'll be a big deal on such short input.
Of course, this assumes you're working in a language and locale where the uppercase equivalent of
```
o
```
,
```
n
```
, and
```
d
```
are
```
O
```
,
```
N
```
, and
```
D
```
. If not, you'll need to tell your regex interpreter to ignore case. The mechanism varies by language/framework.
For python, you'd use something like:
```
```
re.match('[1-9ond][123][0-9]', inputstring, re.IGNORECASE)
```
```
The
```
re.match
```
forces a match at the beginning of string, so you wouldn't need the
```
^
```
in any case.


Question:
Our team (5-10 developers)  plans to adopt Subversion for our .NET (Visual Studio) projects/solutions (VisualSVN Server, TortoiseSVN / VisualSVN).

What is the best way to organize a new repository tree? Is it okay to use one big repository or is it better to create different repositories for every solution / product line etc.?

Our projects can be categorized this way (example):

Main Product Line

Main Web App

Library 1

Library 2

...

Windows Client

Another Windows Client

Windows Service

Tools

Tool A

Tool B

Product Line 2

Software 1

Software 2

Product Line 3

App 1

App 2

Answer:
We use one big repository, and just have everything structured in subfolders (/project1, /project2 etc) and that seems to work fine.
The Apache project has a
huge svn repository
and it seems to do OK for them! :)
In terms of organisation, the structure you gave looks quite reasonable. I think anything goes, pretty much, so long as it's rational (i.e. mixing up every single tool with every single project is probably a bad idea etc). So pick something which works for you (tools/, projects/ etc). Subversion has pretty good support for moving things around in the repository, too, so you can always change if necessary.


Question: I have a need to display many numerical values in columns. These values need to be easily editable so I cannot just display them in a table. I am using textboxes to display them. Is there a way for me to right-justify the text displayed in a textbox? It would also be nice if when the user is entering data for it to start displaying what they type from the right.

Answer:
Did you try setting the style:
```
```
input {
    text-align:right;
}
```
```
Just tested, this works fine (in FF3 at least):
```
```
<html>
    <head>
        <title>Blah</title>
        <style type="text/css">
        input { text-align:right; }
        </style>
    </head>
    <body>
        <input type="text" value="2">
    </body>
</html>
```
```
You'll probably want to throw a class on these inputs, and use that class as the selector.  I would shy away from "rightAligned" or something like that.  In a class name, you want to describe what the element's function is, not how it should be rendered.  "numeric" might be good, or perhaps the business function of the text boxes.


Question: Does anyone know the API call I can use to change the keyboard layout on a windows machine to Dvorak?  Doing it through the UI is easy but I'd like to have a script that I can run on new VM's to automate the process.

Answer:
You can do this via the registry.  Just save it as a .reg file, and open it on the new VM.  I believe this should do it for remapping to Dvorak:
```
```
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"ScanCode Map"=hex:00,00,00,00,00,00,00,00,22,00,00,00,2d,00,30,00,24,00,2e,00,\
11,00,33,00,33,00,11,00,12,00,20,00,34,00,12,00,1b,00,0d,00,0d,00,1b,00,16,\
00,21,00,17,00,22,00,20,00,23,00,1a,00,0c,00,2e,00,17,00,23,00,24,00,14,00,\
25,00,31,00,26,00,35,00,1a,00,30,00,31,00,13,00,18,00,26,00,19,00,2f,00,34,\
00,28,00,10,00,0c,00,28,00,19,00,13,00,18,00,1f,00,1f,00,27,00,2c,00,35,00,\
15,00,14,00,22,00,16,00,25,00,2f,00,10,00,2d,00,21,00,15,00,27,00,2c,00,00,\
00,00,00
```
```
And if you want to go back:
```
```
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"ScanCode Map"=hex:00,00,00,00,00,00,00,00,01,00,00,00,00,00,00,00
```
```


Question:
I'm trying to understand the best way to get the connection to my databases.

At the moment I've got a method which parses the URL (depending on the URL called the application has to connect to a different database, like customer1.example.com will connect to the customer1 database) and calls

ActiveRecord::Base.establish_connection(conn_string)

where conn_string contains the name of the database.

This method (set_db) is called with a

before_filter :set_db

in my Application controller, so basically for each request I get, the URL is parsed and the application try to do an establish_connection.

I was wondering if I can have a connection pool somewhere....do you have any suggestion about that? Is it better to have a Singleton which keep all the connections made and gives back the right one?

Thanks!
Roberto

Answer:
I'm not a Ruby programmer, but generally speaking a connection pool is a good idea. You can make that connection pool a singleton and hand out/take back connections. The pool can check after taking back a connection whether everything is still in order.
You should have a distinct life cycle and ownership for each connection so two threads don't use a connection at the same time.
Be careful with temporary tables because they belong to one database session. We've had a bug where in high load situations we encountered weird errors. Finally we remembered that we were using temporary tables in our application. In the high load situation database connections broke down and were automatically regenerated by the connection object without the application code knowing it (we had implemented the reconnect, but forgot that it was a problem in such a situation). The temporary table we wanted to read had disappeared.


Question: I have an application which is supposed to work on both windows and Mac and is localized in Portuguese, Spanish and German. I have an ini file from where the localized strings are read from. But the ini file doesn't work with same encoding for the files on both platforms. For Windows I have to have the file in ANSI format or else the accented letters in the localized strings get messed up and on the Mac the same file should be in Western( Mac OS) encoding or else the same result. Is there any way I can get a single file to work on both platforms?

Answer:
(1) There is no such thing as
the
ANSI format. That's an unfortunate term for what on Windows means "the local codepage". In particular, this means that in Europe the interpretation of bytes 128-255 as "ANSI format" will differ between countries. So, I am strongly inclined to argue that it won't even work on your first platform, let alone both.
The solution you will eventually migrate to is Unicode. That works everywhere, with all characters, and the number of a character does not depend on the country or the current date (See introduction of €).


Question:
Given a SCHEMA for implementing tags

ITEM
ItemId, ItemContent

TAG
TagId, TagName

ITEM_TAG
ItemId, TagId

What is the best way to limit the number of ITEMS to return when selecting with tags?

SELECT i.ItemContent, t.TagName FROM item i
INNER JOIN ItemTag it ON i.id = it.ItemId
INNER JOIN tag t ON t.id = it.TagId

is of course the easiest way to get them all back, but using a limit clause breaks down, because you get an duplicate of all the items for each tag, which counts toward the number of rows in LIMIT.

Answer:
Maybe something like
```
```
select i.ItemContent, t.TagName from (SELECT ItemId, ItemContent FROM item limit 10) i
INNER JOIN ItemTag it ON i.ItemId = it.ItemId --You will miss tagless items here!
INNER JOIN tag t ON t.id = it.TagId
```
```


Question:
I changed the MembershipProvider in my ASP.net MVC website, and now the stylesheet for the login page isn't referenced correctly. Below is a copy of the forms tag in my web.config if that could be the reason. It looks identical though to the one generated by a new project with the exception of the name and timeout attribute.

<authentication mode="Forms">
      <forms loginUrl="~/Account/Login" name=".ADAuthCookie" timeout="10" />
</authentication>

When I visit the page now, the link tag for the CSS looks like this:

<link href="../Content/Site.css" rel="stylesheet" type="text/css" />

When it should look like this:

<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

Answer:
I haven't used ASP.NET MVC yet myself, but you could try using
ResolveClientUrl
when writing out the href for your CSS:
```
```
<link href="<%= ResolveClientUrl("../../content/Site.css") %> rel="stylesheet" type="text/css" />
```
```


Question:
Having recently discovered this method of development, I'm finding it a rather nice methodology. So, for my first project, I have a small DLL's worth of code (in C#.NET, for what it's worth), and I want to make a set of tests for this code, but I am a bit lost as to how and where to start.

I'm using NUnit, and VS 2008, any tips on what sort of classes to start with, what to write tests for, and any tips on generally how to go about moving code across to test based development would be greatly appreciated.

Answer:
See the book
Working Effectively with Legacy Code
by Michael Feathers.
In summary, it's a lot of work to refactor existing code into testable and tested code; Sometimes it's too much work to be practical. It depends on how large the codebase is, and how much the various classes and functions depend upon each other.
Refactoring without tests will introduce changes in behaviour (i.e. bugs). And purists will say it's not really refactoring because of the lack of tests to check that the behaviour doesn't change.
Rather than adding test across the board to your whole application at once, add tests when  you work in an area of code. Most likely you'll have to return to these "hotspots" again.
Add tests from the bottom up: test little, independent classes and functions for correctness.
Add tests from the top down: Test whole subsystems as black boxes to see if their behaviour changes with changes in code. And so you can step through them to find out what's going on. This approach will probably get you the most benefit.
Don't be too concerned at first with what the "correct" behaviour is while you are adding tests, look to detect and avoid changes in behaviour. Large, untested systems often have internal behaviours that may seem incorrect, but that other parts of the system depend on.
Think about isolating dependencies such as database, filesystem, network, so that they can be swapped out for mock data providers during testing.
If the program doesn't have internal interfaces, lines which define the boundary between one subsystem/layer and another, then you may have to try to introduce these, and test at them.
Also, automatic mocking frameworks like
Rhinomocks
or
Moq
might help mock existing classes here. I haven't really found the need for them in code designed for testability.


Question:
What is the the best of detecting and later altering the screen resolution and multiple desktop within .net

I have a small app that while runs at work on my multiple monitor/high(ish) resolution however what I want to be able to detect is the users primary monitor and set the application to that (main objective) and adjust the resolution to ensure the application fits(more for my own curiosity)

Answer:
I would never suggest altering a user's resolution unless you're doing something like a full-screen game, you can use
```
```
System.Windows.Forms.Screen.PrimaryScreen
```
```
to give you metrics about that main monitor.


Question:
This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this:

a = {1:'', 2:'', 3:'', 4:''}
exclusion = [3, 4, 5]

# have to build up a new list or the iteration breaks
toRemove = []
for var in a.iterkeys():
    if var in exclusion:
        toRemove.append(var)

for var in toRemove:
    del a[var]

This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict.

This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.

Answer:
Consider
dict.pop
:
```
```
for key in exclusion:
     a.pop(key, None)
```
```
The
```
None
```
keeps pop from raising an exception when
```
key
```
isn't a key.


Question:
What is the functional programming approach to convert an IEnumerable<string> to a delimited string?  I know I can use a loop, but I'm trying to wrap my head around functional programming.

Here's my example:

var selectedValues =
from ListItem item in checkboxList.Items
where item.Selected
select item.Value;

var delimitedString = ??

.. or could I do this in just the first var assignment (append each result to the previous)?

Answer:
```
```
string.Join(", ", string[] enumerable)
```
```


Question: Is there a PHP module that you can use to programmatically read a torrent to find out information about it, Seeders for instance?

Answer:
Google comes up with this
PHP client
on sourceforge and
this torrent class
on PHP classes. Should be all you need.


Question:
So I want to start using RSpec stories, but I am not sure where writing controller, model and view specs fit in.

For example, you have the story "Logging in" with "User provides wrong password" scenario, don't you end up testing the same stuff than controller/model specs (response.should render..., user.should be_nil, etc.)

So my question is: for those who are used to doing bdd (or story dd) with RoR, do you still write model/controller specs? If so, how is the workflow you follow ("first story, then narrow to specific specs")?

Answer:
If you are starting with stories now (as opposed to having a lot of legacy stories) you may want to look at
Cucumber
which is the long term replacement for the RSpec story runner.
The easiest way of splitting between specs and stories is to use stories for full-stack testing of business requirements and specs for isolated low-level specifications of the components (views, helpers, controllers and models). 'Full stack' can a range from controller/model/database through client simulation with Webrat to in-browser testing with Watir or Selenium.
The ultimate 'outside in' BDD way of doing things is to start with stories based on customer requirements and then add in specs for the components you find you need when implementing the stories. Ideally you will fully cover the individual components with specs and have stories for the most important workflows of your users so you can check at the highest level that your app is delivering the functionality you have been asked for.


Question:
I have a variable of type Number, and i like to obtain the sign (if is '-' i like to have -1 and if '+' i like to have 1). So, i made this:

var sign = Math.abs(n) / n;

But, there is any other way? Better than this?

Answer:
You'll be in trouble if n == 0... how about this:
```
```
var sign = n < 0 ? -1 : 1;
```
```


Question: Is there a way to configure a Visual Studio 2005 Web Deployment Project to install an application into a named Application Pool rather than the default app pool for a given web site?

Answer:
There is a good article describing custom actions here:
ScottGu's Blog
The question you asked is answered about halfway through the comments by 'Ryan', unfortunately it's in VB, but it shouldn't be hard to translate:
```
```
Private Sub assignApplicationPool(ByVal WebSite As String, ByVal Vdir As String, ByVal appPool As String)
   Try
     Dim IISVdir As New DirectoryEntry(String.Format("IIS://{0}/W3SVC/1/Root/{1}", WebSite, Vdir))
     IISVdir.Properties.Item("AppPoolId").Item(0) = appPool
     IISVdir.CommitChanges()
   Catch ex As Exception
     Throw ex
   End Try
 End Sub

 Private strServer As String = "localhost"
 Private strRootSubPath As String = "/W3SVC/1/Root"
 Private strSchema As String = "IIsWebVirtualDir"
 Public Overrides Sub Install(ByVal stateSaver As IDictionary)
   MyBase.Install(stateSaver)
   Try
     Dim webAppName As String = MyBase.Context.Parameters.Item("TARGETVDIR").ToString
     Dim vdirName As String = MyBase.Context.Parameters.Item("COMMONVDIR").ToString
     Me.assignApplicationPool(Me.strServer, MyBase.Context.Parameters.Item("TARGETVDIR").ToString, MyBase.Context.Parameters.Item("APPPOOL").ToString)
   Catch ex As Exception
     Throw ex
   End Try
 End Sub
```
```
...Where APPPOOL is supplied as an argument in the Custom Action.


Question:
rsync -auve ssh --backup --suffix='2008-10-03-1514539' --backup-dir='/tmp/' module.pm root@web1:/path/to/module.pm

I run this command without the --backup-dir option and when it copies the file over, it creates a backup with a current timestamp. When I include the --backup-dir option, it makes the backup into the /tmp/ directory but never attaches my suffix.

There is nothing in the manual to suggest that you can't use both these options together. I've played around with the order also and nothing seems to fix it.

Does anyone have a solution to this?

Answer:
the manual says:
--backup                make backups (see --suffix & --backup-dir)
--backup-dir=DIR        make backups into hierarchy based in DIR
--suffix=SUFFIX         backup suffix (default ~ w/o --backup-dir)
so it seems that you can use one or the other, not both (as I guess you want a way to determine what's a backup you use a suffix or a directory).
As a way to fix this, why don't you keep the suffix and modify the destination to include the backup directory.


Question:
How do I stop a function/procedure in a superclass from been overridden in a subclass in Delphi (2007)?

I want to mark it so it can not be altered, I believe there is a final keyword but can not for the life of me find the documentation for it, so I am not 100% sure that's what I need.

Answer:
The keyword is
```
final
```
as you thought. See
http://dn.codegear.com/article/34324
and
http://blogs.teamb.com/rudyvelthuis/2005/05/13/4311
. Also you can mark your class as sealed to prevent anyone from inheriting from it. You need a Delphi version higher than 7.
```
```
type
  TSomeClass = class
  protected
    procedure SomeVirtualMethod; virtual;
  end;

  TOtherClass = class(TSomeClass)
  protected
    procedure SomeVirtualMethod; override; final;
  end;
```
```


Question:
Is there a better way to watch for new entries in a table besides selecting from it every n ticks of time or something like that?

I have a table that an external program updates very often, and clients can watch for this new data as it arrive, how can I make that without having to set a fixed period of repeatable select statements?

Answer:
Here's what I do:
I've got some triggers set up for the table (insert, delete, update) and those triggers increment a counter in another table.  My DB access code keeps a local counter and compares it to the returned value, ultimately sending a bool back to the caller, answering the question IsDataCurrent().
Our programs that use this DB access code either poll or check it on-request and then make the appropriate calls to keep themselves up to date.
I'm sure there are other ways to solve this.  It worked for me pretty well, though.


Question: If two users are accessing same database table, how do we prevent users from overwriting each other’s data?

Answer:
There is no straightforward way to do that. You could use transactions to make sure that updates are resolved correctly (i.e. that you do not get partial updates) but you would probably lose the first set of changes as it will be overwritten by the second.
Two options you probably have are:
implement some locking mechanism on the application level (i.e. when someone start editing a record put some flag somewhere which would prevent another user from doing the same)
implement version control so each time someone writes to the database a
new
record is created. This way both sets of data will be in the database and you could have a logic in your application to merge them or select the one you like


Question:
I have a https link that requires user login & password. If I run it in FX like this:
https://usernameassword@www.example.com/link/sublink

it will return the xml data as expected.

However, what i'm trying to do, is to automate this process.
I try to use file_get_contents() in PHP.

I even tried to use AJAX, but still doesn't work.

I tried to get the content (XML) either in Server or in the front-end (ajax), but both don't work.

Does anyone know what I need to go in order to get the content? Do I need to obtain the SSL certificate?

Solution in any ohter languages will be welcome too.

Answer:
There is no straightforward way to do that. You could use transactions to make sure that updates are resolved correctly (i.e. that you do not get partial updates) but you would probably lose the first set of changes as it will be overwritten by the second.
Two options you probably have are:
implement some locking mechanism on the application level (i.e. when someone start editing a record put some flag somewhere which would prevent another user from doing the same)
implement version control so each time someone writes to the database a
new
record is created. This way both sets of data will be in the database and you could have a logic in your application to merge them or select the one you like


Question:
In my Winforms application, I want to export the data from my DataGridView to a Excel spreadsheet.

Is it simply a job of looping and outputting the results comma seperated?

Answer:
Is it simply a job of looping and outputing the results comma seperated?
Yes. It is a simpler way without any dependencies.
If you need more control, you can always automate excel from
vb.net
or from
C#
..


Question: I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?

Answer:
```
```
SELECT DATEADD(ms, -2, DATEADD(dd, 1, DATEDIFF(dd, 0, GetDate())))
```
```
I thought you had c# at first.. I will leave this here in case anyone else stumbles across this.
```
```
DateTime now = DateTime.Now;
DateTime endofDay = now.Date.AddDays(1).AddMilliseconds(-1);
```
```
You can replace the 'now' variable with whatever day you are trying to figure out


Question:
I just want to see what files were modded/added/deleted between 2 arbitrary revisions. How do I do this?

Can I do this in tortoise as well?

Answer:
```
```
svn log -v -rX:Y .
```
```
The -v for "verbose" switch will give you detailed output on which files were affected on that revision.
Note that "." assumes you are currently in a working copy directory, but you can also use a URL such as "
http://svn.myawesomesoftwareproject.com/trunk/lib/foo.c
".
This information can be found by typing "svn help log", or by reading the
SVN Book
, available free online.  Don't forget to
R
ead
T
he
F
riendly
M
anual!


Question:
I have a "Date of Birth" field, and trying to use the timespan() method to get the age in years. But returns "28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes".

Any idea how I can just get the "28 Years" portion?

Answer:
There are many ways to do this, with the string in $date, like so:
```
```
$date = '28 Years, 2 Months, 2 Weeks, 3 Days, 15 Hours, 16 Minutes';
```
```
This will give you "28 Years"
```
```
$yearsPart = substr($date, 0, strpos($date, 'Years') + 5);
```
```
So will this:
```
```
$parts = split(', ', $date);
$yearsPart = $parts[0];
```
```


Question:
We are migrationg from CVS to SVN and embracing some kind of revision management in order to enforce order to development/testing/release cycle. We are currently testing, developing and releasing on the same code line, we know its a bad practice and we want to make end to it.

What are your experience, know how, suggestions working with source code tree.

We are building small/average (2-5 months) custom projects and we have to give early access to customer for review. Requirement creep is common.

EDIT:
please note, i need not only advice on subversion, but more on how whole devel/test/deploy cycle is reflected in trunk/branches/tags/versions etc

Answer:
"Branch early, branch often."
All builds should be completely reproducible without having to pour through logs (consider tagging every build)
If you use an issue tracker then require all check-ins to have a (valid) issue ID included in the commit message (add a pre-hook to check this).
Only the build team should be allowed to make production branches (developers should be encouraged to make personal branches for any non-trivial task)
Build continuously and ensure that everyone is aware that breaking the build is a big deal.
Read the whole SVN book, then read it again. You need to know this tool backwards and forwards. Hold training sessions for your developers ("how to create a temporary branch for my work", "how to merge", etc).
... There is an lack of good reading on this subject, but if I had to recommend one book to a shop completely green in SCM it would be "The Build Master" by Vincent Maraia. It's very short on details but easy to read and provides a (very very brief) overview of SCM good-ideas that make great sense once you know them but which for some reason so many shops completely lack.
Good luck!


Question:
On POSIX systems rename(2) provides for an atomic rename operation, including overwriting of the destination file if it exists and if permissions allow.

Is there any way to get the same semantics on Windows? I know about MoveFileTransacted() on Vista and Server 2008, but I need this to support Win2k and up.

The key word here is atomic... the solution must not be able to fail in any way that leaves the operation in an inconsistent state.

I've seen a lot of people say this is impossible on win32, but I ask you, is it really?

Please provide reliable citations if possible.

Answer:
you still have the rename() call on Windows, though I imagine the guarantees you want cannot be made without knowing the filesystem you're using - no guarantees if you're using FAT for instance.
However, you can use MoveFileEx and use the MOVEFILE_REPLACE_EXISTING
 and MOVEFILE_WRITE_THROUGH options. The latter has this description in MSDN:
Setting this value guarantees that a
  move performed as a copy and delete
  operation is flushed to disk before
  the function returns. The flush occurs
  at the end of the copy operation.
I know that's not necessarily the same as a rename operation, but I think it might be the best guarantee you'll get - if it does that for a file move, it should for a simpler rename.


Question:
Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor?

Motivation: we're migrating from one schema to a another and have a web-page that reads both tables and shows the (int) ID, but I can't have the same ID used for both tables.

I'm using SQL Server 9.0.3068.

Thanks!

Answer:
I think using a
GUID
would be the most straightforward way, if I understand you correctly.
```
```
SELECT NEWID()
```
```


Question:
What's the best way to go about creating a vertical and horizontal ruler bars in an SDI app?  Would you make it part of the frame or the view?  Derive it from CControlBar, or is there a better method?

The vertical ruler must also be docked to a pane and not the frame.

To make it a little clearer as to what I'm after, imagine the vertical ruler in the Dialog Editor in Visual Studio (MFC only). It gets repositioned whenever the tree view is resized.

Answer:
I would
not
use control bars. I have no good reason other then (IMOHO) are difficult to get to do what you want - if what you want if something other than a docking toolbar.
I would just draw them directly on the View window using GDI calls.
I guess I
might
think about making each ruler its own window, and draw the rulers on their own window. I would then create these two CWnd derived classes in the view and position as child windows. This is good if you want to interact with the mouse on these rulers (easier to sort out what messages are for the rulers).


Question:
Example

G76 I0.4779 J270 K7 C90

X20 Y30

If a number begins with I J K C X Y and it doesn't have a decimal then add decimal.
Above example should look like:

G76 I0.4779 J270 K7. C90.

X20. Y30.

Purpose of this code is to convert CNC code for an older Fanuc OPC controller

Answer:
```
```
```
Set RegEx = New RegExp
RegEx.Global = True
RegEx.Pattern = "([IJKCXY]\d+)([^\.]|$)"
newVar = RegEx.Replace (oldString, "$1.$2")
```
```
```
Where oldString is the original string, and newVar is the string with the decimals added.


Question:
I've evaluated some plugins from official IntelliJ repository, but none of them seems to provide more then basic syntax highlighting. Even highlighting is limited. For example, Database Navigator doesn't highlight IF. It would be great to have proper highlighting. And if it would have auto-complete feature and provide file structure view I would be completely happy.
I use SQL Query Plugin when I need to post some little stuff to database or to query something from it. I use PL/SQL Developer when I need to make more complex things, or when I need to modify PL/SQL. But most of the time I need to navigate through mix of Java, JavaScript and PL/SQL code. Unfortunately, SQL Query Plugin doesn't help with that as well as PL/SQL Developer.

Answer:
Have you tried
SQL Query Plugin
? It comes with a great host of features, including multiple query windows, direct editing of tables, and of course, proper highlighting for PL/SQL syntax and a browser of the internal database structure.
It also integrates well with the main editor: you can right-click on any selected Java string containing SQL and "Send to SQLPlugin" to strip out all of the quotes and non-SQL syntax.


Question:
I'm exploring the XML -> XSLT -> HTML meme for producing web content. I have very little XSLT experience.

I'm curious what mechanisms are available in XSLT to handle abstractions or "refactoring".

For example, with generic HTML and a service side include, many pages can be templated and decomposed to where there are, say, common header, nav, and footer segments, and the page itself is basically the body.

The common markup languages, JSP, PHP, ASP, go as far as to allow all of those segments to have dynamic content (such as adding the user name to every header block).

JSP goes even farther by allowing you to create Tag files, which can accept arguments to be used when generating the content, and even surround and work on content within the tags themselves.

I'm curious similar functionality is done within XSLT.  What facilities are there to make reusable block of XSLT for things like creating HTML pages?

Answer:
Templates, Includes.
Xsl is very different from any other programming language.
```
Its rule based.
```
I recommend you to read
something
about Xslt and then ask a bit more spedific.


Question:
In Oracle, given a simple data table:

create table data (
    id       VARCHAR2(255),
    key      VARCHAR2(255),
    value    VARCHAR2(511));

suppose I want to "insert or update" a value. I have something like:

merge into data using dual on
    (id='someid' and key='testKey')
when matched then
    update set value = 'someValue'
when not matched then
    insert (id, key, value) values ('someid', 'testKey', 'someValue');

Is there a better way than this? This command seems to have the following drawbacks:

Every literal needs to be typed twice (or added twice via parameter setting)

The "using dual" syntax seems hacky

If this is the best way, is there any way around having to set each parameter twice in JDBC?

Answer:
I would hide the MERGE inside a PL/SQL API and then call that via JDBC:
```
```
data_pkg.merge_data ('someid', 'testKey', 'someValue');
```
```
As an alternative to MERGE, the API could do:
```
```
begin
   insert into data (...) values (...);
exception
   when dup_val_on_index then
      update data
      set ...
      where ...;
end;
```
```


Question:
Is it possible to have a HasMany relationship of a basic type such as String, on an ActiveRecord class, without the need for creating another entity such as (TodoListItem) to hold the value.

[ActiveRecord]
public class TodoList
{

  [PrimaryKey]
  public int Id
  {
    get { return _id; }
    set { _id = value; }
  }

  [HasMany(typeof(string)]
  public IList<string> Items
  {
    get { return _items; }
    set { _items= value; }
  }
}

Can anyone help?

Answer:
In ActiveRecord, your types map to a record in a table (by default).  It seems like you are confusing how this type should map to your table.
The MyClass type should have a definition something like this (excluding the PK settings):
```
```
[ActiveRecord(Table = "MyTable")]
public class MyClass : ActiveRecordBase<MyClass>
{
    [Property]
    public int Id { get; set; }

    [Property]
    public int MyClassId { get; set; }

    [Property]
    public string ListItem { get; set; }
}
```
```
Then, to load the list:
```
```
public void LoadMyClasses()
{
    MyClass[] results = MyClass.FindAll();
}
```
```
I'd suggest you spend some time with the
ActiveRecord documentation
(or
tutorial
) as that should also help clear up any confusion.


Question:
If I spawn a new thread, and then within it I push a new controller onto my UINavigationController, using code like this...

(a) not working

-(void)myCallbackInThread
{
    // move on...
    UIApplication* app = [UIApplication sharedApplication];
    [app changeView];
}

then I find that the view appears, but does not respond to user input.

If I change the code like this

(b) working

-(void)myCallbackInThread
{
    // move on...
    UIApplication* app = [UIApplication sharedApplication];
    [app performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];
}

Then everything works just fine.

Any hints as to why?

Answer:
Just found this in the iPhone threading docs
If your application has a graphical
  user interface, it is recommended that
  you receive user-related events and
  initiate interface updates from your
  application’s main thread. This
  approach helps avoid synchronization
  issues associated with handling user
  events and drawing window content.
  Some frameworks, such as Cocoa,
  generally require this behavior, but
  it also has the advantage of
  simplifying the logic for managing
  your user interface.
I still don't see what would actually cause something to display but not be able to receive user input, but I'll follow that guideline in future.


Question: How do I in SQL Server 2005 use the DateAdd function to add a day to a date

Answer:
```
```
DECLARE @MyDate datetime

-- ... set your datetime's initial value ...'

DATEADD(d, 1, @MyDate)
```
```


Question:
I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception:

System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.

How do I customize the sorting or comparison logic to handle the null case?

Answer:
The Nullable type exposes a comparison method for comparing nullable types, so the solution is to override the gridview sorting logic and manually specify a comparison:
```
```
gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting);

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
    // Only add custom handling for the sort expression on the
    // Nullable<int> column
    if (e.SortExpression == "MySortExpression")
    {
        // Convert datasource to a List<T>
        list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2)
        {
            return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp);
        }));

        // Bind the sorted list back to the gridview
    }
    else
    {
        // delegate to the gridview to handle its own sorting
    }
}
```
```


Question: We have some raw voice audio that we need to distribute over the internet. We need decent quality, but it doesn't need to be of musical quality. Our main concern is usability by the consumer (i.e. what and where they can play it) and size of the download. My experience has shown that mp3s do not produce the best compression numbers for voice audio, but I am at a loss for what the best alternatives are. Ultimately we would like to automate the conversion process to allow the consumer to choose the quality vs. size level that they would like.

Answer: Assuming your users will be running Windows, there is a WMA speech compression codec that you can use with the Windows Media Encoder SDK. Failing that, you can use ACM to use something like G723/G728, ADPCM, mu-law or a-law, some of which are installed as standard on Windows XP & above. These can be packaged inside WAV files. You'll need to experiment a little to find the right bitrate/quality (probably don't bother with mu-law or a-law). With voice data you can get away with quite low sample rates - e.g. 16000 or 8000, as there isn't much above 4Khz in the human spoken voice.


Question: I'm  trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax.  I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns.

Answer:
Example:
```
```
CREATE TABLE `synthesis`.`INV_MasterItemList` (
   `MasterItemList_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
   `Customer_ID` INTEGER UNSIGNED NOT NULL,
   `Model_ID` INTEGER UNSIGNED NOT NULL,
   `Serial` VARCHAR(45) NOT NULL,
   PRIMARY KEY (`MasterItemList_ID`),
   UNIQUE INDEX `INDEX_UNIQUE`(`Customer_ID`, `Model_ID`, `Serial`)
 )
```
```


Question:
I can't seem to get my application up and running on my dev server and I'm not sure why.

I have compiled my code in VS 2008 with a target framework of 3.5.  I am using 3.5 mainly because I have implemented LINQ rather extensively.  Compiling and runs local without any problems.

The hang up is that my server only has the 2.0 .Net framework and upgrading to 3.5 is apparently not going to happen.

I was under the impression after doing some research that as long as I was trying to execute compiled code the server would not need 3.5 installed.

Today I am trying to publish to the server and I can't get past this error in my WEB.CONFIG

Configuration Error

Parser Error Message: Child nodes not allowed.

providerOption name="CompilerVersion" value="v3.5"/

EDIT ADD ON QUESTION:
I have seen some posts about possibly setting my references to "copy local" which might allow me to run on the 2.0 server.  Thoughts?

Answer:
You're not going to be able to run code targetted to 3.5 on the server unless you get 3.5 installed on it.
The problem isn't your code, rather that the required libraries will be missing.


Question:
Recently I was working with generating a PDF from Crystal Reports through a webform.  It was failing, which I determined to be caused by the permissions settings on the c:\windows\temp dir.   I gave the Network Service account full access to this folder, which promptly fixed the issue.   But is there a reason the Network Service account didn't have these permissions by default?

Rick Strahl asks this question here.  It sounds like there shouldn't be any issues with doing this, but Rick wasn't clear on why the default is set that way.

Web Server is Windows Server 2003

Answer:
These days, the default option will tend to be the more secure one.  I don't think there's any other reason.
I've had the same issue as you, and in my environment just gave the permission and moved on.
This post
suggests it is the fault of Crystal Reports, which is explicitly referencing %WINDIR%\Temp instead of using an API such as Path.GetTempPath().  In fact I have seen Path.GetTempPath() return %WINDIR%\Temp when running under the Network Service account on Windows 2003.


Question:
I am building an application using Spring MVC. I want to make certain changes to my Model for every Controller in the application. In particular, I want to insert certain extra data into the model which will be present for all pages of the application.

I could do this several ways: just add the data at the end of every Controller, use a subclass of Model that adds my extra data, use a subclass of ModelAndView that wraps my Model, use a subclass of VelocityView that wraps the Model before using it... I'm sure there are other options.

But I have an "elegance" constraint: I don't want to write code in each and every Controller, I want this behavior defined in one-and-only-one place. Ideally, it would be controlled by my IOC bean config file.

Does anyone have a recommendation of how to achieve this elegantly?

Answer:
You could take a look at using Aspects.  Spring even has an
AOP
extension that you could use.
In brief an aspect would allow you to define code once that would then get "woven" into your classes either when you compile the classes or when they are loaded by the classloader.  It's relatively advanced stuff and isn't the most intuitive thing for new programmers to pick up, but it's intended to solve exactly the problem you're referring to.


Question:
Let's say I 've added a library foo.so.1.1.1 to a path that is included in /etc/ld.so.conf
When I run ldconfig on the system I get the links foo.so.1.1 and foo.so.1 to foo.so.1.1.1

How can I change the behavior to also get the foo.so link to foo.so.1.1.1?

Answer:
Just make the symlink yourself:
```
```
ln -s /usr/lib/foo.so.1.1.1 /usr/lib/foo.so
```
```
Note that for applications to use libraries in this manner, they need to be explicitly linked against the unversioned shared object.  IE: this is a mechanism to bypass the dynamic loader's version matching system completely.


Question: How do I write the SQL code to INSERT (or UPDATE) an array of values (with probably an attendant array of fieldnames, or with a matrix with them both) without simple iteration?

Answer:
I construct the list as an xml string and pass it to the stored procs. In SQL 2005, it has enhanced xml functionalities to parse the xml and do a bulk insert.
check this post:
Passing lists to SQL Server 2005 with XML Parameters


Question:
I recently began profiling an osgi java application that I am writing using VisualVM.  One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate.  The Heap size and the PermGen size remains constant, however.  The number of classes never falls, even after it stops sending data. Is this a memory leak?  I think it is, because the loaded classes have to be stored somewhere, however the heap and permgen never increase even after I run the application for several hours.

For the screenshot of my profiling application go here

Answer:
Yes, it's usually a memory leak (since we don't really deal with memory directly, it's more of a class instance leak).  I've gone through this process before and usually it's some listener added to an old toolkit that didn't remove it self.
In older code, A listener relationship causes the "listener" object to remain around.  I'd look at older toolkits or ones that haven't been through many revs.  Any long-existing library running on a later JDK would know about reference objects which removes the requirement for "Remove Listener".
Also, call dispose on your windows if you recreate them each time.  I don't think they ever go away if you don't (Actually there is also a dispose on close setting).
Don't worry about Swing or JDK listeners, they should all use references so you should be okay.


Question:
As a programmer I found it very hard to use my laptop and workstation with two different input devices, Can anyone suggest a good solution to use single mouse and keyboard to control my two machines

I am not looking for a Virtual Machine or RDP solution to see my machines in a single monitor,

Answer:
Synergy.
Synergy lets you easily share a single mouse and keyboard between
  multiple computers with different
  operating systems, each with its own
  display, without special hardware.
  It's intended for users with multiple
  computers on their desk since each
  system uses its own monitor(s).
  Redirecting the mouse and keyboard is
  as simple as moving the mouse off the
  edge of your screen. Synergy also
  merges the clipboards of all the
  systems into one, allowing
  cut-and-paste between systems.
  Furthermore, it synchronizes screen
  savers so they all start and stop
  together and, if screen locking is
  enabled, only one screen requires a
  password to unlock them all.
P. S.
See also
how to fix Synergy problems on Vista
.


Question:
I have created a user control to handle adding comments to certain business entities, like contacts and customers.  Works great ... except for one issue.

I am using a ListView control to edit and delete comments, and a separate area, on the same user control to add a new comment.  All of this is wrapped in an UpdatePanel.

Here is my scenario ... the user adds a new comment ... the page does a postback, the data is successfully saved, and the ListView control is updated to show the new comment.  Now, if the user refreshes the browser, it will naturally postback again and will add another duplicate record.

Any ideas on how best to prevent this?

Answer:
I haven't used ASP.NET in a few years, but you should wrap your "do this on postback" code in
```
Page.IsPostBack
```
:
```
```
if(IsPostBack) {
    //do your data-saving code...
}
```
```
MSDN link


Question: I'm specifically thinking about the BugMeNot service, which provides user name and password combos to a good number of sites. Now, I realize that pay-for-content sites might be worried about this (and I would suspect that most watch for shared accounts), but how about other sites? Should administrators be on the lookout for these accounts? Should web developers do anything differently to take them into account (and perhaps prevent their use)?

Answer:
Not make registration mandatory to read something? i.e. Ask people to register when you are providing some functionality for them that 'saves' some settings, data, etc. I would imagine site like stackoverflow gets less fake registrations (reading questions doesn't require an account) than say New York Times, where you need to have an account to read articles.
If that is not upto your control, you may consider removing dormant accounts. i.e. Removing accounts after a certain amount of inactivity.


Question:
I need to do some communications over a serial port in Ruby.  From my research, it appears that there aren't many modern libraries for serial communications and the newest material I can find is from 2006.  Are there any gems that I'm not aware of?

I ultimately need to maintain communications with a serial device attached to USB (I can figure out the port no problem) for back and forth communications like so (somewhat Ruby-esque pseudo code).

def serial_write_read
  if serial.read == "READY"
    serial.write "1"
    until serial.read == "OK"
      serial.write "5"
    end
    return when serial.read == "DONE"
  end
end

Answer:
The serial port specification has not changed in forever, I wouldn't worry about how old the libraries are.
I'm assuming you saw
this
article from 2006 about ruby and serial ports
Here's
someone who got the
Ruby-SerialPort
library mentioned there to work on macs this year.
There's also
this old post
from ruby talk, about interfacing to the Win32 Serial API.


Question:
One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having...

using namespace xyzzy

...statements in them, which impact on my code when I least want or expect it.

Is there a way I can somehow cancel/override a previous "using" statement to avoid this.

Maybe...

unusing namespace xyzzy;

Answer:
No you can't
unuse
a namespace. The only thing you can do is putting the
```
using namespace
```
-statement a block to limit it's scope.
Example:
```
```
{
    using namespace xyzzy;

} // stop using namespace xyzzy here
```
```
Maybe you can change the template which is used of your auto-generated headers.


Question:
I need to be able to GZip compress a file in an Excel VBA function. Specifically I need to be able to use the 'deflate' algorithm.

Is there a way to do this without having to exec a command line application? With no dependency on external tools the code will be more robust.

Ideally the code would make use of pre-installed VBA or COM library functions - I don't want to have to implement this logic myself or install DLLs etc.

If possible, I want installation of the function to be as simple as adding a .xla to the available Excel Add-Ins. No DLLs, EXEs, registry entries etc. required.

Edit Can I make use of the .NET GZipStream to do this?

Answer:
If you want to implement the algorithm in VBA, you would need to (in VBA) save the spreadsheet and then use VB's I/O functions to open the file, deflate it, and save it again. For all intents and purposes it's identical to writing an ordinary VB application that works on a file. You might need to put the VBA macro in a separate workbook to avoid "file in use" types of errors, but if you reopen the file as read-only and save it with a different filename you should be OK keeping everything in one workbook.
But I'm almost certain that shelling out to gzip from within the VBA would be functionally identical and infinitely easier.
EDIT:
Some code. It didn't fail when I ran it, so it's OK to keep everything in the same workbook.
```
```
Sub main()
    ActiveWorkbook.Save
    Open "macrotest.xls" For Binary Access Read As #1
    Open "newfile.zip" For Binary Access Write As #2
        'do your stuff here
    Close #2
    Close #1
End Sub
```
```


Question:
I have a few questions about optimizing this type of load.

One builds a new table of data to be loaded into a partitioned table and then builds the indexes on this new table.

Should you build the index with the COMPUTE STATISTICS option or use the Cascade option of the DBMS_Stats?

Should you gather stats on the table before the swap or on the partition after the swap?

If you do it after the swap and you specify the partition name in the parameter list, what interplay does the granularity parameter have? For instance, if I specify a partition name and then set granularity to 'GLOBAL AND PARTITION' does that do Global at all? Does it do just that one partition?

Answer:
```
DBMS_STATS
```
is considered the proper way to calculate statistics for this version. Building the index with the
```
COMPUTE STATISTICS
```
is doable, but usually you want to calculate all your stats at one time and take snapshots.
You want to gather stats after the swap. This way the optimizer will make the best guess for executing queries using that partitions' data.
Why would you put both?


Question:
So I build an array of various dates. Birthdays, anniversaries, and holidays. I'd like to order the array by which one is happening next, essentially sort October to September (wrapping to next year)

so if my array is

$a = ([0]=>"1980-04-14", [1]=>"2007-06-08",
  [2]=>"2008-12-25", [3]=>"1978-11-03")

I'd like to sort it so it is arranged

$a = ([0]=>"1978-11-03", [1]=>"2008-12-25",
  [2]=>"1980-04-14", [3]=>"2007-06-08")

because the november 'event' is the one that will happen next (based on it being october right now).

I'm trying usort where my cmp function is

function cmp($a, $b)
{
  $a_tmp = split("-", $a);
  $b_tmp = split("-", $b);
  return strcmp($a_tmp[1], $b_tmp[1]);
}

I am not sure how to modify this to get my desired effect.

Answer:
Don't compare strings, instead use seconds since 1970 (ints):
```
```
$date1 = split("-", $a);
$date2 = split("-", $b);
$seconds1 = mktime(0,0,0,$date1[1],$date1[2],$date1[0]);
$seconds2 = mktime(0,0,0,$date2[1],$date2[2],$date2[0]);
// eliminate years
$seconds1 %= 31536000;
$seconds2 %= 31536000;
return $seconds1 - $seconds2;
```
```
Also I don't know PHP but I think the gist is correct.
Edit: The comparison function is encapsulated to perform comparison, nothing more.  To order a list in regards to the original question sort an array with today's date included, locate today's date in the array, and then move the elements before that position to the end in ascending order by position.


Question:
I am developing a small web app project (ColdFusion) and I am trying to keep my project split into multiple files during development, but deploy just one file on completion.

I have references to external files, for instance:

<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<link type="text/css" rel="stylesheet" href="project.css" />

And when I build my project, I want to have the files included and embedded within the single finished product file.

<script type="text/javascript">eval(function(p,a,c,k,e,r) [...]</script>
<style type="text/css">div{font:normal;} [...]</style>

Anyway, it doesn't look like there is a basic way for Ant to do this. Anyone know?

Answer:
Does this do what you want?
```
```
<property
    name="filename"
    value="jquery-1.2.6.pack.js"
/>

<loadfile
    property="contents"
    srcfile="${filename}"
/>

<replace dir=".">
    <include name="index.cfm"/>
    <replacetoken><![CDATA[<script type="text/javascript" src="${filename}"></script>]]></replacetoken>
    <replacevalue><![CDATA[<script type="text/javascript">${contents}</script>]]></replacevalue>
</replace>
```
```


Question:
Does any one know how can I convert a BSTR to an int in VC++ 2008

Thanks in advance.

Answer:
Google suggests
```
VarI4FromStr
```
:
```
```
HRESULT VarI4FromStr(
  _In_   LPCOLESTR strIn,
  _In_   LCID lcid,
  _In_   ULONG dwFlags,
  _Out_  LONG *plOut
);
```
```


Question:
I'm currently writing a website that allows people to download Excel and text files. Is there a way to redirect to a different page when they click, so that we run javascript and do analytics (i.e. keep download count)? Currently, nothing prevents the user from simply right-clicking and saving.

Edit:

To be more specific, it would be nice for a single or double click of a file link to redirect to a temporary download page for analytics, then have the file be downloaded.

Answer:
I'm not sure what you are asking here, are you trying to figure out how to redirect in the controller or are you trying to override the right-click behavior in the browser?
To redirect in the controller you can do something like this documented
here
.
```
```
redirect(controller:"book",action:"list")
```
```
If you are trying to change button or link behavior that's client side and will require some Javascript most likely.
If you clarify I might be able to help more.


Question: I'm planning to build a USB device that has buttons that some software needs to respond to, and indicators that the software needs to control. I'm new to USB, so I'm looking for any pointers that will get me started.

Answer:
When I did some USB development a while ago, I found the information at
USB Central
extremely valuable.
For low bandwidth requirements, you can use something like the
FT232R
which is a single-chip USB serial implementation. The FTDI drivers are readily available and make the device appear as a regular serial port to the host computer. This is orders of magnitude easier than rolling your own USB implementation (for either end!).


Question: I am looking for instructions on how to setup a PEAR channel for our project so that we can deploy it with the pear installer. I have searched the web for a while and cannot find any straightforward information. I followed this tutorial for a while, but I am having a hell of a time getting this to work. Does anyone know how to do this? Is there a simpler way?

Answer:
It looks like you are one of the few people who want to do this. That tutorial you linked to appears to be the latest (!) but the package is still
somewhat in development
. The documentation in that package is also non-existent. It looks like it's up to you to write the docs. Or maybe contact
Greg Beaver
; the author of the package and blog post you linked to. He also
wrote a book about PEAR
(albeit in 2006.) The amazon writeup mentions this:
Next, you will learn how to set up
  your own PEAR Channel for distributing
  PHP applications, both open-source and
  proprietary closed-source PHP
  applications that can be secured using
  technology already built into the PEAR
  Installer
.