q:
I have an asp.net server control (with the asp: in its definition). The button has been set to do post back.

On the server side, I have the on click event handler
e.g btnSave_click()

On the client side, I have a javascript function to be invoked on the click event
e.g btnSave.Attributes.Add("onclick","javascript: return CheckIsDirty();")

Am not sure which order these two will be executed. Because I want first on the client side to warn of any data entry fields that are not yet filled-out before actually saving any data.

Any help?

[A]
First client side, second server-side.
So you can use it.
I also use it in some cases, like:
```
```
close.Attributes["OnClick"] = "return confirm('Are you sure?')";
```
```
In this case if the user presses 'No' then the server-side event handler does not even play a role.


q:
According to this

http://perldoc.perl.org/UNIVERSAL.html

I shouldn't use UNIVERSAL::isa() and should instead use $obj->isa() or CLASS->isa().

This means that to find out if something is a reference in the first place and then is reference to this class I have to do

eval { $poss->isa("Class") }

and check $@ and all that gumph, or else

use Scalar::Util 'blessed';
blessed $ref && $ref->isa($class);

My question is why? What's wrong with UNIVERSAL::isa called like that? It's much cleaner for things like:

my $self = shift if UNIVERSAL::isa($_[0], __PACKAGE__)

To see whether this function is being called on the object or not. And is there a nice clean alternative that doesn't get cumbersome with ampersands and potentially long lines?

[A]
To directly answer your question, the answer is at the bottom of the page you linked to, namely that if a package defines an
```
isa
```
method, then calling
```
UNIVERSAL::isa
```
directly will not call the package
```
isa
```
method. This is very unintuitive behaviour from an object-orientation point of view.
The rest of this post is just more questions about why you're doing this in the first place.
In code like the above, in what cases would that specific
```
isa
```
test fail? i.e., if it's a method, in which case would the first argument not be the package class or an instance thereof?
I ask this because I wonder if there is a legitimate reason why you would want to test whether the first argument is an object in the first place. i.e., are you just trying to catch people saying
```
FooBar::method
```
instead of
```
FooBar->method
```
or
```
$foobar->method
```
? I guess Perl isn't designed for that sort of coddling, and if people mistakenly use
```
FooBar::method
```
they'll find out soon enough.
Your mileage may vary.

s: huggingface

c: devops

d: intermediate


q:
Is there a way to declare a variable as Nullable in c#?

struct MyStruct {
    int _yer, _ner;

    public MyStruct() {

        _yer = Nullable<int>; //This does not work.
        _ner = 0;
    }
}

[A]
Try declaring your variable like this:
```
```
int? yer;
```
```


q: In .net, is there a way using reflection to determine if a parameter on a method is marked with the "params" keyword?

[A]
Test to see whether the final
ParameterInfo
has
ParamArrayAttribute
applied to it.


q: Is it possible to create a simple 3D model (for example in 3DS MAX) and then import it to Android?

[A]
Not sure about Android specifically, but generally speaking you need a script in 3DS Max that manually writes out the formatting you need from the model.
As to whether one exists for Android or not, I do not know.


q:
I'm developing a kind of an exchange format between instances of an application so that user could save information to file and restore it later. The whole 'exchange format' is a single class that gets serialized and written to disk.

How would you suggest to store graphical/sound information inside that class? I'd like to avoid just putting the files into it a .jar.

[A]
** me **
how about more details on your case? the "best" method usually depends on the particular application/use.  does the image/sound come from files? from a stream?  Is each instance of the class expected to store separate images? Or can an image be shared between different instances?
gsmd
images come from files, sounds come
  from a stream; there's actually a Set
  of items some of which may have an
  image attached; an image can't be
  shared
What methods have you tried?
I guess using the Serializable interface is the way to go. Here's
two
articles
on the topic.
Basically,
implement the Serializable interface in your class
mark members which shouldn't be saved in the file as transient (members which contain contextual data like file handles, socket connections ,etc).
you have to customize how your image and sound classes write data using, but implementing:
private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;


q:
When returning objects from a class, when is the right time to release the memory?

Example,

class AnimalLister
{
  public:
  Animal* getNewAnimal()
  {
    Animal* animal1 = new Animal();
    return animal1;
  }
}

If i create an instance of Animal Lister and get Animal reference from it, then where am i supposed to delete it?

int main() {
  AnimalLister al;
  Animal *a1, *a2;
  a1 = al.getNewAnimal();
  a2 = al.getNewAnimal();
}

The problem here is AnimalLister doesnot have a way to track the list of Animals Created, so how do i change the logic of such code to have a way to delete the objects created.

[A]
I advise returning a
```
std::tr1::shared_ptr
```
(or
```
boost::shared_ptr
```
, if your C++ implementation does not have TR1) instead of a raw pointer. So, instead of using
```
Animal*
```
, use
```
std::tr1::shared_ptr<Animal>
```
instead.
Shared pointers handle reference tracking for you, and delete the object automatically if there are no references left to it.


q:
I've made some performance improvements to my application's backend, and to show the benefit to the end users of the GUI, we've been using the Trace.axd page to take timings. (The frontend is .Net 1.1 and the backend is Java, connected via Web services.)

However, these timings show no difference between the old and the new backends.

By putting a breakpoint in the backend and holding a request there for 30 seconds, I can see from Trace.axd that the POST is taking 3ms, and the GET is taking 4s. I'm missing about 26s...

The POST is where the performance improvement should be, but the timing on the Trace page seems to only include the time it takes to send the request, not the time it takes to return.

Is there a way to inrease the granularity of the information in the trace to include the whole of the request? Or is there another way to take the measurements I need?

[A] I'm not sure how you're making the requests on the .NET side, but I'll assume that there's a HttpWebRequest involved somewhere. I'd expect HttpWebRequest.GetResponse() to return as soon as it has received the response headers. That way, you can start processing the start of a large response while the rest is still downloading. If your trace messages are immediately before and after a call to GetResponse, you therefore wouldn't see the whole execution time of the backend. Can you add a trace message immediately after you close the response?


q: Are there any tools to transform SVG (XML) data to Canvas friendly input?

[A]
No I don't think so. SVG is actually rather different to Canvas. SVG is a vector graphics description language, whereas Canvases are programmatically "drawn" by sets of instructions. Also, Canvas isn't actually vector based at all.
Take a look at the
Raphael Javascript Library
. Its API will draw SVG/Canvas/VML depending on the capabilities of the browser.


q:
What tools are available to encrypt or password-protect a file stored on the IFS?

*integrated file-system, accessible from Windows

[A]
You could setup object security so only certain users can view the file.
There are encryption tools available for purchase. There is also some built-in APIs for encrypting.
Here are some resources to look into:
Scenario: Key Management and File Encryption Using the Cryptographic Services APIs
The Next Step in Security
A Simple Encryption/Decryption Algorithm for Numbers
Cryptographic Services APIs
Most of these articles deal with encrypting data in a table, but the concepts should help you encrypt a file on the IFS.


q:
Suppose you have:

A-B-C

Now your build/test fails. The fix should be merged in A.
My current work-flow is like this:

$ git commit -m "fixA"

A-B-C-fixA

$ git rebase -i A~1

And squash fixA in A, result in:

A'-B-C

Is there a command to do something like:

A-B-C + (index with fix for A)

$ git commit -supperdupper A

Result:

A'-B-C

[A]
If you're just looking for the easy solution for fixing up earlier commits, read the question! It explains it all. But since Elmarco was asking for a slick way, here we go:
As of Git 1.7.0, there is an
```
--autosquash
```
option for
```
rebase
```
, which does what you want.  There is also the
```
--fixup
```
and
```
--squash
```
options for
```
commit
```
to make things easier.  With some aliasing you can probably even get the whole thing into a single command.
I'd suggest upgrading to the newest Git for maximum awesomeness:
```
```
git/Documentation/RelNotes $ grep -i -A1 autosquash\\\|fixup *
1.7.0.txt: * "git rebase -i" learned new action "fixup" that squashes the change
1.7.0.txt-   but does not affect existing log message.
--
1.7.0.txt: * "git rebase -i" also learned --autosquash option that is useful
1.7.0.txt:   together with the new "fixup" action.
1.7.0.txt-
--
1.7.3.txt: * "git rebase -i" peeks into rebase.autosquash configuration and acts as
1.7.3.txt:   if you gave --autosquash from the command line.
1.7.3.txt-
--
1.7.4.txt: * "git commit" learned --fixup and --squash options to help later invocation
1.7.4.txt-   of the interactive rebase.
--
1.7.4.txt: * "git rebase --autosquash" can use SHA-1 object names to name which
1.7.4.txt:   commit to fix up (e.g. "fixup! e83c5163").
1.7.4.txt-
```
```


q: Is it different from any other certificate I can generate via makecert or buy from some authority?

[A]
It depends on what you are doing with it. If you want the certificate to be accepted by a browser in an SSL communication, then it must have a root certificate installed in the browser. The certificates generated by authorities already have their root certs installed in browsers.
If you are using the cert just to sign an assembly, then you don't need it. It depends on who is checking the cert and whether they care if the root is a known authority.
More here:
http://en.wikipedia.org/wiki/Root_certificate


q:
So I have the following:

public class Singleton
{

  private Singleton(){}

  public static readonly Singleton instance = new Singleton();

  public string DoSomething(){ ... }

  public string DoSomethingElse(){ ... }

}

Using reflection how can I invoke the DoSomething Method?

Reason I ask is because I store the method names in XML and dynamically create the UI. For example I'm dynamically creating a button and telling it what method to call via reflection when the button is clicked. In some cases it would be DoSomething or in others it would be DoSomethingElse.

[A]
Untested, but should work...
```
```
string methodName = "DoSomething"; // e.g. read from XML
MethodInfo method = typeof(Singleton).GetMethod(methodName);
FieldInfo field = typeof(Singleton).GetField("instance",
    BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
method.Invoke(instance, Type.EmptyTypes);
```
```


q:
I'm a developer who works on both individual and group projects using Microsoft Visual Studio.  I could setup one of several different source control packages, such as VSS, SourceGear Vault or SVN on a server of my own and access them remotely; however, I don't want to deal with the hassle of setting it up, configuring it, etc.

Does anyone offer a hosted source control service?

[A]
I used
CVSDude
a long time ago. They were free up to 10 MBs at that time.


q:
I use LINQ to Objects instructions on an ordered array.
Which operations shouldn't I do to be sure the order of the array is not changed?

[A]
Are you actually talking about SQL, or about arrays? To put it another way, are you using LINQ to SQL or LINQ to Objects?
The LINQ to Objects operators don't actually change their original data source - they build sequences which are effectively backed by the data source. The only operations which change the ordering are OrderBy/OrderByDescending/ThenBy/ThenByDescending - and even then, those are stable for equally ordered elements. Of course, many operations will filter out some elements, but the elements which are returned will be in the same order.
If you convert to a different data structure, e.g. with ToLookup or ToDictionary, I don't believe order is preserved at that point - but that's somewhat different anyway. (The order of values mapping to the same key is preserved for lookups though, I believe.)


q:
What are the best practices when managing a software project involving a non-English-speaking client?

What communication issues are relevant? Would you maintain documentation in both languages (especially updating the specifications regularly)?

[A]
My native language is not English, so I'm on the other side. There were times when we had to write project documents in 4-6 languages.
Try to find somebody who understand English (like a key person). I try to avoid the communication in different languages on a project. Of course you can talk and write on different languages with project members, but if you talk or write to all members of the project at once, it should be one language.
Documentation should be maintained in as many languages as many involved. All documents should be updated on a regular basis and try to avoid the situation when you have to tell them that "the English is the current one". Find someone who is native in the target language and translate from English for you. It will be far more better, understandable, and more native than if you try the other way around.


q:
This is not yet particularly programing related but, I am very interested in how Vista and XP resolve network names in a home LAN situation.

With Windows 2000, network name resolution was either done via the netbeui protocol - tcp/ip networks needes a wins server. XP and Vista no longer install netbeui by default, so its entirely unclear to me how PCs on a lan are meant to find each other.

One part of the puzzle's solution seems to be, IF there is a router appliance on the network that is configured as a DHCP server (and, as a result, a DNS server) then DNS queries of PC names tend to resolve.

In the more isolated case - a couple of XP and Vista PCs connected to an ethernet hub, configured to talk only tcp/ip - what services and what protocols are involved in name resolution and broadcasting?

[A]
It looks like Peer Name Resolution Protocol is being used with Vista and XP.
Peer Name Resolution Protocol
http://technet.microsoft.com/en-us/library/bb726971.aspx
People Near Me
http://technet.microsoft.com/en-us/library/bb726969.aspx
Edit: After doing a little bit more digging after Chris's comment, here is a link on how Windows XP Professional resolves names:
http://technet.microsoft.com/en-us/library/bb457118.aspx#ECAA


q:
I've got nutch and lucene setup to crawl and index some sites and I'd like to use a .net website instead of the JSP site that comes with nutch.

Can anyone recommend some solutions?

I've seen solutions where there was an app running on the index server which the .Net site used remoting to connect to.

Speed is a consideration obviously so can this still perform well?

Edit: could NHibernate.Search work for this?

Edit: We ended up going with Solr index servers being used by our ASP.net site with the solrnet library.

[A]
Instead of using Lucene, you could use
Solr
to index with nutch (see
here
), then you can connect very easily to Solr using one of the two libraries available:
SolrSharp
and
SolrNet
.


q:
I am having a listbox in ASP.net. I am populating the listbox values from another listbox in a page dynamically. During postbacks the values of output listbox are not persisted.
(while going to another page and come back to this page).

Please suggest some good answer. EnableViewstate = "true" is not working.

[A]
Are you doing anything in Page_Load that should be in a
```
```
if(!IsPostBack) {}
```
```
Initialization code in load needs to only be called when the page is first loaded, not on postbacks.
If you are going to another page and then coming back to this page, I think you need to preserve the information yourself in the Session and then restore it when you come back to the page.


q:
I need to insert some data into a table in Oracle.

The only problem is one of the fields is a timestamp(6) type and it is required data. I don't care about what actually goes in here I just need to get the right syntax for an entry so that the database will accept it.

I'm using the gui web client to enter data however I don't mind using raw SQL if I have to.

Thanks.

[A]
I dunno if this helps at all, but in SQL*Plus I did this:
```
```
create table x ( a timestamp(6));
insert into x values ( current_timestamp );
select * from x;
```
```
getting me this:
```
```
T
---------------------------------------------------------------------------
15-OCT-08 02.01.25.604309 PM
```
```
So it looks like that works.
If you need to put a previously-known value into the column, how about the TO_TIMESTAMP() function? Something like this:
```
```
select to_timestamp('27/02/2002 15:51.12.539880', 'dd/mm/yyyy hh24:mi.ss.ff')
from dual ;
```
```


q:
I'm working on scripts that apply database schema updates. I've setup all my SQL update scripts using start transaction/commit. I pass these scripts to psql on the command line.

I now need to apply multiple scripts at the same time, and in one transaction. So far the only solution I've come up with is to remove the start transaction/commit from the original set of scripts, then jam them together inside a new start transaction/commit block. I'm writing perl scripts to do this on the fly.

Effectively I want nested transactions, which I can't figure out how to do in postgresql.

Is there any way to do or simulate nested transactions for this purpose? I have things setup to automatically bail out on any error, so I don't need to continue in the top level transaction if any of the lower ones fail.

[A]
Well you have the possibility to use nested transactions inside postgresql using SavePoints.
Take this code example:
```
```
CREATE TABLE t1 (a integer PRIMARY KEY);

CREATE FUNCTION test_exception() RETURNS boolean LANGUAGE plpgsql AS
$$BEGIN
   INSERT INTO t1 (a) VALUES (1);
   INSERT INTO t1 (a) VALUES (2);
   INSERT INTO t1 (a) VALUES (1);
   INSERT INTO t1 (a) VALUES (3);
   RETURN TRUE;
EXCEPTION
   WHEN integrity_constraint_violation THEN
      RAISE NOTICE 'Rollback to savepoint';
      RETURN FALSE;
END;$$;

BEGIN;

SELECT test_exception();
NOTICE:  Rollback to savepoint
 test_exception
----------------
 f
(1 row)

COMMIT;

SELECT count(*) FROM t1;
 count
-------
     0
(1 row)
```
```
Maybe this will help you out a little bit.


q:
I use the p/invoke method to play wav sounds. There are ways of calling windows media player to play an mp3 sound, but its slow & cumbersome.

Is there an easy way to play a short mp3 file?

This is primarily for application prompting and audible cues when you are not looking at the screen and not music.

Thanks!

[A]
CF Framework 3.5 now includes support for playing .WAV files:
Namespace System.Media.SoundPlayer
Short WAV files for cues and sound-effects might even play
faster
than MP3s since they're "ready-to-play"...


q:
Is there any way to get the custom attributes of a specific object I am receiving in a method?

I do not want nor can to iterate over Type.GetMembers() and search for my member. I have the object, which is also a member, that has the attribute.

How do I get the attribute?

class Custom
{
    [Availability]
    private object MyObject = "Hello";

    private void Do(object o)
    {
        //does object 'o' has any custom attributes of type 'Availability'?
    }

    //somewhere I make the call: Do(MyObject)

}

[A]
You cannot do this without at least 1 Reflection call. After that, save the value somehow.
Example:
```
```
abstract MyBase
{
  public string Name;
  protected MyBase()
  {
    //look up value of Name attribute and assign to Name
  }
}

[Name("Foo")]
class MyClass : MyBase
{
}
```
```


q:
My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is.

More here :

http://www.openplans.org/projects/deliverance/introduction

In theory, the system sounds great when you want a newbie to tweak your plone theme without having to teach him all the complex mechanisms behind the zope products. And apply the same theme on a Drupal web site in one row.

But I don't believe in theory, and would like to know if anybody tried this out in the real world :-)

[A]
I will start answering this question here while we perform tests but I'd love to have feedback from other users.
Install
We have spent a small afternoon from tuto to "how to" to finally install and run the thing on a virtual machine.
This one is ok :
http://www.openplans.org/projects/deliverance/getting-started
There are setuptools packages but this does not works out of the box (and certainly not without compiling anything). We had to install :
setuptools >= 0.6c5 (tested with 0.6c9 from
http://pypi.python.org/pypi/setuptools/
).
of course, compilation implies installing gcc, linux-header et lib6-dev
libxslt in dev (we used libxslt1-dev)
linking with zl so zlib (we used zlib1g-dev)
you'd better install Pastescript BEFORE starting the Deliverance install
installing python-nose is not mandatory but it helps to check if everything went fine
We did not manage to make it works with python-virtualenv to we definitly messed up the debian system but it seems to run ok.
Hope it can help.


q: Why should I do Nightly Builds?

[A]
Nightly builds aren't always necessary - I think they're only really useful on big projects. But if you're on a big project, a nightly build is a good way of checking that everything is working - you can run all your tests (unit tests, integration tests), build all your code - in short, verify that nothing is broken in your project.
If you've got a smaller project your build and test times will be shorter so you can probably afford to do more regular builds.


q:
We are in the process of moving our SVN repositories from one machine to another one, and with it will come a new domain name for the new repo.  The problem is, that within the repository, there are lots of svn:externals references to other projects within the repository.  So for example, we have projectA, which has in the svn:externals properties:

external/libraryA svn://oldserver.net/repo/libraryA
external/libraryB svn://oldserver.net/repo/libraryB

...and so on.  All of the URL's reference this particular domain name, so it can be easily parsed.  Having already learned my lesson, I will migrate these URLs to be "svn://localhost/", but I need to find a way to go through the repository history and rewrite all of the old URLs, so that we can still check out older revisions of these projects without having broken links.

How would I go about doing this?

[A]
You could:
a) check out the old revision, and change your hosts-file to point the old name to the new address, then svn update. In case the URL-path also changed... well then you might as well:
b) take the time to write a script that find the properties in the current (old revision-) working copy and changes the URLs there, without committing them. OR:
c) make a note of the revision(-s) where you checked in the new property values, check out the old version, and simply do a merge those revisions (-that only affect the properties) into your working copy.
d) or, possibly, use svndump to dump the repository data, string-replace the URL in the dump, then restore it.. I would not give you any guarantee that that even works ;-)


q:
Does anyone have a simple, efficient way of checking that a string doesn't contain HTML?  Basically, I want to check that certain fields only contain plain text.  I thought about looking for the < character, but that can easily be used in plain text.  Another way might be to create a new System.Xml.Linq.XElement using:

XElement.Parse("<wrapper>" + MyString + "</wrapper>")

and check that the XElement contains no child elements, but this seems a little heavyweight for what I need.

[A]
The following will match any matching set of tags. i.e. <b>this</b>
```
```
Regex tagRegex = new Regex(@"<\s*([^ >]+)[^>]*>.*?<\s*/\s*\1\s*>");
```
```
The following will match any single tag. i.e. <b> (it doesn't have to be closed).
```
```
Regex tagRegex = new Regex(@"<[^>]+>");
```
```
You can then use it like so
```
```
bool hasTags = tagRegex.IsMatch(myString);
```
```


q:
If I query a table with a condition on the key field as in:

        var user = from u in dc.Users
                   where u.UserName == usn
                   select u;

I know that I will either get zero results or one result. Should I still go ahead and retrieve the results using a for-each or is there another preferred way to handle this kind of situation.

[A]
Why not something like
```
```
var user = dc.Users.SingleOrDefault(u=> u.UserName==usn);
```
```


q:
I'm about to release a set of Eclipse plug-ins as Open Source and noticed that most source code released under the LGPL/EPL contains a header banner in each file that refers to the license or contains the license itself.

Since adding these banners to each file manually seems to be a daunting and error-prone task. How can I go about automating the insertion of these banners?

Edit: I've eventually found Copyright Wizard and Copyright Generator which are Eclipse plug-ins which also allow for updating existing license banners.

[A]
Concerning best practises, I believe you should have your license text in a separate file and have a build tool (ie ant) to add it at the beginning of all other files. Since you are talking about an open source project you would need a build process anyway for thinks like generating the javadocs, publishing releases etc.
BTW,ant tasks are simple Java classes so it should be easy to write one yourself  if you don't find an ant plugin that does exactly that.
Coming to eclipse, to my knowledge, it cannot do something like this. The quickest way I can think of to do it is with bash (if you are using Linux). Assume the file msg contains the text you want to add at the beginning of every file.
Create a new directory to store the files:
mkdir ~/outdir
Add the msg at the beginning of every file and put the result at the outdir
for i in
```
ls "*.java"
```
; do cat msg $i > ~/outdir/$i ; done
Similarly you can write a command that does the same recursively, with an extra step to create the directory strucutre:
```
```
mkdir ~/outdir
for i in `find -type d | sed 's/\.//' | grep -v "^$"`; do mkdir ~/outdir$i; done
for i in `find -name "*.java"`; do cat msg $i > ~/outdir/$i ; done
```
```


q:
Possible Duplicate:

  Why does C# not provide the C++ style ‘friend’ keyword?

I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.

In C++ I'd just declare the Tester class as a friend, how do I do this in C#? Can someone give me an example?

[A]
There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is
InternalsVisibleTo
. I've only ever used this attribute for testing - where it's very handy!
Example:
To be placed in
```
AssemblyInfo.cs
```
```
```
[assembly: InternalsVisibleTo("OtherAssembly")]
```
```


q:
Right now I'm working on a web application that receives a significant amount of data from a database that has a potential to return null results. When going through the cyclomatic complexity for the application a number of functions are weighing in between 10 - 30. For the most part the majority of the functions with the high numbers have a lot of lines similar to the following:

If Not oraData.IsDBNull(4) Then row("Field") = oraData.GetString(4)

Which leads me to my question, what is the best way to go about trying to bring these numbers down? Right now I'm looking at having the majority of the functions below 10.

[A]
The first question is: Why are you "hung" up on CC ?  It's a tool to evaluate how dense the code is and a rule of thumb should be "not too high of a cc number".
It's probably hitting all those "IF"s and bringing up that number - so reduce the number of ifs by calling a wrap function that extracts the data from the result set which handles the null or change the query so it doesn't return nulls.
Keep in mind that nulls do provide information and are not useless. For example Republican or Democrat ?  using null says neither choice.


q:
For a web application, I want to build a WHERE clause AND submit it to the server. There I will append it to a query. The clause will be something like

LASTNAME LIKE 'Pep%' AND (DOB BETWEEN '19600101' AND '19601231 OR SALARY<35000)

Can you propose a regular expression to validate the clause before submitting it to SQL Server?

(Yes, of course, I would like a regex for the ORDER clause)

[A]
This is a monumentally bad idea. I would suggest you build a filter system instead where the user can select all kinds of options in a form, and then you build the correct sql server-side instead of opening yourself up to all kinds of injection attacks.
As an example of what might go wrong, consider this:
```
```
LASTNAME LIKE 'Pep%'--
DROP TABLE People
--
```
```
This will inject a DROP TABLE command into your SQL, which will be hard to detect. You can of course remove things like -- and /*, but I guarantee that someone can find a way in if you do this.


q: I realize this is a quite general question, but I am wondering about the performance impact of implementing business logic with WF contra imperative code in fairly large enterprise system. I would like to hear others experiences in this regard.

[A]
You can check
Performance Characteristics of Windows Workflow Foundation
for key performance considerations and modeling guidelines that are important when developing applications on top of the Windows Workflow Foundation.
However I would suggest to wait for the WF 4.0 announcement at PDC (end of October) since
they are promising
Significant improvements in
  performance and scalability
(Ten-fold
  improvement in performance)
EDIT (after PDC, 11Nov08):
OK, not much revealed about performance at PDC, although Kenny Wolf
said in his talk
that there are 10-100X performance improvements from execution speed to persistence sizes.
Moreover, Rick Garibay posted some post-talk discussions with Kenny Wolf
here
. I am copying a relevant passage:
My first question was around the
  impetus for such a major overhaul.
  Kenny shared that they focused very,
  very deeply on key customer requests
  and opportunities based on earlier
  versions of the framework. There were
  3 feature types that resonated most.
  First, is delivering a truly
  model-based framework that allows
  every aspect of the WF to be
  represented declaratively. Second, was
  being able to truly participate in the
  repository ecosystem, which is key for
  deployment, management and operations
  scenarios. And last, but not least was
  performance.
Earlier in his talk, Kenny cited
  intriguing improvements, including 10x
  to 100x performance improvements and
  persisted workflows becoming
  essentially "free" with WF 4.0. In our
  more one-on-one discussion after his
  talk, he used the analogy of swinging
  at a baseball with a wooden baseball
  bat. While the wooden baseball bat is
  effective, it feels a bit heavy, if
  not clunky at times. When you pick up
  an aluminum baseball bat, it is
  markedly lighter, and feels
  significantly more aerodynamic. WF 3.0
  and 3.5 work, but WF 4 is a new and
  improved aluminum baseball bat.


q: Is there a way to perform an HTTP GET request within a Visual Basic script?  I need to get the contents of the response from a particular URL for processing.

[A]
```
```
Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.
```
```


q:
For debugging purposes, I need to recursively search a directory for all files which start with a UTF-8 byte order mark (BOM). My current solution is a simple shell script:

find -type f |
while read file
do
    if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ]
    then
        echo "found BOM in: $file"
    fi
done

Or, if you prefer short, unreadable one-liners:

find -type f|while read file;do [ "`head -c3 -- "$file"`" == $'\xef\xbb\xbf' ] && echo "found BOM in: $file";done

It doesn't work with filenames that contain a line break,
but such files are not to be expected anyway.

Is there any shorter or more elegant solution?

Are there any interesting text editors or macros for text editors?

[A]
If you accept some false positives (in case there are non-text files, or in the unlikely case there is a ZWNBSP in the middle of a file), you can use grep:
```
```
fgrep -rl `echo -ne '\xef\xbb\xbf'` .
```
```


q:
I'm VERY new to WPF, and still trying to wrap my head around binding in XAML.

I'd like to populate a combobox with the values of a string collection in my.settings. I can do it in code like this:

Me.ComboBox1.ItemsSource = My.Settings.MyCollectionOfStrings

...and it works.

How can I do this in my XAML? is it possible?

Thanks

[A]
Yes
, you can (and should for the most part) declare bindings in XAML, since that's one of the most powerful features in WPF.
In your case, to bind the ComboBox to one of your custom settings you would use the following XAML:
```
```
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:p="clr-namespace:WpfApplication1.Properties"
    Title="Window1">
    <StackPanel>
        <ComboBox
            ItemsSource="{Binding Source={x:Static p:Settings.Default}, Path=MyCollectionOfStrings}" />
    </StackPanel>
</Window>
```
```
Notice the following aspects:
We declared an XML namespace with the prefix 'p' that points to the .NET namespace where the 'Settings' class lives in order to refer to it in XAML
We used the markup extension '{Binding}' in order to declare a binding in XAML
We used the markup extension 'Static' in order to indicate that we want to refer to a static ('shared' in VB) class member in XAML


q:
Given two absolute paths, e.g.

/var/data/stuff/xyz.dat
/var/data

How can one create a relative path that uses the second path as its base? In the example above, the result should be: ./stuff/xyz.dat

[A]
If you know the second string is part of the first:
```
```
String s1 = "/var/data/stuff/xyz.dat";
String s2 = "/var/data";
String s3 = s1.substring(s2.length());
```
```
or if you really want the period at the beginning as in your example:
```
```
String s3 = ".".concat(s1.substring(s2.length()));
```
```


q:
For a website like reddit with lots of up/down votes and lots of comments per topic what should I go with?

Lighttpd/Php or Lighttpd/CherryPy/Genshi/SQLAlchemy?

and for database what would scale better / be fastest MySQL ( 4.1 or 5 ? ) or PostgreSQL?

[A]
I can't speak to the MySQL/PostgreSQL question as I have limited experience with Postgres, but my Masters research project was about high-performance websites with CherryPy, and I don't think you'll be disappointed if you use CherryPy for your site.  It can easily scale to thousands of simultaneous users on commodity hardware.
Of course, the same could be said for PHP, and I don't know of any reasonable benchmarks comparing PHP and CherryPy performance.  But if you were wondering whether CherryPy can handle a high-traffic site with a huge number of requests per second, the answer is definitely yes.


q: Do any one know which sorting algorithm is used by .net when we implement IComparer in our class?

[A]
According to the
MSDN
, .NET uses QuickSort. By the way, the method absolutely doesn't depend on the comparer (as long as it's comparison-based), why should .NET therefore use a different method depending on whether you provide a custom comparer or not?


q: This concept is new to me, and a colleague suggested it. Sadly, I had no idea what he was talking about. Can someone enlighten me?

[A]
You can find plenty of information about it
here
.
In a nutshell, a PIA is a signed interop assembly that provides the "official" definition of types in a COM library from the publisher of the COM library.
As to the benefits, the posted article sums it up pretty good:
PIAs are important because they
  provide unique type identity. The PIA
  distinguishes the official type
  definitions from counterfeit
  definitions provided by other interop
  assemblies. Having a single type
  identity ensures type compatibility
  between applications that share the
  types defined in the PIA. Because the
  PIA is signed by its publisher and
  labeled with the
  PrimaryInteropAssembly attribute, it
  can be differentiated from other
  interop assemblies that define the
  same types.


q: I am looking for a way to create or implement a collapsible side panel inside of a form. Similar in the way a ToolStripContainer works I would like the same general concept except using panels that I can fill with controls. Does anyone know of a simple way to do this with the provided .Net controls or is this a total custom job. Either way I would appreciate some suggestions.

[A]
Try this it's in c# but I am sure it can be easily translated
Start a new Project and add a panel.
Dock that panel to the left of the Form.
Add a button to the Panel dock it to the right
Set the Button Text to "<" and Width to 20.
in the button1_Click event add this
```
```
private void button1_Click(object sender, EventArgs e)
    {
        if (button1.Text == ">")
        {
            panel1.Width = 200;
            button1.Text = "<";
        }
        else
        {
            panel1.Width = button1.Width;
            button1.Text = ">";
        }
    }
```
```
What happens here is when the button is clicked the form is shrunk off to the left, leaving only the button visible.  When the button is clicked again, it expands back out.


q:
I'm required to write documentation for my current project that lists all .c files and for each one lists every .h file which is directly or indirectly included by that file.

This is a large project, and although we have Makefiles which theoretically have this information, those Makefiles are sometimes incorrect (we inherited this project from another company).  We've often had to do a make clean ; make for our changes to actually be reflected in the recompilation, so I don't want to rely on these Makefiles.

So is there a tool which lets us give it the name of a .c file and an include path and have it tell us all of the .h files which are directly or indirectly included by the .c file?  We don't have anything weird like

#define my_include "some_file.h"
#include my_include

so the tool doesn't need to be perfect.  Anything that searched .c and .h files in an include path for regular includes would be good enough.

[A]
```
gcc -M file.c
```
does what you need.


q:
Situation:

text:  a string

R:  a regex that matches part of the string.  This might be expensive to calculate.

I want to both delete the R-matches from the text, and see what they actually contain.  Currently, I do this like:

import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re.findall(text)
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
ab_re.sub('',text)
# 'cdedfe flijijie  lifsjelifjl'

This runs the regex twice, near as I can tell.  Is there a technique to do it all on pass, perhaps using re.split?  It seems like with split based solutions I'd need to do the regex at least twice as well.

[A]
You could use split with capturing parantheses.  If you do, then the text of all groups in the pattern are also returned as part of the resulting list (from
python doc
).
So the code would be
```
```
import re
ab_re = re.compile("([ab])")
text="abcdedfe falijbijie bbbb laifsjelifjl"
matches = ab_re.split(text)
# matches = ['', 'a', '', 'b', 'cdedfe f', 'a', 'lij', 'b', 'ijie ', 'b', '', 'b', '', 'b', '', 'b', ' l', 'a', 'ifsjelifjl']

# now extract the matches
Rmatches = []
remaining = []
for i in range(1, len(matches), 2):
    Rmatches.append(matches[i])
# Rmatches = ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']

for i in range(0, len(matches), 2):
    remaining.append(matches[i])
remainingtext = ''.join(remaining)
# remainingtext = 'cdedfe flijijie  lifsjelifjl'
```
```


q: Anything would be good. Exemples, best practices, samples, etc.

[A]
Hanselman just blogged on this yesterday, he has a huge list of links:
http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx


q: I'm just wondering if the same thread is used for each session, or if its dangerous to count on a particular thread between requests. What I'm getting at, is can I use thread static storage?

[A] The short answer is yes. The thread used for a request is returned to the thread pool and can be used to service other requests. They are NOT session specific, and to answer your second question, you should never count on a particular thread being available for subsequent requests on a particular session. Because of this, it is a very bad idea to use thread static variables in ASP.Net.


q:
Possible Duplicate:

  Where do I find the current C or C++ standard documents?

I want to use STL with the current program I'm working on and the vendor doesn't support what I feel is a reasonable STL, working is not my idea of reasonable.  I have been unable to find a C++ Standard or an STL standard that is not just an API that leaves me wondering if my interpretation is correct or if the vendor interpretation is correct.  I've already spent a great deal of time at SGI's site.  Any reccomendations?  Also, is there any document that's not an API that would be considered the standard?

[A]
The Standard is available as a PDF for ANSI.org.  ($18 last time I checked, downloadable).
$18 for a downloadable PDF was considered a breakthrough, since previously ANSI only sold it standards in hardcopy form, for several thousand dollars a copy. (Normally, ANSI standards have a very limit market -- only motorcycle helmet manufacturers are going to buy the ANSI Standard for motorcycle helmets etc), and Standard sales was the primary way ANSI financed it's operation.
Each national standards body in ISO can make the Standard available as they see fit.  I'm told British Standards had made a deal to publish it in book form, but I don't know it taht ever came about.


q:
What's the best .NET PDF editing library available, and why?

It needs to be used on an IIS web-server.
Specifically, I need to edit a PDF which was generated by reporting services.

Factors I'm interested in:

Speed

Memory Consumption

Price

Quality of documentation

Library stability

Size of library

Whatever else you think is important

[A]
I don't know if it's the best, but I use
PDF-Writer.NET
, for which I paid $89. I have used it in several production applications. I like it because it's easy to set up and use, and it doesn't require a lot of coding, which makes it easier for new developers to ramp up on it.
Before that I was hacking together PDFs using an open source library and the Acrobat interop DLLs. That was rough.


q:
Our web application sends e-mails. We have lots of users, and we get lots of bounces. For example, user changes company and his company e-mail is no longer valid.

To find bounces, I parse SMTP log file with log parser. The logs come from Microsoft SMTP server.

Some bounces are great, like 550+#5.1.0+Address+rejected+user@domain.com. There is user@domain.com in bounce.

But some do not have e-mail in error message, like 550+No+such+recipient.

I have created simple Ruby script that parses logs (uses log parser) to find which mail caused something like 550+No+such+recipient.

I am just surprised that I could not find a tool that does it. I have found tools like Zabbix and Splunk for log analysis, but they look like overkill for such simple task.

Anybody knows a tool that would parse SMTP logs, find bounces and e-mails that cause them?

[A]
This
article
is exactly what you are looking for. It is based on the great tool
log parser
.
Log parser is a powerful, versatile
  tool that provides universal query
  access to text-based data such as log
  files, XML files and CSV files, as
  well as key data sources on the
  Windows® operating system such as the
  Event Log, the Registry, the file
  system, and Active Directory®.  You
  tell Log Parser what information you
  need and how you want it processed.
  The results of your query can be
  custom-formatted in text based output,
  or they can be persisted to more
  specialty targets like SQL, SYSLOG, or
  a chart.  Most software is designed to
  accomplish a limited number of
  specific tasks. Log Parser is
  different... the number of ways it can
  be used is limited only by the needs
  and imagination of the user.  The
  world is your database with Log
  Parser.


q:
Does SQLAlchemy support some kind of caching so if I repeatedly run the same query it returns the response from cache instead of querying the database? Is this cache automatically cleared when the DB is updated?

Or what's the best way to implement this on a CherryPy + SQLAlchemy setup?

[A]
Not an answer to your second question, but from the comments in this link indicates that SQLAlchemy does not support cacheing :
http://spyced.blogspot.com/2007/01/why-sqlalchemy-impresses-me.html
Raven said...
```
```
Does SQLAlchemy do any kind of internal caching?

For example, if you ask for the same data twice (or an obvious subset
of the initially requested data) will the database be hit once or twice?

I recently wrote a caching database abstraction layer for an
application and (while fun) it was a fair bit of work to get it to a
minimally functional state. If SQLAlchemy did that I would seriously
consider jumping on the bandwagon.

I've found things in the docs that imply something like this might be
going on, but nothing explicit.
4:36 PM
```
```
Jonathan Ellis said...
```
```
No; the author of SA [rightly, IMO] considers caching a separate concern.

What you saw in the docs is probably the SA identity map, which makes it so
if you load an instance in  two different places, they will refer
to the same object. But the database will still be queried twice, so it is
not a cache in the sense you mean.
```
```


q:
I know that you can apply CSS in order to style objects in Flex using the StyleManager:

http://livedocs.adobe.com/flex/3/html/help.html?content=styles_07.html

You can also load compiled CSS files (SWFs) dynamically:

http://livedocs.adobe.com/flex/3/html/help.html?content=styles_10.html

However, I'm dynamically creating my CSS files using a web GUI and a server-side script.
If the CSS is changed, then the script would also need to compile the CSS into an SWF (which is not a viable option).  Is there any way around this?

[A]
The application of CSS in Flex is handled on the server side at compilation and not on the client side at run time.
I would see two options then for you (I'm not sure how practical either are):
Use a server side script to compile your CSS as a SWF then load them dynamically.
Parse a CSS Style sheet and use the setStyle functions in flex to apply the styles. An similar example to this approach is the
Flex Style Explorer
where you can check out the
source
.
Good luck.


q: Are there any good code profilers/analyzers for Erlang? I need something that can build a call graph (eg gprof) for my code.

[A]
The 'fprof' module includes profiling features. From the
fprof module documentation
:
```
```
fprof:apply(foo, create_file_slow, [junk, 1024]).
fprof:profile().
fprof:analyse().
```
```
```
fprof:apply
```
(or
```
trace
```
) runs the function,
```
profile
```
converts the trace file into something useful, and
```
analyse
```
prints out the summary. This will give you a list of function calls observed, what called them, and what they called, as well as wall-clock timing info.


q: What is the best way to set the time on a remote machine remotely?  The machine is running Windows XP and is receiving the new time through a web service call.  The goal is to keep the remote machines in synch with the server.  The system is locked down so that our web service is the only access, so I cannot use a time server on each remote machine.

[A]
This is the Win32 API call for setting system time:
```
```
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME {
 public short wYear;
 public short wMonth;
 public short wDayOfWeek;
 public short wDay;
 public short wHour;
 public short wMinute;
 public short wSecond;
 public short wMilliseconds;
 }
 [DllImport("kernel32.dll", SetLastError=true)]
public static extern bool SetSystemTime(ref SYSTEMTIME theDateTime );
```
```
I'm not exactly sure how you would get the security worked out such that you could execute that function on the client, though.
You can get a lot more detail on setting system time at
PInvoke
.


q:
Suppose I have following string:

String asd = "this is test ass this is test"

and I want to split the string using "ass" character sequence.

I used:

asd.split("ass");

It doesn't work. What do I need to do?

[A]
It seems to work fine for me:
```
```
public class Test
{
    public static void main(String[] args) {
        String asd = "this is test ass this is test";
        String[] bits = asd.split("ass");
        for (String bit : bits) {
            System.out.println("'" + bit + "'");
        }
    }
}
```
```
Result:
```
```
'this is test '
' this is test'
```
```
Is your real delimiter different perhaps? Don't forget that split uses its parameter as a regular expression...


q:
If you want to associate some constant value with a class, here are two ways to accomplish the same goal:

class Foo
{
public:
    static const size_t Life = 42;
};

class Bar
{
public:
    enum {Life = 42};
};

Syntactically and semantically they appear to be identical from the client's point of view:

size_t fooLife = Foo::Life;
size_t barLife = Bar::Life;

Is there any reason other than just pure style concerns why one would be preferable to another?

[A]
They're not identical:
```
```
size_t *pLife1 = &Foo::Life;
size_t *pLife2 = &Bar::Life;
```
```


q:
What's the best way to remove a page frame automatically?

I've used this type of code before:

<script language="JavaScript">
setTimeout ("changePage()", 3000);
function changePage() {
if (self.parent.frames.length != 0)
self.parent.location="http://www.example.com";
}
</script>

[A]
Do it this way if you want the frame-breaking step to not appear in the history
```
```
if ( self.location !== top.location )
{
    top.location.replace( self.location );
}
```
```


q:
I have a program in which I've lost the C++ source code.  Are there any good C++ decompilers out there?

I've already ran across Boomerang.

[A]
You can use
IDA Pro
by
Hex-Rays
. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a
lot
of manual labor reversing the code.
If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.


q: Real UID, effective UID, and some systems even have a "saved UID". What's the purpose of all these, especially the last one?

[A]
Each UNIX process has 3 UIDs associated to it. Superuser privilege is UID=0.
Real UID
This is the UID of the user/process that created THIS process. It can be changed only if the running process has EUID=0.
Effective UID
This UID is used to evaluate privileges of the process to perform a particular action. EUID can be changed either to RUID, or SUID if EUID!=0. If EUID=0, it can be changed to anything.
Saved UID
If you run an executable with the set-UID bit set, then the resulting running process will start off with a real UID of the real user running it, and an effective and saved UID of the owner of the executable file. If the process then calls setuid() or seteuid() to change their effective UID, they can still get back their original privileges again thanks to the saved UID. If the set-UID bit is not set, SUID will be the RUID.


q:
This is probably a simple answer but I can't find it.  I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero.  I could do this on the code side but thought it would be best to enforce it on the table.

Thanks!

I was in error with my last comment all is good now.

[A]
Create a database constraint:
```
```
ALTER TABLE Table1 ADD CONSTRAINT Constraint1 CHECK (YourCol > 0)
```
```
You can have pretty sophisticated constraints, too, involving multiple columns. For example:
```
```
ALTER TABLE Table1 ADD CONSTRAINT Constraint2 CHECK (StartDate<EndDate OR EndDate IS NULL)
```
```


q:
I want to put my master pages in a central library so I can use them in several projects without having the maintanance nightmare.
Everything is refactored in a generic and central way, they are all in a "shared" namespace.
But if put them in a seperate project, I can't reference them

[A]
I don't believe you can put that actual .master pages in an external library. You can place your own customer MasterPage-derived class in the library, and have your client apps derive from that, but I don't think that's what your intent is, since you're tagged with asp.net-mvc (implying very narrow views without much logic, and probably no code-behinds).
As far as I'm aware, there isn't a way to reference a master (nor, for that matter, an ASPX or ASCX) from an external library. Wish I had better news for you. (And I actually hope I'm wrong; I hope someone else here has figured out a technique for this, as I'd like to use that kind of thing myself on occasion.)


q:
My web application is relying on container-managed security and I'm wondering if it's possible to use salted passwords at all. As far as I can tell it's easy enough to store digested passwords in a database by just configuring a JDBC or DataSource Realm, but there's no way to add a salt to those digest.

Any suggestions?

Edit: it seems I just need to think some more before asking questions ;-)

It's just a matter of choosing who's doing the digest calculation (client or server) and configure Tomcat accordingly.

[A]
Passord-based encryption in JCE uses salt as per PKCS#5.  See
http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.html#PBEEx
for an example.


q:
I'm exploring git to see how it might work for my company. I've got git installed and I need to know a couple things:

How can I set up a git server on my computer to act as my central repo?

I'm trying to figure out how to manage my workflow with just the GUI on Windows (using the GUI is a requirement). How do I take a bunch of files in a folder and get them into my GIT repo?

If there's a good tutorial for each item I'm plenty happy looking there instead if you can point me in the right direction. Thanks!

[A]
In order to get started, you're going to have to use the command line.
First you'll want to initialize a local repo in place.  cd to the folder your files that you want under version control and issue:
```
```
git init
```
```
You've now initialized a git repository in that foleder.  Now you need to add all of the files to it:
```
```
git add .
git commit -m "Initial Import"
```
```
Now cd to the parent folder of your local repository.  You're going to want to make a "Bare" clone of the repository to act as your central repo.  Issue the following command:
```
```
git clone projectFolder/ ProjectName.git
```
```
ProjectName.git will be created with only the version control repository.  Move this folder to wherever you want to act as your central repository.  From there on out, you can clone and pull from the central repository and push to the central repository.
To clone from a central repository via SSH:
```
```
git clone [user@]host.xz:/path/to/repo.git/
```
```
Or, if your repo is on a network share
```
```
git clone D:/path/to/repo.git/
```
```
This is also doable from the GUI client for checking out and pushing changes back to the repo.


q:
Sorry, that title just hurts.  I'm wondering if there is a Linq to collections extension method that collapses the following code segment into a single line:

public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents){

  var result = new List<Child>();

  foreach(Parent parent in parents)
    foreach(Child child in parent.Children)
      result.Add(child);

  return result;
}

If you can collapse that into a single statement, try it on insane difficulty:

public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas){

  var result = new List<Child>();

  foreach(Grandparent papa in nanas)
    foreach(Parent parent in papa.Children)
      foreach(Child child in parent.Children)
        result.Add(child);

  return result;
}

[A]
This will work:
```
```
public IEnumerable<Child> GetAllChildren(IEnumerable<Parent> parents)
{
    return from parent in parents
           from child in parent.Children
           select child;
}
```
```
and then this:
```
```
public IEnumerable<Child> GetAllChildren(IEnumerable<Grandparent> nanas)
{
    return from papa in nanas
           from parent in papa.Children
           from child in parent.Children
           select child;
}
```
```
Note, in this example I'm not actually returning a list, I'm returning an IEnumerable data source that until you start to foreach over it, or similar, won't actually do any processing.
If you need to return a list, modify each return statement as follows:
```
```
return (from .....
            ...
            select child).ToList();
```
```


q:
I would like to execute ls in a Perl program as part of a CGI script. For this I used exec(ls), but this does not return from the exec call.

Is there a better way to get a listing of a directory in Perl?

[A]
In order to get the output of a system command you need to use backticks.
```
```
$listing = `ls`;
```
```
However, Perl is good in dealing with directories for itself. I'd recommend using File::Find::Rule.


q:
We are running our Junit 4 test suite against Weblogic 9 in front of an Oracle 10 database (using Hudson as a continuous integration server) and occasionally we will get an ORA-12519 crash during script teardown.  However, the error is very intermittent:

It usually happens for the same Test class

It doesn't always happen for the same test cases (sometimes they pass)

It doesn't happen for the same number of test cases (anywhere from 3-9)

Sometimes it doesn't happen at all, everything passes

While I can't guarantee this doesn't happen locally (when running against the same database, of course), I have run the same suite of class multiple times with no issues.

Any ideas?

[A]
Don't know if this will be everybody's answer, but after some digging, here's what we came up with.
The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)?  The key to the issue wasn't that we couldn't connect, but that it was
intermittent
After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went.  Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).
The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.
So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak.  Hope that helps.


q:
As you may already know, the .NET Framework's protected internal access modifier works in a strange way: It doesn't mean the class is protected AND internal, it says the class is protected OR internal; that is, the modified class or member can be accessed from whitin the same assembly as well as from the same hierarchy.

So, knowing this: When would you use it? Can you give an example? Is there a good, illuminating usage example inside .NET Base Class Library?

[A]
I have rarely needed to use this access modifier combination as I think that in all but the most extreme circumstances, it's an indicator of poor design. However, sometimes it is necessary to have helper classes like type converters and editors access the method inside your assembly, but only allow derived classes to access it in other use cases.
An example might be a call that turns a type into a string for the type converter.
```
ToString()
```
generally isn't used for this purpose so you might have a
```
ToPersistableString()
```
call that you want your type converter to use, so you make it
```
internal
```
. Then you decide that people deriving from your class may well want to use this call as part of their own persistence scheme for their derived class so you make it
```
protected
```
as well.
.NET Framework Use
```
AccessibilityNotifyClients
```
on
```
Control
```
is
```
protected internal
```
. Using
Reflector
, I can see that this was done so that the
```
CheckedItemCollection
```
of
```
CheckListBox
```
could access it when changing checked states.


q: What is a DOCVARIABLE in Microsoft Word 2003? How do I set it? How do I make it display in my Word document?

[A]
You can use the Microsoft Visual Basic for Applications Variables collection to set and retrieve the contents of a string variable in a Word document or template.
Also, you can use the DocVariable field to retrieve the value of a document variable after it has been set to display within a Word document.
Source:
How to store and retrieve variables in Word documents
```
```
Sub GetSetDocVars()

Dim fName As String
fName = "Jeff Smith"
' Set contents of variable "fName" in a document using a document
' variable called "FullName".
ActiveDocument.Variables.Add Name:="FullName", Value:=fName
' Retrieve the contents of the document variable.
MsgBox ActiveDocument.Variables("FullName").Value

End Sub
```
```


q:
Is there a way of reusing the same resultMap multiple times in a single query.

For example, suppose I have a "foo" resultMap:

<resultMap id="foo" class="Foo">
  <result property="Bar" column="bar" />
</resultMap>

Is there a way to define another resultMap that reuses the above for different columns? Something like...

<resultMap id="fizz"class="Fizz">
  <result property="Foo1" column="bar=bar1" resultMapping="foo" />
  <result property="Foo2" column="bar=bar2" resultMapping="foo" />
  <result property="Foo3" column="bar=bar3" resultMapping="foo" />
</resultMap>

[A]
Almost.  If you select the ID of the Foo in your query, you can have the Fizz result map execute a SELECT for that ID, which will use the Foo result map.
```
<result property="Foo1" column="bar1Id" select="selectFoo"/>
```
(Assuming you have a
```
selectFoo
```
query defined.)  But that's extremely slow with large result sets, since it does an additional SELECT for every row.
iBATIS has a solution to this problem for the typical case, where you have a composite object that contains various other objects.  First, you define a query that joins your tables, then you can use
```
fooMap
```
to populate a
```
Foo
```
:
```
<result property="Foo1" resultMap="fooMap"/>
```
But you can't use that result map twice for two different
```
Foos
```
because the result map specifies certain column names.  You can use another technique, though:
```
<result property="foo1.bar" column="foo1bar"/>
```
```
<result property="foo2.bar" column="foo2bar"/>
```
More detail in page 35 of the iBatis Datamapper manual.


q:
Clearly the following is incorrect.

INSERT INTO `aTable` (`A`,`B`) VALUES((SELECT MAX(`A`) FROM `aTable`)*2),'name');

I get the value:

SQL query:

INSERT INTO `aTable` (`A`, `B` )
VALUES
(
  (
   SELECT MAX(`A`)
   FROM `aTable`
  ) *2
 , 'name'
)

MySQL said:

1093 - You can't specify target table 'aTable' for update in FROM clause

So, I'm trying to make a bitmap table, each row corresponds to one Bit, and has a 'map' value.

To insert in the table, I don't want to do two queries, I want to do one.
How should I do this?

No one commented on this, but since I am trying to make a bitmap, it should be * 2 not ^ 2, my mistake, please note that is why the comments often say ^ 2, it was an error in the version that the commenters read.

[A]
I think you need to drop the "VALUES", and have a valid select statement.
see this link
I'm not particularly a mySQL guy, I use MSSQL mostly.  But If you format the select statement correctly, It should work.


q:
Consider the following interface in Java:

public interface I {
    public final String KEY = "a";
}

And the following class:

public class A implements I {
    public String KEY = "b";

    public String getKey() {
        return KEY;
    }
}

Why is it possible for class A to come along and override interface I's final constant?

Try for yourself:

A a = new A();
String s = a.getKey(); // returns "b"!!!

[A]
You are hiding it, it's a feature of "Scope".  Any time you are in a smaller scope, you can redefine all the variables you like and the outer scope variables will be "Shadowed"
By the way, you can scope it again if you like:
```
```
public class A implements I {
    public String KEY = "b";

    public String getKey() {
        String KEY = "c";
        return KEY;
    }
}
```
```
Now KEY will return "c";
Edited because the original sucked upon re-reading.


q:
Is it possible with Axis2 and Eclipse to generate a Web Service client and have it use java types that you already have in packages instead of creating it's own types.  Reason being of course if I have type A already created and it creates it's own Type A I can't just assign variable of type A to variable of type B.

The wsdl is being generated from a Web Service deployed to an application server.
If it's not possible to generate it from that would it be possible to generate a client from the already existing java files.

[A]
You are generating the web service client from wsdl, correct?
The only thing that the wsdl2java tool knows about is the information in the wsdl, so it won't know about any types that you have already created.
If you can get the type information into the wsdl you may get it to work, although I have never tried.
If you want an easy way to copy from Type A to Type B then you could try
BeanUtils.copyProperties
, as long as the setters and getters of Type A and Type B match.


q:
I tried the following code in LINQPad and got the results given below:

List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump();
listFromSplit.ForEach(delegate(string s)
{
  s.Trim();
});
listFromSplit.Dump();

"a" and " b"

so the letter b didn't get the white-space removed as I was expecting...?

Anyone have any ideas

[NOTE: the .Dump() method is an extension menthod in LINQPad that prints out the contents of any object in a nice intelligently formatted way]

[A]
you're just creating a trimmed string, not assigning anything to it.
```
```
var s = "  asd   ";
s.Trim();
```
```
won't update s, while..
```
```
var s = "   asd   ";
s = s.Trim();
```
```
will..
```
```
var listFromSplit = "a, b".Split(',').Select(s=>s.Trim());
```
```
would, i suppose, be how i'd go about it.


q: I wish to migrate the database of a legacy web app from SQL Server to MySQL. What are the limitations of MySQL that I must look out for ? And what all items would be part of a comprehensive checklist before jumping into actually modifying the code ?

[A]
First thing I would check is the data types - the exact definition of datatypes varies from database to database. I would create a mapping list that tellme what to map each of the datatypes to. That will help in building the new tables. I would also check for data tables or columns that are not being used now. No point in migrating them. Do the same with functions, job, sps, etc. Now is the time to clean out the junk.
How are you accessing the data through sps or dynamic queries from the database? Check each query by running it aganst a new dev database and make sure they still work. Again there are differences between how the two flavors of SQl work. I've not used my sql so I'm not sure what some of the common failure points are.  While you are at it you might want to time new queries and see if they can be optimized. Optimization also varies from database to database and while you are at it, there are probably some poorly performing queries right now that you can fix as part of the migration.
User defined functions will need to be looked at as well. Don't forget these if you are doing this.
Don't forget scheduled jobs, these will need to be checkd and recreated in myslq as well.
Are you importing any data ona regular schedule? All imports will have to be rewritten.
Key to everything is to use a test database and test, test, test. Test everything especially quarterly or annual reports or jobs that you might forget.
Another thing you want to do is do everything through scripts that are version controlled. Do not move to production until you can run all the scripts in order on dev with no failures.


q:
I have a String such as:

Cerepedia, una apliación web

I would like to transform it into something URL valid such as:

Cerepedia,unaaplicacionweb

Note: the special character transformation and spaces removal.

By the way, are commas allowed in URLs?

[A]
Have you looked at
URLEncoder
? That seems to do what you need it to do. Though the special characters will be transformed to escaped entities and not stripped from their "special" properties.


q:
What are those bad habits you've developed since you've started coding in Cocoa?

I think making a list of bad habits and actively adding to it and, more importantly, breaking those habits is a good technique to produce your code quality. So start now, get your bad habits off your chest. Maybe other people share your bad habits.

[A]
Here's some of mine:
Throwing exceptions without any attempt to catch 'em. I've started to rely on NSError more and more to prevent NSExceptions from flying about like bullets in a John Woo movie, but I still have a lot of
exceptional
code out there.
Writing a quick class to do X, Y & Z and then forgetting to clean up in dealloc. Leaks ahoy!
Using strings directly in various places (KVO) instead of defining a constant and using that (see Dave Dribin's excellent
blog post
on KVO for more)


q:
Is it possible to reload a page that was loaded thru link_to_remote? I'm doing this in my controller:

def create
 if captchas_verified
  do_something
 else
  render :action=>'new'
end

But when the captchas is wrong, it do not render a form that is inside of the new template. By the way, in the webserver log, it shows that the templades was rendered.

Thanks!

UPDATED: Today i changed the render to:

render(:update) { |page| page.call 'location.reload' }

But it makes me update the page that called the link_to_remote not the page that was opened thru the link_to_remote

UPDATED 2: I fixed using
    page.replace_html "mydiv", :partial => "new"
instead of
    page.call 'location.reload'

[A]
Something like this should do what you want.
```
```
render :update do |page| page << 'window.location.reload()' end
```
```


q:
How would you go about creating a random alpha-numeric string that matches a certain regular expression?

This is specifically for creating initial passwords that fulfill regular password requirements.

[A]
If you have a specific problem, you probably have a specific regular expression in mind. I would take that regular expression, work out what it means in simple human terms, and work from there.
I suspect it's
possible
to create a general regex random match generator, but it's likely to be
much
more work than just handling a specific case - even if that case changes a few times a year.
(Actually, it may not be possible to generate random matches in the most general sense - I have a vague memory that the problem of "does any string match this regex" is the halting problem in disguise. With a very cut-down regex language you may have more luck though.)


q:
I like to know if there is a way to read the user input inside a batch file, because i have a file named: "fif.bat" that recives two parameters (just call them paramA and paramB) so i execute the file like this:

fif paramA paramB

I have to change paramA every month, but i call this file lot of times so i like to open a console and have printed this:

fif paramA

So i only have to write paramB and change paramA when i want it.

PD: paramA is very large so it's very helpful if i can have it there instead of writing every time. And i don't want to make another batch file to call fif whit paramA.

[A]
You can prompt for user input in a batch file using
```
SET /P
```
for example:
```
```
SET /P paramB="Prompt String: "
```
```


q:
We are implementing an IP based geolocation service, and we need to find some IP's from various markets (LA, NY etc) to fully test the service.

Does anybody know of a directory where we could find what IP ranges are used where?

EDIT: We have already implemented the system, it uses a 3rd party DB and a webservice. We just want some IP's from known markets to verify its working properly.

I'm going to see if I can get what I need from the free maxmind database.

[A]
Not sure if cost is a factor but there are a few open source databases knocking about.
This one
claims 99.3% accuracy on its free version with 99.8% for its paid version. They've also got a
Free & Open Source City Database
(76% accuracy at city level).
They're both available as CSV-based databases so you can easily take a known location and get an IP range for ISPs in the area.
The tougher part is getting access to a computer in that IP range.


q:
Hey everyone, I am researching a project where we would need to keep a value encrypted from the client all the way to a black box system without decrypting it at any point in between.  We are using SSL between the browser and web server, but the values are automatically decrypted at the web server, which is what we need to keep from happening.  We need to be able to pass it through the web server (still encrypted) and through other back end systems until it hits its final destination where it would be decrypted.

So my question is what options are available to us for maintaining an encrypted state for a value from the browser back, without decrypting it anywhere along the way?

Thanks
Mark

[A]
you'll want to take a look at
public key encryption
. SSL protects your session (browser <-> server) but not the full transport. i'd suggest encrypting your data once it's received from the client, then sending the encrypted data all the way in.
here's a terrible diagram outlining the flow of data
```
```
client browser    web server       random server       blackbox
route   ---- SSL -------------><------------- not encrypted ------->
data                          *-------- PGP/GPG encrypted --------->
```
```
basically your data is encrypted via SSL to the web server, where it is PGP/GPG encrypted, then sent downstream. SSL doesn't matter at this point (or at least, isn't the primary form of encryption).
unless you can guarantee javascript in your environment, it may be better to encrypt at the web server to make sure your data is secure if the user has javascript off for some reason.


q:
I'm a huge fan of robocopy and use it extensively to copy between various servers I need to update.

Lately I've been archiving to an Amazon S3 account that I access via a mapped drive using JungleDisk.  I then robocopy my files from local PC to S3.

Sometimes I get a very strange 'Incorrect function' error message in robocopy and the file fails to copy.  I've tried xcopy and straightforward copy and paste between file explorer windows.  In each case I get some variation of the 'Incorrect function' or 'Illegal MS-DOS function' and the file will never copy.

I delete the target but to no avail.

Any ideas?

[A]
Don't know if you're allowed to answer your own questions but I think I've fixed it...
I found this in the
jungledisk support forums
The quick solution is to zip the
  files, delete the original, then unzip
  the files because zip can't handle
  extended attributes. Another solution
  is to move them to a FAT filesystem,
  then move again to NTFS filesystem,
  because FAT don't manage extended
  attributes.
In both cases the result is the
  deletion of extended attributes, and
  the files can be moved to the
  jungledisk.
The files can have extended attributes
  for different reasons, expecially
  migrations from other filesystems: in
  my case was the migration of a CVS
  repository from a ext2 filesystem to
  NTFS.
Seems to have worked for me...


q:
I'm trying to write a regex to replace all spaces that are not included in quotes so something like this:

a = 4, b = 2, c = "space here"

would return this:

a=4,b=2,c="space here"

I spent some time searching this site and I found a similar q/a ( Split a string by spaces -- preserving quoted substrings -- in Python ) that would replace all the spaces inside quotes with a token that could be re-substituted in after wiping all the other spaces...but I was hoping there was a cleaner way of doing it.

[A]
I consider this very clean:
```
```
mystring.scan(/((".*?")|([^ ]))/).map { |x| x[0] }.join
```
```
I doubt
gsub
could do any better (assuming you want a pure regex approach).


q:
I have image data and i want to get a sub image of that to use as an opengl texture.

glGenTextures(1, &m_name);
glGetIntegerv(GL_TEXTURE_BINDING_2D, &oldName);
glBindTexture(GL_TEXTURE_2D, m_name);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data);

How can i get a sub image of that image loaded as a texture. I think it has something to do with using glTexSubImage2D, but i have no clue how to use it to create a new texture that i can load. Calling:

glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset, xWidth, yHeight, GL_RGBA, GL_UNSIGNED_BYTE, m_data);

does nothing that i can see, and calling glCopyTexSubImage2D just takes part of my framebuffer.
Thanks

[A]
Edit:
Use glPixelStorei. You use it to set
```
GL_UNPACK_ROW_LENGTH
```
to the width (in pixels) of the entire image. Then you call glTexImage2D (or whatever), passing it a pointer to the first pixel of the subimage and the width and height of the subimage.
Don't forget to restore
```
GL_UNPACK_ROW_LENGTH
```
to 0 when you're finished with it.
Ie:
```
```
glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );
char *subimg = (char*)m_data + (sub_x + sub_y*img_width)*4;
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, subimg );
glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
```
```
Or, if you're allergic to pointer maths:
```
```
glPixelStorei( GL_UNPACK_ROW_LENGTH, img_width );
glPixelStorei( GL_UNPACK_SKIP_PIXELS, sub_x );
glPixelStorei( GL_UNPACK_SKIP_ROWS, sub_y );

glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data );

glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );
glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 );
glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 );
```
```
Edit2:
For the sake of completeness, I should point out that if you're using OpenGL-ES then you don't get
```
GL_UNPACK_ROW_LENGTH
```
. In which case, you could either (a) extract the subimage into a new buffer yourself, or (b)...
```
```
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, sub_width, sub_height, 0, GL_RGBA, GL_UNSIGNED_BYTES, NULL );

for( int y = 0; y < sub_height; y++ )
{
    char *row = m_data + ((y + sub_y)*img_width + sub_x) * 4;
    glTexSubImage2D( GL_TEXTURE_2D, 0, 0, y, sub_width, 1, GL_RGBA, GL_UNSIGNED_BYTE, row );
}
```
```


q:
I'm working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria, but they also want the flexibility to query for all people with the first name of "James" that works in the Health Department. The one thing I want to avoid is to simply have the stored procedure take a list of parameters and generate a SQL statement to execute, since that would open doors to SQL injection at an internal level.

Can this be done?

[A]
My first thought was to write a query something like this...
```
```
SELECT EmpId, NameLast, NameMiddle, NameFirst, DepartmentName
  FROM dbo.Employee
       INNER JOIN dbo.Department ON dbo.Employee.DeptId = dbo.Department.Id
 WHERE IdCrq IS NOT NULL
       AND
       (
          @bitSearchFirstName = 0
          OR
          Employee.NameFirst = @vchFirstName
       )
       AND
       (
          @bitSearchMiddleName = 0
          OR
          Employee.NameMiddle = @vchMiddleName
       )
       AND
       (
          @bitSearchFirstName = 0
          OR
          Employee.NameLast = @vchLastName
       )
       AND
       (
          @bitSearchDepartment = 0
          OR
          Department.Id = @intDeptID
       )
```
```
...which would then have the caller provide a bit flag if they want to search a particular field and then supply the value if they are to search for it, but I don't know if this is creating a sloppy WHERE clause or if I can get away with a CASE statement in the WHERE clause.
As you can see this particular code is in T-SQL, but I'll gladly look at some PL-SQL / MySQL code as well and adapt accordingly.


q:
Because I run a blog aggregator website which checks a large list of RSS feeds for new posts every hour so I will be happy if its possible to use google feed api or Google AJAX Feed API instead of making the cron jobs to read the whole feed to know if its updated or not.
like this link text

[A]
You can use the Google Feed API, however instead of polling the feed source every hour you will still need to poll the google feed API every hour.  It doesn't notify you of feed updates.  If you want to be notified when to update feeds, then you should look into using a ping server,
http://en.wikipedia.org/wiki/Ping_blog
to determine when feeds are updated so that you know it is time to fetch the feed again.  Not all feeds use a ping server, but it might help you for those that do.


q:
Say I have a C function which takes a variable number of arguments: How can I call another function which expects a variable number of arguments from inside of it, passing all the arguments that got into the first function?

Example:

void format_string(char *fmt, ...);

void debug_print(int dbg_lvl, char *fmt, ...) {
    format_string(fmt, /* how do I pass all the arguments from '...'? */);
    fprintf(stdout, fmt);
 }

[A]
To pass the ellipses on, you initialize a
```
va_list
```
as usual and simply pass it to your second function. You don't use
```
va_arg()
```
. Specifically;
```
```
void format_string(char *fmt,va_list argptr, char *formatted_string);

void debug_print(int dbg_lvl, char *fmt, ...)
{
 char formatted_string[MAX_FMT_SIZE];

 va_list argptr;
 va_start(argptr,fmt);
 format_string(fmt, argptr, formatted_string);
 va_end(argptr);
 fprintf(stdout, "%s",formatted_string);
}
```
```


q:
Visual Studio makes calling a web service easy, trying to figure out what is going on under the covers is difficult.

How can I see the actual XML generated from my .Net app when making a call to a web service?

[A]
tools like
tcptrace
or
Fiddler
can help.
few troubleshooting links:
Tracing WCF with TcpTrace
Using Fiddler and Excel 07 to debug web services
Fiddler Can Make Debugging Easy


q:
During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this:

select * from customer
where customer.id in (34, 26, ..., 2);

You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string.

My approach I have used so far is something like that:

String result = "";
boolean first = true;
for(String string : collectionOfStrings) {
    if(first) {
        result+=string;
        first=false;
    } else {
        result+=","+string;
    }
}

But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated.

What is your (more) elegant way?

[A]
I'm not sure how "sophisticated" this is, but it's certainly a bit shorter. It will work with various different types of collection e.g. Set<Integer>, List<String>, etc.
```
```
public static final String toSqlList(Collection<?> values) {

    String collectionString = values.toString();

    // Convert the square brackets produced by Collection.toString() to round brackets used by SQL
    return "(" + collectionString.substring(1, collectionString.length() - 1) + ")";
}
```
```
Exercise for reader
: modify this method so that it correctly handles a null/empty collection :)


q:
If you develop for ATG Dynamo, how do you structure your modules and dependencies?

How do you structure the projects? source directories, JARs configs etc.

How do you build and deploy? What tools do you use?

[A]
We have a monolithic architecture with a single ATG module. We originally developed this site with JHTML and have since created a (monolithic) J2EE web app within this ATG module and converted all of our JHTML to JSP.
Our project on disk looks like this:
```
```
root
  deploy
    class (compile java to here)
    config (primary configpath)
    docroot (JHTML docroot)
    dev (configpath for dev environment)
    test (configpath for QA environment)
    prod (configpath for prod environment)
  j2ee (j2ee web-app)
    WEB-INF
    dir-a (application JSPs)
    dir-b (application JSPs)
  src
    java (java src)
    sql (sql src)
```
```
We have an Ant build file that compiles the Java source to deploy/class. On dev/test and prod JAR up. We have a single build server that checks out the CVS repository and uses shell scripts and the build.xml to compile and deploy to the requested server using Interwoven OpenDeploy (essentially rsync).


q:
My initial installation for the MySQL had no password for root. I assigned a password for root and everything worked fine. Due to some reason (don't ask why) I had to revert back to the original settings where root didn't have any password.

I changed the root password to '' (empty string). The problem now is that MySQL doesn't run with 'mysql -uroot', it expects a password. On running 'mysql -uroot -p' and hitting enter on the password prompt gets me into the db, but is not same as the default setting.

Is there any other flag/setting that I am missing to set/unset which tells mysql to not expect a password?

Thanks

[A]
How to Reset MySQL root password:
To reset it, see
How to Reset the Root Password
in the MySQL manual.
How to run MySQL without password controlled access
To run MySQL with the password controls disabled, check out the
--skip-grant-tables
option.
How to avoid typing credentials on the command line
If you simply want to avoid having to type the password on the mysql command line, create a file called .my.cnf (note leading period on that filename!) in your home directory. In your case, for the root user, probably /root
Add the following entries to the file
```
```
[client]
host=localhost
user     = root
password = mypassword
database = mydatabase
```
```
You'd typically chmod 600 this file so that only you can see it, and MySQL will ignore a .my.cnf which is world writable anyway.
See the manual page
Using Option Files
for more information


q:
i got a client side javascript function which is triggered on a button click (basically, its a calculator!!). Sometimes, due to enormous data on the page, the javascript calculator function take to long & makes the page appear inactive to the user. I was planning to display a transparent div over entire page, maybe with a busy indicator (in the center) till the calculator function ends, so that user waits till process ends.

function CalculateAmountOnClick() {
  // Display transparent div

  // MY time consuming loop!
    {

    }

  // Remove transparent div

}

Any ideas on how to go about this? Should i assign a css class to a div (which surrounds my entire page's content) using javascript when my calculator function starts? I tried that but didnt get desired results. Was facing issues with transparency in IE 6. Also how will i show a loading message + image in such a transparent div?

TIA

[A]
I would do something like:
unhide a div (
```
display:inline
```
)
make the
```
position:absolute
```
give it a
```
z-index:99
```
make the height and width
```
100%
```
when the processing is done set
```
display:none
```
To make it transparent you'll have to set the opacity which is different in Firefox, IE, etc.
To show a loading icon you can always create a second div and position it where you want to on the page.  When it's done loading, remove it along with the transparent one.


q:
I came across an issue that makes me think there is bug in the 3.0 framework. When I try to use extension methods I get the following error:

Missing compiler required member
'System.Runtime.CompilerServices.ExtensionAttribute..ctor'

When using this simple code:

public static class StringUtils {
    static void TestExtension(this String targetString) {

    }
}

The only way to make this compile error go away is to add the following code:

namespace System.Runtime.CompilerServices {
    public class ExtensionAttribute : Attribute { }
}

It's been a few months since I have used extensions methods, but I'm pretty sure I didn't have to do this. Has anyone else come across this issue?

[A]
Your framework isn't high enough for Extension Methods.
That's a
hack
for making extension methods work without being in 3.5


q:
It seems that Groovy does not support break and continue from within a closure. What is the best way to simulate this?

revs.eachLine { line ->
    if (line ==~ /-{28}/) {
         // continue to next line...
    }
}

[A]
You can only support continue cleanly, not break.  Especially with stuff like eachLine and each.  The inability to support break has to do with how those methods are evaluated, there is no consideration taken for not finishing the loop that can be communicated to the method.   Here's how to support continue --
Best approach (assuming you don't need the resulting value).
```
```
revs.eachLine { line ->
    if (line ==~ /-{28}/) {
        return // returns from the closure
    }
}
```
```
If your sample really is that simple, this is good for readability.
```
```
revs.eachLine { line ->
    if (!(line ==~ /-{28}/)) {
        // do what you would normally do
    }
}
```
```
another option, simulates what a continue would normally do at a bytecode level.
```
```
revs.eachLine { line ->
    while (true) {
        if (line ==~ /-{28}/) {
            break
        }
        // rest of normal code
        break
    }

}
```
```
One possible way to support break is via exceptions:
```
```
try {
    revs.eachLine { line ->
        if (line ==~ /-{28}/) {
            throw new Exception("Break")
        }
    }
} catch (Exception e) { } // just drop the exception
```
```
You may want to use a custom exception type to avoid masking other real exceptions, especially if you have other processing going on in that class that could throw real exceptions, like NumberFormatExceptions or IOExceptions.


q:
Whats the benefit of:

public string User {get; set;}

over

public string User;

Since you can't access the private member in the first case, how is it any different that just making your property public?

[A]
The second example is making the
field
public, not a property (your question). This provides a simple way of making simple properties. Properties should be your default, not public fields; the list of reasons is endless, but starts with:
encapsulation
ability to add notification
encapsulation
ability to do validation
encapsulation
data binding
encapsulation
security checking
oh - and did I mention encapsulation?
Changing from a field to a property after-the-fact is a breaking change - especially if you use a lot of "ref" code or mutable structs (yeuch).


q:
What are the key use cases for the use of virtualization -- that is, running one or more "virtual PCs" using software such as VMWare and Microsoft Virtual PC -- for software development?

Also -- are there other instances/uses of virtualization that aren't covered by my definition above (use of a tool like MS Virtual PC or VMWare), and that are useful to developers?

My impetus for asking is this StackOverflow comment by Metro Smurf asserting "You'll wonder how you ever developed without it!", regarding use of virtualization.

(Please include just one use case per response.  Thanks!)

[A] Application testing in multiple environments is one obvious use of virtualization that I'm aware of.  Testing your application on other operating systems (without requiring additional physical computers to do so), as well as testing that involves software that generally only allows you to install a single version on a given machine (such as the Internet Explorer browser; running both IE6 and IE7 on the same machine is not an officially supported configuration), are good candidates for virtual machine usage.


q:
Is it possible to call a class's static property to set the navigateurl property?

<asp:HyperLink ID="hlRegister" NavigateUrl="<%= SomeClass.Property %>"  runat="server" />

without using codebehind ofcourse!

[A]
sure, in the code behind:
```
```
hl.NavigateUrl = Class.Static().ToString();
```
```


q: How do I query an Oracle database to display the names of all tables in it?

[A]
```
```
SELECT owner, table_name
  FROM dba_tables
```
```
This is assuming that you have access to the
```
DBA_TABLES
```
data dictionary view.  If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the
```
SELECT ANY DICTIONARY
```
privilege or the
```
SELECT_CATALOG_ROLE
```
role (either of which would allow you to query any data dictionary table).  Of course, you may want to exclude certain schemas like
```
SYS
```
and
```
SYSTEM
```
which have large numbers of Oracle tables that you probably don't care about.
Alternatively, if you do not have access to
```
DBA_TABLES
```
, you can see all the tables that your account has access to through the
```
ALL_TABLES
```
view:
```
```
SELECT owner, table_name
  FROM all_tables
```
```
Although, that may be a subset of the tables available in the database (
```
ALL_TABLES
```
shows you the information for all the tables that your user has been granted access to).
If you are only concerned with the tables that you own, not those that you have access to, you could use
```
USER_TABLES
```
:
```
```
SELECT table_name
  FROM user_tables
```
```
Since
```
USER_TABLES
```
only has information about the tables that you own, it does not have an
```
OWNER
```
column – the owner, by definition, is you.
Oracle also has a number of legacy data dictionary views--
```
TAB
```
,
```
DICT
```
,
```
TABS
```
, and
```
CAT
```
for example-- that could be used.  In general, I would not suggest using these legacy views unless you absolutely need to backport your scripts to Oracle 6.  Oracle has not changed these views in a long time so they often have problems with newer types of objects.  For example, the
```
TAB
```
and
```
CAT
```
views both show information about tables that are in the user's recycle bin while the
```
[DBA|ALL|USER]_TABLES
```
views all filter those out.
```
CAT
```
also shows information about materialized view logs with a
```
TABLE_TYPE
```
of "TABLE" which is unlikely to be what you really want.
```
DICT
```
combines tables and synonyms and doesn't tell you who owns the object.


q:
The code-complete feature in Visual Studio is very useful, and it still works for C# and C++ code - but no longer works for XAML (XML) editing.

Is there a setting somewhere that can re-enable this?  My co-workers still have it working.

[A]
(I'm assuming that you mean intellisense by "code complete")
Intellisense for xml documents is controlled by XSD files.  When you're editing a xaml file, look at the menu bar.  You should see a menu item called XML.  At the bottom of this  you'll see a menu item "Schemas..."  Click on that.
You'll see a list of all the available schemas in the system.  Messing with this list, or the schemas that ship with VS (usually in c:\program files\visual studio 9.0\xml\schemas) can cause xml (aka xaml) intellisense.
I would first suggest making sure there are no checks or X's in the Use column for any schema.  All cells should be blank (aka Automatic).  This way, VS picks up the namespaces from your xml file and applies the corresponding schemas from this list.
Secondly, check the namespaces in your xml file.  Check to see if the corresponding XSD schema is listed.  If not, hunt it down and add it in.
If these two don't fix the problem, get a full copy of your co-worker's schema directory and copy it over yours.  Open up that schema window and make sure every XSD is in there, and set to automatic.
The last step is a repair install of Visual Studio, followed by a good helping of automatic updates.
If you're talking about the addin "code complete", get the latest version from their website and reinstall it.  SP1 might have broken your current installation.


q: How does sharepoint identify a file type? For example, SharePoint will not allow you to upload executable files. Suppose if i rename a file extension from .exe to say, .doc, will the sharepoint allow the upload of this file?

[A]
I believe there are two ways to identify file types. A naive approach is to check the extension. A more secure approach would be to examine the bits of the file and see what type the file is as many file types have a few bits (
magic numbers
) in the header that identify the format.
Depending on how SharePoint checks the file, that will determine how you can cheat the system.