Question: Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?

Answer:
Yes, it is possible:
```
```
public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}
```
```
To chain to a particular superclass constructor instead of one in the same class, use
```
super
```
instead of
```
this
```
. Note that
you can only chain to one constructor
, and
it has to be the first statement in your constructor body
.
See also
this related question
, which is about C# but where the same principles apply.


Question:
I have a database table (sql server 2008) that I want to view data for, what is the quickest way of displaying this data?

(if it could have paging that would be perfect).

Would it be a gridview or ?

query: select * from testData

Answer:
if you're using .NET 3.5 you could use ASP.NET Dynamic Data:
http://www.asp.net/dynamicdata/
Hope this helps!


Question: Can Spirit (part of Boost C++ library) be used to parse out binary data coming from a stream?  For example, can it be used to parse data coming from a socket into structures, bytes, and individual bit flags?  Thanks!

Answer:
Boost Spirit allows for a parser to be defined using
Extended Backus–Naur Form (EBNF)
syntax with
template meta-programming
. It is very flexible and uses abstract classes in all phases of the parsing process that can be customized. In order to process a binary data stream, you would need to implement custom scanner classes since the default types are tailored for text input. You can read further in
The Scanner and Parsing
section of the
Spirit User's Guide
.
In my humble opinion, binary data streams are best handled with hand rolled serialization code. Spirit is geared more towards well formed grammars like mark-up or scripting languages. For example,
The Complete Syntax of Lua
is provided in EBNF. So, it might make sense to use Spirit to build a custom parser. On the other hand, a proprietary serial data link with synchronization bytes and CRC bracketing messages would require a lot more work just to define the EBNF if a
context-free grammar
even exists for it.
Addendum
The latest version of Boost Spirit includes functionality for dealing with binary data.


Question:
We are looking to improve our marketing email list by preventing fake emails from entering in the first place.  We want to confirm that an email address exists (and that there is actually a mailbox for that email address).

Does anyone know of any services or components to validate an email address?

Answer:
the following regular expression is an example of how you could validate an email address is in the correct general format:
```
```
(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})
```
```
For security reasons, very few email servers provide a function to remotely validate whether or not a mailbox exists, so it is very unlikely a service could provide this information with any reliability.
Hope this helps!
Adam


Question:
I'm embedding an IE control into my C++ application. The problem is that although system-wide, ClearType is disabled, IE7 has its own separate setting, and unless I specifically disable that too, text inside the IE control will be antialiased while the rest of the app will not.

The same goes for IE7's font size setting.

It wouldn't be a problem for me to set up IE7 accordingly, but it would affect the experience of users of my app. Can the IE control's cleartype usage and font size be programmatically controlled?

Answer:
the following regular expression is an example of how you could validate an email address is in the correct general format:
```
```
(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})
```
```
For security reasons, very few email servers provide a function to remotely validate whether or not a mailbox exists, so it is very unlikely a service could provide this information with any reliability.
Hope this helps!
Adam


Question: SQL Server 2000: Is there a way to find out server memory / CPU parameters in Query Analyzer?

Answer:
Not that I know of. You'll have to look in
```
perfmon
```
.


Question:
We have a system where customers, mainly European enter texts (in UTF-8) that has to be distributed to different systems, most of them accepting UTF-8, but now we must also distribute the texts to a US system which only accepts US-Ascii 7-bit

So now we'll need to translate all European characters to the nearest US-Ascii. Is there any Java libraries to help with this task?

Right now we've just started adding to a translation table, where Å (swedish AA)->A and so on and where we don't find any match for an entered character, we'll log it and replace with a question mark and try and fix that for the next release, but it seems very inefficient and somebody else must have done something similair before.

Answer:
There are some built in functions to do this. The main class involved is
```
CharsetEncoder
```
, which is part of the
```
nio
```
package. A simpler way is
```
String.getBytes(Charset)
```
that can be sent to a
```
ByteArrayOutputStream
```
.


Question:
To be able to upload large files from a HTML page to a FTP server, I am looking for a Java/Flash FTP upload applet.

I really like the way dhtmlxVault works, but I need it to upload to a FTP server instead of a HTTP file upload.

It would be really nice if the applet has no GUI of it's own, but instead is fully scriptable using Javascript so I can use HTML/CSS for it's appearance.

I hopefully looked into Yahoo!'s YUI Uploader since it requires Flash, but the documentation only mentions HTTP upload and no FTP upload.

Answer:
I tried the
ZUpload
Java applet.
Pro's:
The user interface works as easy as I could hope it to work.
It is a Java applet with it's own GUI, but I was able to implement some Javascript callbacks in it to update progress information in HTML. I would be able to minimize the GUI further.
Con's:
When an upload failes (when the FTP server tells it it is to busy, please retry in a moment) it thinks the upload succeeded and goes on with the next file. I tried to catch the exceptions but was unable to do so because of either the way j-ftp is used in the applet or my own lack of knowledge.
The project seems to be dead since 2003, so I don't expect any updates.
So my conclusion it that it is not ready to be used in a production environment. I still need a better solution.


Question:
Firstly I'm extending an existing class structure and cannot alter the original, with that caveat:

I would like to do this:

class a
{
   int val;

   ... // usual constructor, etc...

   public int displayAlteredValue(int inp)
   {
     return (val*inp);
   }
}

class b extends a
{
   ... // usual constructor, etc...

   public in displayAlteredValue(int inp1, int inp2)
   {
     return (val*inp1*inp2);
   }
}

As I said before I cannot alter class a and I want to maintain the function name displayAlteredValue rather than making a new function.
If this can be done I only have to change a few instantiations of a to instantiations of b. I don't want to spend a lot of time replacing the many function calls to displayAlteredValue. (And yes I do realise there are such things as search and replace however for other reasons, doing that would be problematic).

Any ideas?

Answer:
what if you add this to your derived class
```
```
public int displayAlteredValue(int inp)
{
  return super.displayAlteredValue(inp);
}
```
```


Question:
What are differences between enabling and disabling "Enable 32-Bit applications" in websites application pools under IIS7 on x64 machine?

Mostly I'm thinking about memory usage.

Thanks in advance

Answer:
I believe the current "trend" for hosting like this is to have each site with its own Application Pool, and each application pool running in 32 bitness. This enables Application Pool isolation, and allows each site/application pool to be limited to 4gb of memory, which basically works out to about 2.4 GB before asp.net recycles given the 60% memory threshold.
If you have an individual site that requires more memory, you'd change that application pool to x64, allowing for a much larger application pool.


Question:
I have a number of string arrays. The string in every array are ordered the same way, according the same criteria. However, some string may be missing from some arrays, and there may be no array that has a complete set of strings. Moreover, the criteria used to compare the strings is not available to me: outside of the context of the array, I cannot tell which string should precede another.

I need a way to produce a complete set of strings, properly ordered. Or fail when the arrays do not have enough information for me to do so.

Is anyone familiar with this kind of problem? What is the proper algorithm?

Examples:

A B D
A C D

Can't order correctly, can't decide the order of B and C

A B D
A B C
A C D

This has enough information to order ABCD correctly.

Answer:
How many sets will you have? Something that might work if they aren't too sparse is:
Iterate over the first element of
all arrays counting how common each
string is.
Whichever element is the most common
is selected.
Check each element of all
arrays for said string.
If it exists in any element other than the first of an array, the first element of
its parent array is selected and goto step 3.
Remove the selected element from the
first element of all arrays/trees
and add it to the end of your output
list.
Goto 1 until all elements are
removed.
If you dumped the arrays into
b-trees
the element search could be pretty fast. You may also be able to further speed up step 3 by playing with the order of the arrays. I'm still thinking about that.
If the arrays are very sparse the only thing I can think of is to use some kind of supervised machine learning to try to determine the proper method for ordering.


Question:
I've got an SQL query that looks like this:

INSERT INTO DB..incident
(
    incident_number        --nvarchar(10)
)
VALUES
(
    N'I?'
)

What does the ? do in the value statement?

EDIT:: Turns out there's some funny business via triggers and custom datatypes that occur on insert (we've got a bit of a messed up DB.) Given normal settings I've marked the answer appropriately.

Answer:
At the risk of sounding flippant... Nothing... It puts an I? into the field... Try this...
```
```
DECLARE @TestTable TABLE (test NVARCHAR(10))

INSERT INTO @TestTable (
    test
) VALUES (
    N'I?' )

SELECT *
FROM  @TestTable
```
```


Question:
Is there a way to have the compile deduce the template parameter automatically?

template<class T>
struct TestA
{
    TestA(T v) {}
};
template<class T>
void TestB(T v)
{
}
int main()
{
    TestB (5);
}

Test B works fine, however when i change it to TestA it will not compile with the error " use of class template requires template argument list"

Answer:
No, there isn't. Class templates are never deduced. The usual pattern is to have a
```
make_
```
free function:
```
```
template<class T> TestA<T> make_TestA(T v)
{
    return TestA<T>(v);
}
```
```
See
```
std::pair
```
and
```
std::make_pair
```
, for example.
In C++0x you will be able to do
```
```
auto someVariable = make_TestA(5);
```
```
to avoid having to specify the type for local variables.


Question:
We have a web service that uses up more and more private bytes until that application stops responding.  The managed heap (mostly Gen2) will show some 200-250 MB, while private bytes shows over 1GB.  What are possible causes of a memory leak outside of the managed heap?

I've already checked for the following:

Prolific dynamic assemblies (Xml serialization, regex, etc.)

Session state (turned off)

System.Policy.Evidence memory leak (SP1 installed)

Threading deadlock (no use of Join, only lock)

Use of SQLOLEDB (using SqlClient)

What other sources can I check for?

Answer: Make sure your app is complied in release mode.  If you compile under debug mode, and deploy that, simply instantiating a class that has an event defined (event doesn't even need to be raised), will cause a small piece of memory to leak.  Instantiating enough of these objects over a long enough period of time will cause all the memory to be used.  I've seen web apps that would use up all the memory within a matter of hours, simply because a debug build was used.  Compiling as a release build immediately and permanently fixed the problem.


Question:
I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it.  Something like Date::Extract in Perl

Thank you in advance.

Answer:
The nearest equivalent is probably the
dateutil
module.  Usage is:
```
```
>>> from dateutil.parser import parse
>>> parse("Wed, Nov 12")
datetime.datetime(2008, 11, 12, 0, 0)
```
```
Using the fuzzy parameter should ignore extraneous text.  ie
```
```
>>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True)
datetime.datetime(2006, 12, 1, 14, 30)
```
```


Question:
I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?

I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.

Answer:
I'm not a python guru, but I found this question interesting so I googled around.
This
was the first hit on "python embedding API" - does it help?
If the attributes belong to the global
  scope of a module, then you can  use
  "PyImport_AddModule" to get a handle
  to the module object. For  example, if
  you wanted to get the value of an
  integer in the
main
module named
  "foobar", you would do the following:
```
```
PyObject *m = PyImport_AddModule("__main__");
PyObject *v = PyObject_GetAttrString(m,"foobar");

int foobar = PyInt_AsLong(v);

Py_DECREF(v);
```
```


Question:
Hi Guys I'm very new to regex, can you help me with this.

I have a string like this "<input attribute='value' >" where attribute='value' could be anything and  I want to get do a preg_replace to get just <input />

How do I specify a wildcard to replace any number of any characters in a srting?

like this? preg_replace("/<input.*>/",$replacement,$string);

Many thanks

Answer:
What you have:
```
```
.*
```
```
will match "any character, and as many as possible.
what you
mean
is
```
```
[^>]+
```
```
which translates to "any character, thats not a ">", and there must be at least one
or altertaively,
```
```
.*?
```
```
which means
"any character, but only enough to make this rule work"
BUT DONT
Parsing HTML with regexps is
Bad
use any of the existing html parsers, DOM librarys, anything, Just NOT NAïVE  REGEX
For example:
```
```
<foo attr=">">
```
```
Will get grabbed wrongly by regex as
```
```
'<foo attr=" ' with following text of '">'
```
```
Which will lead you to this regex:
```
```
`<[a-zA-Z]+( [a-zA-Z]+=['"][^"']['"])*)>  etc etc
```
```
at which point you'll discover this lovely gem:
```
```
<foo attr="'>\'\"">
```
```
and your head will explode.
( the syntax highlighter verifies my point, and incorrectly matches thinking i've ended the tag. )


Question:
If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll).  How can I do this in C#?  I tried the Merge statement on the datatable, but this returns void.  Does Merge preserve the data?  For example, if I do:

 dtOne.Merge(dtTwo);

Does dtOne change or does dtTwo change and if either one changes, do the changes preserve?

I know I can't do this because Merge returns void, but I want to be able to store the Merger of both dtOne and dtTwo in dtAll:

//Will Not work, How do I do this
dtAll = dtOne.Merge(dtTwo);

Answer:
The
```
Merge
```
method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.
If you want to preserve both of the original tables, you could copy the original first, then merge:
```
```
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);
```
```


Question:
I have a little c# console program that outputs some text using Console.WriteLine. I then pipe this output into a textfile like:

c:myprogram > textfile.txt

However, the file is always an ansi text file, even when I start cmd with the /u switch.
cmd /? says about the /u switch:

/U    Causes the output of internal
  commands to a pipe or file to be Unicode

And it indeed makes a difference, when I do an

c:echo "foo" > text.txt

the text.txt is unicode (without BOM)

I wonder why piping the output of my console program into a new file does not create an unicode file likewise and how i could change that?

I just use Windows Power Shell (which produces a unicode file with correct BOM), but I'd still like to know how to do it with cmd.

Thanks!

Answer:
The /U switch, as the documentation says, affects whether
internal
commands generate Unicode output. Your program is not one of cmd.exe's internal commands, so the /U option does not affect it.
To create a Unicode text file, you need to make sure your program is generating Unicode text.
Even that may not be enough, though. I came across
this blog from Junfeng Zhang
describing how to write Unicode text in a console program. It checks the file type of the standard output handle. For character files (a console or LPT port), it calls WriteFileW. For all other types of handles (including disk files and pipes), it converts the output string to the console's current code page. I'm afraid I don't know how that translates into .Net terms, though.


Question:
I am binding an SPGridView to a SPList. As code samples suggest, I am using the following code to create a dataview based on the list.

dim data as DataView = myList.Items.GetDataTable.DefaultView
grid.DataSource = data
etc...

What I am finding is that the column names in the resulting dataview do not always match the source fields defined in the SPList. For example I have columns named

Description

ReportItem

ReportStatus

these show up in the resulting dataview with column names like

ReportType0

ReportStatus1

This leads me to think that I have duplicate field names defined, but that does not seem to be the case.

Seems like I am missing something fundamental here?
Thanks.

Answer:
The
```
GetDataTable
```
method is returning the
```
internalName
```
(or
```
staticName
```
-- I can't remember for sure which but they are frequently the same) representation of the columns, rather than the
```
Title
```
representation, which is what you see in the Web interface. I believe
```
GetDataTable
```
does a CAML query under the covers, and you have to use that
```
internalName
```
for field references in CAML.
This
blog
talks about it in a little more detail.


Question:
Please share how you do version control for Lotus Notes/Domino development.

I want to put in our SVN repository all the scripts, views, custom forms, script libraries, etc.

Semi-automated methods are accepted as well (i.e. if I find a way to get all the event scripts for a form in one file, and to be able to place it back in Notes Designer as a whole file).

Answer:
The short answer is that you aren't going to be able to do this reliably in an automated or semi automated way.  If DXL had full fidelity and full round-trip capability then you would be able to store DXL exports of the design elements in SVN, but there are places where DXL isn't good enough.
The only real version control you are gong to get is via propitiatory third part vendors like
TeamStudio's CIAO
product.
Update:
Some people have reported success in exporting elements in an encoded binary format that retains full fidelity on import.  This makes round tripping for the purpose of version control possible.


Question: I am making a post from a .NET console app to a .NET web service.  I know that the timeout on the server side is 20 min, but if my client takes more than 100 seconds to post my data to that service then I get a timeout exception.  How would I tell my client to wait the available 20 min to timeout?

Answer:
on the client side, your webservice object has a timeout value. It should be pretty easy to set by going:
```
```
myServiceInstance.Timeout = 1200000
```
```
for 20 minutes


Question:
Let's say I have an html form.  Each input/select/textarea will have a corresponding <label> with the for attribute set to the id of it's companion. In this case, I know that each input will only have a single label.

Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?

Answer:
Earlier...
```
```
var labels = document.getElementsByTagName("LABEL"),
    lookup = {},
    i, label;

for (i = 0; i < labels.length; i++) {
    label = labels[i];
    if (document.getElementById(label.htmlFor)) {
        lookup[label.htmlFor] = label;
    }
}
```
```
Later...
```
```
var myLabel = lookup[myInput.id];
```
```
Snarky comment: Yes, you can also do it with JQuery. :-)


Question:
Is there a way to determine if the loop is iterating for the last time. My code looks something like this:

int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();

for(int i : array)
{
    builder.append("" + i);
    if(!lastiteration)
        builder.append(",");
}

Now the thing is I don't want to append the comma in the last iteration. Now is there a way to determine if it is the last iteration or am I stuck with the for loop or using an external counter to keep track.

Answer:
It might be easier to always append. And then, when you're done with your loop, just remove the final character. Tons less conditionals that way too.
You can use
```
StringBuilder
```
's
```
deleteCharAt(int index)
```
with index being
```
length() - 1
```


Question:
Up till now all my programming experience has been desktop development (mostly C/C++ with OpenGL/DirectX) but I'm interested in trying my hand at some web dev.

The two directions I'm considering are Ruby on Rails and ASP.net.

Which is most widely used?

Which would be a more marketable skill to have?

Thanks!

Answer:
Learning Ruby will help you learn a different way of thinking about programming. It will help you become a better programmer, even if you determine that it's not a language for you. The same applies to several other languages (including Python). There are fewer job opportunities for Ruby developers.
ASP.Net is a fairly pedestrian way to develop fairly pedestrian webapps that don't really challenge how you think as a programmer. Job and consulting opportunities are more common.
From this point, it's your call. I chose Ruby six years ago.


Question: I have a data acquisition program written in C++ (Visual Studio 6.0).  Some clients would like to control the software from their own custom software or LabView.  I would like to come up with a simple API with a dll I can distribute to them and would like some tips on how to get started.  This is going to be VERY basic, maybe 4 or 5 commands.  My DAQ program will still be running in its own window on the same machine, I would just like to set it up to be controlled from another program.

Answer:
You are on the right track with a DLL.  The real trick, it sounds like, will be deciding what sort of inter-process communication (IPC) you want to use.  Options are: sockets, pipes, shared memory, synchronization objects (events, etc.), files, registry, etc.
Once you decide that, then implement a listener within your executable to wait for incoming IPC messages from whatever software is using your DLL.
As far as the API is concerned, you can keep it simple just like you were wanting.  Have the DLL expose your 4 or 5 functions (make sure you only use native data types, like char* and long, to avoid module boundary issues), and then those will use your IPC mechanism to communicate with your executing app.


Question:
I need to be able to store a date (year/month/day) with no time component. It's an abstract concept of a date, such as a birthday - I need to represent a date in the year and not a particular instant in time.

I am using Java to parse the date from some input text, and need to store in a MySQL database. No matter what timezone the database, application, or any client is in, they should all see the same year/month/day.

My application will run on a machine with a different system timezone from the database server, and I don't have control over either. Does anyone have an elegant solution for ensuring I store the date correctly?

I can think of these solutions, neither of which seems very nice:

Query my MySQL connection for its timezone and parse the input date in that timezone

Process the date entirely as a string yyyy-MM-dd

Answer:
You could zero out all time/timezone stuff:
```
```
public static Date truncateDate(Date date)
    {
        GregorianCalendar cal = getGregorianCalendar();
        cal.set(Calendar.ZONE_OFFSET, 0); // UTC
        cal.set(Calendar.DST_OFFSET, 0); // We don't want DST to get in the way.

        cal.setTime(date);
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.AM_PM, Calendar.AM);

        return cal.getTime();
    }
```
```


Question: I have googled quite a bit and I cannot find the answer. So how many characters can be stored in a Windows Installer property value. If you give an answer can you provide the source of the answer?

Answer:
The MSDN documentation isn't very clear on this, but it does provide some hints.  For example, this article mentions that property values may be written to the registry, which means that registry value limitations apply:
http://msdn.microsoft.com/en-us/library/aa372432%28VS.85%29.aspx
Here is an article detailing registry value limitations:
http://support.microsoft.com/kb/256986
So at a maximum, I'd use the registry value limitations as a guide (and still try to stay well below that).


Question:
When i do

wnd = CreateWindow("EDIT", 0,
    WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE |
    ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN,
    x, y, w, h,
    parentWnd,
    NULL, NULL, NULL);

everything is fine, however if i remove the WS_VSCROLL and WS_HSCROLL then do the below, i do not get them thus have incorrect window. Why?
Not only do i get an incorrect window it is unusable if both WS_VSCROLL and WS_HSCROLL are missing

style = WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE |
    ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN;
SetWindowLong(wnd, GWL_STYLE, style);

Answer:
Some control styles cannot be changed after window creation. The ES_AUTOHSCROLL style (which essentially controls word wrapping) is one of them; this is stated (somewhat indirectly) by the MSDN section on
Edit Control Styles
. You can set the bits using SetWindowLong(), but the control will either ignore them or behave erratically.
The only way to do this cleanly is to recreate the edit control using the required styles. This is actually what Notepad does when you toggle the "Word Wrap" setting.


Question:
Is it possible to use the __unused attribute macro on Objective-C object method parameters? I've tried placing it in various positions around the parameter declaration but it either causes a compilation error or seems to be ignored (i.e., the compiler still generates unused parameter warnings when compiling with -Wall -Wextra).

Has anyone been able to do use this? Is it just unsupported with Objective-C? For reference, I'm currently using Apple's build of GCC 4.0.1.

Answer:
I can compile the following just fine:
```
```
- (NSString *) test:(__unused NSString *)test {
    return nil;
}
```
```
Edit: Actually, that may not be strictly an arch thing:
```
```
Phoenix-VI:CouchPusher louis$ cc -c Pusher.m -Wall -Werror
Phoenix-VI:CouchPusher louis$ cc -c Pusher.m -Wall -Werror  -Wunused-parameter
cc1obj: warnings being treated as errors
Pusher.m:40: warning: unused parameter ‘test’
Phoenix-VI:CouchPusher louis$
```
```
So -Wall does not include not include -Wunused-parameter....


Question:
Another angle:
how do I browse all the XUL for a given chrome path, e.g.

http://kb.mozillazine.org/Dev_:_Firefox_Chrome_URLs has a listing but seems to be out of date.

Answer:
Mozilla
```
chrome://
```
URLs
refer to actual files located in a .jar file in some fairly well-defined places.
The main browser (chrome://browser/content/...) itself:
```
```
{where you installed Firefox}/chrome/browser.jar
```
```
Firefox add-ons:
```
```
{your profile directory}/extensions/{extension id}/chrome/content/...
```
```
where
```
{your profile directory}
```
, on Windows XP at least, is
```
```
c:\Documents and Settings\{your username}\Application Data\Mozilla\Firefox\Profiles\{your profile name, usually ends in .default}
```
```


Question:
I have an input String say Please go to http://stackoverflow.com. The url part of the String is detected and an anchor <a href=""></a> is automatically added by many browser/IDE/applications. So it becomes Please go to <a href='http://stackoverflow.com'>http://stackoverflow.com</a>.

I need to do the same using Java.

Answer:
You could do something like this (adjust the regex to suit your needs):
```
```
String originalString = "Please go to http://www.stackoverflow.com";
String newString = originalString.replaceAll("http://.+?(com|net|org)/{0,1}", "$0");
```
```


Question: Is there a way in FreeBSD to (being root) run a command as unprivileged user, like nobody? Kind of like reverse of sudo. Oh and considering that 'nobody' has /usr/sbin/nologin as shell - so su is not an option.

Answer:
sudo will allow you to run a command as another user.
```
```
sudo -u nobody <command>
```
```
will run  as nobody, even if their login shell is not available.


Question:
In Vim I can :set wrapscan so that when I do an incremental search, the cursor jumps to the first match whether the first match is above or below the cursor.

In Emacs, if I start a search via C-s, the search fails saying Failing I-search if the first match is above the cursor.  If I hit C-s again it then wraps the search, saying Wrapped I-search.  How do I wrap and jump the cursor by default as in Vim, without having to C-s a second time?

Answer:
The easiest way to do this is to use the following defadvice:
```
```
(defadvice isearch-repeat (after isearch-no-fail activate)
  (unless isearch-success
    (ad-disable-advice 'isearch-repeat 'after 'isearch-no-fail)
    (ad-activate 'isearch-repeat)
    (isearch-repeat (if isearch-forward 'forward))
    (ad-enable-advice 'isearch-repeat 'after 'isearch-no-fail)
    (ad-activate 'isearch-repeat)))
```
```
When Isearch fails, it immediately tries again with wrapping. Note that it is important to temporarily disable this defadvice to prevent an infinite loop when there are no matches.


Question:
We've got a WinForms app written in C# that has a very custom GUI.  The user is not allowed to run any other applications and the user cannot go into the OS (WinXP Pro) at all.  We're planning on allowing the user to connect to available wireless networks. We're going to have to create a configuration screen that displays available networks (by SSID) and allows the user to connect.  While connected we want to display signal strength.

Are there any existing components that provide this capability?  I haven't found anything but this.

I can set the TCP/IP settings using WMI, but it's the wireless stuff that I need a direction on.

Many thanks!

Matt

Answer:
Managed Wifi API
should work.
This might not be ideal - you have XP, which is good, but you would have to deploy a hotfix.  I'd go for it, because all the wifi code I've dealt with (for the Compact Framework) is hideous.  This code is as simple as could be.
Their sample code doesn't include reading the signal strength, though, and I'm not sure if the Native wifi API provides that.  I have written C# code that gets the wireless signal strength, but it did this by PInvoking into a manufacturer-specific DLL available only on their devices.  It may be that you'll have to do something similar to get the wireless strength from your PC's wireless card (and that may be why that functionality is not available in an all-purpose API).


Question:
I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I'm only returning a single column from this particular table to get its value.

Edit: This would be SQL Server.

Answer:
Do you want to return a full row?  Does the default row need to have default values or can it be an empty row?  Do you want the default row to have the same column structure as the table in question?
Depending on your requirements, you might do something like this:
1)  run the query and put results in a temp table (or table variable)
2)  check to see if the temp table has results
3)  if not, return an empty row by performing a select statement similar to this (in SQL Server):
```
```
select '' as columnA, '' as columnB, '' as columnC from #tempTable
```
```
Where columnA, columnB and columnC are your actual column names.


Question: I understand that BigDecimal is recommended best practice for representing monetary values in Java. What do you use? Is there a better library that you prefer to use instead?

Answer:
```
BigDecimal
```
all the way. I've heard of some folks creating their own
```
Cash
```
or
```
Money
```
classes which encapsulate a cash value with the currency, but under the skin it's still a
```
BigDecimal
```
, probably with
```
BigDecimal.ROUND_HALF_EVEN
```
rounding.
Edit:
As Don mentions in
his answer
, there are open sourced projects like
timeandmoney
, and whilst I applaud them for trying to prevent developers from having to reinvent the wheel, I just don't have enough confidence in a pre-alpha library to use it in a production environment. Besides, if you dig around under the hood, you'll see
they use
```
BigDecimal
```
too
.


Question:
Here is a nice underhand lob pitch to you guys.

So basically I've got my content table with unique primary key IDs and I've got my tag table with unique primary key IDs.

I've got a table that has an identity column as a primary key but the two other columes are the contentID and tagID.  What do I need to do to the table to make sure that I only have the same contentID and tagID combo only once.

Answer:
You put a Unique constraint on contentID, tagID.
For SQL Server
```
```
ALTER TABLE ContentTag ADD CONSTRAINT
    IX_ContentID_TagID_Unique UNIQUE NONCLUSTERED ( contentID,  tagID )
GO
```
```


Question: i'm looking for a way to programatically convert word documents in docx format to doc format without using ole automation.  i already have a windows service that does this but it means installing office on a server and it is a little unreliable and not supported.  i am aware of the aspose.words product, and i will try it out, but has anyone any recommendations for how to do this as simply, reliably, and cheaply as possible?

Answer:
One option without using OLE automation would be to wrap the converter dlls coming with compatibility pack in order to convert from docx to doc without automating Office.
This requires only that the Compatibility Pack of Office is installed on the machine.
The Office converter dlls convert from the document format that they support to RTF and/or from RTF to their document format using the interface ForeignToRtf/RtfToForeign. You can chain converters as you wish to convert from one format to another, e.g. to do a conversion DOCX -> RTF -> DOC.
You can get the
SDK from Microsoft
, which includes several samples on how to use existing converters. If I remember correctly there is already a command line wrapper sample included. Everything is C/C++ stuff.
You can find out which of the converter dlls are responsible for OpenXML conversion by looking at the following registry key:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Text Converters\Import\Word12
```
```
Let me know if you need further details on this.


Question:
Some of the platforms that I develop on, don't have profiling tools.  I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler.

The target language is C++.

I am interested in what you have personally used.

Answer:
In essence, if a profiling tool is not available, you emulate what a profiler would have done.  You insert counters into functions you think are interesting and count how many times, and potentially with what size/sort of arguments they're called.
If you have access to any timers on your platform, you may start/stop these at the beginning/end of said functions to get execution time information as well, if this is unclear from the code.  This is going to give you the biggest bang for your buck in complex code, as there will usually be too many functions to instrument them all.  Instead, you can obtain the time spent in certain sections of code by dedicating a timer to each one.
These two techniques in tandem can form an iterative approach, where you find the broad section of code that consumes the majority of your cycles using timers, then instrument individual functions at a finer granularity to hone in on the problem.


Question:
I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers.

The problem is that I get an exception every time. Apparently it can't find it (I am sure its spelled correctly). When looking through code examples, it doesn't specify the file's entire file path, only the name of the file itself. How would I go about doing that if its necessary?

Also, when reading the file, will the array automatically contain all the lines of the file, or will I have to make a loop which which copies every line to corresponding subscript i?

I've heard of BufferedReader class, what it's purpose, and how does it corelate to reading input?

Answer:
Here is some example code to help you get started:
```
```
package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}
```
```
And an example unit test:
```
```
package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}
```
```
Hope this helps.


Question: What's the best way to run scheduled tasks in a Rails environment? Script/runner? Rake? I would like to run the task every few minutes.

Answer:
Assuming your tasks don't take too long to complete, just create a new controller with an action for each task. Implement the logic of the task as controller code, Then set up a cronjob at the OS level that uses wget to invoke the URL of this controller and action at the appropriate time intervals. The advantages of this method are you:
Have full access to all your Rails objects just as in a normal controller.
Can develop and test just as you do normal actions.
Can also invoke your tasks adhoc from a simple web page.
Don't consume any more memory by firing up additional ruby/rails processes.


Question:
I've tried the following, but I was unsuccessful:

ALTER TABLE person ALTER COLUMN dob POSITION 37;

Answer:
"
Alter column position
" in the PostgreSQL Wiki says:
PostgreSQL currently defines column
  order based on the
```
attnum
```
column of
  the
```
pg_attribute
```
table. The only way
  to change column order is either by
  recreating the table, or by adding
  columns and rotating data until you
  reach the desired layout.
That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either.  Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.
One other idea occurs to me:  you can define a
```
VIEW
```
that specifies the order of columns how you like it, without changing the physical position of the column in the base table.


Question:
So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on.

I would like to use generics to create a general class for this scenario.  Something like:

 Adder<Double> adder = new Adder<Double>();
 adder.add(10.0d, 10.0d);   // = 20.0d

But, I cannot instantiate the generic type I pass in to my Adder class!  So -- what to do?

Answer:
Uh oh---generics are not C++ templates. Because of type erasure, the
```
Double
```
in your example won't even show through to the runtime system.
In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g.,
```
double add(double, double)
```
,
```
float add(float, fload)
```
,
```
BigDecimal add(BigDecimal, BigDecimal)
```
, etc.


Question: In Python I could've converted it to Unicode and do '(?u)^[\w ]+$' regex search, but PHP doesn't seem to understand international \w, or does it?

Answer:
Although I haven't tested myself, looking at
http://us3.php.net/manual/en/reference.pcre.pattern.syntax.php
suggests the following: '/^[\p{L} ]+$/u' would work - the \p{L} will match any unicode letter.  Additionally, you can apparently write this without the curly brackets - '/^[\pL ]+$/u'.


Question:
One of my columns is called from. I can't change the name because I didn't make it.
Am I allowed to do something like SELECT from FROM TableName or is there a special syntax to avoid the SQL Server being confused?

Answer:
Wrap the column name in brackets like so,
```
from
```
becomes [from].
```
```
select [from] from table;
```
```
It is also possible to use the following (useful when querying multiple tables):
```
```
select table.[from] from table;
```
```


Question:
I have been using git for several months in a project developed only by myself. I have a local repository and push it regularly to github for backup purposes.

I want to add another developer to this project, however I will have the responsibility of integrating the whole project.

What is the recommended workflow?

Do we need a private and a public repository for each developer?

If the github repository is the main one, does the other developer have to clone this repository or the repository in my computer?

Should he have the right to push in my repository or should I pull from his repository?

Answer:
Git is geared towards
pulling
, rather than pushing. Ideally, the other developer would clone from your
public
repo on Github; then, when he was done with his changes, you'd either pull from a repo that he makes available to you, or you'd integrate his changes with patches that he emails to you. Either way, you'd pull the changes into the
private
repo
on your computer
, fix any mistakes that result from the merge, and then push his changes to your public repo (the one on Github).
Of course, there's nothing wrong with giving him commit access to your Github repo, either.


Question:
Eclipse issues warnings when a serialVersionUID is missing.

The serializable class Foo does not declare a static final
  serialVersionUID field of type long

What is serialVersionUID and why is it important?  Please show an example where missing serialVersionUID will cause a problem.

Answer:
The docs for
```
java.io.Serializable
```
are probably about as good an explanation as you'll get:
The serialization runtime associates with each serializable class a version number, called a
```
serialVersionUID
```
, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different
```
serialVersionUID
```
than that of the corresponding sender's class, then deserialization will result in an
```
InvalidClassException
```
. A serializable class can declare its own
```
serialVersionUID
```
explicitly by declaring a field named
```
serialVersionUID
```
that must be static, final, and of type
```
long
```
:
```
```
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
```
```
If a serializable class does not explicitly declare a
```
serialVersionUID
```
, then the serialization runtime will calculate a default
```
serialVersionUID
```
value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is
strongly recommended
that all serializable classes explicitly declare
```
serialVersionUID
```
values, since the default
```
serialVersionUID
```
computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected
```
InvalidClassExceptions
```
during deserialization. Therefore, to guarantee a consistent
```
serialVersionUID
```
value across different java compiler implementations, a serializable class must declare an explicit
```
serialVersionUID
```
value. It is also strongly advised that explicit
```
serialVersionUID
```
declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class —
```
serialVersionUID
```
fields are not useful as inherited members.


Question:
I want to reverse engineer (import into diagram form) the database definition dump of a database I have, then since no foreign keys are defined in this particular database, I want to be able to manually create the table to table key mappings (using crow feet notation if possible).

I've taken a look at MySQL Workbench, and it gets me 85% of the way there.
The nice little relationship lines won't show up though, and the auto arrange is horrible. A quick search of google turns up several other options, so I can evaluate these on my own, but:

Can I get some feedback from you guys for which are your favorite tools to use for this scenario? Why do you like that(your) particular tool?

My intended purpose is to take a legacy database, and train jr. engineers on the organization of the DB. Visual aids are nifty. My fallback option is to recreate an ER diagram by hand. Not fun for 250+ tables.

Answer:
I've had some success using two commercial (but relatively cheap!) tools- but I still haven't found any really solid open source ones after months of looking.
MyEclipseIDE
is a subscription product, I think it's around $60 a year. It's a set of bundled plugins for Eclipse, one of them is an ERD analyzer that works OK. If you're programming in Java (or another eclipse-supported language), it may be worth it.
SQLMaestro for MySQL
: This one is a bit more expensive, with a $99 noncommercial / $179 single seat license. The ERD it generates is much better, and it provides other tools that make it easier to administer and maintain a more complex schema.
My understanding is that MySQL Workbench is still under active development, but they've been banging on it for a long time without really wrapping it up. Maybe now that Sun owns them, they'll get it together.


Question:
Using Java, how can I test that a URL is contactable, and returns a valid response?

http://stackoverflow.com/about

Answer:
The solution as a unit test:
```
```
public void testURL() throws Exception {
    String strUrl = "http://stackoverflow.com/about";

    try {
        URL url = new URL(strUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.connect();

        assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    } catch (IOException e) {
        System.err.println("Error creating HTTP connection");
        e.printStackTrace();
        throw e;
    }
}
```
```


Question:
I want to create an Ant buildfile, that includes some files as a sort of plugin.

So if I want to activate a feature in a project - say pmd-checking - I copy a pmd.xml in a directory and the build.xml get on the start the idea, that pmd.xml exists and imports it, so that new targets can be available to the build.

But the 'import' task can only be used as a top-level task, so I have no idea how to relize this functionality. Is this possible with Ant and if so, how can I do it?

EDIT: I would prefer a solution, that allows new targets to show up in the listing presented by ant -p.

Answer:
You can use the
ant
task and even parameterize the target name. Here's an example:
```
```
<ant antfile="plugins/pmd.xml" target="${pmd-target}"/>
```
```
If you want more flexibility, I recommend checking
gant
or
gradle
.


Question:
Does anyone know how to use the Raw Input facility on Windows from a WX Python application?

What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.

Answer:
Have you tried using ctypes?
```
```
>>> import ctypes
>>> ctypes.windll.user32.RegisterRawInputDevices
<_FuncPtr object at 0x01FCFDC8>
```
```
It would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython.


Question:
On my current project, I came across our master DB script. Taking a closer look at it, I noticed that all of our original primary keys have a data type of numeric(38,0)
We are currently running SQL Server 2005 as our primary DB platform.

For a little context, we support both Oracle and SQL Server as our back-end. In Oracle, our primary keys have a data type of number(38,0).

Does anybody know of possible side-effects and performance impact of such implementation? I have always advocated and implemented int or bigint as primary keys and would love to know if numeric(38,0) is a better alternative.

Answer:
Barring the storage considerations and some initial confusion from future DBAs, I don't see any reason why NUMERIC(38,0) would be a bad idea. You're allowing for up to 9.99 x 10^38 records in your table, which you will certainly never reach. My quick digging into this didn't turn up any glaring reason not to use it. I suspect that your only potential issue will be the storage space consumed by that, but seeing as how storage space is so cheap, that shouldn't be an issue.
I've seen this a fair number of times in Oracle databases since it's a pretty big default value that you don't need to think about when you're creating a table, similar to using INT or BIGINT by default in SQL Server.


Question:
Everyone managing open-source-software runs into the problem, that with the time the process of releasing a new version gets more and more work. You have to tag the release in your version-control, create the distributions (that should be easy with automated builds), upload them to your website and/or open-source-hoster. You have to announce the new release with nearly the same message on chosen web-forums, the news-system on sourceforge, mailinglists and your blog or website. And you have to update the entry of your software on freshmeat. Possible more tasks have to be done for the release.

Do you developed techniques to automate some of these tasks? Does software exist that supports you with this?

Answer:
Barring the storage considerations and some initial confusion from future DBAs, I don't see any reason why NUMERIC(38,0) would be a bad idea. You're allowing for up to 9.99 x 10^38 records in your table, which you will certainly never reach. My quick digging into this didn't turn up any glaring reason not to use it. I suspect that your only potential issue will be the storage space consumed by that, but seeing as how storage space is so cheap, that shouldn't be an issue.
I've seen this a fair number of times in Oracle databases since it's a pretty big default value that you don't need to think about when you're creating a table, similar to using INT or BIGINT by default in SQL Server.


Question:
As the title suggest...
How can I apply a scrum process to anything that doesn't work on new code and can be estimated to some degree?

How can I apply a scrum process to maintenance and emergency fixes (which can take from 5 minutes to 2 weeks to fix) type of environment when I still would like to plan to do things?

Basically, how do I overcome unplanned tasks and tasks that are very difficult to estimate with the scrum process? or am I simply applying the wrong process for this enviroment?

Answer:
Treat all fixes and improvements as individual stories and estimate accordingly. My personal view is that things that take less then 10-15 minutes to fix should just be done straight away. For those that take longer, they become part of the current 'fix & improvement' iteration cycle. As with estimating regular requirements, you take a best guess as a team. As more information comes to light, and the estimates are off adjust the iteration and upcoming sprints.
It's hard to apply a iteration cycle to fixes and improvements as more often then not, they prevent the system from working as they should and the 'business' puts pressure for them to go live asap. At this point it may work out better moving to a really short iteration cycle, like one or two weeks.


Question:
Is it possible to insert a row, but only if one of the values already in the table does not exist?

I'm creating a Tell A Friend with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.

I'm using PHP 4 and MySql 4.1.

Answer:
I'm not sure if I got it, but what about a
```
```
try {
  mysql_query($sql);
}
catch(Exception $e) {

}
```
```
combined with an unique field index in MySQL?
if it throws an exception then you know that you got a duplicated field.
Sorry if that don't answer your question..


Question:
Given an HTML link like

<a href="urltxt" class="someclass" close="true">texttxt</a>

how can I isolate the url and the text?

Updates

I'm using Beautiful Soup, and am unable to figure out how to do that.

I did

soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))

links = soup.findAll('a')

for link in links:
    print "link content:", link.content," and attr:",link.attrs

i get

*link content: None  and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root    /support.asp')]*  ...
...

Why am i missing the content?

edit: elaborated on 'stuck' as advised :)

Answer:
Use
Beautiful Soup
.  Doing it yourself is harder than it looks, you'll be better off using a tried and tested module.
EDIT:
I think you want:
```
```
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
```
```
By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly.
EDIT 2:
This should show you all the links in a page:
```
```
import urlparse, urllib
from BeautifulSoup import BeautifulSoup

url = "http://www.example.com/index.html"
source = urllib.urlopen(url).read()

soup = BeautifulSoup(source)

for item in soup.fetchall('a'):
    try:
        link =  urlparse.urlparse(item['href'].lower())
    except:
        # Not a valid link
        pass
    else:
        print link
```
```


Question: Does anyone know if NHibernate supports returning output parameters from stored procedures? I've had a search in the documentation but can't really find anything that confirms either way.

Answer:
I can't officially
confirm
for you, but as far as I know, not directly. Stored procedure use in NHibernate is very specific to doing standard CRUD.
If you want to grab output paramaters (that are't the standard row count output parameter for INSERT, UPDATE, and DELETE), you could fall back to a different (or the standard) database access tools that give you direct access to SQL and the result set. (Assuming you can get by with bypassing NHibernate's cache. You'll want to make sure you flush NHibernate before you run the query too, etc.)


Question: Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?

Answer:
Something like:
```
```
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;

public class Newest {
    public static void main(String[] args) {
        File dir = new File("C:\\your\\dir");
        File [] files  = dir.listFiles();
        Arrays.sort(files, new Comparator(){
            public int compare(Object o1, Object o2) {
                return compare( (File)o1, (File)o2);
            }
            private int compare( File f1, File f2){
                long result = f2.lastModified() - f1.lastModified();
                if( result > 0 ){
                    return 1;
                } else if( result < 0 ){
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println( Arrays.asList(files ));
    }
}
```
```


Question: The equals() method of the URL class in the Java class library makes a DNS request to get the IP for the hostname, to check the two IP's for equality. This happens even for URLs that are created from the same String. Is there a way to avoid this internet access?

Answer:
Don't use URL.equals. As the documentation says,
Note: The defined behavior for
```
equals
```
is known to be inconsistent with virtual hosting in HTTP.


Question: The renewal wizard doesn't seem to ask for a renewal period.

Answer: I think the Cerficate Supplier sets the renewal period.  So it depends on the type of Cert you buy (or the setup of your certification service).


Question:
I'd love to use WPF for a consumer app. However, some real world tests are not very encouraging. On several high-end computers I've tested, the .NET 3.5 installation has taken 15-20 mins to complete. I've seen reports online mentioning 50 mins.

When Vista marketshare is at 70%, this subject will be moot. Until then, reality is that the majority of consumers are on XP and will need a .NET 3.5 install. Adding 15-20 mins (at best) to the install of a consumer app is simply unacceptable.

1) What the frack is the .NET installer taking so long for?

2) Is there any way to optimize the .NET install?

Oh, and I know about the .NET Client Profile. Doesn't improve the situation much.

Answer:
Its big.
Using the MS supplied web install is the best cause it only installs what it needs (but thats still big)
Only option is to only detect its not there and warn the user and ask them to install it.  Only the first 3.5 app is affected.  All others will be speedy.
Apparently, all supported OSs will be rolled out to this over time using Windows Update and Services Packs and the like.


Question:
There seem to be a decent number of mod_rewrite threads floating around lately with a bit of confusion over how certain aspects of it work. As a result I've compiled a few notes on common functionality, and perhaps a few annoying nuances.

What other features / common issues have you run across using mod_rewrite?

Answer:
Where to place mod_rewrite rules
```
mod_rewrite
```
rules may be placed within the
```
httpd.conf
```
file, or within the
```
.htaccess
```
file. if you have access to
```
httpd.conf
```
, placing rules here will offer a performance benefit (as the rules are processed once, as opposed to each time the
```
.htaccess
```
file is called).
Logging mod_rewrite requests
Logging may be enabled from within the
```
httpd.conf
```
file (including
```
<Virtual Host>
```
):
```
```
# logs can't be enabled from .htaccess
# loglevel > 2 is really spammy!
RewriteLog /path/to/rewrite.log
RewriteLogLevel 2
```
```
Common use cases
To funnel all requests to a single point:
```
```
RewriteEngine on
# ignore existing files
RewriteCond %{REQUEST_FILENAME} !-f
# ignore existing directories
RewriteCond %{REQUEST_FILENAME} !-d
# map requests to index.php and append as a query string
RewriteRule ^(.*)$ index.php?query=$1
```
```
Since Apache 2.2.16 you can also use
```
FallbackResource
```
.
Handling 301/302 redirects:
```
```
RewriteEngine on
# 302 Temporary Redirect (302 is the default, but can be specified for clarity)
RewriteRule ^oldpage\.html$ /newpage.html [R=302]
# 301 Permanent Redirect
RewriteRule ^oldpage2\.html$ /newpage.html [R=301]
```
```
Note
: external redirects are implicitly 302 redirects:
```
```
# this rule:
RewriteRule ^somepage\.html$ http://google.com
# is equivalent to:
RewriteRule ^somepage\.html$ http://google.com [R]
# and:
RewriteRule ^somepage\.html$ http://google.com [R=302]
```
```
Forcing SSL
```
```
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
```
```
Common flags:
```
[R]
```
or
```
[redirect]
```
- force a redirect (defaults to a 302 temporary redirect)
```
[R=301]
```
or
```
[redirect=301]
```
- force a 301 permanent redirect
```
[L]
```
or
```
[last]
```
- stop rewriting process (see note below in common pitfalls)
```
[NC]
```
or
```
[nocase]
```
- specify that matching should be case insensitive
Using the long-form of flags is often more readable and will help others who come to read your code later.
You can separate multiple flags with a comma:
```
```
RewriteRule ^olddir(.*)$ /newdir$1 [L,NC]
```
```
Common pitfalls
Mixing
```
mod_alias
```
style redirects with
```
mod_rewrite
```
```
```
# Bad
Redirect 302 /somepage.html http://example.com/otherpage.html
RewriteEngine on
RewriteRule ^(.*)$ index.php?query=$1

# Good (use mod_rewrite for both)
RewriteEngine on
# 302 redirect and stop processing
RewriteRule ^somepage.html$ /otherpage.html [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# handle other redirects
RewriteRule ^(.*)$ index.php?query=$1
```
```
Note
: you can mix
```
mod_alias
```
with
```
mod_rewrite
```
, but it involves more work than just handling basic redirects as above.
Context affects syntax
Within
```
.htaccess
```
files, a leading slash is not used in the RewriteRule pattern:
```
```
# given: GET /directory/file.html

# .htaccess
# result: /newdirectory/file.html
RewriteRule ^directory(.*)$ /newdirectory$1

# .htaccess
# result: no match!
RewriteRule ^/directory(.*)$ /newdirectory$1

# httpd.conf
# result: /newdirectory/file.html
RewriteRule ^/directory(.*)$ /newdirectory$1

# Putting a "?" after the slash will allow it to work in both contexts:
RewriteRule ^/?directory(.*)$ /newdirectory$1
```
```
[L] is not last! (sometimes)
The
```
[L]
```
flag stops processing any further rewrite rules
for that pass through the rule set
. However, if the URL was modified in that pass and you're in the
```
.htaccess
```
context or the
```
<Directory>
```
section, then your modified request is going to be passed back through the URL parsing engine again. And on the next pass, it may match a different rule this time. If you don't understand this, it often looks like your
```
[L]
```
flag had no effect.
```
```
# processing does not stop here
RewriteRule ^dirA$ /dirB [L]
# /dirC will be the final result
RewriteRule ^dirB$ /dirC
```
```
Our rewrite log shows that the rules are run twice and the URL is updated twice:
```
```
rewrite 'dirA' -> '/dirB'
internal redirect with /dirB [INTERNAL REDIRECT]
rewrite 'dirB' -> '/dirC'
```
```
The best way around this is to use the
```
[END]
```
flag (
see Apache docs
) instead of the
```
[L]
```
flag, if you truly want to stop all further processing of rules (and subsequent passes). However, the
```
[END]
```
flag is only available for
Apache v2.3.9+
, so if you have v2.2 or lower, you're stuck with just the
```
[L]
```
flag.
For earlier versions, you must rely on
```
RewriteCond
```
statements to prevent matching of rules on subsequent passes of the URL parsing engine.
```
```
# Only process the following RewriteRule if on the first pass
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ...
```
```
Or you must ensure that your RewriteRule's are in a context (i.e.
```
httpd.conf
```
) that will not cause your request to be re-parsed.


Question:
I need to configure Tomcat memory settings as part of a larger installation, so manually configuring tomcat with the configuration app after the fact is out of the question. I thought I could just throw the JVM memory settings into the JAVA_OPTS environment variable, but I'm testing that with jconsole to see if it works and it... doesn't.

As per the comment below, CATALINA_OPTS doesn't work either. So far, the only way I can get it to work is via the Tomcat configuration GUI, and that's not an acceptable solution for my problem.

Answer:
Use the
```
CATALINA_OPTS
```
environment variable.


Question:
We have YouTube videos on a site and want to detect if it is likely that they will not be able to view them due to (mostly likely) company policy or otherwise.

We have two sites:

1) Flex / Flash
2) HTML

I think with Flex I can attempt to download http://youtube.com/crossdomain.xml and if it is valid XML assume the site is available

But with HTML I don't know how to do it. I can't even think of a 'nice hack'.

Answer:
This should work.  Basically, it loads a youtube.com javascript file, then checks if a function in that file exists.
```
```
<html>

<head>
    <script src="http://www.youtube.com/js/account.js"></script>
    <script>
        function has_you_tube()
        {
            if(typeof addVideosToQuicklist == 'function')
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    </script>

</head>
<body>
    <script>alert( "has_youtube: " + has_you_tube() ); </script>
</body>

</html>
```
```


Question: Is there a way to get the count of rows in all tables in a MySQL database without running a SELECT count() on each table?

Answer:
You can probably put something together with
Tables table
.  I've never done it, but it looks like it has a column for
TABLE_ROWS
and one for
TABLE NAME
.
To get rows per table, you can use a query like this:
```
```
SELECT table_name, table_rows
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '**YOUR SCHEMA**';
```
```


Question: If I have a key set of 1000, what is a suitable size for my Hash table, and how is that determined?

Answer:
There's some discussion of these factors in the documentation for
```
Hashtable
```


Question: How would I go about creating a Google map that allows the user to zoom beyond the default zoom levels for the map?  Would I have to create a new map type that has a greater maximum zoom?  Are there any tutorials out there that show how to do this?

Answer:
I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably).
```
EDIT:
```
What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine.
```
```
>>> import decimal
>>> print(decimal.Decimal("1.2") ** 2)
1.44
```
```
The
module documentation
explains the need for and usage of
```
decimal.Decimal
```
pretty clearly, you should check it out if you haven't yet.


Question:
My question is a lot like this one. However I'm on MySQL and I'm looking for the "lowest tech" solution that I can find.

The situation is that I have 2 databases that should have the same data in them but they are updated primarily when they are not able to contact each other. I suspect that there is some sort of clustering or master/slave thing that would be able to sync them just fine. However in my cases that is major overkill as this is just a scratch DB for my own use.

What is a good way to do this?

My current approach is to have a Federated table on one of them and, every so often, stuff the data over the wire to the other with an insert/select. It get a bit convoluted trying to deal with primary keys and what not. (insert ignore seems to not work correctly)

p.s. I can easily build a query that selects the rows to transfer.

Answer:
MySQL's inbuilt replication is very easy to set up and works well even when the DBs are disconnected most of the time. I'd say configuring this would be much simpler than any custom solution out there.
See
http://www.howtoforge.com/mysql_database_replication
for instructions, you should be up and running in 10-15 mins and you won't have to think about it again.
The only downside I can see is that it is asynchronous - ie. you must have one designated master that gets all the changes.


Question:
I've installed Subversion on Ubuntu following the guide Installation of Subversion on Ubuntu, with Apache, SSL, and BasicAuth..

It works, and I was able commit and create different repositories, but somehow, from time to time (sometimes minutes), when trying to do a commit, I'm forced to reset or recreate my user and password with the following command.

htpasswd2 -c -m /etc/apache2/dav_svn.passwd $AUTH_USER

Because SVN does not recognize my user/password anymore.

I'm using TortoiseSVN as SVN Client. I would like to know why this is happening. Maybe it's a configuration issue, or maybe TortoiseSVN is sending invalid credentials, causing a locked account. Since I'm far from being an SVN expert/administrator. Are there some pointers in order to attack the problem.

Answer:
I'm using TortoiseSVN as well, but on Windows users' passwords are managed by
Active Directory
on the network domain. So usernames are in the format
```
<domain>\<user>
```
. And from time to time (weeks), I need to reset the password; it seems like the password is changed. I just do not know why.


Question:
I am not a fan of using SQL*PLUS as an interface to Oracle.  I usually use yasql, but it hasn't been updated since 2005 and can do with some improvements.  A quick Google search shows yasql and SQLPal.  I am using linux, so SQLPal is not an option.

Are there any alternatives out there, or am I stuck with an interface that I do not like or one that is no longer maintained?

Answer:
TOAD is pretty expensive, but you can download a 90-day trial from the Quest site to see if it's got the feature set you want (don't be fooled by the "freeware" title - it's only free for 90 days, and then it expires, which definitely makes it shareware):
http://www.toadworld.com/Freeware/ToadforOracleFreeware/tabid/558/Default.aspx
Another options is a tool I've seen on CodeProject:
http://www.codeproject.com/KB/database/OQuery.aspx
It's in .NET, so you'd have to see if it compiled on Mono, but it might be worth a shot. I haven't used either tool (Toad or this one), since I'm a SQL Server guy, but I've heard good things about Toad.


Question:
I want to assert that a method is called exactly one time. I'm using RhinoMocks 3.5.

Here's what I thought would work:

[Test]
public void just_once()
{
    var key = "id_of_something";

    var source = MockRepository.GenerateStub<ISomeDataSource>();
    source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
        .Return(new Something())
        .Repeat.Once();

    var client = new Client(soure);

    // the first call I expect the client to use the source
    client.GetMeMyThing(key);

    // the second call the result should be cached
    // and source is not used
    client.GetMeMyThing(key);
}

I want this test to fail if the second invocation of GetMeMyThing() calls source.GetSomethingThatTakesALotOfResources().

Answer:
Here is what I just did (as recommended by
Ray Houston
). I would still appreciate a more elegant solution...
```
```
[Test]
public void just_once()
{
    var key = "id_of_something";

    var source = MockRepository.GenerateStub<ISomeDataSource>();

    // set a positive expectation
    source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
        .Return(new Something())
        .Repeat.Once();

    var client = new Client(soure);

    client.GetMeMyThing(key);

    // set a negative expectation
    source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
        .Return(new Something())
        .Repeat.Never();

    client.GetMeMyThing(key);
}
```
```


Question:
typedef struct {
        nat id;
        char *data;
        } element_struct;

typedef element_struct * element;

void push(element e, queue s) {
        nat lt = s->length;
        if (lt == max_length - 1) {
                printf("Error in push: Queue is full.\n");
                return;
        }
        else {
                s->contents[lt] = e;
                s->length = lt + 1;
        }
}
int main () {
         push(something_of_type_element, s);
}

How would i go about formatting "something_of_type_element"?

Thanks

Notes:
nat is the same as int

Answer:
How about:
```
```
element elem = malloc(sizeof(element_struct));
if (elem == NULL) {
    /* Handle error. */
}

elem->id = something;
elem->data = something_else;

push(elem, s);
```
```
Note that there's lots of memory management missing here...


Question:
Our Windows Forms application by default saves data files in a user's 'My Documents' folder (on XP) or 'Documents' folder (on Vista). We look up this location by calling:

Environment.GetFolderPath( Environment.SpecialFolder.Personal )

We know for sure this works great for users whose personal folder is on a local disk. What we're not sure about is domain users who have Folder Redirection in effect for their profile/personal data folders.

My question is: Does the above call properly resolve regardless of whether Folder Redirection is active?

I don't have the environment to test this out, and I haven't been able to find any definite confirmation one way or the other.

Answer:
I would expect that it does.  The documentation for both
```
Environment.GetFolderPath
```
and the underlying
```
SHGetSpecialFolderPath
```
don't give any indication that it would not resolve correctly nor can I find anything that you would use its place.


Question: How can I test Controller.ViewData.ModelState? I would prefer to do it without any mock framework.

Answer:
You don't have to use a Mock if you're using the Repository Pattern for your data, of course.
Some examples:
http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx
```
```
// Test for required "FirstName".
   controller.ViewData.ModelState.Clear();

   newCustomer = new Customer
   {
       FirstName = "",
       LastName = "Smith",
       Zip = "34275",
   };

   controller.Create(newCustomer);

   // Make sure that our validation found the error!
   Assert.IsTrue(controller.ViewData.ModelState.Count == 1,
                 "FirstName must be required.");
```
```


Question:
I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div.  All is well and it looks cool.

My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.

Is it possible to use a custom 'MVC View User Control' to suit this need?  Can I create an instance of a control, pass in the model data and render to html?  It would then be a simple matter of rendering and passing back to the calling browser.

Answer:
In rails this is called rendering a partial view, and you do it with
```
render :partial => 'yourfilename'
```
. I believe ASP.NET MVC has a similar
```
RenderPartial
```
method, but I can't find the official docs for MVC to confirm or deny such a thing.


Question:
How do I remove all attributes which are undefined or null in a JavaScript object?

(Question is similar to this one for Arrays)

Answer:
You are probably looking for the
```
delete
```
keyword.
```
```
var obj = { };
obj.theProperty = 1;
delete obj.theProperty;
```
```


Question: So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address http://www.stackoverflow.com/questions/ask. I would need the protocol and domain (e.g. http://www.stackoverflow.com) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?

Answer:
```
```
import re
url = "http://stackoverflow.com/questions/ask"
protocol, domain = re.match(r"(http://[^/]*)(.*)", url).groups()
```
```


Question:
example:

I want to see if array[5] holds a value or is empty.

Answer:
There is no such thing as an "empty" element in a Java array. If the array's length is at least six, then element 5 exists and it has a value. If you have not assigned anything else to that location, then it will have the value zero, just like an object's uninitialized field would have.
If it is an array of
```
Object
```
descendants, then you can check whether the element is equal to
```
null
```
.


Question: I just started getting into BizTalk at work and would love to keep using everything I've learned about DDD, TDD, etc. Is this even possible or am I always going to have to use the Visio like editors when creating things like pipelines and orchestrations?

Answer:
You can certainly apply a lot of the concepts of TDD and DDD to BizTalk development.
You can design and develop around the concept of domain objects (although in BizTalk and integration development I often find interface objects or contract first design to be a more useful way of thinking - what messages get passed around at my interfaces). And you can also follow the 'Build the simplest possible thing that will work' and 'only build things that make tests pass' philosophies of TDD.
However, your question sounds like you are asking more about the code-centric sides of these design and development approaches.
Am I right that you would like to be able to follow the test driven development approach of first writing a unti test that exercises a requirement and fails, then writing a method that fulfils the requirement and causes the test to pass - all within a traditional programing language like C#?
For that, unfortunately, the answer is no. The majority of BizTalk artifacts (pipelines, maps, orchestrations...) can only really be built using the Visual Studio BizTalk plugins. There are ways of viewing the underlying c# code, but one would never want to try and directly develop this code.
There are two tools
BizUnit
and
BizUnit Extensions
that give some ability to control the execution of BizTalk applications and test them but this really only gets you to the point of performing more controled and more test driven integration tests.
The shapes that you drag onto the Orchestration design surface will largely just do their thing as one opaque unit of execution. And Orchestrations, pipelines, maps etc... all these things are largely intended to be executed (and tested) within an entire BizTalk solution.
Good design practices (taking pointers from approaches like TDD) will lead to breaking BizTalk solutions into smaller, more modular and testable chunks, and are there are ways of testing things like pipelines in isolation.
But the detailed specifics of TDD and DDD in code sadly don't translate.
For some related discussion that may be useful see this question:
Mocking WebService consumed by a Biztalk Request-Response port


Question:
Previously it was .net 2.0 which is the big change in .net developement. many developers are working mostly on this. Presently microsoft has introduced .net 3.0 and yet its next version .net 4.0. So the next version is going to be major change in .net development.

I have listed some features of this...

Workflow foundation
WPF
WCF
Windows cardspace
Agile methodalogy implementation.
Silverlight features enhancement.

In the new generation framework what are the features that you like and why it attracts you.

Answer:
If you're asking which new features will the upcoming .NET 4.0 Framework present, I've heard a lot about Parallel Computing, specifically about a Task Parallel Library built in the core of the Framework, also
PLinq
or Parallel Linq, focusing on LINQ-to-Objects and LINQ-to-XML .
Check te
Microsoft PDC Website
and you'll find more interesting info.


Question:
I'm writing an app for Blackberry that was originally implemented in standard J2ME.  The network connection was done using Connector.open("socket://...:80/...") instead of http://

Now, I've implemented the connection using both methods, and it seems like some times, the socket method is more responsive, and some times it doesn't work at all.  Is there a significant difference between the two?  Mostly what I'm trying to achieve is responsiveness from the connection to get a smooth progress bar.

Answer:
Since both operate over a network I don't think you can guarantee a smooth progress bar. You might have more chance of that if you remind the person to stay in one place so you have a chance of a consistent connection ;)
There is less overhead with a socket connection than an HTTP one. In fact, HTTP connections run over the socket connection. You can take advantage of the reduced overhead of the socket connection to appear more responsive, but you will likely have more work to do than you would with HTTP. The API is more low-level so coding is more complex.


Question:
is it possible to throw a custom error message to a ThrowActivity, in windows workflow foundation?

eg. Imagine i want to throw this exception, in my WF :-

CutomException("This is my custom error message", myNumber, myObect);

cheers :)

Answer:
Maybe I do not understand your question well, but you can set the specific exception with the
```
Fault
```
property of
```
ThrowActivity
```
in any place before the activity execution, e.g.:
```
```
throwActivity1.Fault = new CustomException("This is my custom error message", myNumber, myObect);
```
```


Question:
If I am evaluating two variables and not two method calls does it matter weather I use "&&" or "&"

//some logic that sets bool values

boolean X = true;
boolean Y = true;

if (X & Y){
   // perform some operation
}

if (X && Y){
   // perform some operation
}

Further a book I am using for C# 3.0 / .NET 3.5 only makes reference to the && operator, is the & operator going away?

Answer:
Always use && if you are performing a true/false logic test. A single & performs a bit-wise 'and'.  It make work like a logic test in some cases but it is not guaranteed to work for all logic cases.  The most common use of a single & is when applying a bit-mask.
Examples (&&):
```
```
true && true == true
```
```
Example (&):
```
```
00101001 & 00100001 = 00100001
```
```


Question:
I am making a small game number game in Java (Nim) in OS X and was thinking about trying to make the GUI interface of the game using something other than Swing. I looked at SWT, but I read somewhere that SWT has some problems with OS X. I also looked at GTK+ bindings for Java, but I am not sure if that's a good choice either. Do you guys have any suggestions for a good Java GUI Framework that would look good and be compatible with OS X ?

Thanks

Answer:
It depends, with eclipse 3.4, SWT 3.4 is quite supported with
MacOs
.
Now, SWT is OS specific, and you may not have the same flexibility than Swing, so you need to have good reason for looking for an alternative to Swing, especially when you consider there are good
LAFs (look and feel)
for java.


Question:
What is the best way to password protect quicktime streaming videos using php/.htaccess. They are being streamed using rtsp, but I can use other formats if necessary.

I know how to do authentication with php, but I'm not sure how to setup authentication so that will protect the streaming files urls so that a user can't just copy the url and share it.

Or am I overthinking this and I can just use a normal authentication scheme and place the files in a protected directory?

Answer:
First off, it is very easy to spoof a referer. This information is stored in the user's browser, so a user can simply telnet into your server and provide his own referer which matches your domain.
A couple things you could try:
First, more secure, but still spoofable. mod_rewrite provides the ability to check cookies. What you could do is set a cookie when the user visits your website that contains some obscure data. Then, you could modify your RerwriteCond to something like this:
```
```
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_COOKIE} obscurename=obscurevalue [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(asx¦ASX)$ http://www.yourdomain.com/images/leech.gif [R,L]
```
```
Another, better technique would involve working with PHP and mime-types. I'm not sure to what extent this would support streaming content, but I assume it'll work. What you can do is have all your video links point to a .php file (the query string will determine which video has been selected). Then, when a user tries to visit this link, you do something like so:
```
```
<?php
    // You could also check some sort of session variable
    // that is set when the user visits another part of your
    // site
    if(!isLoggedIn()){
       header("Location: errorPage.htm");
       exit;
    }else{
       // Get the name of the file specified
       $file = get_file_name($_GET['fileID']);

       // Specify the proper mime-type for the data you're sending
       // (this may have to change, depending on your situation)
       header("Content-type: video/vnd.rn-realvideo");

       // Read the file and output it to the browser
       readfile($file);
    }
?>
```
```
From what I read, most servers know which mime-types are streaming mime-types, so the browser should be able to figure out how to handle the streaming file properly.


Question:
Given two 3D vectors A and B, I need to derive a rotation matrix which rotates from A to B.

This is what I came up with:

Derive cosine from acos(A . B)

Derive sine from asin(|A x B| / (|A| * |B|))

Use A x B as axis of rotation

Use matrix given near the bottom of this page (axis angle)

This works fine except for rotations of 0° (which I ignore) and 180° (which I treat as a special case). Is there a more graceful way to do this using the Direct3D library? I am looking for a Direct3D specific answer.

Edit: Removed acos and asin (see Hugh Allen's post)

Answer:
No, you're pretty much doing it the best way possible.  I don't think there is a built-in DirectX function that does what you want.  For step 4, you can use
```
D3DXMatrixRotationAxis()
```
.  Just be careful about the edge cases, such as when |A| or |B| is zero, or when the angle is 0° or 180°.


Question:
What's the best way (if any) to make an image appear "grayed out" with CSS (i.e., without loading a separate, grayed out version of the image)?

My context is that I have rows in a table that all have buttons in the right most cell and some rows need to look lighter than others. So I can make the font lighter easily of course but I'd also like to make the images lighter without having to manage two versions of each image.

Answer:
Does it have to be gray? You could just set the opacity of the image lower (to dull it). Alternatively, you could create a
```
<div>
```
overlay and set that to be gray (change the alpha to get the effect).
html:
```
```

```
```
css:
```
```
#myImage {
    opacity: 0.4;
    filter: alpha(opacity=40); /* msie */
}

/* or */

#wrapper {
    opacity: 0.4;
    filter: alpha(opacity=40); /* msie */
    background-color: #000;
}
```
```


Question: How can I make cookies in my Flash application using ActionScript 2.0?

Answer:
You would need to use JavaScript to work with cookies. You can do so from ActionScript using the
ExternalInterface API
.


Question:
I have a suspicion that I'm using the finally block incorrectly, and that I don't understand the fundamentals of its purpose...

 function myFunc() {
      try {
           if (true) {
                throw "An error";
           }
      } catch (e) {
           alert (e);
           return false;
      } finally {
           return true;
      }
 }

This function will run the catch block, alert "An error", but then return true. Why doesn't it return false?

Answer:
The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.
more
The
```
finally
```
block will always run, try returning
```
true
```
after your
```
try
```
block
```
```
function myFunc() {
     try {
         if (true) {
               throw "An error";
          }
          return true;
     } catch (e) {
          alert (e);
          return false;
     } finally {
          //do cleanup, etc here
     }
 }
```
```


Question:
Our team is experienced in web development (tomcat/Oracle) but not with AJAX on our existing projects.  This is new technology for us, so I want to introduce this carefully and correctly.

What should I look at in terms of frameworks or best practice or common pitfalls?

Answer:
read this:
progressive enhancement
and use a library such as
jQuery
,
mootools
, or
YUI
it'll save you many headaches with cross-browser implementation.
this
will show you why you want to use a library.


Question:
I would like to make my application somewhat REST compliant.  I am using Rails on the backend and GWT on the frontend.  I would like to do updates and deletes.  I realize I can do something like mydomain.com/:id/delete (GET) and accomplish the same thing.  However, as I stated previously, I would like to have a REST compliant backend.  Thus, I want to do mydomain.com/:id (DELETE) and have it implicitly call my delete method.

Now, it's my understanding that if a browser (my browser is GWT RequestBuilder) doesn't support DELETE/GET, Rails somehow accomplishes this task with a POST and some other url parameter.  So, how can I accomplish this with a GWT RequestBuilder?

Answer:
Rails does this with hidden attributes. The easiest way to figure this out would be to create a new rails application, generate a scaffold and have a look at the HTML in a browser.
Try this:
```
```
rails jp
cd jp
./script/generate scaffold RequestBuilder name:string
rake db:migrate
./script/server
```
```
Then navigate to
http://localhost:3000/request_builders
, click on New and have a look at the HTML. You'll see something like:
```
```
<form action="/request_builders" class="new_request_builder"
  id="new_request_builder" method="post">

    <input name="authenticity_token" type="hidden" value="e76..." />

```
```
This is a creation, method is POST. Enter a name, save then Edit:
```
```
<form action="/request_builders/1" class="edit_request_builder"
  id="edit_request_builder_1" method="post">

    <input name="_method" type="hidden" value="put" />
    <input name="authenticity_token" type="hidden" value="e76..." />

```
```
Of course the form is sent with POST, but Rails hads a hidden field to simulate a PUT request. Same for deletion, but the scaffold will do it with a bit of Javascript:
```
```
var m = document.createElement('input');
m.setAttribute('type', 'hidden');
m.setAttribute('name', '_method');
m.setAttribute('value', 'delete');
```
```
To have this work with another front-end, you'll have to both:
Use the same style URL such as /request_builders/1 (RESTful URLs)
Include the hidden fields (Rails trick)


Question:
I want to build two-dimentional array of strings where length of one dimention is 2. Similar to this

string[,] array = new string[,]
{
    {"a", "b"},
    {"c", "d"},
    {"e", "f"},
    {"g", "h"}
}

Doing

List<string[]> list = new List<string[]>();

list.Add(new string[2] {"a", "b"});
list.Add(new string[2] {"c", "d"});
list.Add(new string[2] {"e", "f"});
list.Add(new string[2] {"g", "h"});

list.ToArray();

gives me

string[][]

but not

string[,]

array.

Just curious, is there some trick to build dynamically

string[,]

array somehow?

Answer:
This isn't possible with a
```
List<string[]>
```
, as the type
```
string[,]
```
is different from
```
string[]
```
.


Question:
Is it possible to build a .dmg file (for distributing apps) from a non-Mac platform?
And if yes, how?

Answer:
If you're distributing Mac apps, then surely you have a Mac to write and test them. Why not simply use that same Mac to create the disk image?
[Edit] Alternatively, if you're distributing a portable app, for example a Java .jar file, why bother with a disk image? Macs understand .zip and .tar.gz archives just fine.
I guess what I'm getting at is, I don't understand how one might need a DMG disk image, but not have a Mac with which to create it.


Question:
I have a page P1 loading from site S1 which contains an iframe. That iframe loads a page P2 from another site S2. At some point P2 would like to close the browser window, which contains P1 loaded from S1. Of course, since P2 is loaded from another site, it can't just do parent.close().

I have full control over P1 and P2, so I can add JavaScript code to both P1 and P2 as needed.
Suggestions on how to resolve this?

Answer:
It's impossible, I am afraid. JavaScript from an iframe that is loaded to a different site then the one it is being rendered on is strictly prohibited due to security issues.
However, if the iframe is pointed to the same site you can get to it like:
```
```
<iframe name = "frame1" src = "http://yoursite">
</iframe>

<script type = "text/javascript">
    alert(window.frames["frame1"].document);
</script>
```
```


Question:
Inspired by this question and answer, how do I create a generic permutations algorithm in F#?  Google doesn't give any useful answers to this.

EDIT: I provide my best answer below, but I suspect that Tomas's is better (certainly shorter!)

Answer:
My latest best answer
```
```
//mini-extension to List for removing 1 element from a list
module List =
    let remove n lst = List.filter (fun x -> x <> n) lst

//Node type declared outside permutations function allows us to define a pruning filter
type Node<'a> =
    | Branch of ('a * Node<'a> seq)
    | Leaf of 'a

let permutations treefilter lst =
    //Builds a tree representing all possible permutations
    let rec nodeBuilder lst x = //x is the next element to use
        match lst with  //lst is all the remaining elements to be permuted
        | [x] -> seq { yield Leaf(x) }  //only x left in list -> we are at a leaf
        | h ->   //anything else left -> we are at a branch, recurse
            let ilst = List.remove x lst   //get new list without i, use this to build subnodes of branch
            seq { yield Branch(x, Seq.map_concat (nodeBuilder ilst) ilst) }

    //converts a tree to a list for each leafpath
    let rec pathBuilder pth n = // pth is the accumulated path, n is the current node
        match n with
        | Leaf(i) -> seq { yield List.rev (i :: pth) } //path list is constructed from root to leaf, so have to reverse it
        | Branch(i, nodes) -> Seq.map_concat (pathBuilder (i :: pth)) nodes

    let nodes =
        lst                                     //using input list
        |> Seq.map_concat (nodeBuilder lst)     //build permutations tree
        |> Seq.choose treefilter                //prune tree if necessary
        |> Seq.map_concat (pathBuilder [])      //convert to seq of path lists

    nodes
```
```
The permutations function works by constructing an n-ary tree representing all possible permutations of the list of 'things' passed in, then traversing the tree to construct a list of lists. Using 'Seq' dramatically improves performance as it makes everything lazy.
The second parameter of the permutations function allows the caller to define a filter for 'pruning' the tree before generating the paths (see my example below, where I don't want any leading zeros).
Some example usage: Node<'a> is generic, so we can do permutations of 'anything':
```
```
let myfilter n = Some(n)  //i.e., don't filter
permutations myfilter ['A';'B';'C';'D']

//in this case, I want to 'prune' leading zeros from my list before generating paths
let noLeadingZero n =
    match n with
    | Branch(0, _) -> None
    | n -> Some(n)

//Curry myself an int-list permutations function with no leading zeros
let noLZperm = permutations noLeadingZero
noLZperm [0..9]
```
```
(Special thanks to
Tomas Petricek
, any comments welcome)


Question:
In relation to another question, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py".

What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code.

I want the program to be cross-platform, but I expect I may have to use os.name or something to determine which path code block to use.

Answer:
If your file is always in the same directory as your program then:
```
```
def _isInProductionMode():
    """ returns True when running the exe,
        False when running from a script, ie development mode.
    """
    return (hasattr(sys, "frozen") or # new py2exe
           hasattr(sys, "importers") # old py2exe
           or imp.is_frozen("__main__")) #tools/freeze

def _getAppDir():
    """ returns the directory name of the script or the directory
        name of the exe
    """
    if _isInProductionMode():
        return os.path.dirname(sys.executable)
    return os.path.dirname(__file__)
```
```
should work. Also, I've used py2exe for my own application, and haven't tested it with other exe conversion apps.