Question:
For features comparison of Web Canoo Web Functional Test  and Selenium software, it would be good have an assessment, in terms of integration to Java platform applications, speed, how quick is it to deploy Tests, execute, and analyze results, JavaScript support etc.
I am using Canoo project, it is pretty good.

Tatyana

Answer:
So I initially pursued Canoo as a direction for functional tests.
I ended up choosing Selenium as we saw that running selenium in browser
was a better fit for us than Canoo which uses HTTPUnit to run tests.
If you are running tests at build time with selenium you will need to
have the browser
software you wish to use on the build server.  It is not possible for
us to test IE on our build
server for example....So we only run the tests in Firefox.
The killer feature for us was the Selenium IDE.   We have folks using
the selenium IDE
who are not  really developers which is a great help.   The development team
works with them to make sure the tests are running properly.
Canoo has its own advantages that,  A rather biased blog entry is here:
http://mguillem.wordpress.com/2007/10/29/webtest-vs-selenium-webtest-wins-13-5/
Note that in spite of all those things I still prefer Selenium...


Question:
When we submit a job, the following steps are executed sequentially.

Then what is the importance of DPRTY?

Answer:
```
DPRTY
```
is a very old JCL keyword that harks back to the days of MVS/ESA. It was the dispatch priority which dictated to JES what priority individual steps should be given in a job.
On all versions of z/OS I have access to (all the supported ones), it has no effect.  This is because the WLM (workload manager) goal mode is the only mode used in z/OS 1.3 and beyond. I believe this keyword was deprecated in MVS/ESA V5R1M0 (see INFO APAR II09592).
You can safely ignore it, since JES itself ignores it - all your job steps will be executed in a top-down manner in your JCL job card, with the dispatch priority given by the
```
IEAIPSxx
```
PARMLIB member.


Question:
I work on a Fedora Linux box.

I have a whole host of binaries and libraries that I've installed locally under my home directory.

I'd like to set my system up so installing software there functions the same way (for me) as if the root user installed it without a prefix.

I can run binaries installed in ~/local/bin just fine by adding that dir to my PATH variable, but what about linking to libraries in ~/local/lib and ~/local/lib64?

Is there something akin to LD_LIBRARY_PATH variable but to find the library at compile rather than runtime?  I don't want to worry about explicitly passing the path to the compiler via L~/local/lib or through flags in the ./configure script.

Answer:
Set the
```
LIBRARY_PATH
```
environment variable to
```
$HOME/local/lib:$HOME/local/lib64
```
. You can also set the environment variables
```
C_INCLUDE_PATH
```
and
```
CPLUS_INCLUDE_PATH
```
to find include files in
```
$HOME/local/include
```
. These are environment variables used by GCC to find libraries and include files, so they probably won't work with other compilers.


Question:
Although I grasp the concept of Bitwise Operators, I can't say that I have come across many use cases during the webdevelopment process at which I had to resort to using Bitwise Operators.

Do you use Bitwise Operators?

Why do you use them?

What are some example use cases?

Please remember that this question is specifically intended for use of Bitwise Operators in web languages.

Answer:
My main use for bitwise operators could be relevant anywhere - representing a set of flags. For instance, you might have an integer in the database representing a set of security permissions for a user, and in your web app you would have to check those before continuing.
Those tend to only require
```
&
```
and
```
|
```
- e.g.
```
```
if ((permissions & Permission.CreateUser) != 0)
{
    ...
}
```
```
or
```
```
Permission requiredPermission = Permission.CreateUser
                                | Permission.ChangePassword;
```
```
Bit
shifting
operators are less useful in "business" applications in my experience.


Question: We have a database that many persons have to have access to. I am looking for a way that will allow us to get notification whenever "alter" occurs on this database, so other parties can be aware of it. Please advise.

Answer:
Many persons should NOT have ALTER permission on a production database - very few people should have ALTER permission on a production database.  Actually, you probably shouldn't have many people empowered to make changes in test databases, either.
You can consider whether auditing is the correct solution - in some DBMS, it would be one way of detecting changes, but alerting would be harder (other than by some variation on the theme of 'grepping the audit log').  There may be other ways in Oracle.


Question: How is it possible to identify that the browser's close button was clicked?

Answer:
Browsers do not have a close event so you can't really tell when the user has closed their browser, there are some potential workarounds in
This thread
If you let us know what you are trying to achieve, there may be an alternative way


Question:
how is it advisable to control the cpu utilization during run time ?

poll the cpu load and insert sleeps ?

Answer:
I'd recommend OS functionality. There are performance counters and WinAPI functions for this on Windows.
Here is an example using
performance counters
from
BCL Team Blog
:
```
```
foreach (Process proc in Process.GetProcesses()) {
    using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", proc.ProcessName)) {
        pcProcess.NextValue();
        System.Threading.Thread.Sleep(1000);
        Console.WriteLine("Process:{0} CPU% {1}", proc.ProcessName, pcProcess.NextValue());
    }
}
```
```
This code makes the same
with WMI
from
CodeProject
:
```
```
public string GetCPU()
{
    decimal PercentProcessorTime=0;
    mObject_CPU.Get();

    ulong  u_newCPU   =
      (ulong)mObject_CPU.Properties["PercentProcessorTime"].Value;
    ulong u_newNano   =
      (ulong)mObject_CPU.Properties["TimeStamp_Sys100NS"].Value;
    decimal d_newCPU  = Convert.ToDecimal(u_newCPU);
    decimal d_newNano = Convert.ToDecimal(u_newNano);
    decimal d_oldCPU  = Convert.ToDecimal(u_oldCPU);
    decimal d_oldNano = Convert.ToDecimal(u_oldNano);

    // Thanks to MSDN for giving me this formula !

    PercentProcessorTime =
      (1 - ((d_newCPU-d_oldCPU)/(d_newNano - d_oldNano)))*100m;

    // Save the values for the next run

    u_oldCPU          = u_newCPU;
    u_oldNano         = u_newNano;

    return PercentProcessorTime.ToString("N",nfi);;
}
```
```
So you can query these OS providers (or others for your OS) and sleep your thread if processor utilization is high.


Question: What are all AT commands required for GPRS communication?

Answer:
It depends quite a bit on:
The modem
How much of the modem's stack you plan on using
The carrier you're using
If you're using this on a computer and you have a modem configuration file (modem specific), and a carrier configuration or setup then you can intercept the serial commands and find out.
Otherwise, try going to the modem manufacturer's website and find the AT command guide for your modem.
Once you have the modem commands, setting up the connection requires several steps, including initiating the GSM connect, then a GPRS session with a server, and then the PPP session with your carrier's ISP equipement.  You'll need several pieces of information from the carrier, which the AT command set will guide you towards.
Your modem may also have a built in TCP/IP stack, in which case you also have AT commands to initiate the PPP session, and then TCP connections with internet servers.
If you post the modem/carrier/goal/etc you might be able to get more specific help.
-Adam


Question:
I launch a child process in Java as follows:

final String[] cmd = {"<childProcessName>"};
Process process = Runtime.getRuntime().exec(cmd);

It now runs in the background. All good and fine.

If my program now crashes (it is still in dev :-)) the child process still seems to hang around. How can I make it automatically end when the parent Java process dies?

If it helps, I'm using Mac OS X 10.5

Answer:
I worked it out myself already. I add a shutdown hook, as follows:
```
```
final String[] cmd = {"<childProcessName>"};
final Process process = Runtime.getRuntime().exec(cmd);
Runnable runnable = new Runnable() {
    public void run() {
        process.destroy();
    }
};
Runtime.getRuntime().addShutdownHook(new Thread(runnable));
```
```


Question: Does anyone know of a script to colorize C++ code the same as the default MSVC IDE does?

Answer:
Is
SyntaxHighlighter
the sort of thing you're looking for? There is also
GeSHi
, which has been updated more recently.


Question:
I am rendering a rails partial and I want to alternate the background color when it renders the partial.  I know that is not super clear so here is an example of what I want to do:

Row One grey Background

Row Two yellow background

Row Three grey Background

Row Four yellow background

sorry stackoverflow seams to prevent the background colors from being shown but I think this makes my idea clear

This is the view code that I am using

<table>
  <%= render :partial => 'row' :collection => @rows %>
</table>

the _row.html.erb partial looks like this

<tr bgcolor="#AAAAAA">
  <td><%= row.name %></td>
</tr>

The problem is I do not know how to change the background color for every other row.  Is there a way to do this?

Answer:
You could use the Cycle helper. Something like this:
```
```
<tr class="<%= cycle("even", "odd") %>">
  <%= row.name %>

```
```
Or in your case use bgcolor instead, although i would recomend using css classes.
You can cycle through more than two values: cycle(‘first’, ‘second’, ‘third’, ‘and_more’).
There is also: reset_cycle(‘cycle_name’) This makes sure that on each iteration, you will start again with your first value of the cycle list.
Check the rails
documentation
for more examples.


Question:
I've written a little web site in my effort to learn vb.net and asp.net, fairly happy with it so rented some space and uploaded it, it was written using asp.net express edition 2008 and sql server express .... I've uploaded it and I've found that it was written in .NET 3.5 and my host only deals with 2.01 ... I've sorted most of that out, and trimmed my web.config file back to basics, but my forms based authentication isn't working

<compilation debug="true" strict="false" explicit="true">
        </compilation>
        <authentication mode="Forms" />
    <customErrors mode="Off"/>
  </system.web>

And it keeps reporting that the sql server does not support remote access ...... not sure what to do next, I don't have to write my own security routines do i ? I have a sql server back end

Thanks for your time

Chris

Answer:
If the probllem is that you can not access your SQL Server it may be that you are using a trusted connection to it?
It is not likely to work if the website is on a ISP network and your SQL Server is on another network.
What you then need to do is take a look at your connectionstring to change it so that you pass along the username/password in the connection string. NB: This is not optimal in terms of security but it is a way to access remot SQL Servers that are in antother domain.
/joakim


Question:
I need to write the content of a map (key is ID of int, value is of self-defined struct) into a file, and load it from the file later on. Can I do it in MFC with CArchive?

Thank you!

Answer:
I don't know much about MFC, but your problem is rather trivially solved using
Boost.Serialization
```
```
struct MapData {
     int m_int;
     std::string m_str;

  private:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        ar & m_int;
        ar & m_str;
    }
};

std::map< int, MapData > theData;

template<class Archive>
void serialize(Archive & ar, std::map< int, MapData > & data, const unsigned int version)
{
    ar & data;
}
```
```
And then later were you want to do the real archiving:
```
```
std::ofstream ofs("filename");
boost::archive::binary_oarchive oa(ofs);
oa << theData;
```
```
That's it.
(disclaimer: code simply typed in this box, not tested at all, typo's were intended ;)


Question:
I am creating my application using Django, and am wondering how I can make Django use my CSS file? What settings do I need to do to make Django see the css file?

NB: On a local machine

Answer:
What settings do i need to do to make Django see the css file?
None.
Make sure your template includes the CSS file (as standard HTML does) and put the CSS file on the media server.
To clarify: With Django it is highly recommended that you serve all your media (everything that isn't dynamic html) from a different server instance. How you implement that is completely up to you but most people create a subdomain.


Question:
I am currently looking at different ORM solutions for a project that is planned for this spring. Entity Framework is one of the products I am looking closer at, but EF 2.0 would be quite a lot more interesting.

Has there been any indications to when version 2.0 of Entity Framework is planned to be released? With .Net 4.0?

Answer:
AFAIK it hasn't been officially announced. The best hint I saw is
here
, so it's probably coming with .NET 4.0. I bet they will release a CTP before that.


Question:
I'd like to compare two consecutive elements in a std::list while iterating through the list. What is the proper way to access element i+1 while my iterator is at element i?
Thanks
Cobe

Answer:
Boost has a utility called
```
next
```
(and its inverse,
```
prior
```
) for just that purpose.
```
```
*itr == *next(itr)
```
```
Edit: But, if we step back to look at the forest, the
real
question is, why custom-write your
```
adjacent_find
```
function? (I recommend Nicola Bonelli's answer to be accepted.) That's part of the STL, and doesn't require using Boost, if your code doesn't use Boost (thanks to the commenters for pointing this out).


Question:
I have a batch file (in windows XP, with command extension activated) with the following line:

for /f %%s in ('type version.txt') do set VERSION=%%s

On some computer, it works just fine (as illustrated by this SO question), but on other it kills cmd (the console window just closes)

Why ?

Note: the computers seem to have a similar configuration: XpSP2, the user has administrative right, no 'Command processor" defined in HKEY_CURRENT_USER\Software\Microsoft\Command Processor...

Answer:
I got a first empiric answer:
```
```
for /f %%s in (version.txt) do ...
```
```
works just fine, on every computer.
It seems
```
for /f
```
works with a filename, not with any dos command like 'type filename'.
However, it is not true for all my client's computer (on some, the 'type filename' works fine)
If you want 15 (easy ?) points ;-), you can leave an answer to the question:
why 'for /f' sometime does not work with anything else than a file name. And why it just closes the DOS session ?
Edit: 3 years later(!),
barlop
faced a similar situation, detailed in the question "
```
for /f
```
closes cmd prompt immediately?
". His conclusion was:
```
COMSPEC
```
did get listed when doing
```
SET
```
+
ENTER
.
So, I opened the environment variables window, and saw
```
COMSPEC
```
was not listed under user or system variables. I added it to System Variables, started a command prompt, and it seems to work fine.
This
thread on ss64 forum
, mentioned by
Andriy M
in his answer to barlop's question, contains the details.
The shelling out in the "
```
for
```
" loop to complete '
```
dir
```
' (or whatever command you've asked to complete) requires
```
ComSpec
```
to be set in order to reload the
```
cmd
```
window.
```
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\ComSpec=
%SystemRoot%\system32\cmd.exe
```
```


Question:
In C I know about the recursive function but I heard about the re-entrant function.
What is that? And whats the difference between them?

Answer:
A function is re-entrant if it supports having multiple threads of execution "going through" it at the same time. This might be due to actual multi-threading, and I use this case below, or due to other things as pointed out by other posters. Multi-threading was the first that came to mind, and is perhaps also the easiest to understand, so I focused on that case.
This means that the function cannot use static "global" data, since that data would then be accessed by two (or more) threads in parallel, often breaking horribly. A re-entrant function often has an explicit argument to hold any call-specific state, rather than storing it statically.
```
strtok()
```
is a classic case of a function in the C standard library that is well-known
not
to be re-entrant.
[Edit]: There are a bunch of insights, clarifications and corrections in the comments, so please read those as well! Thanks for the help, folks.


Question:
If I declare a temporary auto deleted character buffer using

std::auto_ptr<char> buffer(new char[n]);

then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete.

However the buffer was created using new[], and so strictly speaking the buffer should be deleted using delete[].

What possibility is there that this mismatch might cause a memory leak?

Answer:
The behaviour of calling delete on a pointer allocated with new[] is
undefined
. As you assumed, auto_ptr
does call delete
when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes and other odd behaviours are possible.
If you don't need to transfer the ownership of the pointer, Boost's
scoped_array
class might be what you're looking for.


Question: I want to share an object between my servlets and my webservice (JAX-WS) by storing it as a servlet context attribute. But how can I retrieve the servlet context from a web service?

Answer:
The servlet context is made available by JAX-WS via the message context, which can be retrieved using the web service context. Inserting the following member will cause JAX-WS to inject a reference to the web service context into your web service:
```
```
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

...

@Resource
private WebServiceContext context;
```
```
Then, you can access the servlet context using:
```
```
ServletContext servletContext =
    (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
```
```


Question:
How do you calculate the number of <td> elements in a particular <tr>?

I didn't specify id or name to access directly, we have to use the document.getElementsByTagName concept.

Answer:
You can use something like the following:
```
```
var rowIndex = 0; // rowindex, in this case the first row of your table
var table = document.getElementById('mytable'); // table to perform search on
var row = table.getElementsByTagName('tr')[rowIndex];
var cells = row.getElementsByTagName('td');
var cellCount = cells.length;
alert(cellCount); // will return the number of cells in the row
```
```


Question:
No doubt I'm missing something really simple here but I just can't see the problem with this query which is producing the following error:

SQL query:

INSERT INTO ads(
    ad_id, author, ad_date, category, title,
    description, condition, price, fullname,
    telephone, email, status, photo, photothumb
)
VALUES (
    NULL , 'justal', '1225790938', 'Windsurf Boards',
    'test', 'test', 'Excellent', '12', 'test',
    'test', 'test', '', '', ''
);

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version
for the right syntax to use near ''ad_id', 'author',
'ad_date', 'category', 'title', 'description',
'condition', '' at line 1

Can someone with a fresh pair of eyes spot the problem?

Thanks,
Al.

Answer:
Shouldn't you use back ticks instead of single quotes in column names?
```
```
INSERT INTO ads( `ad_id`, `author`, `ad_date`, `category`, `title`, `description`, `condition`, `price`, `fullname`, `telephone`, `email`, `status`, `photo`, `photothumb` )
VALUES (
NULL , 'justal', '1225790938', 'Windsurf Boards', 'test', 'test', 'Excellent', '12', 'test', 'test', 'test', '', '', ''
);
```
```


Question: I'm new to Flex, and I'm trying to write a simple application. I have a file with an image and I want to display this image on a Graphics. How do I do this? I tried [Embed]-ding it and adding as a child to the component owning the Graphics', but I'm getting a "Type Coercion failed: cannot convert ... to mx.core.IUIComponent" error.

Answer:
Off the top of my head I can think of two things that might help you (depending on what it is exactly that you're trying to achieve):
If you just want to display an image you've embedded, you can add an
Image
component to the stage and set the value of its
```
source
```
as the graphical asset (
```
Class
```
) that you're embedding:
```
```
[Bindable]
[Embed(source="assets/image.png")]
private var MyGfx:Class;

myImage.source = MyGfx;
```
```
If you actually want to
draw
a bitmap onto a
```
Graphics
```
object, you can do this with the
beginBitmapFill()
method:
```
```
[Bindable]
[Embed(source="assets/image.png")]
private var MyGfx:Class;

var myBitmap:BitmapData = new MyGfx().bitmapData;
myGraphics.beginBitmapFill(myBitmap);
myGraphics.endFill();
```
```
You might find the
Flex Quick Starts
articles on Adobe's site useful, especially the
"Embedding Assets"
section.


Question:
Currently I have a structure like this:

A
|
+--B
|
+--C

It's mapped with one table per subclass using joined tables. For historic reasons I also use a discriminator, so the current situation is as described in Section 9.1.3 of the Hibernate manual.

Question: How do I extend the mapping for a structure like this:

A
|
+--B
|  |
|  D
|
+--C

Can I <subclass> a <subclass> in the hibernate mapping? What <key>s do I need?

Answer:
not tested
but, according to the link you posted if you are using hibernate3
```
```
<hibernate-mapping>
  <class name="A" table="A">
    <id name="id" type="long" column="a_id">
      <generator class="native"/>
    </id>
    <discriminator column="discriminator_col" type="string"/>
    <property name="" type=""/>
    <!-- ... -->
  </class>
  <subclass name="B" extends="A" discriminator-value="B">
    <!-- ... -->
  </subclass>
  <subclass name="D" extends="B" discriminator-value="D">
    <!-- ... -->
  </subclass>
  <subclass name="C" extends="A" discriminator-value="C">
    <!-- ... -->
  </subclass>
</hibernate-mapping>
```
```


Question:
It's been a while since I last coded arm assembler and I'm a little rusty on the details. If I call a C function from arm,  I only have to worry about saving r0-r3 and lr, right?

If the C function uses any other registers, is it responsible for saving those on the stack and restoring them? In other words, the compiler would generate code to do this for C functions.

For example if I use r10 in an assembler function, I don't have to push its value on the stack, or to memory, and pop/restore it after a C call, do I?

This is for arm-eabi-gcc 4.3.0.

Answer:
It depends on the
ABI
for the platform you are compiling for. On Linux, there are two ARM ABIs; the old one and the new one. AFAIK, the new one (EABI) is in fact ARM's AAPCS. The complete EABI definitions currently live
here on ARM's infocenter
.
From
the AAPCS, §5.1.1
:
r0-r3
are the argument and scratch registers;
r0-r1
are also the result registers
r4-r8
are callee-save registers
r9
might be a callee-save register or not (on some variants of AAPCS it is a special register)
r10-r11
are callee-save registers
r12-r15
are special registers
A callee-save register must be saved by the callee (in opposition to a caller-save register, where the caller saves the register); so,
if
this is the ABI you are using, you do not have to save r10 before calling another function (the other function is responsible for saving it).
Edit:
Which compiler you are using makes no difference; gcc in particular can be configured for several different ABIs, and it can even be changed on the command line. Looking at the prologue/epilogue code it generates is not that useful, since it is tailored for each function
and
the compiler can use other ways of saving a register (for instance, saving it in the middle of a function).
Terminology: "callee-save" is a synonym for "non-volatile" or "call-preserved":
What are callee and caller saved registers?
When making a function call, you can assume that the values in r4-r11 (except maybe r9) are still there after (call-preserved), but not for r0-r3 (call-clobbered / volatile).


Question: How can we handel key pressed event in asp.net

Answer:
It depends on your situation. In most cases, you will have to handle keypressed event in javascript, and somehow propagate that event to server side.
Consider revising your question to include more background.


Question: So far I've been using public void run() {} methods to execute my code in Java. When/why might one want to use main() or init() instead of run()?

Answer:
The
```
main()
```
method is the entry point for a Java application.
```
run()
```
is typically used for new threads or tasks.
Where have you been writing a
```
run()
```
method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?


Question: I want to detect whether adobe reader is installed using VB6. Also if detected that it's not installed, what would be the best solution?

Answer:
There are crude ways (checking for files on Program files directory), but I'd recommend you declare full-registry functions (not getSetting from vb) as in
http://www.windowsdevcenter.com/pub/a/windows/2004/06/15/VB_Registry_Keys.html
and fetch
HKEY_CLASSES_ROOT\.pdf
If that's there, something capable of reading pdfs is there (which is what you want, right?).
As a bonus,
HKEY_CLASSES_ROOT\.pdf\OpenWithList
has a list (wow) of registered applications that open .pdf files... the key names on that list are programs you can invoke from vb using
shell("start "+ OpenAppName)


Question:
I have a variable

unsigned char* data = MyFunction();

how to find the length of data?

Answer:
Assuming its a
```
string
```
```
```
length = strlen( char* );
```
```
but it doesn't seem to be...so there isn't a way
without
having the function return the length.


Question:
I'm trying to do the classic Insert/Update scenario where I need to update existing rows in a database or insert them if they are not there.

I've found a previous question on the subject, but it deals with stored procedures, which I'm not using.  I'd like to just use plain SQL SELECT, INSERT and UPDATE statements, unless there's something better available (the MERGE statement isn't available in SQL Server 2005).

I guess my general idea is this:

If the row is found
  update
else
  insert

As for checking for a row's existence, how expensive is it to do a SELECT statement before calling an UPDATE or an INSERT?  Or is it better to just try an UPDATE, check for the number of rows affected, and then do an INSERT if the rows affected is 0?

Answer:
The most efficient way is to do the
```
UPDATE
```
, then do an
```
INSERT
```
if
```
@@rowcount
```
is zero,
as explained in this previous answer
.


Question:
We have a couple of web servers using load balancer. Machines are running IIS6 on port 81. Externally, site is accessable using port 80. External name and name of the machine are different.

We're getting

System.ServiceModel.EndpointNotFoundException: The message with To '<url>' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree.

Relevant part of web.config is:

  <endpoint binding="ws2007HttpBinding" bindingConfiguration="MyServiceBinding"
    contract="MyService.IMyService" listenUriMode="Explicit" />

We tried adding listenUri, but that didn't solve our problems.

Any ideas?

Answer:
What is the specific load balancer? Using an F5 BIG-IP we got it working fairly easily, but we were using the same port and (relative) uri on the nlb as individual machines (so we can treat an individual machine the same as the farm if we choose). Obviously each machine has a different name, but this setup also allows you to test individual servers by spoofing the host - for example, by editing your HOSTS file to point [your farm name] to [test server IP].
The biggest pain we had was SSL; using TransportWithMessageCredential security, WCF refuses inbound http connections - so we had to set up the nlb to re-encrypt between the nlb and the server node - but not a biggie.
The only other issue we had was with hosting WCF inside IIS, and WCF not being able to correctly identify the intended site (although IIS was fine) over http (but fine over https). To fix this I wrote a custom factory that simply ignored http completely (only listened on https) - which ties in neatly with the TransportWithMessageCredential requirements anyway, so I wasn't bothered by this.
I wonder if you wouldn't get more joy by hosting on a standard port but as a different site (IP/host-header/etc).


Question:
I'm currently working with Db2 Enterprise Server V 8.2 with FixPak 10

And I want to retrieve list of all the open active connections with an instance.

In Oracle there is a utility program called "Top Session" which does the similar task. Is there any equivalent in DB2?

Answer:
The command you seek is:
```
```
LIST APPLICATIONS
```
```
In the DB2 Command Center there is a tool which list the applications and displays them in a human friendly format as well.


Question:
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g.

Störung%20.doc would be renamed to St_rung_20.doc

In order of preference:

A Windiws batch file

A Windows script file to run with cscript (vbs)

A third party piece of software that can be run from the command-line (i.e. no user interaction required)

Another language script file, for which I'd have to install an additional script engine

Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.

Answer:
Have you tried setting cmd.exe into another codepage before you feed the file names to gnupg? Issue
```
chcp 65001
```
to set cmd.exe to Unicode beforehand and try again.
If that fails, the following VBScript would do it:
```
```
Option Explicit

Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim invalidChars: Set invalidChars = New RegExp

' put all characters that you want to strip inside the brackets
invalidChars.Pattern =  "[äöüß&%]"
invalidChars.IgnoreCase = True
invalidChars.Global = True

If WScript.Arguments.Unnamed.Count = 0 Then
  WScript.Echo "Please give folder name as argument 1."
  WScript.Quit 1
End If

Recurse fso.GetFolder(WScript.Arguments.Unnamed(0))

Sub Recurse(f)
  Dim item

  For Each item In f.SubFolders
    Recurse item
    Sanitize item
  Next
  For Each item In f.Files
    Sanitize item
  Next
End Sub

Sub Sanitize(folderOrFile)
  Dim newName: newName = invalidChars.Replace(folderOrFile.Name, "_")
  If folderOrFile.Name = newName Then Exit Sub
  WScript.Echo folderOrFile.Name, " -> ", newName
  folderOrFile.Name = newName
End Sub
```
```
call it like this:
```
```
cscript replace.vbs "c:\path\to\my\files"
```
```
You can also drag&drop a folder onto it in Windows Explorer.


Question: What is the command to match brackets in Emacs (the equivalent of the % command in Vim)?

Answer:
See
```
show-paren-mode
```
as described in
5.27 How do I show which parenthesis matches the one I'm looking at?


Question:
I'm by no means a sysadmin so please correct me if I'm wrong.

I want to run aspnet_regiis.exe -s.
This requires the metabase path of my website.

How do I find this metabase path?

Answer:
Just run aspnet_regiis.exe -lk to see a list of the registered applications, their metabase paths and the version of the .NET framework installed for this application.
Also, here are a couple of links that you can use to find the metabase path:
http://msdn.microsoft.com/en-us/library/ms524682.aspx
http://www.windowsdevcenter.com/pub/a/windows/2005/10/25/hacking-iis6-with-metabase-explorer.html
http://www.codersource.net/csharp_iis_metabase.html
HTH,
Don


Question:
I'm getting the following error when my win32 (c#) app is calling web services.

The request failed with HTTP status 504: Gateway timeout server response timeout.

I understand 'I think' that this is because the upstream request does not get a response in a timely fashion.

But my question is this?  How do I change the app.config settings in my win32 application to allow more time to process its data.  I assume I require these changes to be made on my app settings as the webservices and IIS hosting the ws are setup with extended times.

Look forward to a response and thank you in advance.

Answer:
CheckUpDown has
a nice explanation of the 504 error
:
A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.
This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.
This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.


Question:
Is there a way to drop a validation that was set in Rails plugin (or included module)?
Let's say I have some model with module included in it:

class User < ActiveRecord::Base
  include SomeModuleWithValidations
  # How to cancel validates_presence_of :something here?
end

module SomeModuleWithValidations
  def self.included(base)
    base.class_eval do
      validates_presence_of :something
    end
  end
end

My only idea so far was to do something like:

validates_presence_of :something, :if => Proc.new{1==2}

which would work, I think, but it isn't particulary pretty.

Answer:
You could overload the validates_precense_of in the class. Something like:
```
```
def self.validates_presence_of(*args)
  return if args.first == :foo
 super
end
```
```
Or if you have validates_presence_of :foo you could do:
```
```
def foo
  self[:foo] || ""
end
```
```
However, none of those solutions are very nice. It would most likely be easier to just uncomment it in the module, or redefine it to no-op in just that module.


Question: How to insert data into a particular cell in a Excel Work sheet in Asp.net

Answer:
Does the worksheet already exist? If it does you can open the worksheet using the open-source component
Koogra
og the commercial component from
Infragistics
(there are others as well) and modify it in code. The alternative is to open the worksheet using excel automation, but that is not recommended in a web project.
By the way.
You are not the first to ask this question.


Question:
I was wondering how to make a toolbar in MFC that used 24bit or 256 colour bitmaps rather than the horrible 16 colour ones.

Can anyone point me in the direction of some simple code?

Thanks

Answer:
The reason this happens is that the MFC CToolbar class uses an image list internally that is initialised to use 16 colours only. The solution is to create our own image list and tell the toolbar to use that instead. I know this will work for 256-colours, but I haven't tested it with higher bit-depths:
First, load a 256-colour bitmap from a resource:
```
```
HBITMAP hBitmap = (HBITMAP) ::LoadImage(AfxGetInstanceHandle(),
    MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_BITMAP,
    0,0, LR_CREATEDIBSECTION | LR_LOADMAP3DCOLORS);
CBitmap bm;
bm.Attach(hBitmap);
```
```
Next, create a 256-colour image list and add our bitmap to it:
```
```
CImageList m_imagelist.Create(20, 20, ILC_COLOR8, 4, 4);
m_imagelist.Add(&bm, (CBitmap*) NULL);
```
```
Finally, we need to tell the toolbar to use the new image list:
```
```
m_toolbar.GetToolBarCtrl().SetImageList(&m_imagelist);
```
```
It's also possible that the new MFC version in VS2008 may have solved this problem as I know that many of the UI elements have been updated. I haven't actually tried using it yet so I can't be certain.


Question:
I'm looking for suggestions on possible IPC mechanisms that I can implement in my self-made OS for an AVR32 board.

My current choice is implementing the massage passing mechanism described in the books written by Tanenbaum.

Is this a good choice? Are there easier way to implement IPC?

Thanks

Answer:
My suggestion is to review the message passing primitives that QNX RTOS (www.qnx.com) supports before making any decisions.  I spent several years programming a complex multi-process system in that environment, and it stands out as the best message-based O/S I have ever encountered.
Some specific points that spring to mind (it's been a while now):
Message data copied between process memory space by the kernel so that a bug in one process cannot affect another.
Ability to send and block for a reply.
Ability to drop a message on a queue and move on immediately.
Ability to send a message an block indefinitely until the receiver responds; the receiver may receive and process other messages in the meantime - this is way more valuable than you at first think it will be.


Question:
Is there an efficient algorithm for detecting cycles within a directed graph?

I have a directed graph representing a schedule of jobs that need to be executed, a job being a node and a dependency being an edge. I need to detect the error case of a cycle within this graph leading to cyclic dependencies.

Answer:
Tarjan's strongly connected components algorithm
has
```
O(|E| + |V|)
```
time complexity.
For other algorithms, see
Strongly connected components
on Wikipedia.


Question:
This declaration causes an overflow in VBA:

Const OVERFLOWS As Long = 10 * 60 * 60

whereas setting the value directly is fine:

Const COMPILES_OK As Long = 36000

How do you persuade VBA to treat literal integers as longs?

Thanks

Answer:
Add the
```
long
```
suffix
```
&
```
to at least one number:
```
```
Const OVERFLOWS As Long = 10& * 60 * 60
```
```
Note that using the
```
CLNG
```
function to convert the values to
```
long
```
will not work, because VBA does not allow assigning the return value of a function to a constant.


Question:
In C# Is there a way of getting a finer granularity with SQL exceptions?

I'm aware that an aweful lot can go wrong but I want to deal with certain cases differently and parsing the Error message doesn't seem to be very elegant.

Also Are the error messages created by the framework or are they db specific?

For example If i have a primary key violation on INSERT is the error message going to always be:

Violation of PRIMARY KEY constraint 'PK_tblProduct'. Cannot insert duplicate key in object 'dbo.tblProduct'.

or is that SQLServer specific.

Update

I looks like I'm after the error number, any idea where I can get the various error numbers?

best I can do with a quick google is:
18456: Logon Failed
18488: Password Expired

Answer:
If you are catching a
```
SqlException
```
, you should have access to
```
.Number
```
, which gives you the SQL error number; this is probably your best approach... (you can get the same from the
```
InfoMessage
```
event as well for non-fatal errors).
Of course, this won't distinguish between tables - you could argue that if you need this level of granularity, you should check first (in a serializable isolation level, ideally with UPDLOCK), raising your own error if there is conflicting data.


Question:
I need to hide a Windows form from the taskbar but I can't use WS_EX_TOOLWINDOW because I need the system menu and min/max buttons on the form's title bar.

If I switch the form to a tool window at runtime the form skinning is stuffed up. From searching on the Web I see that VB has a ShowInTaskbar property and I'm wondering if this would do what I want, and whether it can be implemented in Delphi 2006. Also this project is a COM server and has no MainForm, etc.

Answer:
With thanks to
http://www.scalabium.com/faq/dct0096.htm
.
```
```
procedure TForm1.FormCreate(Sender: TObject);
begin
  ShowWindow(Application.Handle, SW_HIDE);
  SetWindowLong(Application.Handle, GWL_EXSTYLE,
    GetWindowLong(Application.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW);
  ShowWindow(Application.Handle, SW_SHOW);
end;
```
```
I tested it and it worked with Delphi2006. And windows menu and min/max buttons are still visible.


Question:
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time-restricted license file.

If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.

Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".

Is there a good way to handle this problem?

Answer:
Python, being a byte-code-compiled interpreted language, is very difficult to lock down.  Even if you use a exe-packager like
py2exe
, the layout of the executable is well-known, and the Python byte-codes are well understood.
Usually in cases like this, you have to make a tradeoff.  How important is it really to protect the code?  Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid?  Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.
If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.


Question:
I have a list of tuples like this:

[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]

I want to iterate through this keying by the first item, so, for example, I could print something like this:

a 1 2 3
b 1 2
c 1

How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...

Answer:
```
```
l = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]

d = {}
for x, y in l:
    d.setdefault(x, []).append(y)
print d
```
```
produces:
```
```
{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}
```
```


Question:
I have a TreeView windows forms control with an ImageList, and I want some of the nodes to display images, but the others to not have images.

I don't want a blank space where the image should be.  I don't want an image that looks like the lines that the TreeView would draw if it didn't have an ImageList.  How do I get it to draw images for some items and not others, without resorting to clumsy hacks like that?

Answer:
I tried this once and I don't think it is possible.
If you try to set both
```
ImageKey
```
and
```
ImageIndex
```
to "not set" values the control just defaults
```
ImageIndex
```
to 0. The following code:
```
```
treeView.ImageKey = "Value";
Debug.WriteLine(treeView.ImageIndex);
treeView.ImageKey = null;
Debug.WriteLine(treeView.ImageIndex);
treeView.ImageIndex = -1;
Debug.WriteLine(treeView.ImageIndex);
```
```
Produces output:
```
```
-1
0
0
```
```
This kind of tells you that the control developers wanted to make sure that there was always a default image. That just leaves you with the hack options I'm afraid.


Question:
Is it possible to define an implicit conversion of enums in c#?

something that could achieve this?

public enum MyEnum
{
    one = 1, two = 2
}

MyEnum number = MyEnum.one;
long i = number;

If not, why not?

Answer:
If you define the base of the enum as a long then you can perform explicit conversion. I don't know if you can use implicit conversions as enums cannot have methods defined on them.
```
```
public enum MyEnum : long
{
    one = 1,
    two = 2,
}

MyEnum number = MyEnum.one;
long i = (long)number;
```
```
Also, be aware with this that an uninitalised enumeration will default to the 0 value, or the first item - so in the situation above it would probably be best to define
```
zero = 0
```
as well.


Question:
Do you know a way to organize boolean expressions in a database while allowing infinite nesting of the expressions?

Example:

a = 1 AND (b = 1 OR b = 2)

The expression as a whole shouldn't be stored as varchar to preserve data integrity.

Answer:
An expression is a treelike structure. So you need a way to present the tree in a table.
You can for example use the fields:
ID
TypeExpression (and, or etc...)
FirstChildID
SecondChildID
In this case, you have the following types:
AND, Children point to other expression.
OR, Children point to other expression.
Equal, Children point to other expression.
Literal, FirstChild points to an entry in a literal table.
VariableLookup, FirstChild points to an entry in a varable table.
But I think there are better ways to organise expression. I once made a simple expression evaluator that accepts a string and produces a numeric result.


Question:
I'm looking for a dummy SQL statement that will work from a C# SQL connection to check for connectivity.

Basically I need to send a request to the database, I don't care what it returns I just want it to be successful if the database is still there and throw an exception if the database isn't.

The scenario I'm testing for is a loss of connectivity to the database, where the SQLConnections State property seems to still be "Open" but there is no connectivity.

Answer:
Most SQL databases have a 'table' for this purpose.
In DB2, it's:
```
```
select * from sysibm.sysdummy1
```
```
while Oracle has, from memory,
```
```
select * from dual
```
```
It'll depend on the database at the back end.


Question:
is it somehow possible to call a rails function or to access a rails object from within jQuery?
I'd like to do something like:

jQuery(document).ready(function($) {
$('#mydiv').html("<%= @object.name %>");
});

OR

jQuery(document).ready(function($) {
$('#mydiv').html("<%= render :partial => "contacts" %>");
});

At the moment I'm keeping all my jQuery stuff in my application.js, which is included in my layout. Oh yeah....and I'm not using Rails Edge.

Regards,

Sebastian

Answer:
You'll have to have a method in the controller that will render what you need, if you want to do that. Another way to do it is to use view blocks, like in the end of your layout view
```
```
<script type="text/javascript">
<%= yield :footerjs %>
</script>
```
```
and in the view do something like:
```
```
<% content_for :footerjs do %>
jQuery(document).ready(function($) {
$('#mydiv').html('<%= escape_javascript(render :partial => "contacts") %>');
});
<% end %>
```
```
You'll need to make sure that the partial you'll be rendering won't have characters that may cause javascript errors (like finishing the quotes before the end of the string, etc). Also, some browsers don't like multi-line strings, so you'll have to fiddle with that as well.


Question:
I am debugging some code and have encountered the following SQL query (simplified version):

SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9

I'm getting very strange results from the query and I think its because the first OR is negating the AND operators that are found before it.

This results in getting results back for ads of all types and not just for the type 13.

Each time the query is called there may be a differnt amount of county entities that need to be looked up.

Any help on the correct way to go about this would be appreciated.

Answer:
Put parentheses around the "OR"s:
```
```
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
    ads.county_id = 2
    OR ads.county_id = 5
    OR ads.county_id = 7
    OR ads.county_id = 9
)
```
```
Or even better, use IN:
```
```
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
```
```


Question:
i have a server - client application that runs on java 1.3; i want to change to java 1.6 step by step, meaning first few clients, than rest of the clients and finally server...
i was wondering could you direct me to some common problems that can come along and what should i look after?

Answer:
Off the top of my head, look for the names
```
enum
```
and
```
assert
```
in fields and local variables... These words have become keywords in java 1.4 and 5. The java 6 compiler will mark them as compilation errors if it sees them.
Yuval =8-)


Question:
I have use IlMerge to merge all the dlls of my projects in one exe. I use a targets file which is referenced in the "import" of the main csproj.

The ExecCommand in the targets is:

  <Exec Command="&quot;$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe&quot; /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(IlmergeAssemblies->'&quot;%(FullPath)&quot;', ' ')" />

This works.

But then I have a Setup Project, when it builds, it ignores the "import" and it doesn't merge the dlls. How can I use the targets file with the Setup Project?

I have tried writing this same code for Ilmerge in the Post-build event (in properties of the project) of the main project but it gives me error code 1.

Answer:
I'd recommend that you check out the ILMerge Task in the
MSBuild Community Tasks
. Documentation for the ILMerge Task is included in the
download
. It will take away the complexity of specifying the exact command line arguments as you are doing now.
On your specific issue, other than the error code 1, are you getting any other error message as a result?  Comment, and I'll edit my response as best I can.


Question:
I want to use jQuery with asp.net webfoms.  Do I need to get a special toolkit so the .net controls spit out friendly Control ID's?

Reason being, I don't want to write javascript referencing my html ID's like control_123_asdfcontrol_234.

Has this been addressed in version 3.5?  (I remember reading you have to get some special dll that makes ID's friendly).

Answer:
You can use
```
myControlId = "<%= myControl.ClientID %>";
```
to output the (non-friendly) id used to reference it in Javascript.


Question: Can anyone recommend an SVN client for use in Excel with VBA (code modules only).  Ideally, I would also like SVN to ignore case when diffing prior to committing changes so as to avoid excessive churn in the repository (VBA has an annoying habit of changing the case of variables all over the project).

Answer:
TortoiseSVN
integrates well with the Windows File Explorer and allows for the integration of an external diff tool (like
Beyond Compare
.
Beyond Compare
has a specific plugin for Visual Basic code that appears to ignore case for 'unimportant text', meaning anything
not
in quotes.
I don't think this will solve the SVN churn issue, however.  I don't believe that SVN uses the external diff program to decide whether a file has changed prior to committing, and I don't know of any way to override this behavior.


Question:
Which method is preferred?

Session.Remove("foo");

Session["foo"] = null;

Is there a difference?

Answer:
I would go with Remove but can not honestly say if there is a difference.  At a guess there may still be an empty key kept for that null value but not sure.  Remove would give me little doubt and if that's what you want to do it
reads better
in code as well.


Question:
I have been running Apache HTTPD in 64bit mode by stripping out the 32bit architecture from the binary (along with the ppc parts). I did this to make it more compatible for python and mysql.

However I have another machine that needs it to be run in 32bit mode (it has all four original architectures still in it). Is it possible to make sure that it is running in 32 bit mode and that anything compiled against it uses said mode.

Are my options limited to stripping it, or are there start up optiosn that I do not know about.

Answer:
You can use the
```
arch(1)
```
command to change the which architecture is used. This will try Intel 32-bit first and then PPC 32-bit:
```
```
% arch -i386 -ppc /usr/sbin/httpd
```
```


Question:
I am an advocate of ORM-solutions and from time to time I am giving a workshop about Hibernate.

When talking about framework-generated SQL, people usually start talking about how they need to be able to use "hints", and this is supposedly not possible with ORM frameworks.

Usually something like: "We tried Hibernate. It looked promising in the beginning, but when we let it loose on our very very complex production database it broke down because we were not able to apply hints!".

But when asked for a concrete example, the memory of those people is suddenly not so clear any more ...

I usually feel intimidated, because the whole "hints"-topic sounds like voodoo to me...
So can anybody enlighten me? What is meant by SQL-hints or DB-Hints?

The only thing I know, that is somehow "hint-like" is SELECT ... FOR UPDATE. But this is supported by the Hibernate-API...

Answer:
A SQL statement, especially a complex one, can actually be executed by the DB engine in any number of different ways (which table in the join to read first, which index to use based on many different parameters, etc).
An experienced dba can use hints to
encourage
the DB engine to choose a particular method when it generates its execution plan. You would only normally need to do this after extensive testing and analysis of the specific queries (because the DB engines are usually pretty darn good at figuring out the optimum execution plan).
Some MSSQL-specific discussion and syntax here:
http://msdn.microsoft.com/en-us/library/ms181714.aspx
Edit: some additional examples at
http://geeks.netindonesia.net/blogs/kasim.wirama/archive/2007/12/31/sql-server-2005-query-hints.aspx


Question:
I got tired of trying Delphi every year hoping that I will find a stable version to upgrade from my good old Delphi 7.

Should I bother to try Delphi 2009? Or it is as unstable as the previous versions and should I wait until Delphi 2010?

Thanks

Answer:
This is kind of an open-ended question, but the short answer is that Delphi 2009 is stable, fast, and a leap forward from older versions (especially 2005).
The IDE has evolved a bit since Delphi 7 and has more Visual Studio and Eclipse-like features. It also has some updated controls that make building the more 'modern' Windows applications easier, like the Ribbon you see in Office. I find the response time in drag and drop operations to be a lot quicker than previous versions, and overall the reaction time in IDE operations just seem a lot snappier.
So far the IDE hasn't crashed on me at all, but I'm admittedly not a heavy day-to-day user. I mainly use Delphi 2009 for a side project I work on in my own time.


Question:
I need to modify a (xml-)file from Apache Ant. "loadfile" task allows to load the file's content in a property. But how to store the property's value back to a file after its (property) modification?

Of course I could write custom task to perform this operation but I would like to know if there's some existing implementation.

Answer:
You can use the
echo
task.
```
```
<echo file="${fileName}" message="${xmlProperty}"/>
```
```
The
echoxml
task might be of interest to you as well.


Question: Is it possible to obtain the maximum column length for a VARCHAR, CHAR etc?

Answer:
In pure T-SQL you can use this query:
```
```
select max_length from sys.columns as c inner join sys.objects o on c.object_id = o.object_id where o.name = 'myTable' and c.name = 'myColumn'
```
```
For linq-to-sql you need it rewrite into linq.


Question:
I am trying to do something like this:

while @nrOfAuthlevels >= @myAuthLevel
begin
    set @myAuthLevel = @myAuthLevel + 1
    SELECT      Role.name, Role.authorityLevel
    FROM        [dbo].[Role]
    ORDER BY Role.authorityLevel
end

The result of this stored procedure shall be a table with all Role.authorityLevel below my own. But this generates several tables.

Answer:
Create a temp table before the loop and don't select data, but insert data to this temp table:
```
```
create table #tmp (
 Name type,
 authorityLevel type
)

while @nrOfAuthlevels >= @myAuthLevel
begin
        set @myAuthLevel = @myAuthLevel + 1
        insert into #tmp values(
            SELECT          Role.name, Role.authorityLevel
            FROM        [dbo].[Role]
            where ...
        )
end
```
```


Question:
The following doesn't work, but something like this is what I'm looking for.

select *
from Products
where Description like (@SearchedDescription + %)

SSRS uses the @ operator in-front of a parameter to simulate an 'in', and I'm not finding a way to match up a string to a list of strings.

Answer:
Have you tried to do:
```
select * from Products where Description like (@SearchedDescription + '%')
```
(Putting single quotes around the % sign?)


Question:
I've been developing a Smalltalk variant for just the fun of it and I wonder what would be a fellow stackoverflowers choice when it comes to targeting a back-end. These were my current considerations:

.NET, JVM: These two VM's are mainly for statically typed languages and I assume it would be quite hard to target such a dynamic language like smalltalk.

Python (as source code): Seems to be the simplest way. Also it would be better if I could emit Python bytecode but it's not well documented as other VM's AFAIK (Need to dig Python's source code for details!).

Self made interpreter: Out of the question as it's no fun :-)

LLVM, NekoVM, Parrot are other options I'm checking out. What would be your take on this?

Answer:
I would choose the JVM, but mainly because I'm familiar with it.
Objective reasons for
JVM
are: main platforms are supported, many libraries and good performance (within the choices you have given it may have the best performance).
.Net works best on Windows. If you choose it, you should test on
Mono
to be more platform-neutral.
Python
seems a good choice as well. But I think for the JVM more libraries are available.
Parrot
is in my opinion too fresh, it needs some time to mature. But an interesting alternative for the future.
The other choices are new to me, I will take a look at them.


Question:
What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap?

What is the behavior of SQL Server 2005 when it happen?

Answer:
You will get an overflow error when the maximum value is reached
. If you use the bigint datatype with a maximum value of
```
9,223,372,036,854,775,807
```
this will most likely never be the case.
The error message you will get, will look like this:
```
```
Msg 220, Level 16, State 2, Line 10
Arithmetic overflow error for data type tinyint, value = 256.
```
```
(Source)
As far as I know MS SQL provides no functionality to fill the identity gaps, so you will either have to do this by yourself or change the datatype of the identity column.
In addition to this you can set the start value to the smallest negative number, to get an even bigger range of values to use.
Here is a good blog post about this topic
.


Question:
I am looking to clean up some of the HTML generated by a .NET 2.0 TreeView controller.  Switching to another version/model is not an available option.

My first crack yielded an extended TreeView, with an overridden Render that Regex'd out the text I didn't need and output to the page.

The problem was when I tried to collapse/expanded nodes of the tree, my postback event wasn't fired.  My assumption was that I didn't need to do any more overriding as the parent TreeView controller would handle the postback events.

What am I missing?

Answer:
Use the ASP.NET CSS Control Adapters:
http://www.asp.net/CSSAdapters/TreeView.aspx
Without adapters both use HTML <table> tags. Control adapters can be used so that nested <ul> tags are rendered instead. A combination of CSS and JavaScript can then be used to show and hide portions of the hierarchy of the tree or menu.
  When the CSS and JavaScript are removed the adapted HTML degrades into simple nested unordered lists that are easily interpreted by screen readers, etc. You can see this for yourself by setting the theme to None in the Theme Chooser on the left.


Question:
Basically, what I want to is be able to explore an ActiveX DLL.
I normally fire up VB 6, add the DLL to the "References" of the project, and use Object Explorer.

However, in this particular machine I can't install VB / VS.

I'm sure there's a tool out there that does this. Does anyone know of one?

Thanks

Answer:
Is it possible to download the component from that machine and examine it locally in Visual Studio? (That'd be my first suggestion.) (And BTW, the .NET versions of Visual Studio also feature a VB6-like Object Explorer which works nicely for this.)
Alternatively, and it's not free, but you might try
ActiveXplorer
. (I haven't tried this, but it looks promising.)
(Discontinued)


Question:
I have a image button. I wanted to add a text "Search" on it. I am not able to add it because the "imagebutton" property in VS 2008 does not have text control in it. Can anyone tell me how to add text to a image button??

  <asp:ImageButton ID="Searchbutton" runat="server" AlternateText="Search"
        CssClass="bluebutton"
        ImageUrl="../Graphics/bluebutton.gif" Width="110px"
        onclick="Searchbutton_Click"/>

Answer:
```
```
<button runat="server"
  style="background-image:url('/Content/Img/stackoverflow-logo-250.png')" >
  your text here
and some more

 and some more ....
  </button>
```
```


Question: I know SQL Injection is one... what are the others...

Answer:
Buffer overflows
are the classic if you're writing C, as they often allow the execution of arbitrary code by an attacker.


Question:
I have a page where my combo box has hundreds of elements which makes it very hard to pick the one item I want. Is there a good Javascript replacement that would do better than

<select id="field-component" name="field_component">
                  <option selected="selected">1</option><option>2</option>...
</select>

Is there something with "Intellisense"-like auto-complete?

Answer:
You have
dhtmlCombo
, using ajax to retrieve data when you are filling the input field.
dhtmlxCombo is a cross-browser JavaScript combobox with autocomplete feature.
It extends basic selectbox functionality to meet the requirements of the most up-to-date web applications.
dhtmlxCombo can be converted from existing HTML SELECT or populated with JavaScript. Supporting AJAX, it can also
get list values from the server datasource dynamically
.


Question:
I've got menu items that look like this

<ul>
  <li>Item1<span class="context-trigger"></span></li>
  <li>Item2<span class="context-trigger"></span></li>
  <li>Item3<span class="context-trigger"></span></li>
</ul>

with CSS that turns the above into a horizontal menu, and JS that turns the [spans] into buttons that bring up contextual menus. Vaguely like this:

Item1^  Item2^  Item3^

If the menu gets too wide for the browser width, it wraps, which is what I want. The problem is that sometimes it's putting in line-breaks before the [spans]. I only want it to break between [li]s. Any ideas?

Answer:
try using
```
```
white-space: nowrap;
```
```
in the css definition of your context-trigger class.
Edit: I think patmortech is correct though, putting nowrap on the span does not work, because there is no "white space" content. It might also be that sticking the style on the LI element does not work either, because the browser might breakup the parts because the span is a nested element in li. You might reconsider your code, drop the SPAN element and use css on the LI elements.


Question: Sooo...it's only sort of programming related, but I figure it's election day, right? Is there a single good reason why they aren't, not necessarily open source in that anyone can contribute, but open source in that anyone could inspect the source?

Answer:
the problem is opensourcing the software would be a no-op.
They don't have any decent cryptography, and there has been demonstrated and relatively easy ways to contravene them simply by hot-swapping a ROM chip in the voting booth, or Having a device that augments the records in the record cartridge.
Youtube: Sequoia Part 1 Those with access can hack with programmed ROM chip
Youtube: Sequoia Part 2 Logic and Accuracy Test vs Election Mode with vote-stealing firmware
Youtube: Sequoia Part 5 Manipulating Sequoia Voting Results Cartridges from Precincts
@Mnementh
The bad cryptography and the possibility to swap the ROM-chip has nothing
  to do with open-sourcing the code? So there is the point?
There are only 3 logical reasons for opensourcing this code:
To put under scrutiny how the votes are counted to be certain its doing it right.
For somebody to be able to modify that code for their own needs.
To put the software into public domain so public committers can improve on it.
Points 1 and 3 are blown out of the water in terms of usefulness and "proving your vote counts" because you have no assurance that the code you are seeing/improving runs on these devices.
So that leaves only condition 2 being useful, and as you are not going to
own
your own voting machine, and have no need for one for anything more than nefarious causes
or
to simply prove their vulnerability.
For the majority of cases all it would mean is that there would be more information publically available on
how
to contravene these machines, so you would no longer need physical access to one in order to attempt reverse engineer their software and develop compromised ROM chips for use in said devices, grossly reducing the barrier to entry for the compromise of the voting system.
Granted, even in a non-opensource state this information can still leak, and you just have a false sense of security because you assume "theres no leak, I am safe", but on the contrary, if you open source it people will assume "hundreds of people have looked at the source code, I am safe" which is an equally bad false sense of security.
People are looking for a silver bullet safe way of voting, and sadly, there is none. Not without growing a race of purified peoples whom are brought up by non-committal monks in isolationist shrines to have a breed of people simply for the task of witnessing and counting votes accurately, whom are trained to be amoral and can't be bribed to switch the vote.
( It would sort of be like the 'dark angel' series except with voting agents instead of assassins, and we all know how that show works out, one of them would go rouge, we'd trust them, and they'd screw us all )


Question:
In our project we have a large number (hundreds) of FLA files created by the artists in CS3, from which we compile SWFs to use in our Flex/AS3 application.

As part of a streamlined build/deploy system, it would be really handy to be able to automate publishing all these FLAs, and ideally deploying the SWFs too. I found some ways to do the batch publishing from CS3 using JSFL, but was surprised to discover CS3 doesn't apparently have any command-line functionality for this?

This is on a Linux system for what it's worth, I don't have experience with JSFL to know if you can run scripts from the command line somehow?

note: I should have said "Linux is preferred"... I don't use Linux but our server/build PC is Linux... I didn't realise CS3 was not compatible so I guess we can do this part on Windows.

Answer:
How you are running Flash CS3 on Linux ?
you cannot run JSFL from command line but compiling a FLA file should be possible
some old example
http://www.mikechambers.com/blog/2003/11/01/flashcommand-flash-2004-command-line-compiler/
newer stuff from Mike Chambers
http://code.google.com/p/flashcommand/
for OSX
so it's definitely possible seems only through semi automated IDE publishing,
too bad Flex compiler is not capable of such a thing, together with ANT tasks it's a killer...
with FDT editor things are pretty cool and automated


Question:
I have read about a technique involving writing to disk a rendered dynamic page and using that when it exists using mod_rewrite. I was thinking about cleaning out the cached version every X minutes using a cron job.

I was wondering if this was a viable option or if there were better alternatives that I am not aware of.

(Note that I'm on a shared machine and mod_cache is not an option.)

Answer:
You could use your cron job to run the scripts and redirect the output to a file.
If you had a php file index.php, all you would have to do is run
```
php index.php > (location of static file)
```
You just have to make sure that your script runs the same on command line as it does served by apache.


Question:
I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a ° character - Unicode U+00B0 (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a UnicodeDecodeError.

My first attempt to fix the issue simply caught that error (because the app apparently does send some bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the wxTextCtrl can display?

Answer:
I can't say mych about wxPython itself, but I am guessing that it is trying to convert the text to Unicode before displaying it, If you have a string like
```
'123\xB0'
```
and try to convert it to Unicode with teh default encoding (ASCII) then it will throw
```
UnicodeDecodeError
```
. You can probably fix this by replacing
```
```
s = message.get_string()
```
```
with
```
```
s = message.get_string().decode('ISO8859-1')
```
```
(where I am assuming a function
```
get_string()
```
that gets the message as a string). The difference here is that by handong the conversion to Unicode yourself you get to specify the encoding.


Question: How can I use CRTP in C++ to avoid the overhead of virtual member functions?

Answer:
I had to look up
CRTP
. Having done that, however, I found some stuff about
Static Polymorphism
. I suspect that this is the answer to your question.
It turns out that
ATL
uses this pattern quite extensively.


Question: How do I create a toolbar for Excel using an XLA document?

Answer:
Not sure if this is what you're looking for but I thought this might help you out:
Excel -- Macro Toolbar
Since you don't specify a version of Excel I'm not sure if this will work for you or not but perhaps it will furnish you with a good starting point.


Question: In the iPhone is there a way I can use JavaScript to close the browser and return to the home screen? After the last page a wizard I am calling out to another iPhone app (ex: maps) and I do NOT what the user to come back to the browser screen when they are done. My backup plan is to have a "Complete" page but that is not the best experience for the client.

Answer:
Knowing Apple, this may not be possible with JavaScript. Have you tried anything yet? If not, try one of these guys out:
```
```
javascript:self.close();
window.close();
```
```
EDIT: I found this thru google, this may bypass the confirmation box, but I don't think it works with the modern browsers anymore:
```
```
window.opener='x';
window.close();
```
```
I just checked, doesn't look like it will work (IE7 box pops up, FF3 does nothing, Opera 9.61 doesnt have a prompt box at all).


Question: When I get a reference to a System.Diagnostics.Process, how can I know if a process is currently running?

Answer:
This is a way to do it with the name:
```
```
Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
  MessageBox.Show("nothing");
else
  MessageBox.Show("run");
```
```
You can loop all process to get the ID for later manipulation:
```
```
Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
   Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}
```
```


Question:
In oracle, I want to create a delete sproc that returns an integer based on the outcome of the deletion.

this is what i have so far.

create or replace
PROCEDURE Testing
(
iKey IN VARCHAR2
)
 AS

BEGIN
  delete from MyTable WHERE
  TheKey = iKey;

END Testing;

i've tried putting a RETURNS INTEGER in but the sproc won't compile.

Answer:
A procedure does not return a value.  A function returns a value, but you shouldn't be doing DML in a function (otherwise you cannot do things like reference the function in a SQL statement, you confuse permission grants since normally DBAs want to be able to grant read-only users access to all the functions so that users are doing computations consistently, etc.).
You can add an OUT parameter to the procedure to return the status.  If "success" means that one or more rows were updated, you can use SQL%ROWCOUNT to get a count of the number of rows modified by the prior SQL statement and use that to populate the return parameter, i.e.
```
```
CREATE OR REPLACE PROCEDURE test_proc (
  p_iKey    IN VARCHAR2,
  p_retVal OUT INTEGER
)
AS
BEGIN
  DELETE FROM myTable
   WHERE theKey = p_iKey;

  IF( SQL%ROWCOUNT >= 1 )
  THEN
    p_retVal := 1;
  ELSE
    p_retVal := 0;
  END IF;
END test_proc;
```
```
Of course, from a general code clarity standpoint, I'm dubious about OUT parameters that appear to be trying to return a status code.  You are generally much better served by assuming success and throwing exceptions in the event of an error.


Question:
I have several identical elements with different attributes that I'm accessing with SimpleXML:

<data>
    <seg id="A1"/>
    <seg id="A5"/>
    <seg id="A12"/>
    <seg id="A29"/>
    <seg id="A30"/>
</data>

I need to remove a specific seg element, with an id of "A12", how can I do this?  I've tried looping through the seg elements and unsetting the specific one, but this doesn't work, the elements remain.

foreach($doc->seg as $seg)
{
    if($seg['id'] == 'A12')
    {
        unset($seg);
    }
}

Answer:
While
SimpleXML
provides
a way to remove
XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the
DOM
extension.
dom_import_simplexml()
will help you with converting your
```
SimpleXMLElement
```
into a
```
DOMElement
```
.
Just some example code (tested with PHP 5.2.5):
```
```
$data='<data>
    <seg id="A1"/>
    <seg id="A5"/>
    <seg id="A12"/>
    <seg id="A29"/>
    <seg id="A30"/>
</data>';
$doc=new SimpleXMLElement($data);
foreach($doc->seg as $seg)
{
    if($seg['id'] == 'A12') {
        $dom=dom_import_simplexml($seg);
        $dom->parentNode->removeChild($dom);
    }
}
echo $doc->asXml();
```
```
outputs
```
```
<?xml version="1.0"?>
<data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data>
```
```
By the way: selecting specific nodes is much more simple when you use XPath (
SimpleXMLElement->xpath
):
```
```
$segs=$doc->xpath('//seq[@id="A12"]');
if (count($segs)>=1) {
    $seg=$segs[0];
}
// same deletion procedure as above
```
```


Question:
On Ubuntu Linux with Gnome, running my Swing application by double clicking on the jar file in Gnomes file browser leads to errors because required libraries that are dynamically loaded via the Java Plugin Framework (residing in subdirectories) are not found.

The base libraries for the framework itself are resolved correctly, as stated in my executable jar's manifest file.
However, once the framework launches, no plugins (not even the one specifying my platform) are found.

Launching the application from the terminal via

java -jar myjar.jar

works like a charm, ad does running the application by double-clicking a shell-script.

However, I'd like to avoid a terminal window. (I'm a Windows person, maybe it won't annoy linux people as it does annoy those on windows.)

The problem is reproducible across several Linux systems.
Is there something I need to do so Java resolves the libraries correctly?

Answer:
Java loads jars in order in its classpath, i.e. jar1:jar2:jar3... Most java applications ship with some sort of script which sets all of this up by specifying a classpath and a list of jars that the application will need.
What you want to do is probably not terribly advisable, as it means globally specifying a collection of jars that you want to load with every java application, and you're liable to create conflicts with whatever libraries ship with the application.
This isn't really a problem, the easiest solution is probably to throw together a little shell script launcher.


Question:
I'm working on a stripes app that uses a bit of jQuery to make the UI more dynamic/usable.

I set up an Error Resolution, so if an error is thrown, the user is redirected to an error.jsp page.

However, if an error is thrown during a jQuery Ajax call, instead of redirecting to the error.jsp page, I get html printed to the page where the result of the call should have been instead.

How do I tell jQuery to redirect if an exception was thrown instead of printing to the page?

An example of the offending Ajax:

$.post("SendStatusEmail.action",
            {status: newstatus, id : id },
            function(data) {
                column.text(data);
                column.addClass("redfont");
                column.parent().fadeOut(3000, function(){column.parent().remove()});

Answer:
```
```
$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {
    // redirect here.
}
```
```
I should add that I don't redirect when there is an exception in an Ajax call.  Instead, I have the server return an error description in JSON format and display that in the page.


Question:
In my spring application context file, I have something like:

<util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
    <entry key="some_key" value="some value" />
    <entry key="some_key_2" value="some value" />
</util:map>

In java class, the implementation looks like:

private Map<String, String> someMap = new HashMap<String, String>();
someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");

In Eclipse, I see a warning that says:

Type safety: Unchecked cast from Object to HashMap<String,String>

What went wrong?

Answer:
Well, first of all, you're wasting memory with the new
```
HashMap
```
creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:
```
```
private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
```
```
Secondly, the compiler is complaining that you cast the object to a
```
HashMap
```
without checking if it is a
```
HashMap
```
. But, even if you were to do:
```
```
if(getApplicationContext().getBean("someMap") instanceof HashMap) {
    private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}
```
```
You would probably still get this warning. The problem is,
```
getBean
```
returns
```
Object
```
, so it is unknown what the type is. Converting it to
```
HashMap
```
directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a
```
HashMap<String, String>
```
.
HashMaps are really maps that take an object as a key and have an object as a value,
```
HashMap<Object, Object>
```
if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a
```
HashMap<String, String>
```
because you could have
```
HashMap<Date, Calendar>
```
because the non-generic representation that is returned can have any objects.
If the code compiles, and you can execute
```
String value = map.get("thisString");
```
without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a
```
ClassCastException
```
at runtime, because the generics cannot block this from happening in this case.


Question:
After "check-in" of a .docx file to SharePoint and editing it the RevNum property is set to 2.

This does not make sense, can someone explain why this is?

Answer:
Well, first of all, you're wasting memory with the new
```
HashMap
```
creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:
```
```
private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
```
```
Secondly, the compiler is complaining that you cast the object to a
```
HashMap
```
without checking if it is a
```
HashMap
```
. But, even if you were to do:
```
```
if(getApplicationContext().getBean("someMap") instanceof HashMap) {
    private Map<String, String> someMap = (HashMap<String, String>)getApplicationContext().getBean("someMap");
}
```
```
You would probably still get this warning. The problem is,
```
getBean
```
returns
```
Object
```
, so it is unknown what the type is. Converting it to
```
HashMap
```
directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a
```
HashMap<String, String>
```
.
HashMaps are really maps that take an object as a key and have an object as a value,
```
HashMap<Object, Object>
```
if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a
```
HashMap<String, String>
```
because you could have
```
HashMap<Date, Calendar>
```
because the non-generic representation that is returned can have any objects.
If the code compiles, and you can execute
```
String value = map.get("thisString");
```
without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a
```
ClassCastException
```
at runtime, because the generics cannot block this from happening in this case.


Question: How to make a shadow to main window widget on windows using Qt?

Answer:
Correct, the second example is in violation of the strict aliasing rules, so if you compile with the
```
-fstrict-aliasing
```
flag, there's a chance you may get incorrect object code.  The fully correct solution would be to use a union here:
```
```
union
{
  SocketMsgToRecv msg;
  char msgBuff[100];
};

recv(socket, msgBuff, 100);

printf("Got Msg: a: %i, b: %i", msg.a, msg.b);
```
```


Question:
In an actionscript function (method) I have access to arguments.caller which returns a Function object but I can't find out the name of the function represented by this Function object.
Its toString() simply returns [Function] and I can't find any other useful accessors that give me that...
Help :-/

Answer:
A function is just an object like any other - it doesn't have a "name" in and of itself; it only has a name in the sense that you might make one or more references to it. If what you're asking is how to get the name of the reference by which the function was called, then there's no general way to do that. (After all the function could be declared anonymously, in which case it has no name at all.)
It would probably be best to examine why you need to know the function's name, and figure out some other way to pass in or access the information you're trying to derive from that name. Passing in an additional parameter might be one approach, but it depends on what you're doing.


Question: Which component is best to use for receiving HTTP requests in Delphi application?

Answer:
Indy
is the way to go. but you need a server component, not a client one.
TIDHTTPServer
should fit the bill


Question:
From the Mozilla Developer Network:

[1,4,9].map(Math.sqrt)

will yield:

[1,2,3]

Why then does this:

['1','2','3'].map(parseInt)

yield this:

[1, NaN, NaN]

I have tested in Firefox 3.0.1 and Chrome 0.3 and just as a disclaimer, I know this is not cross-browser functionality (no IE).

I found out that the following will accomplish the desired effect. However, it still doesn’t explain the errant behavior of parseInt.

['1','2','3'].map(function(i){return +i;}) // returns [1,2,3]

Answer:
I'm going to wager that it's something funky going on with the parseInt's 2nd parameter, the radix.  Why it is breaking with the use of Array.map and not when you call it directly, I do not know.
```
```
//  Works fine
parseInt( 4 );
parseInt( 9 );

//  Breaks!  Why?
[1,4,9].map( parseInt );

//  Fixes the problem
[1,4,9].map( function( num ){ return parseInt( num, 10 ) } );
```
```


Question:
Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely.   E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point?

Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.

Answer:
As in almost all languages:
```
```
while True:
  # check what you want and eventually break
  print nextValue()
```
```
The second part of your question is more interesting:
Also, if it is based on time then is there anyway I could just extend the time and start it going from that point again rather than having to start again from 0
you can use a
```
yield
```
instead of
```
return
```
in the function
```
nextValue()
```


Question: Is there a way to search Microsoft Visual SourceSafe 6.0d for all files tagged with a specific label?

Answer:
I don't think you can search by label, but you can get by label.
From MSDN:
To get a version by label:
Make sure that you have set a working folder in Visual SourceSafe Explorer. See How to: Set the Working Folder.
Ensure that you have set the history options. See How to: View History.
Select the project that contains the file to retrieve.
On the Tools menu, click Show History.
In the History Options dialog box, select the version of the file to retrieve and click OK.
In the History of  dialog box, click Get to retrieve the version of the file that you have chosen.
In the Get dialog box, make any additional entries needed and click OK to retrieve the file.


Question: I need to programmatically enable READ COMMITTED SNAPSHOT in SQL Server. How can I do that?

Answer:
```
```
ALTER DATABASE [dbname] SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK AFTER 20 SECONDS
```
```


Question:
I want to use the same functionality available when a Panel.AutoScroll is true, but with the scrollbars invisible.

To do so I need to know how can I scroll to left/right up/down using functions in my code.

Answer:
You should be able to use the VerticalScroll and HorizontalScroll properties of the component:
```
```
c.HorizontalScroll.Value += 100;
c.VerticalScroll.Value = c.VerticalScroll.Maximum;
```
```


Question:
You can define a number in various ways in C#,

1F // a float with the value 1
1L // a long with the value 1
1D // a double with the value 1

personally I'm looking for which would a short, however to make the question a better reference for people, what are all the other post-fix's to number literals you can apply?

Answer:
for money:
```
```
decimal mon = 1m;
```
```
for output:
```
```
string curr = String.Format("{0:C}", mon);  //output $1.00
```
```


Question:
Is there a way for me to loop over a Javascript Object's built-in properties?

for...in gets me close to where I want to go, but "A for...in loop does not iterate over built-in properties."

Answer:
This will work with JSON. It hasn't been tested much:
```
```

```
```


Question: See question above.

Answer:
Yes, use IKVM.
http://www.ikvm.net/
And it's incredibly easy to use:
```
```
ikvmc myjar.jar
```
```
outputs myjar.dll


Question:
At what point in a team's growth must process change drastically?  A lone coder can get away with source control and a brain. A team trying to ship large prepackaged software to local and international markets must have a bit more in place.

If you've experienced a large transition in 'process':  Was the team's process successfully changed with the current members or was the team itself mostly replaced by the time the process change came?  What were the important aspects that changed, were some unnecessary?

Answer:
If memory serves me correctly anything above five people is where things get dicey.  The number of paths of comunication between the team gets really large after that.
(2 people = 1 path, 3 = 3 paths, 4 = 6 paths, 5 = 10 paths and so on).
The last three places I've been the IT team went through a massive process change.  Yes, you will lose people, probably some of the better ones too.  it's not that they are stubborn and trying to stick to the old ways, it's just that a change like this will cause a mass amount of stress.  There are deadlines to hit and a need for quality to be met.  People will get confused about what process they are supposed to do, and many will fall back to the "old ways." (i've  been guilty of this too I admit.)
The key to succeeding is to take it slow and in small steps.  People need to take time to understand why the process is changing and how it benefits them.  That is huge, if you don't take time to do this, it won't succeed, and key people will end up quitting causing turmoil.
One of the things to absolutely remember is that ultimately some turnover is good.  It brings new ideas and people with different (and sometimes better) skill sets.  You shouldn't try and force change onto people rapidly, but they shouldn't be a barrier either.  If they don't agree with what is going on, they should either try and come to a middle ground with the people making the process or leave.  One of the real eye openers I learned at my first job is that in reality everyone is replaceable.  Someone will eventually be able to step in take the reigns.


Question:
I use div tags to define areas within my web pages.  I set all the obvious things like background, size, padding, etc.  But it is all very square.

How can I use only CSS to round the corners?

Answer:
You would use the border-radius property.  However, this is only supported in CSS3, which no browser implements yet.  If you only need it to work in a couple browsers you could use -webkit-border-radius and -moz-border-radius which would let it work in Safari and Firefox respectively.
If you are not opposed to using images.  Here's s method I came up with for
making rounded borders
.


Question:
I currently have 2 BufferedReaders initialized on the same text file. When I'm done reading the text file with the first BufferedReader, I use the second one to make another pass through the file from the top. Multiple passes through the same file are necessary.

I know about reset(), but it needs to be preceded with calling mark() and mark() needs to know the size of the file, something I don't think I should have to bother with.

Ideas? Packages? Libs? Code?

Thanks
TJ

Answer:
What's the disadvantage of just creating a new
```
BufferedReader
```
to read from the top? I'd expect the operating system to cache the file if it's small enough.
If you're concerned about performance, have you proved it to be a bottleneck? I'd just do the simplest thing and not worry about it until you have a specific reason to. I mean, you could just read the whole thing into memory and then do the two passes on the result, but again that's going to be more complicated than just reading from the start again with a new reader.


Question:
We currently use VSS 6, this is not going to change I am afraid.

I am attempting to write a script that will allow a user to quickly copy all files that they have checked out to another directory tree. In order to do this I need to get a list of all the files that the user has checked out, and the directory that the file is checked out to. This is easy enough to do using status search in the GUI. But I need a way of doing it from the command line utility ss.exe.

Answer:
See
here
for the command line usage of Status command. The command
```
```
ss.exe Status $/ -R -U
```
```
shows every file in the system that is checked out by the current user.


Question: Is there a canonical way to set up a JS onHover event with the existing onmouseover, onmouseout and some kind of timers?  Or just any method to fire an arbitrary function if and only if user has hovered over element for certain amount of time.

Answer:
Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?
That said, I think what you probably want is...
```
```
var timeout;
element.onmouseover = function(e) {
    timeout = setTimeout(function() {
        // ...
    }, delayTimeMs)
};
element.onmouseout = function(e) {
    if(timeout) {
        clearTimeout(timeout);
    }
};
```
```
Or
```
addEventListener
```
/
```
attachEvent
```
or your favorite library's event abstraction method.


Question:
1) user A goes to the site, creates an account, and logs in
2) user b goes to the site.  Rather than having to log in, user b enters as though user b is user a.  User b gets access to all of user a's data and can brows the site as user a.

Note: user b does not log in.  User b just hits the site, and the site returns as if user b is already logged in as user a.

Note 2: user a and user b are on distinct computers.  Also, static variables are not involved in the code.

Setup:
IIS 6
.Net 2.0
OutputCache off for the pages in the site

Answer:
This question seems quite similar to
Apache/Tomcat error - wrong pages being delivered
. As
my answer
to that question mentions, if you use session cookies, check if your
```
Vary
```
header is correct.


Question:
I'm working on a project and I want to store some easily enumerated information in a table.  MySql's enum data type does exactly what I want: http://dev.mysql.com/doc/refman/5.0/en/enum.html .  Is there an equivalent in SQL Server 2005?

I know I could store the possible values in a type table with a key, but I'd rather not have to link back to it for descriptions.  Our database standards don't allow us to link on non-integer or uniqueidentifier fields, so storing the possible keys as characters is out as well.

Answer:
Does this work for you?
From
http://blechie.com/wtilton/archive/2007/08/24/303.aspx
Create table...
MySQL:
```
```
ColumnName ENUM('upload', 'open', 'close', 'delete', 'edit', 'add')
   DEFAULT 'open'
```
```
SQL Server:
```
```
ColumnName varchar(10)
   CHECK(ColumnName IN ('upload', 'open', 'close', 'delete', 'edit', 'add'))
   DEFAULT 'open'
```
```


Question: Have you ever worked on a (full-time) project where using Agile methodologies actually allowed you to accomplish a 40-hour work-week? If so, what were the most valuable agile practices?

Answer:
Scrum and management that is willing to buy into it.
Fair sprint planning.  When you negotiate your own sprint you can choose what  your team can accomplish rather than have tasks being handed down from above. Having your sprint commitment locked in (management can't change it mid-sprint) gives freedom from the every changing whims of people.
A well maintained, prioritized backlog that is maintained
cooperatively
by the product owner and upper management is very useful.  It forces them to sit down and think about the features they want, when they want them and the costs involved.  They will often say they need a feature
now
, but when they realized they have to give up something else to get what they want their expectations become more realistic.
Time boxing. if you are running into major problems start removing features from the sprint rather than working extra hours.
You need managerial support for you process without it agile is just a word.
Did I mentioned enlightened management?


Question:
I cannot find the translated file after running the solution in BizTalk 2006 Tutorial Lesson 3: Run the EDI-to-XML Solution.

It should be placed in the c:\Program Files\Microsoft BizTalk Server 2006 \EDI\Adapter\Getting Started with EDI\Northwind\In folder.

The Base EDI adapter picks up the file in c:\Documents and Settings\All Users\Application Data\Microsoft\BizTalk Server 2006 \EDI\Subsystem\Documents\PickupEDI folder, but I cannot find the translated file in the X-12 4010 850 document format.

Answer:
Scrum and management that is willing to buy into it.
Fair sprint planning.  When you negotiate your own sprint you can choose what  your team can accomplish rather than have tasks being handed down from above. Having your sprint commitment locked in (management can't change it mid-sprint) gives freedom from the every changing whims of people.
A well maintained, prioritized backlog that is maintained
cooperatively
by the product owner and upper management is very useful.  It forces them to sit down and think about the features they want, when they want them and the costs involved.  They will often say they need a feature
now
, but when they realized they have to give up something else to get what they want their expectations become more realistic.
Time boxing. if you are running into major problems start removing features from the sprint rather than working extra hours.
You need managerial support for you process without it agile is just a word.
Did I mentioned enlightened management?


Question: When would you call Java's thread.run() instead of thread.start()?

Answer:
Call
```
thread.start()
```
, it will in turn call
```
thread.run()
```
.  Can't think of a case when you would want to bypass
```
thread.start()
```
and go directly to
```
thread.run()
```