q:
I've be working with a Java application run through the command-line. It deals with XML files, specially the dblp.xml database which has more than 400MB.

I was using JVM 5 and my app needed sort of 600-700MB of memory to processe the dblp.xml. After updating to JVM 6, it starting needing more than 1gb of memory (something I don't have), although it runs a bit faster.

I'm pretty sure of the memory consumption difference, because I've already tested both again and again in this same computer. Resulting in the same difference of memory consumption.

I didn't set any special parameters, just -Xmx800M or -Xmx1000M.
Running with Ubuntu Hardy Heron on a dual core 1.7ghz, with 1,5gb of memory
Using only the top/ps commands to measure

Any one have an idea why this occurs? I really wanted to use JVM 6, because in my production server it is the JVM in use, and I'm not quite able to change easily.

Thanks

[A]
My advice would be to use a tool like
JProfiler
to try to get a handle on exactly where your memory consumption increased.  If you can't spend on JProfiler, check out this list of
open source java profiling tools
.
Guessing at the cause of performance problems is a bad idea, because you are almost always wrong in your guess, and you waste time optimizing the wrong piece of the system.  Once you have some objective data, you may be able to come up with an optimization reducing your memory consumption.
If it is true that the newer JVM is trading memory for speed (by caching) then there is likely a jvm arg you can use to stop this behavior.  Best bet is to check out the release notes for Java 6 and see if any such feature is mentioned.


q: What does RESTful Authentication mean and how does it work?  I can't find a good overview on Google.  My only understanding is that you pass the session key (remeberal) in the URL, but this could be horribly wrong.

[A]
It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST.  Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.
The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in
RFC 2617
.

s: huggingface

c: devops

d: intermediate


q:
I am working on setting up a Drupal based website and wanted to replace the site title in the header with an image file.  I came across this article: "Revised Image Replacement" summarizing several techniques for doing just that.

I was wondering what the current best practice is, in terms of SEO and browser compatibility?

[A]
```
```
function myget($string)
{
  return mysql_real_escape_string(stripslashes($_GET[$string]));
}
```
```
This is the solution in PHP.


q:
Does anyone know of a freeware shipping calculator for PHP?  I do not want anything too fancy, and it can be compatible with any of the major US domestic shipping services.

If anyone knows of one that is a plugin for CodeIgniter that would be nice.

Travis

[A]
Usually services like this are based on web services offered from the various couriers.  You would send the weight and dimensions of the box you want to ship to their web service, and they would return a corresponding shipping price. Each couriers API would be different.  I'm not sure if there are any libraries that aggregate all these services together, but I've never seen one.  Since prices can change at any time, you pretty much have to use some kind of web service to access this information.   That is, unless you are Amazon sized and have preexisting arrangements for pricing rates on shipping with the various couriers.  Just from a quick lookup, here is some of the services that
FedEx
offers.


q:
I'm trying to make a TCP Client program in C where the client will start up, connect to a server. Then it will send a little information and then just listen to what it receives and react accordingly.

The part that I'm having trouble with is the continuous listening. Here is what I have

...

while (1) {
   numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0);
   buf[numbytes] = '\0';
   printf("Received: %s\n", buf);
   // more code to react goes here
}

...

Upon connecting to the server, after sending two lines of data, the server should receive a good bit of information, but when I run this, it prints:

Received:

And then continues to just sit there until i force it to close.

** EDIT ** when i do what Jonathan told me to do, I get the following:

Count: -1, Error: 111, Received:

So that means its erroring, but what do i do about it?

[A]
Print out the number of bytes received - it is likely to be zero, but confirm that.
It would be worth checking that you aren't getting an error - and therefore underflowing your buffer.
[
Note: from here onwards is the work of Pax -
thank you
, and I've converted it to Community Wiki so I don't get rep points undeservedly.
]
The following code will do this.  Try it and report back on the results, please.
```
```
while (1) {
    numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0);
    buf[numbytes] = '\0';
    printf("Count: %d, Error: %d, Received: %s\n", numbytes, errno, buf);
    // more code to react goes here
}
```
```
After question edit:
Error number 111 is ECONNREFUSED - this is not a usual error code for recv(), but is more suited to the open-type call (open(), connect(), etc).
In any case, ECONNREFUSED is a problem at the server end, not the client - the server has purposefully refused to accept your incoming connection, so you will need to investigate that end of the link.
In order to test this, change your code so that it's connecting to www.microsoft.com on port 80, then send a couple of lines of any old rubbish.  You should get back an error from their web server indicating a malformed HTTP request. This will prove there's no problem on your client end.
This is what I get back when I
```
telnet www.microsoft.com 80
```
and type in
```
hello
```
followed by
```
ENTER
```
twice:
```
```
HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 27 Nov 2008 01:45:09 GMT
Connection: close
Content-Length: 326

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Verb

HTTP Error 400. The request verb is invalid.

```
```
You should see something similar.


q:
I have an app that I'm writing a little wizard for.  It automated a small part of the app by moving the mouse to appropriate buttons, menus and clicking them so the user can watch.

So far it moves the mouse to a tree item and sends a right-click.  That pops up a menu via TrackPopupMenu.  Next I move the mouse to the appropriate item on the popup menu.  What I can't figure out is how to select the menu item.

I've tried sending left-clicks to the menu's owner window, tried sending WM_COMMAND to the menu's owner, etc.  Nothing works.

I suppose the menu is a window in and of itself, but I don't know how to get the HWND for it from the HMENU that I have.

Any thoughts on how to PostMessage a click to the popup menu?

PS I'm using a separate thread to drive the mouse and post messages, so no problems with TrackPopupMenu being synchronous.

[A]
I expect you could generate the necessary click messages by calling
```
SendInput
```
. Move the mouse over where the menu is, and then click.
You might want to take a look at the
WH_JOURNALPLAYBACK
hook. I think it's designed to do exactly what you seem to be trying to do manually.


q:
Given two colors and n steps, how can one calculate n colors including the two given colors that create a fade effect?

If possible pseudo-code is preferred but this will probably be implemented in Java.

Thanks!

[A]
Divide each colour into its RGB components and then calculate the individual steps required.
```
```
oldRed = 120;
newRed = 200;
steps = 10;
redStepAmount = (newRed - oldRed) / steps;

currentRed = oldRed;
for (i = 0; i < steps; i++) {
   currentRed += redStepAmount;
}
```
```
Obviously extend that for green and blue.


q:
Hi if I am creating something on the stack using new I declare it like:

object *myObject = new object(contr, params);

Is there a way to declare this such as:

object *myObject;
myObject = new object(constr, params);

Is this correct?

[A]
Yes, that is correct.  But new does not create things on the stack, it creates them on the heap.
To create object on the stack you would do:
```
```
object myObject(constr, params);
```
```
There is no other way to create an object on the stack and once it is created on the stack you can't "recreate" it with the same name later in the same function.


q: i have a windows client and i want to upgrade subversion from 1.5.3 to 1.5.4.  are there installation steps. . do i just copy the zip and extract and override the existing directoies ..  i can't find any clear upgrade instructions . .

[A]
Which windows client are you using?
TortoiseSVN's upgrade path for me so far has been pretty flawless. You just download the latest installer, run it, and get back to work.
The only time I had an issue was upgrading from 1.4x to 1.5x, you
do
have to restart the computer after this installation, otherwise you'll start getting all sorts of funky errors because the Tortoise SVN in memory cache will be out of date and incompatible.
After a restart everything was fine. The repositories always get auto-upgraded, and unless there's something in the changelog saying otherwise, you can upgrade worry free.
Upgrading the client side of things should be a low concern anyways, just make a backup of your working copy, perform the upgrade, and if you do have problems, checkout the project into a new folder, move any changed files in, and your all set.
Upgrading the repository could have more ramifications, but again, I've yet to have a problem on that side of the system.
Having backups is a good fail safe.


q:
void (int a[]) {
    a[5] = 3; // this is wrong?
    }

Can I do this so that the array that is passed in is modified?

Sorry for deleting, a bit new here...

I have another question which might answer my question:

If I have

void Test(int a) {
}

void Best(int &a) {
}

are these two statements equivalent?

Test(a);
Best(&a);

[A]
If you get the variable not by reference and not by pointer, it means that the function is essentially isolated, getting an ad-hoc copy of a. No matter what you do (without trying to hack the stack or things like that) you wouldn't have access to that value in the calling context.
If you know something about the calling context, you may be able to do things based on some anticipation of stack contents, but it's generally a bad idea.
If your method takes a[] which is essentially a*, then yes, you can alter the contents of the cell that a points to, but you won't be able to alter a (the pointer) itself to point at something else.


q:
Duplicate:

What is aspect-oriented programming?

Every time I here a podcast or read a blog entry about it, even here, they make it sound like string theory or something.  Is the best way to describe it OOP with Dependency Injection on steroids?

Every time someone tries to explain it, it’s like, Aspects, [Adults from Peanuts Cartoon sound],  Orthogonal, [more noise], cross cutting concerns, etc.  Seriously, can anyone describe it in layman’s terms.

[A]
Laymans terms so let me give you an example. Let's say you have a web application, and you need to add error logging / auditing. One implementation would be to go into every public method and add your try catch blocks etc...
Well Aspect oriented says hogwash with that, let me inject my method around your method so for example instead of calling YourClass.UpdateModel(), the system might call,
LoggingHandler.CallMethod() this method might then redirect the call to UpdateModel but wraps it in a try catch block to handle logging errors.
Now the trick is that this redirection happens automagically, through configuration or by applying attributes to methods.
This works for as you said cross cutting things which are very common programing elements that exist in every domain, such as: Logging, Auditing, Transaction Mgmt, Authorization.
The idea behind it is to remove all this common plumbing code out of your business / app tier so you can focus on solving the problem not worrying about logging this method call or that method call.


q:
I was using GetWindowLong like this:

[DllImport("user32.dll")]
private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);

But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible.
http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx

The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):

LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex);

I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:

[DllImport("user32.dll")]
private static extern long GetWindowLong(IntPtr hWnd, int nIndex);

What is right, and how can I ensure proper 64bit compatibility?

[A]
You should define GetWindowLongPtr using an IntPtr.  In C/C++ a LONG_PTR is 32-bits on a 32-bit system and 64-bits on a 64-bit system (see
here
).  IntPtr in C# is designed to work the same way (see
here
).
So what you want is:
```
```
[DllImport("user32.dll")]
private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex);
```
```


q:
This is probably pretty basic... but I don't seem to get it:

How does

(2 & 1) = 0
(3 & 1) = 1
(4 & 1) = 0

etc..

This pattern above seems to help find even numbers

or

(0 | 1) = 1
(1 | 1) = 1
(2 | 1) = 3
(3 | 1) = 4
(4 | 1) = 5
(5 | 1) = 5

I know how boolean algebra works between bits. But I don't understand how Boolean algebra works with integers (in C# at the least).

thanks in advance.

[A]
It works the same way in C# as it does in binary.
```
2 | 1 = 3
```
and
```
4 | 1 = 5
```
.
To understand this, you need to think about the binary representation of 1,2,3,4,and 5:
```
010 | 001 = 011
```
and
```
100 | 001 = 101
```
.
Similarly:
```
010 & 001 = 000
```
and
```
011 & 001 = 001
```


q:
I'm working on a .Net application which uses Asp.net 3.5 and Lucene.Net I am showing search results given by Lucene.Net in an asp.net datagrid. I need to implement Paging (10 records on each page) for this aspx page.

How do I get this done using Lucene.Net?

[A]
Here is a way to build a simple list matching a specific page with Lucene.Net. This is not ASP.Net specific.
```
```
int first = 0, last = 9; // TODO: Set first and last to correct values according to page number and size
Searcher searcher = new IndexSearcher(YourIndexFolder);
Query query = BuildQuery(); // TODO: Implement BuildQuery
Hits hits = searcher.Search(query);
List<Document> results = new List<Document>();
for (int i = first; i <= last && i < hits.Length(); i++)
    results.Add(hits.Doc(i));

// results now contains a page of documents matching the query
```
```
Basically the Hits collection is very lightweight. The cost of getting this list is minimal. You just instantiate the needed Documents by calling hits.Doc(i) to build your page.


q: Has anyone ever used the Bridge pattern in a real world application? If so, how did you use it? Is it me, or is it just the Adapter pattern with a little dependency injection thrown into the mix? Does it really deserve its own pattern?

[A]
A classic example of the Bridge pattern is used in the definition of shapes in an UI environment (see the
Bridge pattern Wikipedia entry
).  The Bridge pattern is a
composite
of the
Template
and
Strategy
patterns.
It is a common view some aspects of the Adapter pattern in the Bridge pattern.  However, to quote from
this article
:
At first sight, the Bridge pattern looks a lot like the Adapter pattern in that a class is used to convert one kind of interface to another. However, the intent of the Adapter pattern is to make one or more classes' interfaces look the same as that of a particular class. The Bridge pattern is designed to separate a class's interface from its implementation so you can vary or replace the implementation without changing the client code.


q:
How can I escape a bracket in a full-text SQL Server contains() query? I've tried all the following, none of which work:

CONTAINS(crev.RawText, 'arg[0]')
CONTAINS(crev.RawText, 'arg[[0]]')
CONTAINS(crev.RawText, 'arg\[0\]')

Using double quotes does work, but it forces the entire search to be a phrase, which is a showstopper for multiple word queries.

CONTAINS(crev.RawText, '"arg[0]"')

All I really want to do is escape the bracket, but I can't seem to do that..

[A]
Not in the spirit of fulltext indexing apparently.
word
Is a string of characters without
  spaces or punctuation.
phrase
Is one or more words with spaces
  between each word.
And
Punctuation is ignored. Therefore,
  CONTAINS(testing, "computer failure")
  matches a row with the value, "Where
  is my computer? Failure to find it
  would be expensive."
I'm not sure what your options are.
Obviously
```
LIKE
```
works fine:
```
```
SELECT *
FROM dbo.stackoverflow_319730
WHERE txtcol LIKE 'arg[ [ ]0]'
```
```
But
```
```
SELECT *
FROM dbo.stackoverflow_319730
WHERE CONTAINS(txtcol, '"arg[0]"')
```
```
Even matches a column with
```
'arg[1]'
```
in it, for instance:
```
```
CREATE TABLE [dbo].[stackoverflow_319730](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [txtcol] [text] NOT NULL,
 CONSTRAINT [PK_stackoverflow_319730] PRIMARY KEY CLUSTERED
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

INSERT INTO [dbo].[stackoverflow_319730] (txtcol) VALUES ('arg[0]')
INSERT INTO [dbo].[stackoverflow_319730] (txtcol) VALUES ('arg[1]')
INSERT INTO [dbo].[stackoverflow_319730] (txtcol) VALUES ('some other text')
INSERT INTO [dbo].[stackoverflow_319730] (txtcol) VALUES ('arg[0], arg[1]')

EXEC sp_fulltext_catalog   'FTCatalog','create'
EXEC sp_fulltext_table     'stackoverflow_319730', 'create', 'FTCatalog', 'pk_stackoverflow_319730'
EXEC sp_fulltext_column    'stackoverflow_319730', 'txtcol', 'add'
EXEC sp_fulltext_table     'stackoverflow_319730','activate'
EXEC sp_fulltext_catalog   'FTCatalog', 'start_full'

SELECT *
FROM dbo.stackoverflow_319730
WHERE txtcol LIKE 'arg[ [ ]0]'

SELECT *
FROM dbo.stackoverflow_319730
WHERE CONTAINS(txtcol, '"arg[0]"')
```
```
With results which hint at the problem with punctuation:
```
```
id          txtcol
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1           arg[0]

(1 row(s) affected)

id          txtcol
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1           arg[0]
2           arg[1]
4           arg[0], arg[1]
Informational: The full-text search condition contained noise word(s).
```
```


q:
Here is pseudo-code of how I setup an array representing the MandelBrot set, yet it becomes horribly stretched when leaving an aspect ratio of 1:1.

xStep = (maxX - minX) / width;
yStep = (maxY - minY) / height;

for(i = 0; i < width; i++)
 for(j = 0; j < height; j++)
  {
   constantReal = minReal + xStep * i;
   constantImag = minImag + yStep * j;
   image[i][j] = inSet(constantReal, constantImag);
  }

Thanks!

[A]
It probably has to do with how you are displaying the
```
image
```
array.  You use the width variable i as the first index, but usually the first index should be the slowest changing, that is, the height.
Try changing the last line to
```
image[j][i] =
```
...


q:
I am trying to use this in my page class. I only just started using objects in PHP so I'm still a little clueless (but learning as much as I can). This is in my page() function (so called when there is a new instance of page)

set_error_handler('$this->appendError');

This is causing an error

Warning: set_error_handler() expects the argument (appendError) to be a valid callback

Now how do I set a class internal function whilst passing the function as a string. Is this not possible? Should I use a normal function which then calls the class function and sends through all arguments? This sounds a little cumbersome to me.

Or have I missed the problem? I've tried making my appendError return a string, and echo.. but it still isn't playing nice.

Any help would be greatly appreciated.

Thank you!!

[A]
Few problems with that.
First:
```
'$this->appendError'
```
is a nogo.  It doesn't interpret $this to the current class, php interprets it as the string '$this'.
Second: Try
```
set_error_handler(array($this, 'appendError'));
```
If that doesn't work, replace $this with the classname and use it statically.


q:
escaping html is fine - it will remove <'s and >'s etc.

ive run into a problem where i am outputting a filename inside a comment tag eg. <!-- ${filename} -->

of course things can be bad if you dont escape, so it becomes:
<!-- <c:out value="${filename}"/> -->

the problem is that if the file has "--" in the name, all the html gets screwed, since youre not allowed to have <!-- -- -->.

the standard html escape doesnt escape these dashes, and i was wondering if anyone is familiar with a simple / standard way to escape them.

[A]
Definition of a HTML comment
:
A comment declaration starts with <!, followed by zero or more comments, followed by >. A comment starts and ends with "--", and does not contain any occurrence of "--".
Of course the parsing of a comment is up to the browser.
Nothing strikes me as an obvious solution here, so I'd suggest you str_replace those double dashes out.


q:
Does anyone have an example AUTORUN.INF which can launch an MSI installer automatically when the user inserts the CD.

I'm sure this can be done but I've been Googling around for ages and have not found any working solution.

UPDATE: I have an AUTORUN.INF similar to this but it won't launch the installer:

[autorun]
open=MyInstaller-1.0.0.msi
label=My CD Label
icon=MyIcon.ico

[A]
Try shellexecute= instead of open=
```
[autorun]
shellexecute=MyInstaller-1.0.0.msi
label=My CD Label
icon=MyIcon.ico
```


q:
Could someone please point me toward a cleaner method to generate a random enum member. This works but seems ugly.

Thanks!

public T RandomEnum<T>()
{
  string[] items = Enum.GetNames(typeof( T ));
  Random r = new Random();
  string e = items[r.Next(0, items.Length - 1)];
  return (T)Enum.Parse(typeof (T), e, true);
}

[A]
```
```
public T RandomEnum<T>()
{
  T[] values = (T[]) Enum.GetValues(typeof(T));
  return values[new Random().Next(0,values.Length)];
}
```
```
Thanks to @[Marc Gravell] for ponting out that the max in Random.Next(min,max) is exclusive.


q:
In a program to find whether the given number is an Armstrong number, I stored the input no (3 digit) as string as follows.

char input[10];
scanf("%s",&input);

Now I have to calculate cube of each digit by using pow method of math.h as follows.

int a;
a = pow(input[0],3);

By coding like this, I could not get correct result.  If I print the value of "a", it shows some irrelevant answer. My doubt is, how to convert from string value to integer value?

[A]
You do not need to get the address of the
```
input
```
array using
```
&input
```
. Simply passing
```
input
```
will pass the pointer to your string to scanf(). Your call to scanf() should look like this:
```
```
scanf("%s", input);
```
```
Another way of doing it, with the address of operator:
```
```
scanf("%s", &input[0]);
```
```


q:
I have two strings

<EM>is <i>love</i></EM>,<PARTITION />

and

<EM>is <i>love</i>,<PARTITION />

I want a regex to match the second string completely but should not match the first one.  Please help.

Note: Everything can change except the EM and PARTITION tags.

[A]
I don't think you're asking the right question.  This regex matches the second string completely and not the first:
```
/^<EM>is <i>love<\/i>,<PARTITION \/>$/
```
But obviously, you want to match a class of strings, not just the second string... right?  Define the class of strings you want to match and you can be 1 step closer to getting the regular expression you need.


q:
Suppose a and b are both of type int, and b is nonzero.  Consider the result of performing a/b in the following cases:

a and b are both nonnegative.

a and b are both negative.

Exactly one of them is negative.

In Case 1 the result is rounded down to the nearest integer.  But what does the standard say about Cases 2 and 3?  An old draft I found floating on the Internet indicates that it is implementation dependent (yes, even case 2) but the committee is leaning toward making it always 'round toward zero.'  Does anyone know what the (latest) standard says?  Please answer only based on the standard, not what makes sense, or what particular compilers do.

[A]
According to the May 2008 revision,
You're right:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined75).
Note 75 says:
According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.
Chances are that C++ will lag C in this respect.  As it stands, it's undefined but they have an eye towards changing it.
I work in the same department as Stroustrup and with a member of the committee.  Things take AGES to get accomplished, and its endlessly political.  If it seems silly, it probably is.


q: How to integrate JQuery Intellisense support in VS 2005

[A]
Doesn't seem like it's possible.
See answer 10
here
.


q:
Suppose I have a text file with data separated by whitespace into columns. I want to write a shell script which takes as input a filename and a number N and prints out only that column. With awk I can do the following:

awk < /tmp/in '{print $2}' > /tmp/out

This code prints out the second column.

But how would one wrap that in a shell script so that a arbitrary column could be passed in argv?

[A]
```
awk -v x=2 '{print $x}'
```
or in a shell script:
```
#!/bin/sh
num=$1
awk < /tmp/in -v x=$num '{print $x}' > /tmp/out
```


q:
In asp.net 3.5, I'm rewriting the url

http://www.abc.com/archive/1108/harpersdecember

to the following

http://www.abc.com/article.aspx?docId=78

I'm using this code to do it:

                Context.RewritePath("/article.aspx?docId=78");

It works fine locally but when I upload to the remote web server, I get a 404 when trying to reference the above page.  Any suggestions why it works locally but not remotely?

[A]
You may need to create a wildcard mapping in IIS on the remote server so that all requests are processed by ASP.Net. If you do not do this any URLs without .ASPX on the end will not run through your URL rewriting code.
There is a good explanation of this (and other reasons you might use it) on
Scott Guthrie's blog
.


q:
i want to create a number of databases in ms-access using a code or any option of ms-access, but i want delete databases also.
            Please help me

[A]
You could have an empty database named "db1.mdb", and then add this code inside a module
in another
Access database:
```
```
Set fso = CreateObject("scripting.filesystemobject")
  fso.CopyFile "c:\db.mdb", "c:\db_copy1.mdb", True
  fso.CopyFile "c:\db.mdb", "c:\db_copy2.mdb", True
  fso.CopyFile "c:\db.mdb", "c:\db_copy3.mdb", True
  fso.DeleteFile "c:\db.mdb"
```
```


q:
I have spent lot of time  doing research on VIM. I am Windows guy since last 6 yrs and was using VS.
Now started working on Linux. I want to make VIM as close as possible to VS.
I want features like
Project Navigation
Files in Different Tabs
Search in Project
AutoCompletion

I have found plugins for the above requirements
Project Pligin
MiniExplore
Taglist
OmniComplete

I am not able to correctly set vimrc script.
When I try to open file from Project it gets open in different tabs.I want to get it open in different buffers.
Also when I want to close file in buffer , complete window gets closed.
Open taglist and project window makes all mess.

Has any one done settings with these plugin..
Could  you guys please post your vimrc files??
It will save lot of time for newbies like me..

[A]
Vim is a very different tool than Visual Studio. Plugins may help you get certain bits of functionality you desire, but do not expect them to work exactly like VS, work well together, or even work at all.
If you are looking for a programming environment more like Visual Studio, there are many good graphical IDE's you can use such as NetBeans, Eclipse, Code::Blocks, KDevelop, Anjuta, etc. Some of these tools are, IMHO, better heavyweight IDE's than Visual Studio, and all are available on Linux for free.
You should either learn to use Vim the way it was built to be used, or find a different tool that suits you better. Shoehorning Vim into a surrogate for Visual Studio will probably cause you more pain than it's worth.


q:
I would like to use Linq to query a bus schedule in my project, so that at any time I can get the next 5 bus arrival times. How can I limit my query to the first 5 results?

More generally, how can I take a slice of a list in C#? (In Python I would use mylist[:5] to get the first 5 elements.)

[A]
```
```
var firstFiveItems = myList.Take(5);
```
```
Or to slice:
```
```
var secondFiveItems = myList.Skip(5).Take(5);
```
```
And of course often it's convenient to get the first five items according to some kind of order:
```
```
var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);
```
```


q:
This is a follow up question. So, Java store's integers in two's-complements and you can do the following:

int ALPHA_MASK = 0xff000000;

In C# this requires the use of an unsigned integer, uint, because it interprets this to be 4278190080 instead of -16777216.

My question, how do declare negative values in hexadecimal notation in c#, and how exactly are integers represented internally? What are the differences to Java here?

[A]
C# (rather, .NET) also uses the two's complement, but it supports both signed and unsigned types (which Java doesn't). A bit mask is more naturally an unsigned thing - why should one bit be different than all the other bits?
In this specific case, it is safe to use an unchecked cast:
```
```
int ALPHA_MASK = unchecked((int)0xFF000000);
```
```
To "directly" represent this number as a signed value, you write
```
```
int ALPHA_MASK = -0x1000000; // == -16777216
```
```
Hexadecimal is not (or should not) be any different from decimal: to represent a negative number, you need to write a negative sign, followed by the digits representing the absolute value.


q:
Given a couple of simple tables like so:

create table R(foo text);
create table S(bar text);

If I were to union them together in a query, what do I call the column?

select T.????
from (
    select foo
    from R
    union
    select bar
    from S) as T;

Now, in mysql, I can apparently refer to the column of T as 'foo' -- the name of the matching column for the first relation in the union. In sqlite3, however, that doesn't seem to work. Is there a way to do it that's standard across all SQL implementations?

If not, how about just for sqlite3?

Correction: sqlite3 does allow you to refer to T's column as 'foo' after all! Oops!

[A]
Try to give an alias to columns;
```
```
select T.Col1
from (
    select foo as Col1
    from R
    union
    select bar as Col1
    from S) as T;
```
```
or If the name of column is not necessary then T.* will be enough.


q:
In C++, I code this way:

//foo.h
class cBar
{
    void foobar();
}

//foo.cpp
void cBar::foobar()
{
    //Code
}

I tried to do this on PHP but the parser would complain. PHP's documentation also doesn't help. Can this be done in PHP?

[A]
You can't really do this in the same manner.
You can use
class abstraction
and
interfaces
, though. The main difference between the two is that and interface does not allow you to specify the function body, where (not abstract) methods in an abstract object can hold all kinds of default behaviour.
Abstraction:
```
```
abstract class cBar
{
    // MUST be extended
    abstract protected function foobar();

    // MAY be extended
    protected function someMethod()
    {
        // do stuff
    }
}

class cBarExtender extends cBar
{
    protected function foobar()
    {
        // do stuff
    }

}
```
```
Interfacing:
```
```
interface cBar
{
    // MUST be implemented
    protected function foobar();
}

class cBarImplementation implements cBar
{
    protected function foobar()
    {
        // do stuff
    }
}
```
```


q:
I cannot get a two-way bind in WPF to work.

I have a string property in my app's main window that is bound to a TextBox (I set the mode to "TwoWay").

The only time that the value of the TextBox will update is when the window initializes.

When I type into the TextBox, the underlying string properties value does not change.

When the string property's value is changed by an external source (an event on Click, for example, that just resets the TextBox's value), the change doesn't propagate up to the TextBox.

What are the steps that I must implement to get two-way binding to work properly in even this almost trivial example?

[A]
We might need to see the code. Does your string property raise a PropertyChanged event? Or (even better) is it implemented as a DependencyProperty? If not, the bound TextBox won't know when the value changes.
As for typing into the TextBox and not seeing the property's value change, that may be because your TextBox isn't losing focus. By default, bound TextBoxes don't write their values back to the source property until focus leaves the control. Try tabbing out of it and seeing if the property value changes.


q:
This is intended to be a more concrete, easily expressable form of my earlier question.

Take a list of words from a dictionary with common letter length.

How to reorder this list tto keep as many letters as possible common between adjacent words?

Example 1:

AGNI, CIVA, DEVA, DEWA, KAMA, RAMA, SIVA, VAYU
reorders to:
AGNI, CIVA, SIVA, DEVA, DEWA, KAMA, RAMA, VAYU

Example 2:

DEVI, KALI, SHRI, VACH
reorders to:
DEVI, SHRI, KALI, VACH

The simplest algorithm seems to be:  Pick anything, then search for the shortest distance?

However, DEVI->KALI  (1 common) is equivalent to DEVI->SHRI (1 common)

Choosing the first match would result in fewer common pairs in the entire list (4 versus 5).

This seems that it should be simpler than full TSP?

[A]
This can be done with a recursive approach. Pseudo-code:
```
```
Start with one of the words, call it w
FindNext(w, l) // l = list of words without w
  Get a list l of the words near to w
  If only one word in list
    Return that word
  Else
    For every word w' in l do FindNext(w', l') //l' = l without w'
```
```
You can add some score to count common pairs and to prefer "better" lists.


q:
How do you add that little "X" button on the right side of a UITextField that clears the text?  I can't find an attribute for adding this sub-control in Interface Builder in the iPhone OS 2.2 SDK.

Note: In Xcode 4.x and later (iPhone 3.0 SDK and later), you can do this in Interface Builder.

[A]
This button is a built-in overlay that is provided by the
```
UITextField
```
class, but as of the iOS 2.2 SDK, there isn't any way to set it via Interface Builder.  You have to enable it programmatically.
Add this line of code somewhere (
```
viewDidLoad
```
, for example):
Objective-C
```
```
myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;
```
```
Swift 5.0
```
```
myUITextField.clearButtonMode = .whileEditing
```
```


q: Does anyone know of shared TODO list plugin for Eclipse that allows users in a a development team to all view and edit the same list of tasks?

[A]
Mylyn
can be used to integrate issue tracking systems into the IDE.
It does this by making tasks a first class part of Eclipse, and integrating rich and offline editing for repositories such as Bugzilla, Trac, and JIRA.
If you are not looking for a lightweight solution, then you might give it a try.


q:
If there a way to protect against concurrent modifications of the same data base entry by two or more users?

It would be acceptable to show an error message to the user performing the second commit/save operation, but data should not be silently overwritten.

I think locking the entry is not an option, as a user might use the "Back" button or simply close his browser, leaving the lock for ever.

[A]
To be safe the database needs to support
transactions
.
If the fields is "free-form" e.g. text etc. and you need to allow several users to be able to edit the same fields (you can't have single user ownership to the data), you could store the original data in a variable.
When the user committs, check if the input data has changed from the original data (if not, you don't need to bother the DB by rewriting old data),
if the original data compared to the current data in the db is the same you can save, if it has changed you can show the user the difference and ask the user what to do.
If the fields is numbers e.g. account balance, number of items in a store etc., you can handle it more automatically if you calculate the difference between the original value (stored when the user started filling out the form) and the new value you can start a transaction read the current value and add the difference, then end transaction. If you can't have negative values, you should abort the transaction if the result is negative, and tell the user.
I don't know django, so I can't give you teh cod3s.. ;)


q:
Using the Facebook API, is there a way of getting a friend's phone/cell number? I'm sure I saw an app a while ago that could sync Facebook with your Mac Address Book, but I haven't found anything in the API documentation that allows you to get a friend's number. Is this possible?

Thanks in advance.


q: Can someone illustrate what really is the difference between the two?

[A]
A design pattern is a concept, or a receipt for how to get a specific problem done.
A Framework is code ready for use, usually packaged in a way that makes creating an application much easier.
It does not make sense to explain the differences because they are two totally different things.


q:
I have a xml file like this:

<customer>
  <field1 />
  <field2 />
  <field3>
    <item1 />
  </field3>
  <field3>
    <item1 />
  </field3>
</customer>

field* can appear in any order and only field3 can appear more than once.

How can I create a XSD file to validate this?

Thank you!

[A]
Try this
I'm not a guru, but this appears to work.
```
```
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="customer" type="customerType"/>
  <xs:complexType name="customerType">
    <xs:sequence>
      <xs:element name="field1" minOccurs="1" maxOccurs="1">
      </xs:element>
      <xs:element name="field2" minOccurs="1" maxOccurs="1">
      </xs:element>
      <xs:element name="field3" type="field3Type"
                  minOccurs="1" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="field3Type">
    <xs:sequence>
      <xs:element name="item1">
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:schema>
```
```
tools
I used
XML Copy Editor
, but there are loads of editors which will validate XML.
links
You might also be interested in
this article
about generating an XSD from an XML file.


q:
Does anyone have a good algorithm for taking an ordered list of integers, i.e.:

[1, 3, 6, 7, 8, 10, 11, 13, 14, 17, 19, 23, 25, 27, 28]

into a given number of evenly sized ordered sublists, i.e. for 4 it will be:

[1, 3, 6] [7, 8, 10, 11] [13, 14, 17, 19] [23, 25, 27, 28]

The requirement being that each of the sublists are ordered and as similar in size as possible.

[A]
Here is my own recursive solution, inspired by merge sort and breadth first tree traversal:
```
```
private static void splitOrderedDurationsIntoIntervals(Integer[] durations, List<Integer[]> intervals, int numberOfInterals) {
    int middle = durations.length / 2;
    Integer[] lowerHalf = Arrays.copyOfRange(durations, 0, middle);
    Integer[] upperHalf = Arrays.copyOfRange(durations, middle, durations.length);
    if (lowerHalf.length > upperHalf.length) {
        intervals.add(lowerHalf);
        intervals.add(upperHalf);
    } else {
        intervals.add(upperHalf);
        intervals.add(lowerHalf);
    }
    if (intervals.size() < numberOfIntervals) {
        int largestElementLength = intervals.get(0).length;
        if (largestElementLength > 1) {
            Integer[] duration = intervals.remove(0);
            splitOrderedDurationsIntoIntervals(duration,  intervals);
        }
    }
}
```
```
I was hoping someone might have a suggestion for an iterative solution.


q: I want to build an Axis2 client (I'm only accessing a remote web service, I'm not implementing one!) with Maven2 and I don't want to add 21MB of JARs to my project. What do I have to put in my pom.xml to compile the code when I've converted the WSDL with ADB?

[A]
(
Note:
This response was provided by Aaron Digulla himself. What follows is the exact text of his own answer.)
In maven2, the minimum dependency set to make an ADB client work ("ADB" as in the way you created the Java classes from the WSDL) is this:
```
```
<dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-kernel</artifactId>
            <version>1.4.1</version>
    </dependency>
    <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-adb</artifactId>
            <version>1.4.1</version>
    </dependency>
```
```
Hmmm... it seems I can't flag that as the correct answer. Can someone please copy this so I can flag his post?


q:
Ever since switching from TABLE-layout to DIV-layout, one common problem remains:

PROBLEM: you fill your DIV with dynamic text and inevitably there is a super-long word that extends over the edge of your div column and makes your site look unprofessional.

RETRO-WHINING: This never happened with table layouts. A table cell will always nicely expand to the width of the longest word.

SEVERITY: I see this problem on even the most major sites, especially on German sites where even common words such as "speed limit" are very long ("Geschwindigkeitsbegrenzung").

Does anyone have a workable solution to this?

[A]
Two fixes:
```
overflow:scroll
```
-- this makes sure your content can be seen at the cost of design (scrollbars are ugly)
```
overflow:hidden
```
-- just cuts off any overflow. It means people can't read the content though.
If (in the SO example) you want to stop it overlapping the padding, you'd probably have to create another div, inside the padding, to hold your content.
Edit: As the other answers state, there are a variety of methods for truncating the words, be that working out the render width on the client side (never attempt to do this server-side as it will never work reliably, cross platform) through JS and inserting break-characters, or using non-standard and/or wildly incompatible CSS tags (
```
word-wrap: break-word
```
doesn't appear to work in Firefox
).
You will always need an overflow descriptor though. If your div contains another too-wide block-type piece of content (image, table, etc), you'll need overflow to make it not destroy the layout/design.
So by all means use another method (or a combination of them) but remember to add overflow too so you cover all browsers.
Edit 2 (to address your comment below):
Start off using the CSS
```
overflow
```
property isn't perfect but it stops designs breaking. Apply
```
overflow:hidden
```
first. Remember that overflow might not break on padding so either nest
```
div
```
s or use a border (whatever works best for you).
This will hide overflowing content and therefore you might lose meaning. You could use a scrollbar (using
```
overflow:auto
```
or
```
overflow:scroll
```
instead of
```
overflow:hidden
```
) but depending on the dimensions of the div, and your design, this might not look or work great.
To fix it, we can use JS to pull things back and do some form of automated truncation. I was half-way through writing out some pseudo code for you but it gets seriously complicated about half-way through. If you need to show as much as possible, give
hyphenator
a look in (
as mentioned below
).
Just be aware that this comes at the cost of user's CPUs. It could result in pages taking a long time to load and/or resize.


q:
I would like to build a web application on Castle MonoRail, I was wondering how can we use an action with extension and another action without extension? How can HTML helper generator url for us?

Ex:

http://mysite.com/Products/list

http://mysite.com/Products/abc.castle

[A]
You can try creating a routing role like
```
```
/<controller>/<action>.castle
```
```
and it would do the trick.


q: In Ruby on Rails, how to add foreign key constraint in migration?

[A]
AFAIK, there isn't any built-in support for that, but there are
several plugins
that help you with that. You can also add them manually to your migration files, just use the execute method for that, e.g. (sample from Rails API):
```
```
class MakeJoinUnique < ActiveRecord::Migration
    def self.up
      execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
    end

    def self.down
      execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
    end
  end
```
```


q:
I have a JFrame that contains a "display" JPanel with JTextField and a "control" JPanel with buttons that should access the contents of the display JPanel. I think my problem is related on how to use the observer pattern, which in principle I understand. You need to place listeners and update messages, but I don't have a clue where to put these, how to get access from one panel to the other and maybe if necessary to introduce a "datamodel" class. For example, I want to access the contents of the JTextField from the control panel and I use an anonymous action listener as follows:

JButton openfile = new JButton("Convert file");
openfile.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        openButtonPressed();
    }
});

[A]
It does make the code cleaner if you create the models in one layer and add a layer or two above to create the components and layout. Certainly do not extend the likes of
```
JFrame
```
and
```
JPanel
```
.
Do not feel the need to make the composition hierarchy in the model layer exactly match the display. Then it's just a matter of taking the text from the
```
Document
```
and performing the relevant operation.
Okay, perhpas not that simple. Swing models are a little bit messy. In particular ButtonModel is brain damaged, and the controller area of code might not be entirely pure.


q:
We're experimenting with following an agile approach to software development where I work.  It's working well so far, however, towards the end of the iteration, we had a problem with a build and it cost a day's worth of time fixing: time that should have been dedicated to testing.

As a result, our QA doesn't have enough time to complete the testing before the end of the iteration.  How do you deal with this scenario - where unforeseen problems impact on tasks during the iteration?

[A]
It depends on the scheduling of your QA - can you let them continue testing while developers are working on the next iteration already or not?
If yes, I'd let them finish testing.
Just continue on with the next iteration with the data that you have already.  You really don't want to hold back a number of people because of one bottleneck.  You could add a little extra slack on the next iteration to fix bugs that haven't been reported yet, by assigning slightly less work than a full iteration's worth for every developer.
If no, just plan the next iteration as any normal iteration and test at the end of the iteration as before.


q: How to Connect to PickBasic database using Ole db driver .. I need it badly help me out

[A]
There are tools available from www.rainingdata.com. I can't see any freeware options.
Rainingdata is now tiger logic.
http://www.tigerlogic.com/tigerlogic/
And I've been to their worldwide conferences, but I don't recall any freeware.  Its easy to program if you can stand using a dump terminal or a terminal emulation like Accuterm.  Accuterm will allow you to program with GUI interface, but you will still have a lot of fun finding the files and programs you have to use.


q:
I have some javascript menu code that works just fine from a separate directory.
But, when I try to call the same .js files from within the same directory, it won't see the files.

The following works from another directory:

script type="text/javascript"> var vbImgPath="../00-Menu-Files/"

But, if I do this from within the same folder, how would I do it?

THE SOLUTION (edited this in after much experimentation):

I experimented A LOT!!!
There is only ONE solution that ultimately worked:

"../00-Menu-Files/"

The SAME thing as from the other directory!
Pretty strange that there is no other way to call this from within its own directory. But I cannot find another alternative that actually works.

[A]
Maybe you'd use:
```
```
script type="text/javascript"> var vbImgPath="00-Menu-Files/"
```
```
You may want to make this work anywhere by using absolute urls with a / at the beginning and the full path afterwards, ie.
```
```
script type="text/javascript"> var vbImgPath="/00-Menu-Files/"
```
```
Whether this works or not depends on your site's directory structure.


q:
I have a dll that contains a dot net assembly - common intermediate language. The problem is that it's lacking documentation and I need to figure out the api like available classes, properties and methods, correct parameters to pass etc.

Whats the best way to do this. I need some sort of viewer/inspector but I couldn't find any.

Thanks.

[A]
Try reflector.
http://www.red-gate.com/products/reflector/
Its free :-)
Edit
:
As of February 2011, its no longer free ...:(
There are alternatives
like
ilspy
or
JetBrains dotPeek
.


q: I need to determine the number of pages in a specified PDF file using C# code (.NET 2.0).  The PDF file will be read from the file system, and not from an URL.  Does anyone have any idea on how this could be done?  Note: Adobe Acrobat Reader is installed on the PC where this check will be carried out.

[A]
You'll need a PDF API for C#. iTextSharp is one possible API, though better ones might exist.
iTextSharp Example
You must install iTextSharp.dll as a reference. Download iTextsharp from SourceForge.net This is a complete working program using a console application.
```
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace GetPages_PDF
{
  class Program
{
    static void Main(string[] args)
      {
       // Right side of equation is location of YOUR pdf file
        string ppath = "C:\\aworking\\Hawkins.pdf";
        PdfReader pdfReader = new PdfReader(ppath);
        int numberOfPages = pdfReader.NumberOfPages;
        Console.WriteLine(numberOfPages);
        Console.ReadLine();
      }
   }
}
```
```


q:
I have heard a few developers recently say that they are simply polling stuff (databases, files, etc.) to determine when something has changed and then run a task, such as an import.

I'm really against this idea and feel that utilising available technology such as Remoting, WCF, etc. would be far better than polling.

However, I'd like to identify the reasons why other people prefer one approach over the other and more importantly, how can I convince others that polling is wrong in this day and age?

[A]
Polling is not "wrong" as such.
A lot depends on how it is implemented and for what purpose. If you really care about immedatly notification of a change, it is very efficient. Your code sits in tight loop, constantly polling (asking) a resource whether it has changed / updated. This means you are notified as soon as you can be that something is different. But, your code is not doing anything else and there is overhead in terms of many many calls to the object in question.
If you are less concerned with immediate notification you can increase the interval between polls, and this can also work well, but picking the correct interval can be difficult. Too long and you might miss critical changes, too short and you are back to the problems of the first method.
Alternatives, such as interrupts or messages, etc. can provide a better compromise in these situations. You are notified of a change as soon as is practically possible, but this delay is not something you control, it depends on the component tself being timely about passing on changes in state.
What is "wrong" with polling?
It can be resource hogging.
It can be limiting (especially if you have many things you want to know about / poll).
It can be overkill.
But...
It is not inherently wrong.
It can be very effective.
It is very simple.


q: What is the C# equivalent of Delphi's FillChar?

[A]
If I understand FillChar correctly, it sets all elements of an array to the same value, yes?
In which case, unless the value is 0, you probably have to loop:
```
```
for(int i = 0 ; i < arr.Length ; i++) {
    arr[i] = value;
}
```
```
For setting the values to the type's 0, there is
```
Array.Clear
```
Obviously, with the loop answer you can stick this code in a utility method if you need... for example, as an extension method:
```
```
public static void FillChar<T>(this T[] arr, T value) {...}
```
```
Then you can use:
```
```
int[] data = {1,2,3,4,5};
//...
data.FillChar(7);
```
```
If you
absolutely
must have block operations, then
```
Buffer.BlockCopy
```
can be used to blit data between array locatiosn - for example, you could write the first chunk, then blit it a few times to fill the bulk of the array.


q:
My current code looks like the following. How can I pass my array to the controller and what kind of parameters must my controller action accept?

function getplaceholders() {
    var placeholders = $('.ui-sortable');
    var result = new Array();
    placeholders.each(function() {
        var ph = $(this).attr('id');
        var sections = $(this).find('.sort');
        var section;

        sections.each(function(i, item) {
            var sid = $(item).attr('id');

            result.push({ 'SectionId': sid, 'Placeholder': ph, 'Position': i });
        });
    });
    alert(result.toString());
    $.post(
        '/portal/Designer.mvc/SaveOrUpdate',
        result,
        function(data) {
            alert(data.Result);
        }, "json");
};

My controller action method looks like

public JsonResult SaveOrUpdate(IList<PageDesignWidget> widgets)

[A]
Towards the second half of
Create REST API using ASP.NET MVC that speaks both JSON and plain XML
, to quote:
Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."
He then implements an action filter that maps the JSON to C# objects with code shown.


q:
Is there a way to limit the rows returned at the Oracle datasource level in a Tomcat application?

It seems maxRows is only available if you set it on the datasource in the Java code. Putting maxRows="2" on the datasource doesn't apply.

Is there any other way limit the rows returned? Without a code change?

[A]
It isn't something that is available at the configuration level. You may want to double check that it does what you want it to do anyway:
see the javadoc for setMaxRows
. With Oracle it is still going to fetch every row back for the query and then just drop the ones outside the range. You would really need to use rownum to make it work well with Oracle and you can't do that either in the configuration.


q:
I'd like to have some of the ScriptManager features in the new Asp.net MVC model:

1- Script combining

2- Resolving different paths for external Javascript files

3- Minify and Gzip Compression

Here is what I found, but I'm not sure is the best way for MVC approach.  In general what is a good approach to deal with Javascript code in the MVC model?

[A]
Maybe you could just create a new 'Scripts' controller with different actions serving different combinations of compressed JS files. Since MVC is designed with a resource oriented approach, i.e. URLs are now at the center of your programming model, why not define simple URIs for your Javascripts too ?
In your views, for example you could reference your files like this :
```
```
<script src="http://your_domain/scripts/all"/>
```
```
This would call your 'all' action, resulting in all your compressed script files being sent.
Of course you would need to code the combining and compressing for now, or maybe reuse the Scriptmanager internally, I don't know if it's possible.
This is just an idea though, currently I'm referencing individual javascript files directly in my master pages.


q:
I am new to php and wanted to make a blog using php where every one can see the contents posted in the site but another administrator page should be there which can edit, add or delete posts

How can i code a page like that? What are the logics required?

[A]
There are
lots
of
tutorials
for this sort of venture
around the internet
.
I think It may be a bit too much to write in a single answer here.. You're best to choose one of these tutorials or find a book that uses building a blog as a means for learning more about PHP.


q:
I would like to create a WLST script to create my Weblogic domain. However I'm having problems adding the LDAP config.

cd("/SecurityConfiguration/myDomain")
cmo.createRealm("myrealm")

cd("/SecurityConfiguration/myDomain/Realms/myrealm")
cmo.createAuthenticationProvider("myLDAP", "weblogic.security.providers.authentication.NovellAuthenticator")

This is currently failing because at this point I don't seem to have a SecurityConfiguration object

No SecurityConfiguration object with name myDomain

Does this configuration have to be done online? Are there any other work arounds?

[A]
From what I've found, this configuration has to be done using WLST Online.
The script I have created looks something like this
```
```
connect("username", "password", "t3://ip:port");

edit()
startEdit()

create_AuthenticationProvider_54("/SecurityConfiguration/myDomain/Realms/myrealm", "value")
cd("/SecurityConfiguration/myDomain/Realms/myrealm")
cmo.createAuthenticationProvider("myLDAP", "weblogic.security.providers.authentication.NovellAuthenticator")

cd("/SecurityConfiguration/myDomain/Realms/myrealm/AuthenticationProviders/myLDAP")
set("GroupBaseDN", "value")
set("UserNameAttribute", "value")
set("StaticGroupObjectClass", "value")
set("UserBaseDN", "value")
set("UserObjectClass", "value")
set("AllGroupsFilter", "value")
set("Principal", "value")
set("UseRetrievedUserNameAsPrincipal", "value")
set("Host", "value")
set("StaticGroupDNsfromMemberDNFilter", "value")
set("StaticMemberDNAttribute", "value")
set("ControlFlag", "value")
set("UserFromNameFilter", "value")
set("Credential", "value")
set("GroupFromNameFilter", "value")

startEdit()
save()
activate(block="true")
```
```


q:
Is there a way to speed up the rendering of Polylines in Google Maps when using Internet Explorer (7)? My map loads quickly in other browsers.

I've encoded the Polylines as described here - http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/ and they are loaded from a static JavaScript file.

[A]
The ie7 is slower than firefox3 (and ie6 is slower than ie7) to render large and complex polylines with Javascript.
There could be some minor tricks to speed up the rendering, (smooth the lines before rendering, adjusting for zoomlevel and such).
One trick is maybe to create a kml instead and leave on a public URL and use that in Google maps.
A more "enterprise" trick is to use geoserver or mapserver and create overlays. That would really boost performance. (They are truly serverside.)


q:
I've written my first C# iterator today. Woohoo.

Interestingly, it has side effects. My iterator filters out invalid files from a directory and returns a sequence of valid files to process. Wheneve it encounters an invlaid file, it moves it to another directory.

I tried implementing it as a LINQ query, but really don't like the fact that the predicate for the where clause has side effects. That's a definite smell.

I could implement it explicitly, looping over all files and handling the good or the bad in turn, but it's not very elegant. A better solution is to split it into two lists (good and bad) and process each in turn.

But then I remembered iterators. And I've now got an iterator that yields the valid files and handles (moves) the invalid ones.

So, my question is this: is it a bad idea for an iterator to have side effects such as this? Am I hiding too much functionality in an iterator?

[A]
I'd say it's
generally
a bad idea to have side-effects in an iterator, but it's not a complete no-no. If you have side-effects, it makes it hard/impossible for callers to work in a purely functional way. This may or may not be a problem depending on your use case.
I suggest you have two ways of getting the iterator - one which has the side-effect (which is presumably an optimisation, basically) and one which doesn't (slower, but simpler to reason about). This could just be by passing a flag into the method, or having two methods named differently.


q:
I can't seem to find an answer to this problem, and I'm wondering if one exists. Simplified example:

Consider a string "nnnn", where I want to find all matches of "nn" - but also those that overlap with each other. So the regex would provide the following 3 matches:

nnnn

nnnn

nnnn

I realize this is not exactly what regexes are meant for, but walking the string and parsing this manually seems like an awful lot of code, considering that in reality the matches would have to be done using a pattern, not a literal string.

[A]
AFAIK, there is no pure regex way to do that at once (ie. returning the three captures you request without loop).
Now, you can find a pattern once, and loop on the search starting with offset (found position + 1). Should combine regex use with simple code.
[EDIT] Great, I am downvoted when I basically said what Jan shown...
[EDIT 2] To be clear: Jan's answer is better. Not more precise, but certainly more detailed, it deserves to be chosen. I just don't understand why mine is downvoted, since I still see nothing incorrect in it. Not a big deal, just annoying.


q:
I have a SQL table which has a number of fields

ID | Value | Type

A typical record may be :-
1000,10,[int]

a second row may be:-

1001,foo,[string]

a third row may be:-

1002,10/12/2008,[DateTime]

I have been asked to look at this as at the moment, each time we wish to select from this table we have to cast the value to the type specified. I am able to do a database redesign on this and am wondering the best route to go to optimise this. (SQL 2000).

[A]
Horrors!  This is the dreaded
Entity-Attribute-Value (EAV)
model! Run away!
But seriously, assuming there is some reason for needing this kind of model, maybe create a properly typed column for each data type?
```
```
ID       Type      StringValue       DateValue      NumberValue
1001     String    Foo
1002     Date                        10/12/2008
1003     Number                                     123.46
```
```


q:
I have a threading issue,

I'm setting the ThreadPool.SetMaxThreads(maxThreads, System.Environment.ProcessorCount) to 10.

But when I check how many are avaliable ThreadPool.GetAvailableThreads() it says there are (maxThreads - 1) so 9, but then goes on to use 10 threads.

Any ideas why this is?

Thanks for the help.

[A]
In an ideal world, we would have 1 thread/physical core. That way, we would no longer have context switches, which are rather costly operations. But until we have processors with hundreds of cores, that won't be practical.
Anyway, as Marc suggested, you shouldn't mess with the ThreadPool parameters unless you REALLY know what you are doing. The logic behind the .Net implementation of the ThreadPool is rather good, and it can successfully handle most scenarios.


q:
Nested If or single if with And operator,  which is better approach?

Single If with And

if (txtPackage.Text != string.Empty && txtPackage.Text == "abc")
{
   //
}

Nested If

if (txtPackage.Text != string.Empty)
{
  if (txtPackage.Text == "abc")
  {
     //
  }
}

[A]
Are you going to do something different in the 'nested if' example if, in fact, txtPackage.Text isn't empty but contains something other than "abc"?
If you aren't, I'd ask why are you checking for string.empty at all?
You could just write:
```
```
if (txtPackage.Text == "abc")
{

//

}
```
```
and be done with it.
Totally depends upon what you want to do in the end.


q:
Is it possible to access the following formatted menu item like any other standard menu item (using the underscore-method, e.g. "_File" would be accessible by pressing "f")? I would like to use "O" as "access key" here.

Unfortunately, <AccessText> does not seem to be usable directly (I imaginged something like

<AccessText Visibility="Collapsed">_O2-Genion</AccessText>

in a <StackPanel>, but alas, this did not work out.)

<MenuItem>
  <MenuItem.Header>
    <TextBlock>
      O
      <Span BaselineAlignment="Subscript">
        <TextBlock Margin="-3,0,0,0" FontSize="8">
        2
        </TextBlock>
      </Span>
      -Genion
    </TextBlock>
  </MenuItem.Header>
</MenuItem>

Any suggestions?

[A]
Do you even need to use an AccessKey at all? Assuming that you didn't need/want the custom styling of the MenuItem header text, you could get the same affect by doing the following:
```
```
<MenuItem HeaderText="_02" />
```
```
Would just putting an underscore before the 0 work? Although I seem to recall that one difference between TextBlock and Label is that TextBlock doesn't support access keys, but Label does. If that's the case, maybe use a Label instead of a TextBlock in your menu item?


q:
There is a groupwall of which I want to download and store all messages in a db.
In the documentation I cannot find a good way to do it. Did I miss something? What's the good way to do this?


q:
I have MAMP set up on my iMac and on my Macbook. I want to keep both installs synced using dropbox. When upgrading MAMP the only 2 folders you need to transfer are 'db' & 'htdocs'. My theory is then that these are the only 2 folders I need to keep in sync. Sound right to you so far?

Syncing the 'htdocs' folder is easy as you can put it in your dropbox and point the MAMP preferences to the dropbox folder, but the 'db' folder has no such option.

Any suggestions on how I could keep the 'db' folder synced? Thanks.

[A]
Ok, so I am thinking that my solution is going to have to be a combination of chronosync
http://www.econtechnologies.com/site/Pages/ChronoSync/chrono_overview.html
& dropbox.
Have a copy of cronosync on both the macbook and the iMac then before starting work on either machine manually run chronosync to sync the MAMP 'db' folder with the dropbox 'db' folder.
Unless someone out there has a better idea. Thanks.


q:
Consider the following piece of Java code.

int N = 10;
Object obj[] = new Object[N];
for (int i = 0; i < N; i++) {
    int capacity = 1000 * i;
    obj[i] = new ArrayList(capacity);
}

Because in Java, all objects live on the Heap, the array does not
contain the objects themselves, but references to the objects. Also,
the array itself is also an object, thus it lives on the heap.

What is the equivalent in C++, but keeping the array and objects on
the stack, to avoid as much as possible needing new and delete ?

Edit: changed the code to use a custom constructor.

[A]
Simply declaring
```
```
Object array_of_objects[10];
```
```
in C++ creates 10 default-constructed objects of type Object on the stack.
If you want to use a non-default constructor, that's not so easy in C++.  There might be a way with placement new but I couldn't tell you off the top of my head.
EDIT: Link to other question on StackOverflow
How to use placement new for the array is explained in the answer to
this question
here on StackOverflow.


q:
I'm sure this must be possible, but I can't find out how to do it.

Any clues?

[A]
```
```
$startinfo = new-object System.Diagnostics.ProcessStartInfo
$startinfo.FileName = "explorer.exe"
$startinfo.WorkingDirectory = 'D:\foldername'

[System.Diagnostics.Process]::Start($startinfo)
```
```
Hope this helps


q:
What would be the easiest way to view classes, methods, properties, etc. inside a jar file?
I'm looking for something equivalent to the very useful  Lutz Roeder .NET Reflector  - for Java

[A]
I usually open them with 7-Zip... It allows at least to see packages and classes and resources.
Should I need to see methods or fields, I would use Jad but of course, it is better to rely on (good) JavaDoc...
Now, somewhere on SO was mentioned some Eclipse plug-ins, to find in which jar file a class is located, perhaps they can do more (ie. what you requested).
[EDIT] Reference to SO thread. Not what is asked, but somehow related, thus useful:
Java: How do I know which jar file to use given a class name?


q:
I created a protected folder on my ASP.NET site with the "ASP.NET Configuration" tool.

It made a database called App_Data/ASPNETDB.MDF where it stores one (1) user.

While uploading I noticed now that the database has grown to 10 MB and the .ldf file is 5 MB. (!)

I tried to look at it with SQL Server 2008 Management Studio but when attaching it said "Failed to retrieve data for this request."

Has this ASPNETDB.MDF bloat every happened to anyone else?

[A] I think this is just the default size for the aspnetdb, at least in sql 2005 express all my aspnetdb databases are 10mb initially


q:
My code runs inside a JAR file, say foo.jar, and I need to know, in the code, in which folder the running foo.jar is.

So, if foo.jar is in C:\FOO\, I want to get that path no matter what my current working directory is.

[A]
Use ClassLoader.getResource() to find the URL for your current class.
For example:
```
```
package foo;

public class Test
{
    public static void main(String[] args)
    {
        ClassLoader loader = Test.class.getClassLoader();
        System.out.println(loader.getResource("foo/Test.class"));
    }
}
```
```
(This example taken from
a similar question
.)
To find the directory, you'd then need to take apart the URL manually. See the
JarClassLoader tutorial
for the format of a jar URL.


q:
I am just wondering what are the steps followed by you guys when starting a new project? Do you used to create UML diagrams, SRS or any design documents? I am starting a new project and like to get some expert advice on all these practices. I know to code, but I never tried UML and other stuffs.

Any help would be great

[A]
Typically, my process runs something like this:
I usually start with a logical model - a bastardised UML if you like - so I can visualise the key entities and relationships in my system.
Then I think about a the underlying datamodel (thinking through potential issues around data consumption patterns, performance and so on)
Then I choose an appropriate data access architecture
Then I start coding the data layer and business objects (with any redesign of the logical model as required)
I dont think there is too much point 'over-designing' at the logical stage because requirements change as the project progresses, both from a business and technical / design perspective, in ways you can't always anticipate in advance.


q:
I 'd like to use Criteria for my SQL query.
I have 3 tables "home", "person" and a third table "liveIn" for correspondance between home and person.

My sql query is
"select home.id
from home, person, liveIn
where home.country = 'Japan'
and person.id = '15'
and liveIn.Homeid = home.id
and liveIn.PersonId = person.id"

A little help anybody ?


q: How can I simplify an expression using basic arithmetic?

[A]
You can use the technique described here:
http://augustss.blogspot.com/2007/04/overloading-haskell-numbers-part-2.html
. Make your type be of the necassary type-classes (Num, Fractional, Floating) so that -, +, * and so on works for your type. Then if the expression tree is finally built, you can operate on it to see what you can simplify.


q:
I'm trying to add a special markup to Python documentation strings in emacs (python-mode).

Currently I'm able to extract a single line with:

(font-lock-add-keywords
 'python-mode
 '(("\\(\"\\{3\\}\\.+\"\\{3\\}\\)"
    1 font-lock-doc-face prepend)))

This works now:

"""Foo"""

But as soon there is a newline like:

"""
Foo

"""

It doesn't work anymore. This is logical, since . doesn't include newlines (\n).
Should I use a character class?

How can I correct this regular expression to include everything between """ """?

Thanks in advance!


q:
I am putting together an architecture for a mid sized company who want to introduce a BPM (Business Process Management) tool. I understand that this would be helpful and want to introduce it but stuggle to find its appropriate place within the architecture.

I want to know when and how you should use a BPM tool, how do you differentiate Business Process from Application Workflow?

[A]
Why do you want to introduce a BPM tool? Is it buzzword compliance? If you are struggling to find a place in the architecture, then I would suspect that the tool isn't going to bring a big win (at least not with your current understanding).
Application workflow tools typically concern themselves with modeling a specific process and giving semi-technical process designers the ability to show the steps and interactions, while allowing programmers to flesh the skeleton out with code that implements the pieces. Personally, I have found that the overhead of training semi-technical process leads can offset the promised gains in effective communication and turnaround, but in large organizations it can ensure the the process "owner" has the illusion of control necessary for buyoff on plans. I say illusion, because at the end of the day it is the IT staff that regenerates the code that implements the process, and often suggested changes get reverted due to problems on the technical side (such tools often make changes easier to suggest than to implement).
Some Business Process Management tools are little more than Application Workflow tools with higher price tags. Some take a higher view and incorporate the manual flows and other non-IT processes into the architecture (although obviously such steps are really nothing more than stubs or gatekeepers for exiting and re-entering the IT flow). I have no idea what you are calling a mid sized company, but at a 160 man aerospace engineering firm, we found BPM tools that we evaluated overkill.
Sadly, this is one of those questions where only subjected answers can be given, even with all the facts (different System Analysts will give different opinions). I hope that a quick overview is at least of some help. Just beware sales hype: I find such tools to be of value only in specific organizations with specific process flows and a hindrance in others.


q:
I have a library consisting of approx 100 source files. I want one of the sources to be always rebuilt if any of the other files have been compiled but I don't want it built every time I run the make/build.

Basically I want this file to have the last build date/time built into it so any application linking to the library can check the last build time/date. Is there any other way to do this?

[A]
Let the object file containing the build timestamp depend on all the other object files:
```
```
version.o: $(OBJECTS)
```
```


q:
if i have :

<div class="carBig"></div>

and

<div class="car"></div>

and $(".car").size();

i get 2 items ..

[A]
What version of jquery are you using?
Using this code:
```
```
<title>Testing</title>

Big Car

Regular Car

```
```
My output document looked like this:
```
```
Big Car
Regular Car
1Regular Car
```
```
Mine only found 1 element, the one with the class of "car"...


q: How do I set the executable icon for my C++ application in visual studio 2008?

[A]
First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon.
Use the embedded image editor in order to edit the existing or new icon. Note that an icon can include several types (sizes), selected from Image menu.
Then compile your project and see the effect.
See:
http://social.microsoft.com/Forums/en-US/vcgeneral/thread/87614e26-075c-4d5d-a45a-f462c79ab0a0


q:
Wnen I use external resources such as files or DB connection I need to close them before I let them go.

Do I need to do the same thing with Swing components ? If yes then how ?

[A]
Objects are automatically garbage collected if there are no references to them. You do not have to treat Swing components the same way that you do external resources. However, if you have a component that you are not going to need later you can set any references to that component to null.
```
```
JPanel p = new JPanel();
p = null;
```
```
Setting p to null does not delete the object but it removes any references to the object so the next time the garbage collector passes it gets picked up.
You will have to be careful though that other reference to the component do not exist.


q: Is it possible to checkout only those files from a SVN repository that were modified in a revision or range of revisions, without checking out any files that were not modified?

[A]
I'm not completly sure if this is possible but you can also do something like this:
```
```
svn checkout --revision <revisionNumber>
```
```
to get a certain revision and
```
```
svn log --revision <revisionNumber>
```
```
to list all files chaned in a revision


q:
I have just come across a Visual C++ option that allows you to force file(s) to be included - this came about when I was looking at some code that was missing a #include "StdAfx.h" on each .cpp file, but was actually doing so via this option.

The option can be found on the Advanced C/C++ Configuration Properties page and equates to  the /FI compiler option.

This option could prove really useful but before I rush off and start using it I thought I'd ask if there are any gotchas?

[A]
I would discourage from /FI  (
MSDN
says it's called /FI . Not sure whether i looked at the right page though), simply because people or yourself reading the files don't notice a header is magically included anyway.
You can be sure this will cause much debugging time for someone that wants to figure out where specific macros come from, even though there are no
```
#include
```
lines at the top of the file.


q:
I'm working on a site (http://easy2speak.com) with about 10 flash SWFs on each page. Each of the SWFs are playing back a sound when clicked. Loading the sound, and playing it without any latency works fine, but in Flash player version 9 on all major browsers except IE, the sound suddenly drops out. It usually works for the first 10-20 clicks, then the SWFs will be totally silent until the next machine/browser restart.

In Flash player v10 (exactly the same code) it works perfectly. It also works perfectly in Flash player v9 in Internet Explorer.

Any ideas ?

Would love to hear some brain-storming on how to get around this problem as well, as I start to suspect there is no easy fix I can do in code.

By the way, the site has 1000+ sounds in MP3, so any solution can't involve embedding the sounds.


q:
I find that in my daily Flex/Flash work, I do this number a lot:

//Calling a function...
MyCustomObject(container.getChildAt(i)).mySpecialFunction();

The question is - is this the best way to do this?  Should I do this:

//Calling a function
var tempItem:MyCustomObject = container.getChildAt(i) as MyCustomObject;
tempItem.mySpecialFunction();

It might be incidental but I'm just wondering if there is an "accepted" way or a preferred way to do this.  The second option seems more readable but I wonder if it takes more of a performance hit to create a new variable.  Or does it all come down to style and preference?

[A]
It generally doesn't matter.  Creating a var just creates a pointer to the object, so it's not using more memory or anything like that.
The second example is definitely more readable and debuggable and should thus be preferred.
The risk you run from creating temp vars is that you might delay or prevent garbage collection for that object.  This generally isn't a problem when it's just a local var in a function; just keep scope in mind when you're creating vars and passing them around.
For in-depth on the subject, read Grant Skinner's series on resource management in AVM2:
http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html


q:
Using a macro I have consolidated info from several workbooks into one sheet in new workbook.

In one column  I have created a named range called ColRange.  That column has numbers ranging from -350 to 500.

How do I change the color of the cells based on the value of the text in the cell.

red(0-500)
yellow(-5-0)
green(-350--5)

[A]
Assume that value is the number stored in the column then:
```
```
If value >= 0 AND value <= 500 Then
    ColRange.Interior.Color = RGB(255,0,0)
ElseIf  value >= -5 Then
    ColRange.Interior.Color = RGB(255,255,200)
Else
    ColRange.Interior.Color = RGB(0,255,0)
End If
```
```
And assuming that values greater than 500 or less than -350 is either not possible or validated by your script. Also, your ranges overlap a bit, what color should 0 be? Red or Yellow?


q:
Good morning,

I work in a small shop (only two of us) and we currently manage more .vbs scripts that we would like to (we would like to manage zero).  One of the nice things about these scripts is that it's quick to make changes (as necessary) and go back to our day jobs.

That's all nice and good until we decide that the job needs to be changed substantially, and then a PITA to develop and debug, mostly because it feels like I'm shooting pool with a baseball bat.

Is there a more DotNet-y way to do Windows Scripting Host-like stuff that people have used and like?  I'd prefer free/cheap tools, naturally.

Regards,

-Alan.

[A]
PowerShell
is the "next generation, .NET-based scripting platform" from Microsoft. I haven't looked at it in detail, but from what I've heard it's trying to combine the simplicity of Unix-style pipelines with the power of a rich object model.
Whether or not it fits in with exactly what you want to achieve is something I can't really say, of course - but it's certainly worth a look.
There are other .NET languages which are amenable to scripting - there are the dynamic languages such as
IronRuby
and
IronPython
, and also
Boo
(mostly static, but with duck-typing where you want it).


q: What are some of the techniques available to debug multi threading issues in .net environment.

[A]
Debugging and unit-testing multithreaded code is notoriously difficult, and I don't believe there are any tried and true solutions to debugging multiple threads.
However, you can make it easier to write multithreaded code by taking a few notes from functional programming languages:
Use immutable data structures:
its very easy to write multithreaded code in F#, Haskell, Erlang, OCaml, etc because data structures and values in these languages are immutable, meaning that you can't modify a variable once it has been assigned. Essentially, this means every variable is declared constant, and there are no methods like List.Add or Dictionary.Add which mutate the collection.
Immuability means that nothing can be mutated after its been declared, therefore you never have to worry about one thread mutating shared state used by another thread. Since that's the case, you don't have to use locks or mutexes in your code, and you've eliminated a whole class of threading errors related to race conditions and dead locks.
Rely on message passing to share data between process
Read these blog post:
http://www.defmacro.org/ramblings/concurrency.html
http://en.wikipedia.org/wiki/Erlang_(programming_language)#Concurrency_and_distribution_oriented_language
Erlang is a remarkable language, specifically because its concurrency model is scalable up to 1000s and 1000s of computer. Rather than giving threads access to shared state, it relies on message passing to send information from one thread to another.
Rely on channels to syncronize threads
Here is a nice video on the Newsqueak language:
http://video.google.com/videoplay?docid=810232012617965344
It describes Newsqueak's interesting approach to concurrency. It uses objects called "channels" to pipe data from one thread to another. Its easy to find C# implementations of channels.
Remember, you can learn a lot about solving problems in .NET by studying how the same problems are solved in other languages.


q:
I have an Access 2002 application which links an Oracle table via ODBC with this code:

Set HRSWsp = CreateWorkspace("CONNODBC", "", "", dbUseODBC)
Set HRSConn = HRSWsp.OpenConnection("HRSCONN", dbDriverPrompt, , "ODBC;")
DoCmd.TransferDatabase acLink, "Database ODBC", HRSConn.Connect, acTable, "SCHEMA.TABLE", "TABLE", False, True

Unfortunately, Access 2007 doesn't accept this syntax anymore, saying that ODBCDirect is no more supported (Runtime error 3847) and suggesting to use ADO instead of DAO.
Could someone please tell me how can I modify this code to satisfy Access 2007?

[A]
Try this:
```
```
Dim tbl As New ADOX.Table
Dim cat As New ADOX.Catalog

cat.ActiveConnection = _
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[x:\your_access_db.mdb];Jet OLEDB:Engine Type=4"

tbl.NAME = "[Access_table_name]"

Set tbl.ParentCatalog = cat

tbl.Properties("Jet OLEDB:Create Link") = True
tbl.Properties("Jet OLEDB:Link Provider String") = "ODBC;Driver={Microsoft ODBC For Oracle};Server=OracleServerName;Uid=[user];Pwd=[password];"
tbl.Properties("Jet OLEDB:Cache Link Name/Password") = True
tbl.Properties("Jet OLEDB:Remote Table Name") = "[Oracle_Schema].[Table]"

cat.Tables.Append tbl
cat.ActiveConnection.Close
```
```
Replace text in brackets (
```
[]
```
) with your info.


q:
I would like to modify an MSI installer (created through WiX) to delete an entire directory on uninstall.

I understand the RemoveFile and RemoveFolder options in WiX, but these are not robust enough to recursively delete an entire folder that has content created after the installation.

I noticed the similar Stack Overflow question Removing files when uninstalling WiX, but I was wondering if this could be done more simply using a call to a batch script to delete the folder.

This is my first time using WiX, and I'm still getting the hang of custom actions. What would be a basic example of a custom action that will run a batch script on uninstall?

[A]
You can do this with a custom action.  You can add a refrence to your custom action under
```
<InstallExecuteSequence>
```
:
```
```
<InstallExecuteSequence>
...
  <Custom Action="FileCleaner" After='InstallFinalize'>
          Installed AND NOT UPGRADINGPRODUCTCODE</Custom>
```
```
Then you will also have to define your Action under
```
<Product>
```
:
```
```
<Product>
...
  <CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE'
                ExeCommand='' Return='asyncNoWait'  />
```
```
Where FileCleanerEXE is a binary (in my case a little c++ program that does the custom action) which is also defined under
```
<Product>
```
:
```
```
<Product>
...
  <Binary Id="FileCleanerEXE" SourceFile="path\to\fileCleaner.exe" />
```
```
The real trick to this is the
```
Installed AND NOT UPGRADINGPRODUCTCODE
```
condition on the Custom Action, with out that your action will get run on every upgrade (since an upgrade is really an uninstall then reinstall). Which if you are deleting files is probably not want you want during upgrading.
On a side note: I recommend going through the trouble of using something like C++ program to do the action, instead of a batch script because of the power and control it provides -- and you can prevent the "cmd prompt" window from flashing while your installer runs.


q:
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.

How can I do this?

[A]
See the
locale
module.
This does currency (and date) formatting.
```
```
>>> import locale
>>> locale.setlocale( locale.LC_ALL, '' )
'English_United States.1252'
>>> locale.currency( 188518982.18 )
'$188518982.18'
>>> locale.currency( 188518982.18, grouping=True )
'$188,518,982.18'
```
```


q:
I need to disable PUT, DELETE & TRACE HTTP requests on my Application Server, Apache Tomcat 6.0.

All other sources, i have searched till now, have directed me towards the limit parameter in httpd.conf, Hence I'd put it before-hand that I am not using Apache Web Server, and requests are directly being handled by Tomcat, and so there is no httpd.conf in picture.

Please suggest how should I do it on Tomcat?

[A]
Inside your WEBINF, add you can add a security constraint:
```
```
<security-constraint>
     <web-resource-collection>
          <web-resource-name>Forbidden</web-resource-name>
          <url-pattern>/blah/*</url-pattern>
          <http-method>PUT</http-method>
          <http-method>DELETE</http-method>
          <http-method>TRACE</http-method>
     </web-resource-collection>
     <auth-constraint>
          <role-name>empty_role</role-name>
     </auth-constraint>
</security-constraint>
```
```
Alternatively, you can do these two things:
In server.xml, edit the
```
<connector>
```
element, add an attribute:
```
allowTrace="false"
```
.  Then edit the DefaultServlet: $CATALINA_HOME/conf/web.xml
```
```
<servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>
        org.apache.catalina.servlets.DefaultServlet
    </servlet-class>
    <!-- blah blah blah -->
    <init-param>
        <param-name>readonly</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>
```
```


q:
I'm sure you've all seen them.  Line of Business UIs that have logic such as: "When ComboA is selected, query for values based on that selection, and populate Textbox B", or "When ButtonC is pressed, disable Textboxes C and D", and on and on ... it gets particularly bad when you can have multiple permutations of the logic above.

If presented with the chance to redesign one of these lovely screens, how would you approach it?  would you put a wizard in front of the UI? would you keep the single screen paradigm but use some other pattern to make the logic of the UI state maintainable? what would be the process you use to determine how this would ideally be presented and implemented?

Not that I think this should matter for the responses, but I am currently presented with just this "opportunity", and it's an ASP.NET web page that uses javascript to respond to the user's choices, disable controls, and make ajax calls for additional data.

[A]
Start with the KISS principle, and work from there. Don't over-engineer the solution, and try to think about the problem from the user's POV. Your first impression of what would make a good layout is probably close to what you should be building, as a good UI is intuitive.
That being said, single screen versus multiple screens, JavaScript or AJAX, it doesn't really matter. If it looks good, is easy to understand, and behind the scenes, is well commented and written with clear code, it works. It should be maintainable, so aim for modular code blocks with clear functionality.


q:
What happens in the memory when a class instantiates the following object?

public class SomeObject{

    private String strSomeProperty;

    public SomeObject(String strSomeProperty){
        this.strSomeProperty = strSomeProperty;
    }
    public void setSomeProperty(String strSomeProperty){
        this.strSomeProperty = strSomeProperty;
    }
    public String getSomeProperty(){
        return this.strSomeProperty;
    }
}

In class SomeClass1:

SomeObject so1 = new SomeObject("some property value");

In class SomeClass2:

SomeObject so2 = new SomeObject("another property value");

How is memory allocated to the newly instantiated object and its properties?

[A]
Let's step through it:
```
```
SomeObject so1 = new SomeObject("some property value");
```
```
... is actually more complicated than it looks, because you're creating a new String. It might be easier to think of as:
```
```
String tmp = new String("some property value");
SomeObject so1 = new SomeObject(tmp);
// Not that you would normally write it in this way.
```
```
(To be absolutely accurate - these are not really equivalent. In the original the 'new String' is created at compile time and is part of the .class image. You can think of this as a performance hack.)
So, first the JVM allocates space for the String. You typically don't know or care about the internals of the String implementation, so just take it on trust that a chunk of memory is being used to represent "some property value". Also, you have some memory temporarily allocated containing a reference to the String. In the second form, it's explicitly called
```
tmp
```
; in your original form Java handles it without naming it.
Next the JVM allocates space for a new SomeObject. That's a bit of space for Java's internal bookkeeping, and space for each of the object's fields. In this case, there's just one field,
```
strSomeProperty
```
.
Bear in mind that
```
strSomeProperty
```
is just a reference to a String. For now, it'll be initialised to null.
Next, the constructor is executed.
```
```
this.strSomeProperty = strSomeProperty;
```
```
All this does is copy the
reference
to the String, into your
```
strSomeProperty
```
field.
Finally, space is allocated for the object reference
```
so1
```
. This is set with a reference to the SomeObject.
```
so2
```
works in exactly the same way.


q:
I wish to execute a javascript function after asp.net postback with out using ajax.

I've tried the following in my even method with no luck:

Page.ClientScript.RegisterStartupScript(GetType(), "ShowPopup", "showCheckOutPopIn('Livraison',556);");

[A]
I don't remember offhand what is the exact syntax/usage for the Page.ClientScript stuff ... that looks like it should work offhand.  But if push comes to shove, just have a simple user control that you can enable/disable dynamically that will write out a javascript method in script blocks after the postback.  When the page loads, this script execute whatever functionality you wish to execute.
of course, the question is then, what is it that this javascript should do that you couldn't just do on the serverside via some property or other setting that would reflect in the markup?


q:
I know python functions are virtual by default. Let's say I have this:

class Foo:
    def __init__(self, args):
        do some stuff
    def goo():
        print "You can overload me"
    def roo():
        print "You cannot overload me"

I don't want them to be able to do this:

class Aoo(Foo):
    def roo():
        print "I don't want you to be able to do this"

Is there a way to prevent users from overloading roo()?

[A]
Since Python has monkey patching, not only can you not make anything "private".  Even if you could, someone could still monkeypatch in a new version of the method function.
You can use this kind of name as a "don't go near" warning.
```
```
class Foo( object ):
    def _roo( self ):
       """Change this at your own risk."""
```
```
That's the usual approach.  Everyone can read your source.  They were warned.  If they boldly go where they were warned not to go, they get what they deserve.  It doesn't work and you can't help them.
You can try to make this intentionally obcure with inner classes and "hidden" implementation modules that are called by the "private" methods.  But... everyone has your source.  You can't
prevent
anything.  You can only advise people of the consequences of their actions.