q:
When you have a derived class, is there an simpler way to refer to a variable from a method other than:

BaseClass::variable

EDIT

As it so happens, I found a page that explained this issue using functions instead:
Template-Derived-Classes Errors. Apparently it makes a difference when using templates classes.

[A]
If the base class member variable is protected or public than you can just refer to it by name in any member function of the derived class.  If it is private to the base class the compiler will not let the derived class access it at all.  Example:
```
```
class Base
{
protected:
  int a;

private:
  int b;
};

class Derived : public Base
{
  void foo()
  {
    a = 5;  // works
    b = 10; // error!
  }
};
```
```
There is also something to be said for keeping all member variables private, and providing getters and setters as needed.
Also, beware of "hiding" data members:
```
```
class Base
{
public:
  int a;
};

class Derived : public Base
{
public:
  int a;
};
```
```
This will create two variables named
```
a
```
: one in
```
Base
```
, one in
```
Derived
```
, and it will likely lead to confusion and bugs.


q:
From the MSDN documentation:

"Synchronized supports multiple writing threads, provided that no threads are reading the Hashtable. The synchronized wrapper does not provide thread-safe access in the case of one or more readers and one or more writers."

Source:
http://msdn.microsoft.com/en-us/library/system.collections.hashtable.synchronized.aspx

It sounds like I still have to use locks anyways, so my question is why would we use Hashtable.Synchronized at all?

[A]
For the same reason there are different levels of DB transaction.  You may care that writes are guaranteed, but not mind reading stale/possibly bad data.
EDIT
I note that their specific example is an Enumerator.  They can't handle this case in their wrapper, because if you break from the enumeration early, the wrapper class would have no way to know that it can release its lock.
Think instead of the case of a counter.  Multiple threads can increase a value in the table, and you want to display the value of the count.  It doesn't matter if you display 1,200,453 and the count is actually 1,200,454 - you just need it close.  However, you don't want the data to be corrupt.  This is a case where thread-safety is important for writes, but not reads.

s: huggingface

c: devops

d: intermediate


q:
Is there some way to get a value from the last inserted row?

I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table.

I am using Java with a JDBC and PostgreSQL.

[A]
The sequences in postgresql are transaction safe. So you can use the
```
```
currval(sequence)
```
```
Quote:
currval
Return the value most recently obtained by nextval for this sequence
    in the current session. (An error is
    reported if nextval has never been
    called for this sequence in this
    session.) Notice that because this is
    returning a session-local value, it
    gives a predictable answer even if
    other sessions are executing nextval
    meanwhile.


q:
I have a rich-text editor on my site that I'm trying to protect against XSS attacks. I think I have pretty much everything handled, but I'm still unsure about what to do with images. Right now I'm using the following regex to validate image URLs, which I'm assuming will block inline javascript XSS attacks:

"https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+"

What I'm not sure of is how open this leaves me to XSS attacks from the remote image. Is linking to an external image a serious security threat?

The only thing I can think of is that the URL entered references a resource that returns "text/javascript" as its MIME type instead of some sort of image, and that javascript is then executed.

Is that possible? Is there any other security threat I should consider?

[A] Another thing to worry about is that you can easily embed PHP code inside an image and upload that most of the time. The only thing an attack would then have to be able to do is find a way to include the image. (Only the PHP code will get executed, the rest is just echoed). Check the MIME-type won't help you with this because the attacker can easily just upload an image with the correct first few bytes, followed by arbitrary PHP code. (The same is somewhat true for HTML and Javascript code).


q: Im just starting a project and since this project is personal I was wondering what are the advantages of using Enterprise Library? We use the version 2 for several projects in the office but im not quite sure (aside of the good practices) of the advantages of it, especially in the database component. Any advice? Thanks

[A]
For the database application block, the main advantage is that it makes it easier to produce database-agnostic code. The developer interacts mainly with generic Database and DbCommand objects, rather than eg SqlConnection, SqlCommand, etc.  Thus, switching to a different database (ie Oracle) becomes more feasible. Depending on your business needs, this could be a definite advantage.  EntLib also gently prods the developer in the direction of using DbParameter for query parameters, which reduces the risk of SQL injection attacks.
As another poster mentionned, the data app block is somewhat higher-level than the straight ADO.NET classes, so it tends to require fewer lines of code to do the same thing.
From my point of view, the data, exception and logging blocks are the most useful.  Exception and Logging together make it very easy to log exceptions (duh) to a number of places and in a number of formats.  For example, they can put the entire exception log entry, including the stack trace, in the Windows event log making it relatively easy to diagnose a problem.
One disadvantage of EntLib is that some app blocks place quite a bit of logic into configuration files.  So your logic is more spread out; some of it is in code, some in config files.  The upside is that the configuration can be modified post-build and even post-deployment.


q:
I have a DataGridView with one DataGridViewComboBoxColumn in my WinForms application. I need to drop down (open) this DataGridViewComboBoxColumn manually, let's say after a button is clicked.

The reason I need this is I have set SelectionMode to FullRowSelect and I need to click 2-3 times to open the combo box. I want to click on the combobox cell and it should drop down immediately. I want to do this with CellClick event, or is there any other way?

I am searching in Google and VS help, but I haven't found any information yet.

Can anybody help please?

[A]
I know this can't be the ideal solution but it does create a single click combo box that works within the cell.
```
```
Private Sub cell_Click(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        DataGridView1.BeginEdit(True)
        If DataGridView1.Rows(e.RowIndex).Cells(ddl.Name).Selected = True Then
            DirectCast(DataGridView1.EditingControl, DataGridViewComboBoxEditingControl).DroppedDown = True
        End If
    End Sub
```
```
where "ddl" is the combobox cell I added in the gridview.


q:
I recently introduced HTML into some RSS feeds that I publish (which up to now only had plain text, no markup), and I was wondering which method is better: use character encoding (such as htmlspecialchars) or just encapsulate everything in CDATA?

It seems to me that CDATA might be easier, but I'm unclear as to whether there might be any reasons (subtle or otherwise) for choosing one approach versus the other. (For starters, the CDATA approach would be easier to read when viewing source...)

[A]
At the risk of giving you the answer you may not want to hear: use
Atom
instead of
RSS.
Atom is nicely namespaced XML, so you can mix and match XHTML right in, without having to worry about the encoding issue you ask about.
It's pretty much supported everywhere RSS is, and because it's just vanilla Atom, it's easier to roll your own if you really don't want to use a library to manipulate it.
Atom is also a IETF standard, which RSS isn't.


q:
I've got a workspace with multiple RCP plugin projects.

We've set the target platform, so we can build against a standard set of plugins, but are not able to see source code and Javadoc for all the platform plugins.

The Windows -> Preferences -> Plug-in Development -> Target Platform -> Source Code Locations page doesn't seem to have any effect when I add the eclipse directory (it only allows you to add directories).

Copying the source jars from the eclipse directory into the target platform has a similar effect.

What am I doing wrong? How do I attach a set of Source jars to my target platform?

[A]
I can modify the target platform at runtime, using the
```
-install
```
runtime option. Keep the targetPlatform as the eclipse platform.
However, this loses a lot of the benefits of using a target platform in the first place - i.e. compile time safety.


q:
I was recently working with a DateTime object, and wrote something like this:

DateTime dt = DateTime.Now;
dt.AddDays(1);
return dt; // still today's date! WTF?

The intellisense documentation for AddDays() says it adds a day to the date, which it doesn't - it actually returns a date with a day added to it, so you have to write it like:

DateTime dt = DateTime.Now;
dt = dt.AddDays(1);
return dt; // tomorrow's date

This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.

[A]
I saw this one posted the other day, and I think it is pretty obscure, and painful for those that don't know
```
```
int x = 0;
x = x++;
return x;
```
```
As that will return 0 and not 1 as most would expect


q:
How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex?

For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?

[A]
You can create a simple rule by doing something like this:
```
```
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
    return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
```
```
And then applying this like so:
```
```
$('validatorElement').validate({
    rules : {
        amount : { greaterThanZero : true }
    }
});
```
```
Just change the contents of the 'addMethod' to validate your checkboxes.


q:
I want to filter the selectable dates on a datepicker. I basically need to filter by work days - i.e. make holidays and weekends not selectable.

I know you can specify dates using a function in the beforeShowDate: and you can also use $.datepicker.noWeekends.

Question is: can you do both?

[A]
$.datepicker.noWeekends is a pretty simple bit of code:
```
```
function (date) {
    var day = date.getDay();
    return [day > 0 && day < 6, ""];
}
```
```
Since you're going to have to write up the function for holidays, you can just include this logic in that function too.


q:
Is there anything built into Windows and the .Net framework for programmatically installing and executing applications remotely? Ie: an API for remote software deployment. I'd like to build a tool that can install services on a pool of new computers from one central admin workstation.

Update: The computers are part of an internal IT network, and the applications and services are mostly internally developed. The deployment program would be completely internal, and not sold commercially.

[A]
All of the pieces are there (copying files to a remote machine, spawning a process on a remote machine, etc.) You will be looking at a fair amount of programming to put it all together into a robust application. You will also need to make sure the clients are configured properly and safely. Naively configuring the client to allow you to do this would most likely wind up with massive security holes on your client machines. I would suggest looking at SMS or one of the many similar third party apps. At the very least even if you can't afford to use an already written app (highly recommend that you do) then you could look at their feature lists to get an idea of what sort of issues you need to be thinking about.
With the further provided information, I would ask if you are using Group Policies in your environment. If you are, then you may be able to package your application as an MSI then deploy via policy.


q:
Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance?

Thanks!

[A]
There's no such thing as "the" xpath of a node. For any given node there may well be many xpath expressions which will match it.
You can probably work up the tree to build up
an
expression which will match it, taking into account the index of particular elements etc, but it's not going to be terribly nice code.
Why do you need this? There may be a better solution.


q:
My boss is bidding on a project to convert a desktop application into one that runs online as a client-server application. The original app has a little more than a quarter of a million lines of C++ (MFC) code that's not cleanly divided between engine and front-end.

I need to come up with estimates of how long it will take and how many people would be needed for such a project. We don't have anyone on staff capable of doing this project, and we don't have any Windows machines, so we'd have to subcontract/outsource.

Alternatively, what arguments can I use to convince my boss that this project is a bad idea?

[A]
Without a clear division between the engine and the front-end, it's a bad idea. Giving over the code to a contractor or such would require a large amount of training just to understand the code, including parts that are meant to be rewritten as web apps.
You would first need to estimate how long it would take to clearly define that boundary, and then you can work out how long the rest of the project would take. That way you can train the contractor etc. on the parts that relate to the presentation tier and the API for the engine without explaining how the engine works (which should be irrelevant to the presentation components).


q:
Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate.

Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving.

In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect).

[A]
There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes).
I wrote a
tutorial
on what's going on under the hood.
You can also reference the official docs on
model inheritance
.


q: In Team Foundation Server is there a way to have work items in one project linked to other projects so they show up in the reports in both. We are thinking about keeping release engineering items in their own project and want them linked to the project they are actaully for as well. Is this possible? So for instance I would create the item under release engineering assign it to an engineer and then link it to Product X so it showed up as a work item for Project X as well.

[A]
Not out of the box as projects are discrete.  However there is nothing to stop you from writing against the API to fulfill this need, although this would take some considerable work.
Now for the good news.  If you keep your eyes
here
, you may find the answer in time.  As I see cross project reports are planned in
Rosario


q:
I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)

I realize that I could .match() substrings with a Regex, but that doesn't solve nesting /*, or having a // inside a /* */.

Ideally, I would prefer a non-naive implementation that properly handles awkward cases.

[A]
C (and C++) comments cannot be nested. Regular expressions work well:
```
```
//.*?\n|/\*.*?\*/
```
```
This requires the “Single line” flag (
```
Re.S
```
) because a C comment can span multiple lines.
```
```
def stripcomments(text):
    return re.sub('//.*?\n|/\*.*?\*/', '', text, flags=re.S)
```
```
This code should work.
/EDIT: Notice that my above code actually makes an assumption about line endings! This code won't work on a Mac text file. However, this can be amended relatively easily:
```
```
//.*?(\r\n?|\n)|/\*.*?\*/
```
```
This regular expression should work on all text files, regardless of their line endings (covers Windows, Unix and Mac line endings).
/EDIT: MizardX and Brian (in the comments) made a valid remark about the handling of strings. I completely forgot about that because the above regex is plucked from a parsing module that has additional handling for strings. MizardX's solution should work very well but it only handles double-quoted strings.


q:
I'm looking at the following code snippet:

my @ret = <someMethod>
return (undef) if( $DB_ERROR );
return (undef) unless ($#ret >= 0);

Does $# just give you a count of elements in a array?

[A]
```
$#arrayname
```
gives you the index of the last element, so if array
```
@ret
```
has 2 elements then
```
$#ret
```
is 1.
And, as noted by Barry Brown, an empty array gives -1.
To get the length you can use the array in scalar context:
```
```
print scalar @ret;
```
```


q:
I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now.

<body>
  $("body").addClass("active");
  ...
</body>

Thanks,
Steve

[A]
If the element doesn't exist in the DOM, the search will fail to find it and the action won't be applied.   If you can't do it in the $(document).ready() function, you might want to try putting the code after the element being referenced.  I believe this will work.
```
```

```
```
If you need to add the class to the body, I would definitely use $(document).ready().


q:
How do I get a list of domain user accounts with win32 api?

In particular, I can't get this list when the computer is not the domain controller.  Instead it is a member of the domain.


q:
I have a string that I need to convert to the equivalent array of bytes in .NET.

This ought to be easy, but I am having a brain cramp.

[A]
You need to use an encoding
(
```
System.Text.Encoding
```
) to tell .NET what you expect as the output. For example, in
UTF-16 (=
```
System.Text.Encoding.Unicode
```
)
:
```
```
var result = System.Text.Encoding.Unicode.GetBytes(text);
```
```


q:
For this xml (in a SQL 2005 XML column):

<doc>
 <a>1</a>
 <b ba="1" bb="2" bc="3" />
 <c bd="3"/>
<doc>

I'd like to be able to retrieve the names of the attributes (ba, bb, bc, bd) rather than the values inside SQL Server 2005. Well, XPath certainly allows this with name() but SQL doesn't support that. This is my chief complaint with using XML in SQL; you have to figure out which parts of the XML/Xpath/XQuery spec are in there.

The only way I can think of to do this is to build a CLR proc that loads the XML into an XML Document (iirc) and runs the XPath to extract the names of the nodes. I'm open to suggestions here.

[A]
```
```
DECLARE @xml as xml
DECLARE @path as varchar(max)
DECLARE @index int, @count int

SET @xml =
'<doc>
 1

 <c bd="3"/>
</doc>'

SELECT @index = 1

SET @count = @xml.query('count(/doc/b/@*)').value('.','int')

WHILE @index <= @count
BEGIN
    SELECT  @xml.value('local-name((/doc/b/@*[sql:variable("@index")])[1])', 'varchar(max)')
    SET @index = @index + 1
END
```
```
for element 'b'
it returns
ba
bb
bc
You can build a loop to get attributes for each element in the xml.
BTW
The XML in your sample should be closed at closing doc tag.


q: I'm also interested in other Symbian SDKs that allow to set their emulator's IMEI.

[A]
I have never actually tried that but here's my best guess:
The emulator doesn't have a proper telephony implementation unless:
you link it to an actual phone over infrared/usb/serial. In which case the emulator telephony component will need configuration to use AT commands to pilot the phone (even if the phone isn't a Symbian phone). This allows you to make phone calls, send and receive SMS/MMS but certainly not change the IMEI.
you use the SIMTSY module. This is a component that uses configuration files to simulate telephony events. It can pretend to send SMS/MMS, pretend you are receiving a phone call...none of that actually creates any kind of network traffic, you understand. I assume the IMEI is in the configuration file but I don't expect you can properly change it  without restarting the emulator. I have never seen SIMTSY used outside of Symbian itself so I don't know whether it is available to third-party developer. It should be open-sourced with the rest of the operating system within the next 2 years, though.
There is also the possibility that the way the SDK itself was built disabled most of the telephony framework for the emulator, using build-time macro. You should check
http://forum.nokia.com


q:
What is the best way to manage a database connection in a Java servlet?

Currently, I simply open a connection in the init() function, and then close it in destroy().

However, I am concerned that "permanently" holding onto a database connection could be a bad thing.

Is this the correct way to handle this?  If not, what are some better options?

edit: to give a bit more clarification: I have tried simply opening/closing a new connection for each request, but with testing I've seen performance issues due to creating too many connections.

Is there any value in sharing a connection over multiple requests?   The requests for this application are almost all "read-only" and come fairly rapidly (although the data requested is fairly small).

[A]
You should only hold a database connection open for as long as you need it, which dependent on what you're doing is probably within the scope of your
```
doGet/doPost
```
methods.


q:
As title.  I didn't find one via google, at any rate.

Update: thanks for the links from the two answers; this is very useful, but not what I was after - I am curious to see whether it is possible to query an IRepository backed by memcached (or some other distributed cache), backed by a RDBMS.  I've really no idea how that might work in practise; I don't know very much about the internals of either distributed caches or LINQ providers.

I'm maybe envisaging something like the cache LINQ provider generating cache-keys based on the query automatically (where query could be Expression> or some kind of Specification pattern implementation), and basically can be plumped down inbetween my app and my DB.  Does that sound useful?

[A]
If you don't mind throwing
NHibernate
between them, you can use
LINQ to NHibernate
to query entities which
can be set
to use
memcached
as their cache.


q:
I think the title pretty much says it all... I'm looking to implement an interface similar to the standard OS X sidebar used in all the above mentioned programs, and I'm wondering if anybody has any thoughts as to the easiest way to do it, namely about what view to use for the left hand selection pane. Really I don't think I even need the hierarchical component as seen in the apple apps, I just need a good looking flat list of choices which determine what's shown in the right hand pane.

The obvious start is a vertical split layout view, but beyond that I'm not entirely sure where to go. A collection view with only one column or something like that?

[A]
I've done a few applications that use a similar setup.
I generally use an NSSplitView, with a single column NSTableView in the left pane.  Don't forget to disable the headers, and make it display as a "Source View" style.
If you want the disclosure triangles, then you'll want to use NSOutlineView instead of NSTableView, but at least for the first go, I'd stick to a simple NSTableView.
A pattern I also use is to make the NSTableView slightly shorter than the NSSplitView, and have buttons at the bottom (add, delete, etc).  I've usually built the program around Core Data, so it's easy to hook up these to methods to create/delete objects, and then bind the NSTableView to the array of objects.


q:
My HTML is as follows:

<ul id="nav">
    <li><a href="./">Home</a></li>
    <li><a href="/About">About</a></li>
    <li><a href="/Contact">Contact</a></li>
</ul>

And my css:

#nav {
    display: inline;
}

However the whitespace between the li's shows up. I can remove the whitespace by collapsing them like so:

<ul id="nav">
    <li><a href="./">Home</a></li><li><a href="/About">About</a></li><li><a href="/Contact">Contact</a></li>
</ul>

But this is being maintained largely by hand and I was wondering if there was a cleaner way of doing it.

[A]
Several options here, first I'll give you my normal practice when creating inline lists:
```
```

Home

Home

Home

```
```
Then the CSS to make it function as you intend:
```
```
#navigation li
  {
    display: inline;
    list-style: none;
  }
#navigation li a, #navigation li a:link, #navigation li a:visited
  {
    display: block;
    padding: 2px 5px 2px 5px;
    float: left;
    margin: 0 5px 0 0;
  }
```
```
Obviously I left out the hover and active sets, but this creates a nice block level navigation, and is a very common method for doing this while still keeping with standards. /* remember to tweak to your liking, add color to the background, et cetera */
If you would like to keep it just with text and just inline, no block elements I believe you'd want to add:
```
```
margin: 0 5px 0 0; /* that's, top 0, right 5px, bottom 0, left 0 */
```
```
Realizing you would like to REMOVE the whitespace, just adjust the margins/padding accordingly.


q:
I want to write a program that would print every combination of a set of variables to a text file, creating a word list. Each answer should be written on a separate line and write all of the results for 1 digit, 2 digits, and 3 digits to a single text file.

Is there a simple way I can write a python program that can accomplish this? Here is an example of the output I am expecting when printing all the binary number combinations possible for 1, 2, and 3 digits:

Output:
0
1

00
01
10
11

000
001
010
011
100
101
110
111

[A]
It shouldn't be too hard in most languages.  Does the following pseudo-code help?
```
```
for(int i=0; i < 2^digits; i++)
{
     WriteLine(ToBinaryString(i));
}
```
```


q:
I just started creating my data-access layer using LinqToSql. Everybody is talking about the cool syntax and I really like Linq in general.

But when I saw how your classes get generated if you drag some tables on the LinqContext I was amazed: So much code which nobody would need?!

So I looked how other people used LinqToSql, for example Rob Connery at his StoreFront Demo.

As I don't like the way that all this code is generated I created my domain layer by hand and used the generated classes as reference. With that solution I'm fine, as I can use the features provided by Linq (dereferred execution, lazy loading, ...) and my domain layer is quite easy to understand.

How are you using LinqToSql?

[A]
The created classes are not as heavy as it seems. Of course it takes quite a few lines of code, but all in all it is as lightweight as it can be for the features it's providing.
I used to create my own tables, too, but now instead I just use the LINQtoSQL DataContext. Why? Creating is simpler, the features are better, interoperability works, it is probably even faster than my own stuff (not in every aspect. Usually my own stuff was extremely fast in one thing, but the generic stuff was faster in everything else).
But the most important part: it is easier to bring new developers into the LINQ stuff than into my own. There are tutorials, example codes, documentation, everything, which I'd have to create for my code by myself. Same with using my stuff with other technology, like WCF or data binding. There are a lot of pitfalls to be taken care of.
I learned not to develop myself into a corner the hard way, it looks fast and easy at the start, is a lot more fun than learning how to use the libs, but is a real pain in the a after a few months down the road, usually even for myself.
After some time the novelty of creating my own data containers wears off, and I noticed the pain connected to adding a feature. A feature I would have had for free, if I had used the provided classes.
Next thing I had to explain my code to some other programmer. Had I used the provided classes, I could have pointed him to some web site to learn about the stuff. But for my classes, I had to train him himself, which took a long time and made it hard to get new people on a project.


q: I'm a little unsure how the open source licensing stuff works.  If I were to choose a particular open source license, what do you actually have to do to make it applicable to your software?  I would imagine it would be a little more involved than just 'stating' that you're releasing your software under LGPL.  And how does this 'contract' bind legally to your software?

[A]
It's as simple as deciding to license your software under a particular license.  This is not technically contract law, but copyright law.  As the owner/licenser of your intellectual property (the source and binaries) you may license its distribution anyway you see fit.  Providing a clear disclaimer as to the recipients rights under the license is all that is necessary.  Without a license, whether closed or open, no one has a right to distribute your copyrighted work.  The purpose of all licenses is to grant some of your rights to other parties.
See here
for more information.  Or for perhaps too much information, check out O'Reilly's
Understanding Open Source and Free Software Licensing
.
~ William Riley-Land


q: What are some good jQuery Resources along with some gotchas when using it with ASP.Net?

[A]
ASP.Net's autogenerated id's make using jQuery's selector syntax somewhat difficult.
Two easy ways around this problem:
Search for objects using css class instead of id
You can weed out the uniqueid garbage with:
```
$('[id$=myid]')
```


q: Is there anyway to automatically run javascript:window.print() when the page finishes loading?

[A]
```
<body onload="window.print()">
```
or
```
window.onload = function() { window.print(); }
```


q:
Our testers are in the process of evaluating Visual Studio Team System 2008 Test Edition. As they are unfamiliar with the use of Visual Studio, I would like to give them as much help as I can.

I have had a look on Amazon for books on the Test edition of VS.Net, but there is only one VS.Net 2005 test edition book.

Does anyone know of any good books, or online training resources with a particular focus on the features of the Test Edition of Visual Studio Team System 2008?

[A]
For someone evaluating features who isn't that familiar with Visual Studio, I'd recommend the videos from a few places:
"How Do I?" Videos for Team System
ASP.net's Learn section
Video tutorials at TeamSystemRocks.com
Plenty of videos between those sites on the various VSTS Test Edition features.  Note that many are about VS2005, but the fundamental concepts don't change when moving to 2008.
Once they get the basic features, here's a summary of
What's New in VS2008 Test Edition
.
See also:
VSTS 2008 Test Edition Home
(BTW, there's a link to a trial VPC w/TFS & VSTS Suite on the right-hand side)
Visual Studio 2008 Training Kit
- Not a lot on VSTS in here, but there are a few demos and resources that touch on the Test features, and it's a good general resource to have, anyway.


q: If I import a library to use a method, would it be worth it? Does importing take up a lot of memory?

[A]
Importing such a module is not likely to cost that much memory that you should refrain from it, though in this case probably a simple hash would be just as good. Something like
```
```
my %number_for = (
    jan => 1,
    feb => 2,
#etc...
);
#...
do_something_with($number_for{$month})
```
```


q:
I have the Profile, CCK, and Views2 modules installed on a Drupal 6 site.  I added a string field to the user profile.  I can filter easily on preset values, thru the Views GUI builder, really nicely.  However, I'd like the filter criteria to be dynamically set based on other environment variables (namely the $_SERVER['SERVER_NAME']).

Is there a basic 'How-to-write-a-custom-drupal-views-filter' somewhere out there?  I've been looking thru the documentation, but it's not obvious to my simple mind on how to do it.

[A]
There is the possibility, having looked at the sort of filters installed for my own site, that filters have to be based on some database field, in which case what you're trying to achieve is not possible.  It appears that the filters provide the WHERE clause to the generated SQL query.
Having said all that, if you want to pursue it further, your best bet is to start with a module that already provides filters for Views.  There are filters provided with Views for the Node module; alternatively, you could look at the
audio module
which also provides some filters.  Additionally, posting to the Drupal forums or support list may turn up another module that will allow you to achieve what you're attempting.


q:
I have a few questions about whether or not it would be best to not use indexing.

BACKGROUND:
My records have a timestamp attribute, and the records will be inserted in order of their timestamps (i.e., inserted chronologically).

QUESTIONS:

If I DON'T use indexing is it typical for the database to insert the records in the order that they were inserted?

If answer to #1 is yes, when I do a "SELECT .. WHERE timestamp > X" type query will the database be efficient at it, or will it have to go through every single record since it isn't indexed?  I would assume if there were no index, the database would not "know" that the records were inserted in sorted order and could not, therefore, make use of sorted property of the database.

I assume a clustered index would be best for these types of records & their inserts.

Please let me know what you guys think.

Thanks,
jbu

[A]
In my experience, yes, the database will insert stuff in the chronological order, especially if you never delete anything.  However, it is not guaranteed, and it's a really bad idea to try to rely on behaviour that is not guaranteed.
Also, the query planner isn't going to know this fact, so any query you do without an index will cause a full table scan.  Whether that's slower than an indexed query will depend a lot on what sort of data you have, and what percentage of it comes after the "X" in your query.


q:
$fp_src=fopen('file','r');

$filter = stream_filter_prepend($fp_src, 'convert.iconv.ISO-8859-1/UTF-8');

while(fread($fp_src,4096)){
    ++$count;
    if($count%1000==0) print ftell($fp_src)."\n";
}

When I run this the script ends up consuming ~ 200 MB of RAM after going through just 35MB of the file.

Running it without the stream_filter zips right through with a constant memory footprint of ~10 MB.

What gives?

[A]
From what I'm reading
here
, you are not implementing
```
stream_filter_prepend()
```
correctly, although there could be something I misunderstand about the process.
Als, I'm not totally sure, but I'm willing to bet that this has more to do with the fact that iconv is an expensive process, and less to do with the fact that you're using it as stream filter.
Good luck.


q:
if(!eregi("^([0-9a-z_\[\]\*\- ])+$", $subuser))
    $form->setError($field, "* Username not alphanumeric");

Can anybody tell me why it is not allowing characters such as - and *?

if(!eregi("^([0-9a-z])+$", $subuser))
    $form->setError($field, "* Username not alphanumeric");

That is the original piece of code. A friend changed it to the top piece and it will allow a-z and 0-9 but it wont allow the other characters I need it to. Can anyone help me?

Thanks in advance.

[A]
Your regex uses PCRE syntax, so you have to use preg_match() instead of eregi().
Try this code instead:
```
```
else if (!preg_match("/^([0-9a-z_\[\]* -])+$/i", $subuser)) {
$form->setError($field, "* Username not alphanumeric");
}
```
```


q:
I am writing PHP code where I want to pass the session id myself using POST. I don't want a cookie to store the session, as it should get lost when the user gets out of the POST cycle.

PHP automatically sets the cookie where available. I learned it is possible to change this behaviour by setting session.use_cookies to 0 in php.ini. Unfortunately, I don't have access to that file and I also wouldn't want to break the behaviour of other scripts running on the same server.

Is there a way to disable or void the session cookie inside the PHP script?

EDIT: As the proposed solutions don't work for me, I used $_SESSION = array() at positions in the code where I found the session should be invalidated.

[A]
Use
ini_set()
:
```
```
ini_set('session.use_cookies', '0');
```
```
Or in your php.ini file:
```
```
session.use_cookies = 0
```
```


q:
If I had the following select, and did not know the value to use to select an item in advance like in this question or the index of the item I wanted selected, how could I select one of the options with jQuery if I did know the text value like Option C?

<select id='list'>
<option value='45'>Option A</option>
<option value='23'>Option B</option>
<option value='17'>Option C</option>
</select>

[A]
```
```
var option;
$('#list option').each(function() {
    if($(this).text() == 'Option C') {
        option = this;
        return false;
    }
});
```
```


q:
In a database prototype, I have a set of fields (like name, description, status) that are required in multiple, functionally different tables.

These fields always have the same end user functionality for labeling, display, search, filtering etc. They are not part of a foreign key constraint. How should this be modeled?

I can think of the following variants:

Each table gets all these attributes. In this case, how would you name them? The same, in each table, or with a table name prefix (like usrName, prodName)

Move them into a table Attributes, add a foreign key to the "core" tables, referencing Attributes.PK

As above, but instead of a foreign key, use the Attributes.PK as PK in the respective core table as well.

[A]
Normalisation is often best practice in any relational database (within reason).
If you have fields like state (meaning the state within a country), then a reference table like "State" with (id, short_name, long_name etc...) might be the way to go, then each record that references a state only need a state_id column which, as you did mention, is a reference to a record in the State table.
However, in some instances normalisation of all data is not necessarily required as it just complicates things, but it should be obvious where to do it and where not to do it.
Hope this helps.


q:
In VB6 you can do this:

Dim a As Variant
a = Array(1, 2, 3)

Can you do a similar thing in VB.NET with specific types, like so?:

Dim a() As Integer
a = Array(1, 2, 3)


q:
I'm trying to parse an international datetime string similar to:

24-okt-08 21:09:06 CEST

So far I've got something like:

CultureInfo culture = CultureInfo.CreateSpecificCulture("nl-BE");
DateTime dt = DateTime.ParseExact("24-okt-08 21:09:06 CEST",
    "dd-MMM-yy HH:mm:ss ...", culture);

The problem is what should I use for the '...' in the format string? Looking at the Custom Date and Time Format String MSDN page doesn't seem to list a format string for parsing timezones in PST/CEST/GMT/UTC form.

[A]
AFAIK the time zone abbreviations are not recognized. However if you replace the abbreviation with the time zone offset, it will be OK. E.g.:
```
```
DateTime dt1 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+2"), "dd-MMM-yy HH:mm:ss z", culture);
DateTime dt2 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02"), "dd-MMM-yy HH:mm:ss zz", culture);
DateTime dt3 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02:00"), "dd-MMM-yy HH:mm:ss zzz", culture);
```
```


q:
There have been a couple of questions that sort of dealt with this but not covering my exact question so here we go.

For site settings, if these are stored in a database do you:

retrieve them from the db every time someone makes a request

store them in a session variable on login

???????

For user specific settings do I do the same as site settings??

Any guidance/best practice would be greatly appreciated.

Cheers

[A]
Generally I would put site settings in the web.config file, unless you are building an application that has multiple sites and gets changed by the application itself frequently, it usually wouldn't make sense to put it in the database at first.
For user specific settings I would look into starting with the default asp.net Profile Provider which will store the settings in the database and manage the retrival of the user settings once per Request and save the updates to the end to minimize the number of DB calls. Once you start to hit performance problems you can consider extending the profile provider for caching and/or your specific needs.


q:
I am writing a desktop application written in Swing developed using Java 1.5. Some of the users seem to be using Mac, but I am interested in Java 6's scripting feature (Java 6 ships with Rhino). Java 6, although it came out almost 2 years ago, doesn't seem to be widely in use. I also hear Apple ships Java 6 only for Intel 64 Macs only. Is Java 1.5 the last Java that runs everywhere?

Is Java 6 ready for end-user desktop application now? If not now, when?

Edit:
Don't get too hung up on the fact that I am using Swing. I would like to know when Java 6 can be considered ready for prime time, not the choice of UI library.

[A] Java 6 is not officially out for all Macs yet.  If you want to be more widely accepted, go with 1.5 (5).


q:
What's the difference between the two and when should I use each:

<person>
     <firstname>Joe</firstname>
     <lastname>Plumber</lastname>
</person>

versus

<person firstname="Joe" lastname="Plumber" />

Thanks

[A]
In my company, we would favour the 2nd approach.
The way we think about it is that "firstname" and "lastname" are
attributes
of the "person" node, rather than
sub-fields
of the "person" node.  It's a subtle difference.
In my opinion the 2nd approach is more concise, and readability/maintainability is significantly improved, which is very important.
Of course it would depend on your application.  I don't think there is a blanket rule that covers all scenarios.


q:
Has anyone had experience with MySource Matrix as a content management system? If so, thoughts/opinions/comments?

Thanks in advance.

[A]
Absolutely excellent. It takes little while to get used to how it does things with its asset structure, but it is really flexible and powerful. Simple edit interfaces are great too.
Make sure you give it enough hardware. If you want dynamic content without caching you need heaps of grunt to make it hum.


q:
I'm trying to use XPath to parse an XML document. One of my NSXMLElement's looks like the following, hypothetically speaking:

<foo bar="yummy">

I'm trying to get the value for the attribute bar, however any interpretation of code I use, gives me back bar="woo", which means I need to do further string processing in order to obtain access to woo and woo alone.

Essentially I'm doing something like

NSArray *nodes = [xmlDoc nodesForXPath:@"foo/@bar" error:&error];
xmlElement = [nodes objectAtIndex:0];

Is there anyway to write the code above to just give me yummy, versus bar="yummy" so I can relieve myself of parsing the string?

Thanks.

Assuming TouchXML is being used, is there still anyway to obtain similar results? As in grabbing just the value for the attribute, without the attribute="value"? That results in then further having to parse the string to get the value out.

[A]
If you're trying to use the NSXMLDocument class on an iPhone, you're going to be sorely disappointed, because this class (and related NSXMLNode, NSXMLElement, etc classes) are not available on the phone (they ARE available in the Simulator, which can be confusing).
Take a look at libxml2 to do XML parsing on the phone. There are several free frameworks (I believe TouchXML is a good one) for doing this.
That being said, if you want to run this code on a Mac, you can use the NSXMLElement method
```
-attributeForName:
```
to pull out just the attribute you want.


q:
Say I want to get the HTML of

http://www.google.com

as a String using some built-in classes of the Cocoa Touch framework.

What is the least amount of code I need to write?

I've gotten this far, but can't figure out how to progress. There must be an easier way.

CFHTTPMessageRef req;
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
req = CFHTTPMessageCreateRequest(kCFAllocatorDefault,
                                 CFSTR("GET"),
                                 (CFURLRef)url,
                                 kCFHTTPVersion1_1);

[A]
The
quickest
way is to use NSString's
```
+stringWithContentsOfURL:
```
method. However, this is a modal call, and your application will be non-responsive while it runs. You can either move it to a background thread, or use the NSURLConnection class to make a proper, asynchronous request.


q:
I'm investigating SUDS as a SOAP client for python.  I want to inspect the methods available from a specified service, and the types required by a specified method.

The aim is to generate a user interface, allowing users to select a method, then fill in values in a dynamically generated form.

I can get some information on a particular method, but am unsure how to parse it:

client = Client(url)
method = client.sd.service.methods['MyMethod']

I am unable to programmaticaly  figure out what object type I need to create to be able to call the service

obj = client.factory.create('?')

res = client.service.MyMethod(obj, soapheaders=authen)

Does anyone have some sample code?

[A]
According to
```
suds
```
documentation
, you can inspect
```
service
```
object with
```
__str()__
```
. So the following gets a list of methods and complex types:
```
```
from suds.client import Client;

url = 'http://www.webservicex.net/WeatherForecast.asmx?WSDL'
client = Client(url)

temp = str(client);
```
```
The code above produces following result (contents of
```
temp
```
):
```
```
Suds ( https://fedorahosted.org/suds/ )  version: 0.3.4 (beta)  build: R418-20081208

Service ( WeatherForecast ) tns="http://www.webservicex.net"
   Prefixes (1)
      ns0 = "http://www.webservicex.net"
   Ports (2):
      (WeatherForecastSoap)
         Methods (2):
            GetWeatherByPlaceName(xs:string PlaceName, )
            GetWeatherByZipCode(xs:string ZipCode, )
         Types (3):
            ArrayOfWeatherData
            WeatherData
            WeatherForecasts
      (WeatherForecastSoap12)
         Methods (2):
            GetWeatherByPlaceName(xs:string PlaceName, )
            GetWeatherByZipCode(xs:string ZipCode, )
         Types (3):
            ArrayOfWeatherData
            WeatherData
            WeatherForecasts
```
```
This would be much easier to parse. Also every method is listed with their parameters along with their types. You could, probably, even use just regular expression to extract information you need.


q:
How do I alternate HTML table row colors using JSP?

My CSS looks something like:

tr.odd {background-color: #EEDDEE}
tr.even {background-color: #EEEEDD}

I want to use <c:forEach> to iterate over a collection.

<c:forEach items="${element}" var="myCollection">
  <tr>
    <td><c:out value="${element.field}"/></td>
    ...
  </tr>
</c:forEach>

I need an int count variable or boolean odd/even variable to track the row. Then my <tr> tag would look something like:

<tr class="odd or even depending on the row">

[A]
I don't use JSP, so I can't give you an answer in your language, but here's what I do (using pseudo code)
```
```
counter = 0
foreach (elements)
    counter = counter + 1
    output:
...

```
```
Personally, I name the classes "row0" and "row1", which lets you alternate between them with a simple modulus calculation, also, if you decide to have rows alternating in triples or quads (instead of pairs), you can easily extend it to
```
row2
```
,
```
row3
```
and change your output code to be
```
counter % 4
```
, etc.


q:
I would like create a web service in ASP.Net 2.0 that will supports JSON.  Is there a way to do this without WCF and .Net 3.5?  Can anyone point me to a good article or sample code?

Clarification

I need direction on what is the best method, using the .Net 2.0 framework, to communicate JSON objects to a client.  Is it possible to do this without serializing the object to a string and then deserializing on the client?

[A]
You can utilize WCF for your website, The WCF JSON endpoint can even generate javascript client proxy for the service.
Check out this post
REST / SOAP endpoints for a WCF service
A download sample can be found
http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html


q:
I have a number of generated .sql files that I want to run in succession.  I'd like to run them from a SQL statement in a query (i.e. Query Analyzer/Server Management Studio).

Is it possible to do something like this and if so what is the syntax for doing this?

I'm hoping for something like:

exec 'c:\temp\file01.sql'
exec 'c:\temp\file02.sql'

I am using SQL Server 2005 and running queries in management studio.

[A]
use
xp_cmdshell
and
sqlcmd
```
```
EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName
```
```


q:
The deceptively simple foundation of dynamic code generation within a C/C++ framework has already been covered in another question. Are there any gentle introductions into topic with code examples?

My eyes are starting to bleed staring at highly intricate open source JIT compilers when my needs are much more modest.

Are there good texts on the subject that don't assume a doctorate in computer science? I'm looking for well worn patterns, things to watch out for, performance considerations, etc. Electronic or tree-based resources can be equally valuable. You can assume a working knowledge of (not just x86) assembly language.

[A]
I'm not aware of any sources specifically related to JITs, but I imagine that it's pretty much like a normal compiler, only simpler if you aren't worried about performance.
The easiest way is to start with a VM interpreter.  Then, for each VM instruction, generate the assembly code that the interpreter would have executed.
To go beyond that, I imagine that you would parse the VM byte codes and convert them into some sort of suitable intermediate form (three address code?  SSA?) and then optimize and generate code as in any other compiler.
For a stack based VM, it may help to to keep track of the "current" stack depth as you translate the byte codes into intermediate form, and treat each stack location as a variable.  For example, if you think that the current stack depth is 4, and you see a "push" instruction, you might generate an assignment to "stack_variable_5" and increment a compile time stack counter, or something like that.  An "add" when the stack depth is 5 might generate the code "stack_variable_4 = stack_variable_4+stack_variable_5" and decrement the compile time stack counter.
It is also possible to translate stack based code into syntax trees.  Maintain a compile-time stack.  Every "push" instruction causes a representation of the thing being pushed to be stored on the stack.  Operators create syntax tree nodes that include their operands.  For example, "X Y +" might cause the stack to contain "var(X)", then "var(X) var(Y)" and then the plus pops both var references off and pushes "plus(var(X), var(Y))".


q:
How do I drop a Groovlet into a Grails app?  Say, for example, in web-app/groovlet.groovy

import java.util.Date

if (session == null) {
  session = request.getSession(true);
}

if (session.counter == null) {
  session.counter = 1
}

println """
<html>
    <head>
        <title>Groovy Servlet</title>
    </head>
    <body>
Hello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()}
<br>
"""

[A]
The way I understand it, groovlets are used when you have a Servlet container with Groovy scripting support,
I think in Grails you would need to move your business logic code to a
controller
and leave the view part to an HTML or a
GSP file
.
Something along those lines (meta-code from the top of my head, not tested):
grails-app/controllers/SampleController.groovy
```
```
class DateController {
    def index = {
        if (session == null) {
          session = request.getSession(true);
        }

        if (session.counter == null) {
          session.counter = 1
        }
    }
}
```
```
web-app/sample/index.gsp
```
```
<html>
    <head>
    <title>Groovy Servlet</title>
    </head>
    <body>
Hello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()}
<br>
```
```
Hope that helps!


q: How to set internationalization to a DateTimepicker or Calendar WinForm control in .Net when the desire culture is different to the one installed in the PC?

[A]
For DateTimePicker
```
```
dtp.Format = DateTimePickerFormat.Custom;
dtp.CustomFormat = "yyyy-MM-dd"; // or the format you prefer
```
```


q:
I am playing with the new stuff of C#3.0 and I have this code (mostly taken from MSDN) but I can only get true,false,true... and not the real value :

        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        var oddNumbers = numbers.Select(n => n % 2 == 1);

        Console.WriteLine("Numbers < 5:");
        foreach (var x in oddNumbers)
        {
            Console.WriteLine(x);
        }

How can I fix that to show the list of integer?

[A]
Change your "Select" to a "Where"
```
```
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var oddNumbers = numbers.Where(n => n % 2 == 1);

    Console.WriteLine("Odd Number:");
    foreach (var x in oddNumbers)
    {
        Console.WriteLine(x);
    }
```
```
The "Select" method is creating a new list of the lambda result for each element (true/false).  The "Where" method is filtering based on the lambda.
In C#, you could also use this syntax, which you may find clearer:
```
```
var oddNumbers = from n in numbers
                         where n % 2 == 1
                         select n;
```
```
which the compiler translates to:
```
```
var oddNumbers = numbers.Where(n => n % 2 == 1).Select(n => n);
```
```


q:
When I restart my apache2 and reload a page, the log file shows

boogie.tontut.fi - - [28/Oct/2008:03:27:49 +0200] "GET /test HTTP/1.1" 404 457 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3"

...as supposed to, as it's 03:27:49 now. However, when I click the refresh button again, the new log entry is:

boogie.tontut.fi - - [27/Oct/2008:21:27:52 -0400] "GET /test HTTP/1.1" 404 457 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3"

Offset has changed from +0200 to -0400 and I have no clue where this comes from.

How can I start troubleshooting this problem?

[A]
Try and set your timezone explicitly in the
```
httpd.conf
```
:
```
```
SetEnv TZ GMT+2
```
```


q: I would like to be able to drop to the python REPL from the debugger -- if this is not possible is there an easier way to evaluate python expressions in the context of the  current breakpoint other than manually adding them all as watch expressions?

[A]
I don't use
pydev
, but to drop to python's interactive REPL from code:
```
```
import code
code.interact(local=locals())
```
```
To drop to python's debugger from code:
```
```
import pdb
pdb.set_trace()
```
```
Finally, to run a interactive REPL after running some code, you can use python's
```
-i
```
switch:
```
```
python -i script.py
```
```
That will give you a python prompt after the code, even if it throws an exception.
You may be able to hook some of those solutions into
pydev
, I think.


q: Is there a way to get the directory of a project in Eclipse?  We are writing a plugin that will allow the user to select files, and then run some processes on those files.  I would ideally like to be able to get all the files with a certain extension, but that is not necessary.

[A]
sure:
```
```
ResourcesPlugin.getWorkspace().getRoot().getProjects()
```
```
will get you a list of all the projects in the workspace.  you can easily iterate to find the one you want.  At that point, you can look for certain files by extensions, etc.


q:
I have been enjoying learning the basics of python, but before I started reading things I tried to install various python versions and modules clumsily. Now that I have some ideas of what I want to do and how to do it I'm finding that various aspects are broken. For instance, 2.6 IDLE won't launch, and when I try to import modules they usually don't work.

My question is, how would you recommend I clean this up and start fresh? I have read information about modifying the 2.6 install, but I still can't get it to work.

IDLE 2.4 works, and when I launch python from the terminal I am running python 2.4.4.

[A]
I had this problem so much when I first got my Mac. The best solution I found was to delete everything I'd installed and just go with the
pythonmac.org
version of Python (2.6). I then installed setuptools from the same site, and then used easy_install to install every other package.
Oh, and I got the GNU C Compiler from the Xcode developer tools CD (which you can download from Apple's website), so that I can compile C extensions.


q:
I am currently validating a client's HTML Source and I am getting a lot of validation errors for images and input files which do not have the Omittag. I would do it manually but this client literally has thousands of files, with a lot of instances where the  is not .

This client has validated some img tags (for whatever reason).

Just wondering if there is a unix command I could run to check to see if the  does not have a Omittag to add it.

I have done simple search and replaces with the following command:

find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/<b>/<strong>/g;p}' {} \;

But never something this large. Any help would be appreciated.

[A]
Try this. It'll go through your files, make a
```
.orig
```
backup of each file (perl's
```
-i
```
operator), and replace
```
<img>
```
and
```
<input>
```
tags with
```
<img />
```
and
```
<input >
```
.
```
```
find . \! -path '*.svn*' -type f -exec perl -pi.orig -e 's{ ( <(?:img|input)\b ([^>]*?) ) \ ?/?> }{$1\ />}sgxi' {} \;
```
```
Given input:
```
```

<input>  <input/>  <input id="..">  <input id="" >
```
```
It changes the file to:
```
```

<input />  <input />  <input id=".." />  <input id="" />
```
```
Here's what the regexp is doing:
```
```
s{(<(?:img|input)\b ([^>]*?)) # capture "<img" or "<input" followed by non-">" chars
  \ ?/?>}                     # optional space, optional slash, followed by ">"
{$1\ />}sgxi                  # replace with: captured text, plus " />"
```
```


q:
I am using WCF to upload data to a server.

If the communication fails, is there any way to resume the upload?

[A]
You will probably have to do some level of sanitisation. For example, the
perlre
man page describes the following construct:
```
```
(?{ code })
```
```
which allows executable code inside a pattern match.


q:
How is Silverlight going to change the internet in the next 10 years?

Is this going to be a scene changer or just another blip?

[A]
It will be another blip.  It's not seriously cross-platform, unlike Flash or any of its other competition, and no one seems particularly interested in it.  It might be neat and shiny but I haven't seen any real reason to move past playing around with it.
Put another way, it's a cool toy but not much else.


q:
How is profiling different from logging?

Is it just that profiling is used for performance measurements to see how long each function takes?  Or am I off?

Typically, how are profiling libraries used?

What types of stats are obtained by profiling?

[A]
I see profiling as performance measurement, and you don't have to profile every piece of code running, it's sometimes better to target specific areas.
Logging is storing information for later use, information which may relate to profiling but not necessarily.  It may just be to log what happened.
All the profiling stuff I've ever used basically allows you to store a start time and end time for a 'transaction' and later manipulate the data to see what's taking the most time.


q:
I understand object oriented programming, and have been writing OO programs for a long time.  People seem to talk about aspect-oriented programming, but I've never really learned what it is or how to use it.  What is the basic paradigm?

This question is related, but doesn't quite ask it:

Aspect-Oriented Programming vs. Object Oriented Programming

[A]
AOP addresses the problem of
cross-cutting concerns
, which would be any kind of code that is repeated in different methods and can't normally be completely refactored into its own module, like with logging or verification. So, with AOP you can leave that stuff out of the main code and define it vertically like so:
```
```
function mainProgram()
{
   var x =  foo();
   doSomethingWith(x);
   return x;
}

aspect logging
{
    before (mainProgram is called):
    {
       log.Write("entering mainProgram");
    }

    after (mainProgram is called):
    {
       log.Write(  "exiting mainProgram with return value of "
                  + mainProgram.returnValue);
    }
 }

aspect verification
{
    before (doSomethingWith is called):
    {
       if (doSomethingWith.arguments[0] == null)
       {
          throw NullArgumentException();
       }

       if (!doSomethingWith.caller.isAuthenticated)
       {
          throw Securityexception();
       }
    }
 }
```
```
And then an
aspect-weaver
is used to compile the code into this:
```
```
function mainProgram()
{
   log.Write("entering mainProgram");

   var x = foo();

   if (x == null) throw NullArgumentException();
   if (!mainProgramIsAuthenticated()) throw Securityexception();
   doSomethingWith(x);

   log.Write("exiting mainProgram with return value of "+ x);
   return x;
}
```
```


q: I have a page with a "Print" link that takes the user to a printer-friendly page.  The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page.  How can I do this with javascript?

[A]
```
```
window.print();
```
```
unless you mean a custom looking popup.


q:
I required to write a small web application that allow customer to select predefined layout template in html and be able to modify it. The application need to allow customer to add block text to pre defined area and images. The block texts need to be able to reorder based on customer need. eg. move up , move down or move to sidebar. THe complete layout will be able to convert to table layout and inline css due to email program doesn't like div & css. I don't know where should I looking for the information to make this happen, could anyone show me how to do this.

Thank you

[A]
I'm not sure why someone downvoted you, but check out a javascript framework like
script.aculo.us
or
Yahoo's YUI
Those will go a long way towards creating the interface you need.  Also they have a lot of examples.
The Yahoo framework has an inplace html editor (I think that is what you are asking for).  Another editing is the
fckeditor
.


q:
I always hear that programmers try to pick the right tool for the job.  I've never programmed in Java, so I was wondering What are its benefits?  Why is it so popular?  What should I use it for?

I just program recreationally.  Is there anything about it that makes it particularly fun??

[A]
Cross platform is in my opinion the most relevant benefit.
The main goal of Java was to create a programming language that could run anywhere. The target was GUI apps. This however never happen because the environment was too slow at the beginning ( now it has been improved )  but it prove true in the server side where the cost of development reduced a lot because the product development can be done in PCs and the deployment in very expensive hardware.
It brought easy of development also, because it was designed to have C++ like syntax but running on a virtual platform to avoid platform specific code.  At first the penalty was the execution speed, because it was interpreted, but release after release the interpreters became more and more faster that even MS model its next generation of development after java and call it .net
Additionally
You can have a read of the Java design goals
here


q:
I am digging into LINQ--trying to understand basic models (it seems pretty cool to me). The code below is the code to perform before committing an update.

   Linq01.Account acc = context.Accounts.Single( pc => pc.AccountID == AccountID );
   acc.Name = textboxAccountNameRead.Text.Trim();
   context.SubmitChanges();

So far, so good. But what do you do if the Single() method failed--if the account ID wasn't found?

Thank you!

[A]
You should use
```
SingleOrDefault
```
, if the query does not return a value you can check it against null:
```
```
var acc = context.Accounts.SingleOrDefault(pc => pc.AccountId == AccountId);
if(acc != null)
{
  acc.Name = textboxAccountNameRead.Text.Trim();
  context.SubmitChanges();
}
```
```


q:
While surfing, I came to know that somebody has done Tower of Hanoi using vim. WOW!!!

Can you people share what all cool things you have been doing in vim.

Edit: Not sure about the Tower of Hanoi solution using vim being all that useful. But I think this question should be re-opened to allow people to comment on any useful things that they've done using vim. For me? See my answer below. (-:

[A]
I was working on a system that had massive log files. We're talking 30,000 10MB logs.
Per day!
Distinguishing between log messages that were coming from the middleware (same company but custom rolled) and our application was getting tedious.
That is until I wrote some custom vim syntax parsing so that anything vim displayed in green was from the middleware (done by the guys in Sophia Antipolis near Cannes) as opposed to anything vim displayed in blue that was from our application software that sat over the top of the SA code.
I also added highlighting to really make exceptions stand out with white lettering on a read background!
Made life so much easier! And it wasn't that hard to do!
Thanks vim!


q:
I'm running Windows Server 2008 64-bit "workstation" and would like to get corflags.exe. Which SDK do I need to download?

I know about .NET Framework 2.0 Software Development Kit (SDK) (x64) and Windows SDK for Windows Server 2008 and .NET Framework 3.5 but I was hoping to find something smaller as these are quite large downloads.

Also the note about 2.0 SDK seems to suggest to download the 3.5 one, should I follow that?

[A]
If you install the .NET framework (you should already have it), it'll be at C:\Program Files (x86)\Microsoft.NET\SDK\v2.0\Bin\corflags.exe
Come to think of it, you may need to install
the Microsoft .NET 2.0 SDK from
.NET Framework 2.0 Software Development Kit (SDK) (x64)
-- check for that file first.


q: Visual Studio 2005 is very slow with a solution with 21 projects.  Any ideas how to speed it up?

[A]
a) Buy more memory
b) Break up into different solutions
c) Upgrade to VS 2008
d)
Link


q:
Is there a way to bind a Generic List to a multicolumn listbox, yes listbox...I know but this is what I am stuck with and can't add a grid or listview.

Thanks

[A]
You could bind a list to a listbox like this:
```
```
List<int> list = new List<int> { 1, 2, 4, 8, 16 };
listBox1.DataSource = list;
```
```
As for multicolumn listbox documentation says
ListBox.MultiColumn
only places items into as many columns as are needed to make vertical scrolling unnecessary.
If you want to show several columns of information for which an entire row will get selected you could use
Multi Column List Box
by Chris Rickard.


q:
I want this page to return 200 whilst still sending the redirect...

<script>
    sub page_load
        'Get the parameters
         dim content As String
         content = request.querystring("text")
         response.redirect ("http://100.200.100.10/test1/Default.aspx?CommandParm=" + content)
    end sub
</script>
<html>
    <head>
    </head>
    <body>
        <form runat="server">
        </form>
    </body>
</html>

[A]
No way with
```
Response.Redirect()
```
. I... think. Maybe setting
```
Response.Status = "200 OK"
```
after calling
```
Redirect()
```
works, I've never tried.
You could fake it by setting the "Location" header manually in an otherwise empty response. Not sure what that is good for, though. ;-)
```
```
Response.AddHeader("Location", "http://100.200.100.10/test1/Default.aspx?CommandParm=" + content)
Response.End()
```
```
(And, for the record: You would be producing an invalid HTTP header constellation. Should not break anything, but still.)


q:
I want create a drop shadow around the canvas component in flex. Technically speaking it will not be a shadow, as I want it to wrap around the component giving the component a floating look. I may be able to do it with glow, but can anyone drop an line or two who has already done it?

Thanks in advance.

[A]
I actually solved it by doing this:
```
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
        width="780" height="100%" borderStyle="solid" borderColor="gray"
            creationComplete="init();" backgroundColor="white">

  <mx:Script>
        <![CDATA[
            import mx.styles.StyleManager;

            private function init():void {
                var glow:GlowFilter = new GlowFilter();
                glow.color = StyleManager.getColorName("gray");
                glow.alpha = 0.8;
                glow.blurX = 4;
                glow.blurY = 4;
                glow.strength = 6;
                glow.quality = BitmapFilterQuality.HIGH;

                this.filters = [glow];
            }
        ]]>
    </mx:Script>

</mx:Canvas>
```
```


q:
I am developing iPhone application and In that application I've one TableViewController,
and that TableViewController made up of Custom table cell.

into those cell I am loading image from URL, but the scrolling is not that smooth, (because each cell load images every time when scrolling happen).

So I decided to store those images into application document folder, but I don't know how to use document folder in iPhone when application is in running state.

Any suggestion?

And on other forums I found that SQLITE has blob datatype to store binary data,

Which method is efficient, document folder or sqlite to store image?

[A]
You could use
```
NSFileManager
```
's
```
createFileAtPath
```
to save any
```
NSData
```
into a file.
To get the Documents directory, use this:
```
```
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
```
```


q:
I want to autowire a bean partially - that is, I want some args to be autowired but other to be explicitly set. For example:

public MyClient(Service svc, boolean b)

In the case of this constructor, I would like to specify in my xml the value for b, but have svc autowired. Is that possible?

Thanks,
Lowell

[A]
I don't think it is possible with constructors, but with explicit setters it certainly is. Just annotate the ones you want autowired with @Autowired, and set the others in your config-file
Something like:
```
```
public MyClient() {}

@Autowired
public setService (Service svc) {...}

public setBoolean (boolean b) {...}
```
```
and then in your config
```
```
<context:annotation-config />

<bean id="service">...</bean>

<bean id="yourbean" class="MyClient">
    <property name="b" value="true"/>
</bean>
```
```


q:
I have the following classes

public interface InterfaceBase
{
}

public class ImplementA:InterfaceBase
{
}

public class ImplementB:InterfaceBase
{
}

public void TestImplementType<T>(T obj) where T: InterfaceBase
{
}

How to infer what the T is whether ImplementA or ImplementB? I tried to use

typeof(T) is ImplementA

but this expression is always evaluated to false.

Edit: And how am I going to cast obj to ImplementA or ImplementB?

[A]
```
obj is ImplementA
```


q:
I have two lists that are of the same length, is it possible to loop through these two lists at once?

I am looking for the correct syntax to do the below

foreach itemA, itemB in ListA, ListB
{
  Console.WriteLine(itemA.ToString()+","+itemB.ToString());
}

do you think this is possible in C#? And if it is, what is the lambda expression equivalent of this?

[A]
[edit]: to clarify; this is useful in the generic LINQ /
```
IEnumerable<T>
```
context, where you
can't use
an indexer, because a: it doesn't exist on an enumerable, and b: you can't guarantee that you can read the data more than once. Since the OP mentions lambdas, it occurs that LINQ might not be too far away (and yes, I do realise that LINQ and lambdas are not quite the same thing).
It sounds like you need the missing
```
Zip
```
operator; you can spoof it:
```
```
static void Main()
{
    int[] left = { 1, 2, 3, 4, 5 };
    string[] right = { "abc", "def", "ghi", "jkl", "mno" };

    // using KeyValuePair<,> approach
    foreach (var item in left.Zip(right))
    {
        Console.WriteLine("{0}/{1}", item.Key, item.Value);
    }

    // using projection approach
    foreach (string item in left.Zip(right,
        (x,y) => string.Format("{0}/{1}", x, y)))
    {
        Console.WriteLine(item);
    }
}

// library code; written once and stuffed away in a util assembly...

// returns each pais as a KeyValuePair<,>
static IEnumerable<KeyValuePair<TLeft,TRight>> Zip<TLeft, TRight>(
    this IEnumerable<TLeft> left, IEnumerable<TRight> right)
{
    return Zip(left, right, (x, y) => new KeyValuePair<TLeft, TRight>(x, y));
}

// accepts a projection from the caller for each pair
static IEnumerable<TResult> Zip<TLeft, TRight, TResult>(
    this IEnumerable<TLeft> left, IEnumerable<TRight> right,
    Func<TLeft, TRight, TResult> selector)
{
    using(IEnumerator<TLeft> leftE = left.GetEnumerator())
    using (IEnumerator<TRight> rightE = right.GetEnumerator())
    {
        while (leftE.MoveNext() && rightE.MoveNext())
        {
            yield return selector(leftE.Current, rightE.Current);
        }
    }
}
```
```


q:
I know how to move a layer based on touch. But I would also like to be able to rotate the image.

Is there any sample code that shows how to do this? Or can anyone give me some advice?

Thanks!

[A]
You would use the view's transform property.
There's some example code for rotating the view in the iPhone OS Programming Guide, under
Launching in Landscape Mode


q:
I am trying to compare two decimal values in Java script. I have two objects as  one assogned value "3" and the other as "3.00". When i say if (obj1 == obj2) it does not pass the condition as it is does the string comparision.

I would instead want it to do a decimal comparision where 3 = 3.00. Please let me know how to do this.

[A]
This page
describes how to convert a string to a floating-point number; I believe that is what you want. This would let you compare the numbers as numbers, which I think is what you mean by "decimally". Beware that doing an exact comparison between two floating-point numbers is often considered a bit "hazardous", since there are precision issues that might cause two numbers that you would consider "equal" to not compare as such. See, for instance,
What Every Computer Scientist Should Know About Floating-Point Arithmetic
, which is a classic text on the topic. Perhaps a bit on the advanced side, but try searching for something more basic in that case.


q: This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I am not against having an extra import statement at the top of the file, nor a few extra lines of code.

[A]
This isn't the debugger, but probably just as useful(?)
I know I heard Guido mention this in a speech somewhere.
I just checked python -?, and if you use the -i command you can interact where your script stopped.
So given this script:
```
```
testlist = [1,2,3,4,5, 0]

prev_i = None
for i in testlist:
    if not prev_i:
        prev_i = i
    else:
        result = prev_i/i
```
```
You can get this output!
```
```
PS D:\> python -i debugtest.py
Traceback (most recent call last):
  File "debugtest.py", line 10, in <module>
    result = prev_i/i
ZeroDivisionError: integer division or modulo by zero
>>>
>>>
>>> prev_i
1
>>> i
0
>>>
```
```
To be honest I haven't used this, but I should be, seems very useful.


q: How can I generate a report in access with the data from a recordset (instead of a query or table). I have updates to the recordset that also must be shown in the report.

[A]
Please explain in more detail. For example, do you wish to show what the field was and what it is now? If so, you will need an audit trail. Here is an example from Microsoft:
http://support.microsoft.com/kb/q197592/
What do you mean by report? If you mean a printed paper document, Access has a good report builder. If you mean you wish to view the data, you can use a form. If you are unfamilar with building reports and forms, there are wizards.
It is always wise to study the Northwind sample database that ships with every version of Access.


q:
private const int THE_ANSWER = 42;

or

private const int theAnswer = 42;

Personally I think with modern IDEs we should go with camelCase as ALL_CAPS looks strange. What do you think?

[A]
Leave Hungarian to the Hungarians.
In the example I'd even leave out the definitive article and just go with
```
```
private const int Answer = 42;
```
```
Is that answer or is that the answer?
*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to
life, the universe and everything
.


q:
I have MainViewController calling WebViewController (From UICatalog sample application)
In WebViewController I make some function setValue(){...} to set some value passed as parameter to the variable (NSString *value) from WebViewController.h but when I try from MainViewController something like WebViewController targetViewController...
targetViewController.setValue(value), it says: "error: request for member 'setValue' in something not s structure or union"...

[A]
If you have a property named "value", and use @sythesize to create a method for you, in which case you call using that "." notation:
```
```
targetViewController.value = whatever;
```
```
Or you can call the setter outright regardless of you or the @synthesize writing the method:
```
```
[targetViewController setValue:whatever];
```
```
The property syntax (class.property = whatever) is really just a shortcut of calling a "setValue:" method, and in return the @property and @synthesize mechanisms of properties are just writing a helpful bit of code for you.
Edit:  I had said before if you just wrote a "setValue:" method you could call it using the "class.value = newValue" notation, but that was incorrect - you have to define an @property to use "." notation.


q:
I have a long URL with tons of parameters that I want to open in the default browser from Java on a Windows system using

Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url)

For short URLs like "http://www.google.com" this works fine. But for long URLs (say, 2000 characters), this simply does absolutely nothing at all: no exception or anything of the sort, it is simply ignored.

Is there a character limit a) for a Runtime.exec command or b) for the rundll32 url.dll command? If so, what is the limit?

[A]
You will be running up against
this (archived)
operating system/browser specific maximum URL length problem:
For "rundll32 url.dll" (i.e. Microsoft IE) you will be limited to 2,083 characters (including http://).
From where I sit you have two alternatives:
Build (or use) a TinyURL-style service
that turns your long-urls into
short, redirected ones. However even
here you are going to run into the
same URL length issue, just within
the browser itself rather than your
Runtime() statement. e.g. The browser window would open, go to the short-URL which would perform the redirect to the long-URL and fail.
Use a POST request and bury some or
all of your URL parameters within
it. Rather than using a GET call you
can supply very long parameters
within the body of an HTTP POST request. This
would not be as simple as your example code. In fact this maybe quite tricky (or impossible) with the rundll32 url.dll combination (I am not familiar with it)...


q: How can I draw a 2D rubber band rectangle in DirectX? Preferable using C#.

[A]
The classic way to do rubberbanding is to:
Draw the regular scene, i.e. the "background"
Switch to "XOR mode", where your pen will XOR the pixels already in the framebuffer. It is important that the mode here is XOR, since XOR is losslessly "revertable", unlike for instance an add operation.
While "rubberbanding":
Draw the rubberband rectangle in its current coordinates
On the next frame, draw the rectangle again, still using XOR, using its previous coordinates. This removes the rectangle, leaving the framebuffer intact.
Update the rectangle's coordinates
Details on how to do this "with DirectX" are a bit harder ... I believe DirectDraw, the "old school" way of doing 2D in DirectX is obsolete, so I guess you must be using Direct3D. Unfortunately I'm not sure on the details, there. It might be that you're out of luck with finding pre-defined functionality to do XOR drawing, and need to roll your own. Hopefully someone can provide better details on that. Apologies if you were already up to speed on the rubberbanding theory itself.


q:
This is probably a simple question but how can I best use an AJAX loader in ASP.NET to provide a loading dialog whilst the page is being built?

I currently have an UpdatePanel with an associated UpdateProgressPanel which contains the loading message and gif in a ProgressTemplate.

Currently I have a page that onLoad() goes and gets the business entities and then displays them. While it is doing this I would like to display an AJAX loader.

Would it be better to have nothing in the page load and have a hidden button that is triggered onLoadComplete or unLoad() which would then wait for the button click method to complete displaying the UpdateProgressPanel?

[A]
You can do it in HTML outside of .Net.  In your ASPX page you have code like:
```
<div id="loading">
<!-- Animated GIF or other indication that stuff is happening -->
</div>
```
At the very bottom of your page, right before the  you can have a code snippet that looks like this:
```
<script language="javascript">
document.getElementById("loading").style.display = "none";
</script>
```
The graphic--- as long as it's at the top of the page--- will render first.  Then all of your onLoad stuff will happen, and finally the inline JavaScript will happen last since it's at the bottom of the page.
A lot of times I'll disable the buttons in their unloaded state and enable them in that bottom JavaScript too.  That prevents the user from getting click happy and triggering events before the page is ready.


q: Is it possible to make a POST request from Ruby with open-uri?

[A]
Unfortunately
```
open-uri
```
only supports the
```
GET
```
verb.
You can either drop down a level and use
```
net/http
```
, or use
```
rest-open-uri
```
, which was designed to support
```
POST
```
and other verbs. You can do
```
gem install rest-open-uri
```
to install it.


q: Is it possible to disable the browsers vertical and horizontal scrollbars using jQuery or javascript?

[A]
Try CSS
```
```
<body style="overflow: hidden">
```
```


q:
A classic ASP.NET app - AppSrv + MS SQL DB. Both servers are heavy-lifters 8 cores, 20 GB of RAM. When load testing, the throughput goes somewhere to 400 VirtualUsers (according to LoadRunner) with CPU being approximately 30% utilized an DB server primarily idling - response times go dramatically up, to the point of unresponsive.

The usual suspects, such as Max Pool being exhausted and conn limit on ASP.NET set are not at fault: Max Pool is set to 200 and about 80 conns are used; conn limit is set to 0.

I ran with ANTS profiler the code and it showed that Thread blocking did not contribute significantly.

Ideas very very welcome!

[A]
Does the host utilize App Pool?
Did you try increase the number to 5 to 10 in
```
```
An Application Pool -> Performance ->
Web Garden -> Max Number of worker processes
```
```


q: When I launch perfmon and try to add a counter, the displayed performance objects are all numbers. How can I reset these Performance objects?

[A]
What do you mean my "reset"? What's the behavior you're expecting?
The perfmon "System Monitor" view shows the (near) real time value of the counter. Since these measurements are always being taken there will (almost) always be a number there.
If you want to be able to control the collection of these measurements, you need to create a Counter Log. Additionally, you can use the logman command to manage the log from the command line or a script.


q:
today1 = new Date();
today2 = Date.parse("2008-28-10");

To compare the time (millisecond) values of these I have to do the following, because today2 is just a number.

if (today1.getTime() == today2)

Why is this?

[A]
If I remember correctly, Date gives you a value down to the millisecond you created the Date object. So unless this code runs exactly on 2008-28-10 at 00:00:00:000, they won't be the same.
Just an addition: Date.parse() by definition returns a long value representing the millisecond value of the Date, and not the Date object itself. If you want to hold the Date object itself, just build it like so:
```
```
var newDate = new Date();
newDate.setFullYear(2008,9,28);
```
```
For more reference check out:
the Date class reference


q:
Whilst investigating a memory leak I discovered that it was caused by calling NewRow() on a Table inside a loop many times. However the DataRow created was never added to the Table Rows collection and the Table Rows Count never got above zero.

My question is why does this use up more memory every time NewRow is called even though the newly created DataRow never gets added to the Rows collection and the DataRow returned from NewRow is always assigned to the same local variable (thereby apparently discarding the last new row).

Please ignore the issue of why the code is creating DataRows that don't get added to the table!

[A]
I think your two issues are related.
Table.NewRow creates a new data row that has the same column format as the initial Table.
This new row needs to be added to the table using table.Rows.Add(newRow). Your loop will be creating objects that are never used and hence will eat up memory.
See this article for more information
http://msdn.microsoft.com/en-us/library/system.data.datatable.newrow.aspx


q:
Omitting details of methods to calculate primes, and methods of factorisation.

Why bother to factorise ?

What are its applications ?

[A]
Wow, so much fighting in this thread.
Ironically, this question HAS a major valid answer.
Factorization is actually used heavily in encryption/decryption algorithms, so much so that the RSA regularly conducts competitions wherein the task is to factorize certain large numbers that are multiples of very large prime numbers.
This is, in turn, because several encryption/decryption algorithms are based on the premise that factorization takes a very long time, which (supposedly) makes it difficult and/or impractical to crack certain encryption/decryption algorithms given the assumption that the hacker/cracker does not have access to public/private keys.
Factorization algorithms can then be used to verify just how strong any given encryption/decryption algorithm is.


q:
I have one aspx page with some controls.
Also i have one DIV which is dynamically populated from AJAX call.
This AJAX call return couple of controls, for example HtmlInputText1 and HtmlInputText2.

When page is submitted, I can get values from this controls through Request.Form.
If possible access to the attributes of this control on pege code behind (for example HtmlInputText1.Height, etc).

I think that is impossible, but I am not sure.
I can use hidden field. Is any other way?

[A]
The data you want the server to know can be set by the javascript within the form.
Then You can process postback data for the target values manually.
You can write some javascript which modify the value of the server control within browser.
```
```
<script language="javascript" type="text/javascript">
function changeValue() {
    var txtControlClient = document.getElementById('<%= txtControl.ClientID %>');
    txtControlClient.value = "modified text";
}
</script>
```
```
In the expected event, you call changeValue() function before the postback, then you can just use server control object txtControl to obtain the value or property you have altered.


q:
Do you have any examples of real life applications of mutation testing? Does it work better than simple test coverage tools? Or is it useless?

What are the advantages/disadvantages of mutation testing in the real world?

[A]
I looked at mutation test some time ago as a method for checking the efficacy of my automated regression testing scripts.  Basically, a number of these scripts had missing checkpoints, so while they were exercising the application being tested correctly, they weren't verifying the results against the baseline data.  I found that a far simpler method than changing the code was to write another application to introduce modifications to a copy of the baseline, and re-run the tests against the modified baseline.  In this scenario, any test that passed was either faulty or incomplete.
This is not genuine mutation testing, but a method that uses a similar paradigm to test the efficacy of test scripts.  It is simple enough to implement, and IMO does a good job.


q:
I need to implement a SSO between a SharePoint site and a custom PHP-based site which resides on a different domain. I need to use the SharePoint user accounts to log in the PHP site. (I'll have a full control over the PHP source)

Is this possible? Any tips and tricks?

[A]
I don't know much about this area but hopefully this might help point you in the right direction.
Investigate LDAP...
You can set up PHP to use LDAP credentials. If your SharePoint site uses Active Directory, then you can expose this directory as an LDAP source and use that in the PHP application.
Automated sign-in...
Having the sign in happen automatically between each site is a very different matter. e.g. I'm logged into MOSS already, click on a link that goes to the PHP app and find that I'm already logged in there as well. For this you will need to investigate using something like Kerberos keys/authentication. It's a messy and difficult area.


q:
I am trying to write a replacement regular expression to surround all words in quotes except the words AND, OR and NOT.

I have tried the following for the match part of the expression:

(?i)(?<word>[a-z0-9]+)(?<!and|not|or)

and

(?i)(?<word>[a-z0-9]+)(?!and|not|or)

but neither work. The replacement expression is simple and currently surrounds all words.

"${word}"

So

This and This not That

becomes

"This" and "This" not "That"

[A]
This is a little dirty, but it works:
```
```
(?<!\b(?:and| or|not))\b(?!(?:and|or|not)\b)
```
```
In plain English, this matches any word boundary not preceded by and not followed by "and", "or", or "not". It matches whole words only, e.g. the position after the word "sand" would not be a match just because it is preceded by "and".
The space in front of the "or" in the zero-width look-behind assertion is necessary to make it a fixed length look-behind. Try if that already solves your problem.
EDIT: Applied to the string "except the words AND, OR and NOT." as a global replace with single quotes, this returns:
```
```
'except' 'the' 'words' AND, OR and NOT.
```
```


q:
Which SQL statement is faster?

SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price
FROM Table1 AS c1, Table2 AS c2, ..... Table49 AS c49, Table50 AS c50
WHERE c1.Date = c2.Date AND c2.Date = c3.Date ..... c49.Date = c50.Date
ORDER BY c1.ID DESC

        OR

SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price
FROM (Table1 AS c1
 INNER JOIN (Table2 AS c2
    ........
  INNER JOIN (Table49 AS c49
   INNER JOIN Table50 AS c50
  ON c49.Date = c50.Date)
    ........
 ON c2.FullDate__ = c3.FullDate__)
ON c1.FullDate__ = c2.FullDate__)
ORDER BY c1.ID DESC";

Basically I need to extract 2 rows from each table to produce a summary periodically.
Which statement is faster?

[A]
WHERE would usually be better but the best way is
case by case
and throw this into profiler, or simpler yet
display execution plan
.  Folk often have very strong opinions on which approach is fastest/best in theory but there is no replacement for actually tuning according to the data you actually deal with as theories applicable change depending on your data load.
If you do not have
real data
in your app yet, try and create some realistic stress data.  This will continue to be useful for testing.  Then schedule time to tune once the application is live.


q:
I think this must be simple but I can't get it right...

I have an MxM triangular matrix, the coefficients of which are stored in a vector, row by row.
For example:

M =   [ m00 m01 m02 m03 ]
      [     m11 m12 m13 ]
      [         m22 m23 ]
      [             m33 ]

is stored as

coef[ m00 m01 m02 m03 m11 m12 m13 m22 m23 m33 ]

Now I'm looking for a non-recursive algorithm that gives me for matrix size M and coefficient array index i

unsigned int row_index(i,M)

and

unsigned int column_index(i,M)

of the matrix element that it refers to. So,
row_index(9,4) == 3, column_index(7,4) == 2 etc. if the index counting is zero-based.

EDIT: Several replies using an iteration have been given. Does anyone know of algebraic expressions?

[A]
Took me some time to understand what you needed! :)
```
```
unsigned int row_index(int i, int m)
{
    int iCurrentRow = 0;
    int iTotalItems = 0;
    for(int j = m; j > 0; j--)
    {
        iTotalItems += j;

        if( (i+1) <= iTotalItems)
            return iCurrentRow;

        iCurrentRow ++;
    }

    return -1; // Not checking if "i" can be in a MxM matrix.
}
```
```
Sorry forgot the other function.....
```
```
unsigned int column_index(int i, int m)
{
    int iTotalItems = 0;
    for(int j = m; j > 0; j--)
    {
        iTotalItems += j;

        if( (i+1) <= iTotalItems)
            return m - (iTotalItems - i);
    }

    return -1; // Not checking if "i" can be in a MxM matrix.
}
```
```


q:
My client wants to send email announcements and reports for customers. Now. The python-side code doesn't seem too hard but there's the rest of the story.

What do I require in order to send such emails that won't end up getting blocked by email servers and clients?

[A]
There's no sure fire way, as email filters can do as they wish, but a few recommendations:
Use a real SMTP server, usually your client's (Authenticating if needs be). By real I mean one that's in real usage not a special one to send your emails only.
Send from a real account able to receive responses.
Avoid HTML if possible, if not possible, send a
multipart message
.
Send all mandatory headers plus some headers usually sent by common MUAs.
Generally, check the common spam
detection rules
to get a feel what's common in spam mails.


q:
How do you split a string?

Lets say i have a string "dog, cat, mouse,bird"

My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.

but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this?

im using asp c#

[A]
```
```
string[] tokens = text.Split(',');

    for (int i = 0; i < tokens.Length; i++)
    {
          yourListBox.Add(new ListItem(token[i], token[i]));
    }
```
```


q:
Recently developers highlighted that it is bit hard for them to keep track of which document has been updated. And they thus suggested that using SVN to keep track of document changes will be better as they will be able to know if document if being updated when doing checking out of the project.

But i also highlighted the several cons that may occur

Binary file using up alot of diskspace everytime word, excel document is commited

Checkout a project will take much more time although we can separate the documents into another project in the repository

It will take time to teach personnel on how to use SVN.

Another feature is that for these kind of functional documents, it should be locked while editing.

Anyone have any idea on how to go about it? Or what are the pros and cons to it. Please feel free to share with me.

[A]
We use Subversion for document management at work. It works great.
Don't worry about the disk space. Revisions are stored compressed anyway.
Checking out a project with documentation doesn't take much more time than one without. Unless your documents are absolutely huge, this shouldn't be a problem.
Training time is a consideration. Fortunately, TortoiseSVN makes this easy.
To manage Word documents so they can only be edited by one person at a time, use the
```
svn:needs-lock
```
property. This will make the files appear as read-only on a normal checkout, and read-write when a developer has locked them for editing. After commit, the file will be unlocked and read-only again.
An additional benefit of TortoiseSVN is that it can do diffs of Word documents and present the differences in Word itself. This alone is a killer feature for me.


q:
When I add the textBox.TextChanged to watch list I get a message saying
The event 'System.Windows.Forms.Control.TextChanged'
can only appear on the left hand side of += or -=

Is there any way to check what event's are called on text change?