Question: I want to learn MVC "architecture pattern" but I don't want to jump into a framework like Rails or Django just yet.  I want to understand the concept first and write some simple code in my currently familiar environment, which happens to be PHP/HTML/CSS/MySQL.  I don't necessarily need a tutorial that is based on PHP, as I do understand a lot of different languages. And I don't want to have to install any frameworks or APIs or libraries.  I just want to learn how to think in MVC and apply it to my projects. Any suggestions?

Answer:
Almost every framework does MVC differently, so you might end up getting even more confused. The general principles of MVC are very simple: "Model is state; view reacts to model; controller reacts to view; controller changes model". The model, view and controller are concepts - they are whatever you feel them to be. Classes, bunches of classes, instances of classes with XML configuration files, you name it.
I actually think that about covers the basic principles. Without a framework, you'd not get much further. What matters is how a particular framework defines model, view and controller and their interactions.


Question: How can I set points on a 24h period spreaded by the Gaussian distributions? For example to have the peak at 10 o'clock?

Answer:
If you have trouble generating gaussian distributed random points look up
http://en.wikipedia.org/wiki/Box-Muller_transform
Else please clarify your question.


Question:
I am trying to use Lucene Java 2.3.2 to implement search on a catalog of products. Apart from the regular fields for a product, there is field called 'Category'. A product can fall in multiple categories. Currently, I use FilteredQuery to search for the same search term with every Category to get the number of results per category.

This results in 20-30 internal search calls per query to display the results. This is slowing down the search considerably. Is there a faster way of achieving the same result using Lucene?

Answer:
You may want to consider looking through all the documents that match categories using a
TermDocs iterator
.
This example code goes through each "Category" term, and then counts the number of documents that match that term.
```
```
public static void countDocumentsInCategories(IndexReader reader) throws IOException {
    TermEnum terms = null;
    TermDocs td = null;

    try {
        terms = reader.terms(new Term("Category", ""));
        td = reader.termDocs();
        do {
            Term currentTerm = terms.term();

            if (!currentTerm.field().equals("Category")) {
                break;
            }

            int numDocs = 0;
            td.seek(terms);
            while (td.next()) {
                numDocs++;
            }

            System.out.println(currentTerm.field() + " : " + currentTerm.text() + " --> " + numDocs);
        } while (terms.next());
    } finally {
        if (td != null) td.close();
        if (terms != null) terms.close();
    }
}
```
```
This code should run reasonably fast even for large indexes.
Here is some code that tests that method:
```
```
public static void main(String[] args) throws Exception {
    RAMDirectory store = new RAMDirectory();

    IndexWriter w = new IndexWriter(store, new StandardAnalyzer());
    addDocument(w, 1, "Apple", "fruit", "computer");
    addDocument(w, 2, "Orange", "fruit", "colour");
    addDocument(w, 3, "Dell", "computer");
    addDocument(w, 4, "Cumquat", "fruit");
    w.close();

    IndexReader r = IndexReader.open(store);
    countDocumentsInCategories(r);
    r.close();
}

private static void addDocument(IndexWriter w, int id, String name, String... categories) throws IOException {
    Document d = new Document();
    d.add(new Field("ID", String.valueOf(id), Field.Store.YES, Field.Index.UN_TOKENIZED));
    d.add(new Field("Name", name, Field.Store.NO, Field.Index.UN_TOKENIZED));

    for (String category : categories) {
        d.add(new Field("Category", category, Field.Store.NO, Field.Index.UN_TOKENIZED));
    }

    w.addDocument(d);
}
```
```


Question:
I don't need a Link but rather only the href= part of the ActionLink.

But if I call Html.ActionLink(...) I get a  back.
Is there a way to just return the URL of the Action while not getting the ?

Answer:
Edit: in response to commment, now including parameters:
```
```
<% =Html.BuildUrlFromExpression<YourController>(c => c.YourAction(parameter)) %>
```
```


Question: Has anyone used the noweb literate programming tool on a large Java project, where several source code files must be generated in different subdirectories? How did you manage this with noweb? Are there any resources and/or best practices out there?

Answer:
Literate Programming works its best if the generated intermediate code can point back to the original source file to allow debugging, and analyzing compiler errors.  This usually means pre processor support, which Java doesn't support.
Additionally Literate Programming is really not necessary for Java, as the original need for a strict sequential order - which was what prompted Knuth to write a tool to put snippets together in the appropriate sequence - is not present.    The final benefit of literate programming, namely being able to write prose about the code, is also available as Javadoc which allow you to put everything in as comments.
To me, there is no benefit in literate programming for Java, and only troubles (just imagine getting IDE support).
Any particular reason you are considering it?


Question:
What type of authentication would you suggest for the service that is:

implemented as WCF and exposed via
varios enpoints (including XML-RPC)

has to be consumed easily by various cross-platform clients

Why?

Options that I'm aware of are:

Forms-based authentication for IIS-hosted WCF (easy to implement, but has horrible cross-platform support, plus it is not REST)

Sending plain-text username/pwd with every call (easy to use on any platform, but totally unsecure)

Using ticket-based authentication, when username&pwd are used to create a ticket that is valid for some time and is passed with every request (can be consumed by any client easily, but the API model is bound to this type of security)

Thanks for your time!

Answer:
Literate Programming works its best if the generated intermediate code can point back to the original source file to allow debugging, and analyzing compiler errors.  This usually means pre processor support, which Java doesn't support.
Additionally Literate Programming is really not necessary for Java, as the original need for a strict sequential order - which was what prompted Knuth to write a tool to put snippets together in the appropriate sequence - is not present.    The final benefit of literate programming, namely being able to write prose about the code, is also available as Javadoc which allow you to put everything in as comments.
To me, there is no benefit in literate programming for Java, and only troubles (just imagine getting IDE support).
Any particular reason you are considering it?


Question: I have read in some of the ClickOnce posts that ClickOnce does not allow you to create a desktop icon for you application. Is there any way around this?

Answer:
The desktop icon can be a shortcut to the
```
.application
```
file. Install this as one of the first things your application does.


Question:
I'm working on a Java library and would like to remove some functions from it. My reasons for this is public API and design cleanup. Some objects have setters, but should be immutable, some functionality has been implemented better/cleaner in different methods, etc.

I have marked these methods 'deprecated', and would like to remove them eventually. At the moment I'm thinking about removing these after few sprints (two week development cycles).

Are there any 'best practices' about removing redundant public code?

/JaanusSiim

Answer:
Use
@deprecated
tag. Read the
Deprecation of APIs
document for more info.
After everyone using the code tells you they have cleaned up on their side, start removing the deprecated code and wait and see if someone complains - then tell them to fix their own code...


Question:
Here's the problem:

split=re.compile('\\W*')

This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like k&amp;auml;ytt&amp;auml;j&aml;auml;.

What should I add to the regex to include the & and ; characters?

Answer:
You probably want to take the problem reverse, i.e. finding all the character without the spaces:
```
```
[^ \t\n]*
```
```
Or you want to add the extra characters:
```
```
[a-zA-Z0-9&;]*
```
```
In case you want to match HTML entities, you should try something like:
```
```
(\w+|&\w+;)*
```
```


Question: Can someone point me in the right direction? I wish to distribute a WCF peer to peer cloud over the internet. So far I've seen examples of how it works on the same subnet. I wish to push it a little further.

Answer:
I believe you'll need to look into using
IPV6 Teredo Tunneling
for crossing NAT and firewalls, so maybe check out this on
WCF transports
from MSDN.
Also, take a look at the
PRNP series
Kevn Hoffman did this year.


Question: Say if I had a table of books in a MySQL database and I wanted to search the 'title' field for keywords (input by the user in a search field); what's the best way of doing this in PHP? Is the MySQL LIKE command the most efficient way to search?

Answer:
Yes, the most efficient way usually is searching in the database. To do that you have three alternatives:
LIKE, ILIKE
to match exact substrings
RLIKE
to match POSIX regexes
FULLTEXT
indexes to match another three different kinds of search aimed at natural language processing
So it depends on what will you be actually searching for to decide what would the best be. For book titles I'd offer a LIKE search for exact substring match, useful when people know the book they're looking for and also a FULLTEXT search to help find titles similar to a word or phrase. I'd give them different names on the interface of course, probably something like exact for the substring search and similar for the fulltext search.
An example about fulltext:
http://www.onlamp.com/pub/a/onlamp/2003/06/26/fulltext.html


Question:
I have a Delphi DLL with a function defined as:

function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer;

I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as:

[DllImport("opt7bja.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int SubmitJobStringList(string[] tStringList, ref int jobno);

But when I call it I get a memory access violation exception.

Anyone know how to pass to a tStringList correctly from C#?

Answer:
You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#, and pass it with the help of your best friend, the Interop Marshaller. Note that even the Delphi string type is different from the .NET string type, and passing it without telling the marshaller what he should do, he will pass it as a char-array, most likely.
Other than that, I would suggest changing the Delphi DLL. It's never a good thing to expose anything Delphi-specific in a DLL that is to be used by non-Delphi clients. Make the parameter an array of PChar and you should be fine.


Question:
I am about to set up a subversion server to be accessed via svn+ssh. I was wondering, where the default repository location is (on a unix box).

Do you put it in

/opt/svn

or

/home/svn

or

/usr/subversion

or even

/svn

or somewhere else?

I am looking for the place, most people put it. Is there a convention?

EDIT:

It is absolutely possible to "hide" the actual repository location from the user. For example (in my case) by wrapping the svnserve executable in a way that it is called like:

svnserve -r /var/svn/repos

Answer:
I typically place the repositories somewhere under
```
/var
```
, usually in
```
/var/lib/svn
```
- I'm trying to follow the
Filesystem Hierarchy Standard
which has this to say about the
purpose of /var
:
```
/var
```
is specified here in order to make it possible to mount
```
/usr
```
read-only. Everything that once went into
```
/usr
```
that is written to during system operation (as opposed to installation and software maintenance) must be in
```
/var
```
.


Question:
Why isn't this project maintained anymore?  I love this app, however not updating it seems like a crime against all .Net developers. There are several items that I would love to add to it given the chance of a future release.

Can anyone share something I don't know?

Answer:
http://nunit.org
shows that the latest release is 2.4.8, released on July 21, 2008. It looks like it's still an active project to me.


Question:
I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice.

Please note that this is to work with MS Project 2003, so should avoid any of the Excel native functions and anything .net related.

Answer:
Take a look
here
:
Edit:
The referenced source (allexperts.com) has since closed, but here are the relevant
author
comments:
There are many algorithms available on the web for sorting.  The most versatile and usually the quickest is the
Quicksort algorithm
.  Below is a function for it.
Call it simply by passing an array of values (string or numeric; it doesn't matter) with the
Lower Array Boundary
(usually
```
0
```
) and the
Upper Array Boundary
(i.e.
```
UBound(myArray)
```
.)
Example
:
```
Call QuickSort(myArray, 0, UBound(myArray))
```
When it's done,
```
myArray
```
will be sorted and you can do what you want with it.
(Source:
archive.org
)
```
```
Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi) \ 2)

  While (tmpLow <= tmpHi)
     While (vArray(tmpLow) < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If
  Wend

  If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
  If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub
```
```
Note that this only works with
single-dimensional
(aka "normal"?) arrays.  (There's a working multi-dimensional array QuickSort
here
.)


Question:
I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box.

The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server.

Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software?

Edit:

Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary.

I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here.

Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so:

wscript sendmail.vbs

Answer:
I think that you'll have to install some ActiveX or other component what could be invoked from WScript, such as:
http://www.activexperts.com/ActivEmail/
and:
http://www.emailarchitect.net/webapp/SMTPCOM/developers/scripting.asp
Otherwise, you'll have to write the entire SMTP logic (if possible, not sure) in WScript all on your own.


Question: How to unit test WCF services? Any 3rd Party tools available?

Answer:
What exactly do you want to test? Connectivity or service methods?
Cool thing about WCF is that you can just define interfaces (err, contracts) and test them as regular code. Then you can assume that they will work via any connection type supported by WCF.
Connectivity can be tested by hosting your service directly in UT or on development web-server.
As for tools, you there are tons of unit testing frameworks: NUnit, built-in tests in Visual Studio, xUnit, etc, etc.
You can download "
Visual Studio 2008 and .NET Framework 3.5 Training Kit
" and "
.NET Framework 3.5 Enhancements Training Kit
" if I recall correctly there were samples for WCF unit tests


Question:
I fill a collection one single time when my J2EE webapp starts.
Then, several thread may access it at same time but only to read it.

I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ?

Answer:
Normally no because you are not changing the internal state of the collection in this case. When you iterate over the collection a new instance of the iterator is created and the state of the iteration is per iterator instance.
Aside note:
Remember that by keeping a read-only collection you are only preventing modifications to the collection itself. Each collection element is still changeable.
```
```
class Test {
    public Test(final int a, final int b) {
        this.a = a;
        this.b = b;
    }

    public int a;
    public int b;
}

public class Main {

    public static void main(String[] args) throws Exception {
        List<Test> values = new ArrayList<Test>(2);
        values.add(new Test(1, 2));
        values.add(new Test(3, 4));

        List<Test> readOnly = Collections.unmodifiableList(values);
        for (Test t : readOnly) {
            t.a = 5;
        }

        for (Test t : values) {
            System.out.println(t.a);
        }
    }

}
```
```
This outputs:
```
```
5
5
```
```
Important considerations from @WMR answser.
It depends on if the threads that are
  reading your collection are started
  before or after you're filling it. If
  they're started before you fill it,
  you have no guarantees (without
  synchronizing), that these threads
  will ever see the updated values.
The reason for this is the Java Memory
  Model, if you wanna know more read the
  section "Visibility" at this link:
http://gee.cs.oswego.edu/dl/cpj/jmm.html
And even if the threads are started
  after you fill your collection, you
  might have to synchronize because your
  collection implementation could change
  its internal state even on read
  operations (thanks
Michael
  Bar-Sinai
,
  I didn't know such collections
  existed).
Another very interesting read on the
  topic of concurrency which covers
  topics like publishing of objects,
  visibility, etc. in much more detail
  is Brian Goetz's book
Java
  Concurrency in
  Practice
.


Question: Does anyone have tools or experience with code coverage for PL/SQL. I believe this is possible using DBMS_PROFILER?

Answer:
Not sure if this is quite what you're after, but in 10g onwards there's a tool to do static PL/SQL code analysis.
Info here...
http://www.psoug.org/reference/plsql_warnings.html
Note that it can be enabled at either session or database level.
In my experience it's thrown up quite a few false negatives so far.


Question:
I am actually new to this forum and I kept trying for a few days to find an easy way to copy an entire LDAP subtree to another tree. Since I couldn't find anything useful, i thought of dropping a question here as well. Does anybody know how to do this programatically ?

For normal operations like add, remove, search, I've been using Spring LDAP.

Thanks a lot !

Answer:
I actually don't know Spring LDAP but if your LDAP interface does not provide any high level abstraction for moving/renaming or copying an entire subtree you have to move/rename or copy all subtree nodes recursively. The LDAP API does not provide such an option directly.
The following is pseudo-code:
```
```
function copySubtree(oldDn, newDn)
{
    copyNode(oldDn, newDn); // the new node will be created here
    if (nodeHasChildren(oldDn) {
        foreach (nodeGetChildren(oldDn) as childDn) {
            childRdn=getRdn(childDn); // we have to get the 'local' part, the so called RDN
            newChildDn=childRdn + ',' + newDn; // the new DN will be the old RDN concatenated with the new parent's DN
            copySubtree(childDn, newChildDn); // call this function recursively
        }
    }
}
```
```


Question: Is there a way to print all methods of an object in JavaScript?

Answer:
From
here
:
Example 1: This example writes out all the properties of the "navigator" object, plus their values:
```
```
for (var myprop in navigator){
 document.write(myprop+": "+navigator[myprop]+"<br>")
}
```
```
Just replace 'navigator' with whatever object you are interested in and you should be good to go.
As mentioned by Anthony in the comments section - This returns all attributes not just methods as the question asked for.
Oops!  That'll teach me to try and answer a question in a language I don't know.  Still, I think the code is useful - just not what was required.


Question:
I have a stored procedure that looks like:

CREATE PROCEDURE dbo.usp_TestFilter
  @AdditionalFilter BIT = 1
AS
  SELECT *
  FROM dbo.SomeTable T
  WHERE
    T.Column1 IS NOT NULL
    AND CASE WHEN @AdditionalFilter = 1 THEN
      T.Column2 IS NOT NULL

Needless to say, this doesn't work. How can I activate the additional where clause that checks for the @AdditionalFilter parameter? Thanks for any help.

Answer:
```
```
CREATE PROCEDURE dbo.usp_TestFilter
  @AdditionalFilter BIT = 1
AS
  SELECT *
  FROM dbo.SomeTable T
  WHERE
    T.Column1 IS NOT NULL
    AND (NOT @AdditionalFilter OR T.Column2 IS NOT NULL)
```
```


Question:
I've always used a *.h file for my class definitions, but after reading some boost library code, I realised they all use *.hpp. I've always had an aversion to that file extension, I think mainly because I'm not used to it.

What are the advantages and disadvantages of using *.hpp over *.h?

Answer:
It does not matter which extension you use. Either one is OK.
I use
```
*.h
```
for C and
```
*.hpp
```
for C++.


Question:
How do I check if an object is of a given type, or if it inherits from a given type?

How do I check if the object o is of type str?

Beginners often wrongly expect the string to already be "a number" - either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultaneously an integer. This is the wrong canonical for those questions. Please carefully read the question and then use How do I check if a string represents a number (float or int)?, How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate.

Answer:
```
```
isinstance(o, str)
```
```
Link to docs


Question: What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $_GET and $_POST variables in PHP?

Answer:
You can use the
```
request.get?
```
and
```
request.post?
```
methods to distinguish between HTTP Gets and Posts.
See
http://api.rubyonrails.org/classes/ActionDispatch/Request.html


Question:
For an std::map<std::string, std::string> variables, I'd like to do this:

BOOST_CHECK_EQUAL(variables["a"], "b");

The only problem is, in this context variables is const, so operator[] won't work :(

Now, there are several workarounds to this; casting away the const, using variables.count("a") ? variables.find("a")->second : std::string() or even making a function wrapping that. None of these seem to me to be as nice as operator[]. What should I do? Is there a standard way of doing this (beautifully)?

Edit: Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.

Answer:
```
find
```
is the idiomatic form. Casting away
```
const
```
is almost always a bad idea. You'd have to guarantee that no write operation is performed. While this can be reasonably expected of a read access on a map, the specification doesn't say anything about this.
If you
know
that the value exists you can of course forego the test using
```
count
```
(which is quite inefficient, anyway, since it means traversing the map twice. Even if you don't know whether the element exists I wouldn't use this. Use the following instead:
```
```
T const& item(map<TKey, T> const& m, TKey const& key, T const& def = T()) {
    map<TKey, T>::const_iterator i = m.find(key);
    return i == m.end() ? def : i->second;
}
```
```
/EDIT: As Chris has correctly pointed out, default-construction of objects of type
```
T
```
might
be expensive, especially since this is done even if this object isn't actually needed (because the entry exists). If this is the case, don't use the default value for the
```
def
```
argument in the above case.


Question: I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?

Answer:
Have a look at the
ItemTemplateSelector
property of your list control. You can point it to a custom TemplateSelector and decide which template to use in code.
Here's a blog post describing TemplateSelectors:
http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20463.aspx
Edit: Here's a better post:
http://blog.paranoidferret.com/index.php/2008/07/16/wpf-tutorial-how-to-use-a-datatemplateselector/


Question:
Is it possible to prevent the Windows Installer from running every time Access 2003 and Access 2007 are started, when they are both installed on the same machine at the same time..?

Like many developers I need to run more than 1 version of MS Access.  I have just installed Access 2007.  If I open Access 2003 and then open Access 2007 I have to wait 3mins for the 'Configuring Microsoft Office Enterprise 2007..." dialog.  Then if I open Access 2003 again it takes another 30secs or so to configure that.

PLEASE NOTE: I am using shortcuts to open the files that include the full path to Access.  Eg to open Access 2007:

 "C:\program files\microsoft office 12\office12\msaccess.exe" "C:\test.accdb"

and for 2003:

 "C:\program files\microsoft office 11\office11\msaccess.exe" "C:\test.mdb"

Answer:
This is caused by Windows Installer, which is used by both installers. Advertised shortcuts as used by both Office 2003 and Office 2007 invoke Windows Installer to check that the entire feature is installed properly; the installer detects that something else (in this case the other product) has registered the file extensions used by Access (possibly the ProgIds as well) and decides that a repair is necessary, so it invokes the 'Configuring Office' dialog and proceeds to reinstall various components.
To avoid this, run Access from Program Files directly; create shortcuts if you'll be doing this frequently.


Question:
There is probably is simple fix for this but I currently have code similar to

dim dr as dbDataReader

try
      dr = connection.getDataReader(sql_str)
Catch ex as sqlClientException
     log.error(ex)
finally

  if not IsNothing(dr) then
    dr.close
  end if
end try

However Visual Studio still warns me that the

if not IsNothing(dr) then
        dr.close
      end if

Can cause a NullReferenceException. What is the best way to mitigate this? I can't move the declaration into the try block.

Answer:
Your code is correct. In the
```
finally
```
statement, as long as you check to make sure your objects are not null, it won't throw a null reference exception based on what happens in your code.


Question:
I have an if condition which checks for value and the it throws new NumberFormatException

Is there any other way to code this

if (foo)
{
    throw new NumberFormatException
}

// ..

catch (NumberFormatException exc)
{
    // some msg...
}

Answer:
If your aim is to avoid to throw a new exception:
```
```
if(foo)
{
  //some msg...
} else
{
  //do something else
}
```
```


Question:
I'm setting up a new project using CruiseControl.net 1.4.

I see from ccnet contributions
that there are two options for a subversion repository number labeller - a
feature that I would really like to make use of.

1) SVNLabeller available from jcxsoftware

and

2) Svnrevisionlabeller available from google code

My problem is that (1) claims support for ccnet 1.4 but I can't find
any documentation on how to configure it.

(2) comes with documentation but does not claim to support ccnet 1.4

Can anyone help me with either how to configure SVNLabeller or tell me
if Svnrevisionlabeller works with 1.4?

Answer:
Have you looked at
David Keaveny’s Blog Post
regarding the SVNRevisionLabeller? The link will take you to a detailed post on it's usage.
We are currently testing this utility against the current release (1.4) of CCNet without any problems, i.e. it's producing the correct revision and build labels appended to the major/minor digits we specify.
Hope this helps


Question:
In Python, you can do this:

import webbrowser
webbrowser.open_new("http://example.com/")

It will open the passed in url in the default browser

Is there a ruby equivalent?

Answer:
Windows Only Solution:
```
```
require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute(...)
```
```
Shell Execute on MSDN


Question:
I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using find piped with xargs grep:

find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN'

But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.

Answer:
So I discovered
pcregrep
which stands for
Perl Compatible Regular Expressions GREP
.
the -M option makes it possible to search for patterns that span line boundaries.
For example, you need to find files where the '
_name
' variable is followed on the next line by the '
_description
' variable:
```
```
find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description'
```
```
Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...


Question:
I am relatively new to matchers. I am toying around with hamcrest in combination with JUnit and I kinda like it.

Is there a way, to state that one of multiple choices is correct?

Something like

assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest

The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java?

(I am open to hamcrest-alternatives)

Answer:
```
```
assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3)))
```
```
From
Hamcrest tutorial
:
```
anyOf
```
- matches if any matchers match, short circuits (like Java ||)
See also
Javadoc
.
Moreover, you could write your own Matcher, which is quite easy to do.


Question:
If you use Image.Save Method to save an image to a EMF/WMF, you get an exception (http://msdn.microsoft.com/en-us/library/ktx83wah.aspx)

Is there another way to save the image to an EMF/WMF?
Are there any encoders available?

Answer:
A metafile is a file which records a sequence of GDI operations. It is scalable because the original sequence of operations that generated the picture are captured, and therefore the co-ordinates that were recorded can be scaled.
I think, in .NET, that you should create a
```
Metafile
```
object, create a
```
Graphics
```
object using
```
Graphics.FromImage
```
, then perform your drawing steps. The file is automatically updated as you draw on it. You can find a small sample in the documentation for
Graphics.AddMetafileComment
.
If you really want to store a bitmap in a metafile, use these steps then use
```
Graphics.DrawImage
```
to paint the bitmap. However, when it is scaled it will be stretched using
```
StretchBlt
```
.


Question:
in Erlang I have a supervisor-tree of processes, containing one that accepts tcp/ip connections. For each incoming connection I spawn a new process. Should this process be added to the supervisor tree or not?

Regards,
 Steve

Answer:
If you expect these processes to be many, it could be a good idea to add a supervisor under your main supervisor as to separate responsibility (and maybe use the
```
simple_one_for_one
```
setting to make things simpler, maybe even simpler than your current case).
The thing is, if you need to control these processes, it's always nice to have a supervisor. If it doesn't matter if they succeed or not, then you might not need one. But then again, I always argue that that is sloppy coding. ;-)
The only thing I
wouldn't
do, is to add them to your existing tree, unless it is very obvious where they come from and they're fairly few.


Question: I am wondering whether it is safe to mix jdk 1.5 and 1.6 (Java 6) object serialization (biderctional communication). I searched for an explicit statement from sun concerning this question but did not succeed. So, besides the technical feasability I am searching for an "official" statement concerning the problem.

Answer: After testing with a serialized object written to a file using the ObjectOutputStream in a Java 1.5 program, then running a read with a ObjectInputStream in a Java 1.6 program I can say this worked without any issue.


Question: I need to understand the differences between windows main/mdi/child/dialogs.... how win32 messages should be propagated... why some messages are present in one type and not other...

Answer:
Im not a windows developer, but heres what I understand:
main window - toplevel container which you can active/see in the taskbar.
dialog - little box locking (if modal) your window, not seeable in the taskbar. Mostly used to display message to the user.
mdi (Multiple Document Interface) - Not directly a window but more a simple container for storing child windows. Each child window can be maximized/minimized/closed inside this container, but you wont find any of these in the taskbar.
http://en.wikipedia.org/wiki/Multiple_document_interface


Question:
Is there any facility of transposing rows to columns in SQL Server (it is possible in MS-Access)?
I was befuddled because this facility is available in MS-Access but not in SQL Server. Is it by design that this feature has not been included in SQL Server?

Answer:
The example at
http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm
only works if you know in advance what the row values can be.   For example, let's say you have an entity with custom attributes and the custom attributes are implemented as rows in a child table, where the child table is basically variable/value pairs, and those variable/value pairs are configurable.
```
```
color red
size  big
city  Chicago
```
```
I'm going to describe a technique that works.  I've used it.  I'm NOT promoting it, but it works.
To pivot the data where you don't know what the values can be in advance, create a temp table on the fly with no columns.  Then use a cursor to loop through your rows, issuing a dynamically built "alter table" for each variable, so that in the end your temp table has the columns, color, size, city.
Then you insert one row in your temp table, update it via another cursor through the variable, value pairs, and then select it, usually joined with its parent entity, in effect making it seem like those custom variable/value pairs were like built-in columns in the original parent entity.


Question:
What's the best way to trim a DateTime object to a specific precision?  For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this?

private static DateTime TrimDateToMinute(DateTime date)
{
    return new DateTime(
        date.Year,
        date.Month,
        date.Day,
        date.Hour,
        date.Minute,
        0);
}

What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.

Answer:
You could use an enumeration
```
```
public enum DateTimePrecision
{
  Hour, Minute, Second
}

public static DateTime TrimDate(DateTime date, DateTimePrecision precision)
{
  switch (precision)
  {
    case DateTimePrecision.Hour:
      return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
    case DateTimePrecision.Minute:
      return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0);
    case DateTimePrecision.Second:
      return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
    default:
      break;
  }
}
```
```
and expand as required.


Question:
I want something like this:

<msxsl:script language="C#">
   ??? getNodes() { ... return ... }
</msxsl:script>

<xsl:for-each select="user:getNodes()">
    ...
</xsl:for-each>

What return type should i use for getNodes() and what should i put in it's body?

Answer:
A quick google for C# xslt msxml revealed a link to the following page which gives many examples of extending XSLT in microsoft environments.
http://msdn.microsoft.com/en-us/magazine/cc302079.aspx
Specifically the section on Mapping Types between XSLT and .Net gives you exactly the information you need:
W3C XPath Type -  Equivalent .NET Class (Type)
String - System.String
Boolean - System.Boolean
Number - System.Double
Result Tree Fragment - System.Xml.XPath.XPathNavigator
Node Set - System.Xml.XPath.XPathNodeIterator
So in your example I would try XPathNodeLiterator.


Question:
How can I write an insert statement which includes the & character?  For example, if I wanted to insert "J&J Construction" into a column in the database.

I'm not sure if it makes a difference, but I'm using Oracle 9i.

Answer:
If you are using sql plus then I think that you need to issue the command
```
```
SET SCAN OFF
```
```


Question:
I just got started using Adobe Flex SDK.  I was very excited because it's the first time I've found a good, free way to create Flash applications.  But then I noticed something: Flex doesn't seem to be much about making animations or designs.  It seems more like an application to build forms and menus and the like... which I can already do in (D)HTML.

What features does Flex have that make it better than HTML in some cases?

Also, are there any techniques/software programs that would allow me to add the flash/design components that I mentioned earlier?

Thanks!

Answer:
Flex, like Silverlight, is marketed for the creation of something called RIA = rich internet application. The idea being that (D)HTML isn't really well-suited to create large-scale, well-responding applications on the web. I'm not sure whether this is really (still) true but historically, it fits.
Flex and Silverlight attempt to correct this by providing two things: a different, extensible technology along with a large library and an adapted toolset for the creation of applications. The disadvantage in both cases is the dependency from further (non-free, non-standard) components. The advantage is a potentially much more productive workflow and better performance.


Question:
It is easy to highlight a selected datagrid row, by for example using toggleClass in the tr's click event.  But how best to later remove the highlight after a different row has been selected?   Iterating over all the rows to unhighlight them could become expensive for larger datagrids.  I'd be interested in the simplest solution, as well as the most performant.

Thanks,

Mike

Answer:
If you just want to find items that have
toggledClass
and turn that off using jQuery:
```
```
$('.toggledClass').removeClass('toggledClass');
```
```


Question:
When loading XML into an XmlDocument, i.e.

XmlDocument document = new XmlDocument();
document.LoadXml(xmlData);

is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol)

Thanks

Answer:
I confess things get a little confusing with XML documents and encodings, but I'd hope that it would get set appropriate when you save it again, if you're still using ISO-8859-1 - but that if you save with UTF-8, it wouldn't need to. In some ways, logically the document really contains the symbol rather the entity reference - the latter is just an encoding matter. (I'm thinking aloud here - please don't take this as authoritative information.)
What are you doing with the document after loading it?


Question:
I'm a VMware user and far too often I use keyboard shortcuts while programming. However, this has proved to be quite distressing as sometimes the VMware gets hold of it and turns off / pauses (Ctrl+Z) the virtual machine.

Is there a way to disable keyboard shortcuts on VMware? Has anyone here ever found a workaround?

Answer:
I use AutoHotKey (are you running VMWare on Windows ?) to disable certain shortcuts. You can find this tool here:
http://www.autohotkey.com/
It's open source and I quite like it. Can be used for automation tasks, but you can also have it respond differently to different windows. With some AHK scripting, I think you should be able to fix your problem.
The site had got loads of tutorials too on writing handy scripts.
Good luck.


Question:
In Visual Studio with TFS as source control, when I view the history and double click a cs file, the file is loaded in notepad. How can i change the application to be notepad++?

I also would like the OS's default application for the file to still be visual studio

Answer:
I don't see any options in Visual Studio for changing that, so I'm guessing it uses the system's default text editor.
Try assigning Notepad++ as the default handler for *.cs files.
You can do this from withing Notepad++ by going to Settings/Preference/File Association.
You can also do it by right-clicking on a .cs file in explorer, go to Open With/Choose Program..., then select Notepad++ and check the "Always use the selected program to open this kind of file" box before hitting OK.


Question:
There is a GUI ADM2 Progress v9 application using AppServer.

It needs to give users an ability to view MS Excel files stored on the AppServer. So far it:

Pulls .xls file from AppServer to a local drive.

Fires up a copy of MS Excel and opens the file.

The problem is that the temporary file on the local drive needs to be removed once it's no longer required. Any hints?

Answer:
If you are "firing up a copy of Excel", is there any special reason you can't just point that "fired-up" Excel application at the file on your App Server?
If you are starting Excel from a command-line shell, you could just go
```
Excel.exe "http://myserver/myexcelbook.xls"
```
right?
If you are opening it via something like Office Interop Assemblies, then you can key off of the
```
Application.WorkBookBeforeClose
```
event like
```
```
ThisMethodHandlesTheWorkbookBeforeCloseEvent()
{
  DeleteTheFile();
}
```
```


Question:
I'm wondering if a Java library can be called from a VB.net application.

(A Google search turns up lots of shady answers, but nothing definitive)

Answer:
No, you can't. Unless you are willing to use some "J#" libraries (which is not nearly the same as Java) or
IKVM
which is a Java implementation that runs on top of .NET, but as their documentation says:
IKVM.OpenJDK.ClassLibrary.dll: compiled version of the Java class libraries derived from the OpenJDK class library with some parts filled in with code from GNU Classpath and IcedTea, plus some additional IKVM.NET specific code.
So it's not the real deal.


Question:
Do you know an easy and straight-forward method/sub/module which allows me to convert a number (say 1234567.89) to an easily readable form - something like 1.23M?

Right now I can do this by making several comparisons, but I'm not happy with my method:

if($bytes > 1000000000){
   $bytes = ( sprintf( "%0.2f", $bytes/1000000000 )). " Gb/s";
}
elsif ($bytes > 1000000){
   $bytes = ( sprintf( "%0.2f", $bytes/1000000 )). " Mb/s";
}
elsif ($bytes > 1000){
   $bytes = ( sprintf( "%0.2f", $bytes/1000 )). " Kb/s";
}
else{
   $bytes = sprintf( "%0.2f", $bytes ). "b/s";
}

Thank you for your help!

Answer:
The
Number::Bytes::Human
module should be able to help you out.
An example of how to use it can be found in its synopsis:
```
```
use Number::Bytes::Human qw(format_bytes);

  $size = format_bytes(0); # '0'
  $size = format_bytes(2*1024); # '2.0K'

  $size = format_bytes(1_234_890, bs => 1000); # '1.3M'
  $size = format_bytes(1E9, bs => 1000); # '1.0G'

  # the OO way
  $human = Number::Bytes::Human->new(bs => 1000, si => 1);
  $size = $human->format(1E7); # '10MB'
  $human->set_options(zero => '-');
  $size = $human->format(0); # '-'
```
```


Question:
I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.

The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface.

What's the best way around this?  Should I just use instance methods (which seems wrong) or is there another solution?

Answer:
I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.
i.e. in your class with the static method have:
```
```
private static final MethodObject methodObject = new MethodObject();

public static void doSomething(){
    methodObject.doSomething();
}
```
```
and your method object can be a very simple, easily-tested:
```
```
public class MethodObject {
    public void doSomething() {
        // do your thang
    }
}
```
```


Question: I need to change the app name based on what configuration I'm using in Visual Studio. For example, if I'm in Debug configuration, I want the app name to show as 'App_Debug' in the Application field in the Elmah_Error table. Does anyone have any experience with this? Or is there another way to do it?

Answer:
By default, Elmah uses the AppPool's application GUID as the default application name.  It uses this as the key to identify the errors in the Elmah_Error table when you look at the web interface that's created through it's HTTP Module.
I was tasked to explore this option for my company earlier this year.  I couldn't find a way to manipulate this by default since Elmah pulls the application name from
```
HttpRuntime.AppDomainAppId
```
in the ErrorLog.cs file.  You could manipulate it by whatever key you want; however, that is the AppPool's GUID.
With that said, I was able to manipulate the ErrorLog.cs file to turn Elmah into a callable framework instead of a handler based one and allow for me set the ApplicationName.  What I ended up doing was modifying ErrorLog.cs to include a property that allowed me to set the name as below:
```
```
public virtual string ApplicationName
{
    get
    {
        if (_applicationName == null) {  _applicationName = HttpRuntime.AppDomainAppId; }
        return _applicationName;
    }
    set { _applicationName = value; }
}
```
```
What you will probably need to do is adjust this differently and set the ApplicationName not to
```
HttpRuntime.AppDomainAppId
```
but, instead, a value pulled from the web.config.  All in all, it's possible.  The way I did it enhanced the
```
ErrorLog.Log(ex)
```
method so I could use Elmah has a callable framework beyond web applications.  Looking back I wish I did the app/web.config approach instead.
One thing to keep in mind when changing the application name in Elmah.  The http handler that generates the /elmah/default.aspx interface will no longer work. I'm still trying to find time to circle back around to such; however, you may need to look into creating a custom interface when implementing.


Question:
I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example:

void function(MESSAGE_ID id, void* param)
{
    if(id == FOO) {
        int real_param = (int)param;
        // ...
    }
}

Of course, on a 64 bit machine, I get the error:

error: cast from 'void*' to 'int' loses precision

I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?

Answer:
Use
```
intptr_t
```
and
```
uintptr_t
```
.
To ensure it is defined in a portable way, you can use code like this:
```
```
#if defined(__BORLANDC__)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
    typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
#else
    #include <stdint.h>
#endif
```
```
Just place that in some .h file and include wherever you need it.
Alternatively, you can download Microsoft’s version of the
```
stdint.h
```
file from
here
or use a portable one from
here
.


Question:
The interop library is slow and needs MS Office installed.
Many times you don't want to install MS Office on servers.

I'd like to use Apache POI, but I'm on .NET.

I need only to extract the text portion of the files, not creating nor "storing information" in Office files.

I need to tell you that I've got a very large document library, and I can't convert it to newer XML files.

I don't want to write a parser for the binaries files.
A library like Apache POI does this for us. Unfortunately, it is only for the Java platform. Maybe I should consider writing this application in Java.

I am still not finding an open source alternative to POI in .NET, I think I'll write my own application in Java.

Answer:
What do you need to do with those file?  If you just want to stream them to the user, then the basic file streams are fine.  If you want to create new files (perhaps based on a template) to send to the user that the user can open in Office, there are a variety or
work-arounds
.
If you're actually keeping data in Office documents for use by your web site, you're doing it wrong.  Office documents, even Excel spreadsheets and access databases, are not really an appropriate choice for use with an interactive web site.


Question:
I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers?

After a quick google, I found only the WMI solution and a suggestion to PInvoke GetSecurityInfo

Answer:
No need to P/Invoke.
System.IO.File.GetAccessControl
will return a
FileSecurity
object, which has a
GetOwner
method.
Edit: Reading the owner is pretty simple, though it's a bit of a cumbersome API:
```
```
const string FILE = @"C:\test.txt";

var fs = File.GetAccessControl(FILE);

var sid = fs.GetOwner(typeof(SecurityIdentifier));
Console.WriteLine(sid); // SID

var ntAccount = sid.Translate(typeof(NTAccount));
Console.WriteLine(ntAccount); // DOMAIN\username
```
```
Setting the owner requires a call to SetAccessControl to save the changes. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership.
```
```
var ntAccount = new NTAccount("DOMAIN", "username");
fs.SetOwner(ntAccount);

try {
   File.SetAccessControl(FILE, fs);
} catch (InvalidOperationException ex) {
   Console.WriteLine("You cannot assign ownership to that user." +
    "Either you don't have TakeOwnership permissions, or it is not your user account."
   );
   throw;
}
```
```


Question:
I would like to be able to step through an application deployed to a remote location which as yet has nothing bar version 3.5 of the .Net framework.

What steps do I need to go through to achieve this and how long would you envisage this taking?

Answer:
How to: Set Up Remote Debugging
Screencast for Visual Studio 2008 - Remote Debugging with MSVSMON.EXE
This is also a
good KB
showing some troubleshooting scenarios..


Question:
I am looking for pointers to the solution of the following problem: I have a set of rectangles, whose height is known and x-positions also and I want to pack them in the more compact form. With a little drawing (where all rectangles are of the same width, but the width may vary in real life), i would like, instead of.

-r1-
  -r2--
     -r3--
       -r4-
        -r5--

something like.

-r1-  -r3--
  -r2-- -r4-
         -r5--

All hints will be appreciated. I am not necessarily looking for "the" best solution.

Answer:
Something like this?
Sort your collection of rectangles by x-position
write a method that checks which rectangles are present on a certain interval of the x-axis
```
```
Collection<Rectangle> overlaps (int startx, int endx, Collection<Rectangle> rects){
...
}
```
```
loop over the collection of rectangles
```
```
Collection<Rectangle> toDraw;
Collection<Rectangle> drawn;
foreach (Rectangle r in toDraw){
Collection<Rectangle> overlapping = overlaps (r.x, r.x+r.width, drawn);
int y = 0;
foreach(Rectangle overlapRect in overlapping){
y += overlapRect.height;
}
drawRectangle(y, Rectangle);
drawn.add(r);
}
```
```


Question:
I recently upgraded my oracle client to 10g (10.2.0.1.0).

Now when I try to connect to a legacy 8.0 database, I get

ORA-03134: Connections to this server version are no longer supported.

Is there any workaround for this problem, or do I have to install two clients on my local machine?

Answer:
I had to connect a C# code to an Oracle 7 (I know you it's 8...)... the only way I get it was to get the CD to install the Oracle Server and to go in the "Optional Configuration Component" and to use the Oracle73 Ver2.5.
I think you should go check the CD of the Oracle 8 Server and check if an ODBC is still available.


Question:
I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes.

How do I resize the iframes to fit the height of the iframes' content?

I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far.

Update: Please note that content is loaded from other domains, so the same-origin policy applies.

Answer: This is slightly tricky as you have to know when the iframe page has loaded, which is difficuly when you're not in control of its content. Its possible to add an onload handler to the iframe, but I've tried this in the past and it has vastly different behaviour across browsers (not guess who's the most annoying...). You'd probably have to add a function to the iframe page that performs the resize and inject some script into the content that either listens to load events or resize events, which then calls the previous function. I'm thinking add a function to the page since you want to make sure its secure, but I have no idea how easy it will be to do.


Question:
When I call

help(Mod.Cls.f)

(Mod is a C extension module), I get the output

Help on method_descriptor:

f(...)
    doc_string

What do I need to do so that the help output is of the form

Help on method f in module Mod:

f(x, y, z)
    doc_string

like it is for random.Random.shuffle, for example?

My PyMethodDef entry is currently:

{ "f", f, METH_VARARGS, "doc_string" }

Answer:
You cannot. The inspect module, which is what 'pydoc' and 'help()' use, has no way of figuring out what the exact signature of a C function is. The best you can do is what the builtin functions do: include the signature in the first line of the docstring:
```
```
>>> help(range)
Help on built-in function range in module __builtin__:

range(...)
    range([start,] stop[, step]) -> list of integers

...
```
```
The reason random.shuffle's docstring looks "correct" is that it isn't a C function. It's a function written in Python.


Question:
I have an MS SQL database and have a varchar field that I would like to do queries like  where name like '%searchTerm%'.  But right now it is too slow, even with SQL enterprise's full text indexing.

Can someone explain how Lucene .Net might help my situation?   How does the indexer work? How do queries work?

What is done for me, and what do I have to do?

Answer:
This
article
(strangely enough it's on the top of the Google search results :) has a fairly good description of how the Lucene search could be optimised.
Properly configured Lucene should easily beat SQL (pre 2005) full-text indexing search. If you on MS SQL 2005 and your search performance is still too slow you might consider checking your DB setup.


Question:
In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number.
e.g long x = 0l;

How can I tell the C# compiler that a number is a byte?

Answer:
```
```
byte b = (byte) 123;
```
```
even though
```
```
byte b = 123;
```
```
does the same thing. If you have a variable:
```
```
int a = 42;
byte b = (byte) a;
```
```


Question:
Summary for the impatient: I'm searching for good references on generating code for common language constructs but not parsing.

I am interested in programming languages and try to read the literature as much as possible. But most of them covers the topic in a functional and theoretical perspective that, I find them hard to understand let alone implement the ideas.

So the question is; Which resources do you suggest about programming language implementations that covers the topic in a more imperative and practical fashion?

For example, I find "The Implementation of Lua 5.0" paper very instructive.

Note that, I am not seeking articles about parsing or tokenizing.

Answer:
Here are a bunch of good textbooks:
Modern Compiler Implementation in Java (Tiger book)
A.W. Appel
Cambridge University Press, 1998
ISBN 0-52158-388-8
A textbook tutorial on compiler implementation, including techniques for many language features
Compilers: Principles, Techniques and Tools (Dragon book)
Aho, Lam, Sethi and Ullman
Addison-Wesley, 2006
ISBN 0321486811
The classic compilers textbook, although its front-end emphasis reflects its age.
Advanced Compiler Design and Implementation (Whale book)
Steven Muchnick
Morgan Kaufman Publishers, 1997
ISBN 1-55860-320-4
Essentially a recipe book of optimizations; very complete and suited for industrial practitioners and researchers.
Engineering a Compiler (Ark book)
Keith D. Cooper, Linda Torczon
Morgan Kaufman Publishers, 2003
ISBN 1-55860-698-X
A modern classroom textbook, with increased emphasis on the back-end and implementation techniques.
Optimizing Compilers for Modern Architectures
Randy Allen and Ken Kennedy
Morgan Kaufman Publishers, 2001
ISBN 1-55860-286-0
A modern textbook that focuses on optimizations including parallelization and memory hierarchy optimizations.
Programming Languages Pragmatics
Michael L. Scott
Morgan Kaufmann Publishers, 2005
ISBN 0126339511


Question:
I have a class Animal and an interface it inherits from IAnimal.

@MappedSuperclass
public class Animal implements Serializable, IAnimal{...}.

@Entity
public class Jaguar extends Animal{...}

My first question is, do I need to annotate the interface?

I asked this because I am getting this error when I run my tests:

Error compiling the query [SELECT s
  FROM  animal s WHERE s.atype =
  :atype].
  Unknown abstract schema type
  [animal]

If I remember correctly, before I added this interface it was working.

Answer:
Here are a bunch of good textbooks:
Modern Compiler Implementation in Java (Tiger book)
A.W. Appel
Cambridge University Press, 1998
ISBN 0-52158-388-8
A textbook tutorial on compiler implementation, including techniques for many language features
Compilers: Principles, Techniques and Tools (Dragon book)
Aho, Lam, Sethi and Ullman
Addison-Wesley, 2006
ISBN 0321486811
The classic compilers textbook, although its front-end emphasis reflects its age.
Advanced Compiler Design and Implementation (Whale book)
Steven Muchnick
Morgan Kaufman Publishers, 1997
ISBN 1-55860-320-4
Essentially a recipe book of optimizations; very complete and suited for industrial practitioners and researchers.
Engineering a Compiler (Ark book)
Keith D. Cooper, Linda Torczon
Morgan Kaufman Publishers, 2003
ISBN 1-55860-698-X
A modern classroom textbook, with increased emphasis on the back-end and implementation techniques.
Optimizing Compilers for Modern Architectures
Randy Allen and Ken Kennedy
Morgan Kaufman Publishers, 2001
ISBN 1-55860-286-0
A modern textbook that focuses on optimizations including parallelization and memory hierarchy optimizations.
Programming Languages Pragmatics
Michael L. Scott
Morgan Kaufmann Publishers, 2005
ISBN 0126339511


Question: Microsoft has come out with this fairly new technology that I am considering using for a .NET 3.5 application.  I am curious, is anyone using this technology already?  I am worried that the use of the secure virtual machine will negatively affect performance.  Also, the way Microsoft advertises the product, it seems as though the licensing integration is very seamless and does not require any development work in the code.  It seems like a great product but I want to make sure I know of any pitfalls before committing to it.

Answer:
It seems that SLP does not support .NET 3.5 at the moment.
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3526285&SiteID=1
Your best bet would be to implement an auxiliary DLL containing SLP API calls in .NET 2.0 or 3.0, secure it and add it as a reference to your .NET 3.5 app.


Question:
I am trying to create a StringNameSpaceBinding using the wsadmin tool of Websphere 6.1

Here are the steps i take
set cell [$AdminConfig getid /Cell:cell/]
$AdminConfig create StringNameSpaceBinding $cell { {name bindname}  {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }

But when i run this last step i get an error like this:
WASX7015E: Exception running command: "$AdminConfig create StringNameSpaceBinding $cell { {name bindname}  {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }"; exception information:
 com.ibm.ws.scripting.ScriptingException: WASX7444E: Invalid parameter value "" for parameter "parent config id" on command "create"

Any idea what could be up with this?

Thanks
Damien

Answer:
I'm betting that the following command:
```
```
set cell [$AdminConfig getid /Cell:cell/]
```
```
Doesn't work. Most likely,
```
cell
```
is not the name of your cell.
You don't need to specify a cell name; there's only one cell in the WAS topology. I would change this to:
```
```
set cell [$AdminConfig getid /Cell:/]
```
```
Good luck.


Question:
I'm starting a project using a Restful architecture implemented in Java (using the new JAX-RS standard)

We are planning to develop the GUI with a Flex application. I have already found some problems with this implementation using the HTTPService component (the response error codes, headers access...).

Any of you guys have some experience in a similar project. Is it feasible?

Answer:
There are definite shortcomings of Flex's ability to act as a pure RESTful client.
The comments below are from this
blog
:
The problem is HTTPService class has
  several major limitations:
Only GET and POST methods are supported out of the box (unless you
  use FDS and set useProxy attribute to
  true)
Not able to set request headers and there is no access to response
  headers. Therefore I am not able to
  access the response body in the case
  of an error.
It HTTPService gets a status code anything other 200, it consider
  an error. (event 201, ouch!!). The
  FaultEvent doesn’t provide information
  about the status code any response
  body. The Flex client will have no
  idea what went wrong.
Matt Raible
also gave a
nice presentation on REST with Rails, Grails, GWT and Flex
that have some good references linked from it.
Whether it's feasible or not really depends on how much your willing to work around by proxying, etc.


Question:
Most applications only have "Restore, Move, Size, Minimize, Maximize and Close", however MS SQL offers extra options "Help, Customize view". Along those lines, is it possible to add to the right click menu of an application in the task bar?

Note: I'm not referring to an icon in the notification area next to the clock.

Answer:
This is a simpler
answer
I found.  I quickly tested it and it works.
My code:
```
```
private const int WMTaskbarRClick = 0x0313;

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WMTaskbarRClick:
                {
                    // Show your own context menu here, i do it like this
                    // there's a context menu present on my main form so i use it

                    MessageBox.Show("I see that.");

                    break;
                }
            default:
                {
                    base.WndProc(ref m);
                    break;
                }
        }
    }
```
```


Question:
I notice that Rails 2.2 (currently edge) supports setting HttpOnly on the session cookie.

Is there a way of setting it on a Rails 2.1 application without moving to edge/2.2?

Answer:
Set the
```
http_only
```
option to true in the cookie's options hash:
```
```
cookies['visits'] = { :value => '20', :http_only => true }
```
```


Question:
.Net Compact Framework

Scenario: User is on a screen. Device can't finds a printer and asks the user if they want to try again. If they click "No", the current screen is closed and they are returned to the parent menu screen. If they click the "No" button multiple times, the first click will be used by the No button and the next click will take effect once the screen has completed redrawing. (In effect clicking a menu item which then takes the user to another screen.)

I don't see a good place to put a wait cursor...there isn't much happening when the user clicks "No" except a form closing. But the CF framework is slow to redraw the screen.

Any ideas?

Answer:
Random thoughts:
Disable the some of the controls on the parent dialog while a modal dialog is up.  I do not believe that you can disable the entire form since it is the parent of the modal dialog.
Alternatively I would suggest using a Transparent control to catch the clicks but transparency is not supported on CF.
How many controls are on the parent dialog?  I have not found CF.Net that slow in updating.  Is there any chance that the dialog is overloaded and could be custom drawn faster that with sub controls?
override the DialogResult property and the Dispose method of the class to handle adding/remvoing a wait cursor.


Question:
How do I calculate the position of an accelerating body (e.g. a car) after a certain time (e.g. 1 second)?

For a moving body that it not accelerating, it is a linear relationship, so I presume for an accelerating body it involves a square somewhere.

Any ideas?

Answer:
The equation is: s = ut + (1/2)a t^2
where s is position, u is velocity at t=0, t is time and a is a constant acceleration.
For example, if a car starts off stationary, and accelerates for two seconds with an acceleration of 3m/s^2, it moves (1/2) * 3 * 2^2 = 6m
This equation comes from integrating analytically the equations stating that velocity is the rate-of-change of position, and acceleration is the rate-of-change of velocity.
Usually in a game-programming situation, one would use a slightly different formulation: at every frame, the variables for velocity and position are integrated not analytically, but numerically:
```
```
s = s + u * dt;
u = u + a * dt;
```
```
where dt is the length of a frame (measured using a timer: 1/60th second or so). This method has the advantage that the acceleration can vary in time.
Edit
A couple of people have noted that the Euler method of numerical integration (as shown here), though the simplest to demonstrate with, has fairly poor accuracy. See
Velocity Verlet
(often used in games), and
4th order Runge Kutta
(a 'standard' method for scientific applications) for improved algorithms.


Question:
What is the ideal code to logging ratio? I'm not used to writing logs as most of the applications I've developed have not had much logging.

Recently though I've changed job, and I've noticed that you can't see the application code for the calls to log4net. I appreciate that this is useful but surely having too many debug statements is just as bad as not having any at all?

There are logging statements that tell you when every method starts and finishes and what they are returning. and when pretty much anything is done.

Would it not be easier to have some addon that used reflection to add the logging statements in at compile time so they didn't get in the way as you were trying to look at the code?

Also in these days of powerful IDEs and remote debugging is that much logging really nescisary?

Answer:
There is actually a nice library for adding in logging after the fact as you say,
PostSharp
. It lets you do it via attribute-based programming, among many other very useful things beyond just logging.
I agree that what you say is a little excessive for logging.
Some others bring up some good points, especially the banking scenario and other mission critical apps. It may be necessary for extreme logging, or at least be able to turn it on and off if needed, or have various levels set.


Question:
I have a page that contains a form. This page is served with content type text/html;charset=utf-8. I need to submit this form to server using ISO-8859-1 character encoding. Is this possible with Internet Explorer?

Setting accept-charset attribute to form element, like this, works for Firefox, Opera etc. but not for IE.

<form accept-charset="ISO-8859-1">
  ...
</form>

Edit: This form is created by server A and will be submitted to server B. I have no control over server B.

If I set server A to serve content with charset ISO-8859-1 everything works, but I am looking a way to make this work without changes to server A's encoding. I have another question about setting the encoding in server A.

Answer:
I am pretty sure it won't be possible with older versions of IE. Before the
```
accept-charset
```
attribute was devised, there was no way for
```
form
```
elements to specify which character encoding they accepted, and the best that browsers could do is assume the encoding of the page the form is in will do.
It is a bit sad that you need to know which encoding was used -- nowadays we would expect our web frameworks to take care of such details invisibly and expose the text data to the application as Unicode strings, already decoded...


Question:
Take the following C# class:

c1 {
 event EventHandler someEvent;
}

If there are a lot of subscriptions to c1's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.

Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences.

Answer:
Add a method to c1 that will set 'someEvent' to null.
```
```
public class c1
{
    event EventHandler someEvent;
    public ResetSubscriptions() => someEvent = null;
}
```
```


Question: Is it possible to assign a global hotkey to a specific feature in an Adobe AIR app, i.e. the app feature responds to the hotkey whether the app is active or not (it must be running of course, but only in the system tray).

Answer:
I don't this it's possible with Adobe AIR itself. The only method I can think of:
Install 3rd party hotkey application (like
AutoHotkey
or
HotKeyBind
)
Configure hotkey application to make
CTRL
+
ALT
+
Q
to launch
"
```
c:\programs\thvo42\coolapp.exe --hotkey q
```
"
In your AIR application, register for the
NativeApplication.invoke
event, and watch for arguments like '--hotkey q' to know that the Q hotkey was pressed, and then act accordingly.
Of course, this is kind of a hassle, maybe with some hacking you can roll it all into a single install file.


Question:
In MS Transact SQL, let's say I have a table (Orders) like this:

 Order Date       Order Total     Customer #
 09/30/2008       8.00            1
 09/15/2008       6.00            1
 09/01/2008       9.50            1
 09/01/2008       1.45            2
 09/16/2008       4.50            2
 09/17/2008       8.75            3
 09/18/2008       2.50            3

What I need out of this is: for each customer the average order amount for the most recent two orders.  So for Customer #1, I should get 7.00 (and not 7.83).

I've been staring at this for an hour now (inside a larger problem, which I've solved) and I think my brain has frozen.  Help for a simple problem?

Answer:
This should make it
```
```
select avg(total), customer
from orders o1
where orderdate in
  ( select top 2 date
    from orders o2
    where o2.customer = o1.customer
    order by date desc )
group by customer
```
```


Question:
What are my options for programmatically accessing a Microsoft Project file? What are the pros and cons of each approach?

I will basically need to import all data from the file into another data structure. Using the Office Interop assembies is low on the preference scale.

Answer:
The Microsoft Office API provides programmatic access to MS Project. I have only used it for Word and Excel so I don't know how rich the interface is - you will have to do some digging around on MSDN to find out what you can and can't do.
One of the Java projects at my company uses a commerical product by
Aspose
which allows applications to manipulate Office documents including Project. It works well for their purposes, but again, they have only used it for Word and Excel so can't offer much advice on Project.
EDIT (2019)
: I can confirm that it is a very capable product.


Question:
What would be the most efficient way of recording to a log (.txt) from a console program on C# and .NET 2.2? My program loops multiple times always outputting different data based on what the user wants, so I'm searching for the most efficient way to achieve this.

I know I can always reopen a stream and then close it, but everytime I do that it would be writing just one line, then next time around (seconds later) the program reloops and needs tor write again. In my opinion, that doesn't seem very resourse friendly.

I'm using multiple threads that all have output data that I want to log (opening/closing the same file or accessing the same file on different threads might be bad). The "holds a reference to a stream writer that auto-flushes" sounds like a good idea, however I don't know how to do that.

Answer:
Consider using
log4net
:
a tool to help the programmer output log statements to a variety of output targets... We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the .NET runtime. For more information on log4net see the
features
document...


Question: How can I write a scheduler application in C# .NET?

Answer:
It all depends on your requirements:
If you have access to a database you use a table as a queue and a service to poll the queue at regular intervals.
If your application is client only (CLI) you can use the system scheduler ("Scheduled Tasks").
Lastly, if your application is only in a database (using the CLR in SQL Server 2005 for example) then you can create a SQL Server job to schedule it.


Question:
Unfortunately, I need to do this.  I'm using ELMAH for my error log.  Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception.  You used to be able to use

Elmah.ErrorLog.Default

However, this is now marked as obsolete.  The compiler directs me to use the method

Elmah.ErrorLog.GetDefault(HttpContext context)

MVC's context is of type HttpContextBase, which enables us to mock it (YAY!).  How can we deal with MVC-unaware libraries that require the old style HttpContext?

Answer:
Try
```
System.Web.HttpContext.Current
```
. It should do the trick.
Gets HTTP-specific information about an individual HTTP request.
MSDN


Question:
Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array @myarray and a hash %myhash, why do you need to do:

$x = $myarray[1];
$y = $myhash{'foo'};

instead of just doing :

$x = myarray[1];
$y = myhash{'foo'};

Why are the above ambiguous?

Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?

@var[0];
@var{'key'};
%var[0];
%var{'key'};

Answer:
I can think of one way that
```
```
$x = myarray[1];
```
```
is ambiguous - what if you wanted a array called m?
```
```
$x = m[1];
```
```
How can you tell that apart from a regex match?
In other words, the syntax is there to help the Perl interpreter, well, interpret!


Question: It seems to me that phpMyAdmin imports tables by default with collation latin1_swedish_ci, how i change this?

Answer:
This is not a phpMyAdmin question.
Collations are part of recent MySQL releases, you must set the default collation of the server (or at least of the database) to change that behaviour.
To convert already imported tables to UTF-8 you can do (in PHP):
```
```
$dbname = 'my_databaseName';
mysql_connect('127.0.0.1', 'root', '');
mysql_query("ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
$res = mysql_query("SHOW TABLES FROM `$dbname`");
while($row = mysql_fetch_row($res)) {
   $query = "ALTER TABLE {$dbname}.`{$row[0]}` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci";
   mysql_query($query);
   $query = "ALTER TABLE {$dbname}.`{$row[0]}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
   mysql_query($query);
}
echo 'all tables converted';
```
```
Code snippet taken from
here
.


Question:
Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format (someone@domain.subdomain), but that's it's a real active e-mail address.

I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.

Answer:
Without sending an email, it could be hard to get 100%, but if you
do a DNS lookup on the host
that should at least tell you that it is a viable destination system.


Question:
How do I use the jQuery Datepicker with a textbox input:

$("#my_txtbox").datepicker({
  // options
});

that doesn't allow the user to input random text in the textbox.
I want the Datepicker to pop up when the textbox gains focus or the user clicks on it, but I want the textbox to ignore any user input using the keyboard (copy & paste, or any other). I want to fill the textbox exclusively from the Datepicker calendar.

Is this possible?

jQuery 1.2.6

Datepicker 1.5.2

Answer:
You should be able to use the
readonly
attribute on the text input, and jQuery will still be able to edit its contents.
```
```
<input type='text' id='foo' readonly='true'>
```
```


Question: As in subject... is there a way of looking at an empty table schema without inserting any rows and issuing a SELECT?

Answer:
Are you looking for
DESCRIBE
?
```
db2 describe table user1.department
```
```
```
Table: USER1.DEPARTMENT

Column             Type        Type
name               schema      name               Length   Scale    Nulls
------------------ ----------- ------------------ -------- -------- --------
AREA               SYSIBM      SMALLINT                  2        0 No
DEPT               SYSIBM      CHARACTER                 3        0 No
DEPTNAME           SYSIBM      CHARACTER                20        0 Yes
```
```


Question:
I am using a codebehind page in ASP.NET to perform a SQL query.  The query is loaded into a string, the connection is established (To Oracle), and we get it started by having the connection perform .ExecuteReader into a OleDBDataReader (We'll call it DataRead).  I'll try to hammer out an example below.  (Consider Drop as an ASP DropDownList control)

Dim LookFor as String = "Fuzzy Bunnies"

While DataRead.Read
    If LookFor = DataRead.Item("Kinds of Bunnies") Then
        'Meets special critera, do secondary function'

         Drop.Items.Add(DataRead.Item("Subgroup of Bunnies"))
         ...
    End if
    ...
End While

This is the only way I know of doing a dynamic add to a DropDownList.  However, each item in a DropDownList has a .text property and a .value property.  How can we define the .value as being different from the .text in code?

Answer:
Pardon my possibly faulty VB
```
```
Dim item as New ListItem()
item.Value = "foo"
item.Text = "bar"

Drop.Items.Add(item)
```
```
You can also use the ListItem constructor (e.g. new ListItem("text", "value"))


Question:
I am coming from the SQL server world where we had uniqueidentifier. Is there an equivalent in oracle? This column will be frequently queried so performance is the key.

I am generating the GUID in .Net and will be passing it to Oracle. For a couple reasons it cannot be generated by oracle so I cannot use sequence.

Answer:
There is no uniqueidentifier in Oracle.
You can implement one yourself by using RAW (kind of a pain) or CHAR.  Performance on queries that JOIN on a CHAR field will suffer (maybe as much as 40%) in comparison with using an integer.
If you're doing distributed/replicated databases, the performance hit is worth it.  Otherwise, just use an integer.


Question:
I've got the following query to determine how many votes a story has received:

SELECT s_id, s_title, s_time, (s_time-now()) AS s_timediff,

(
 (SELECT COUNT(*) FROM s_ups WHERE stories.q_id=s_ups.s_id) -
 (SELECT COUNT(*) FROM s_downs WHERE stories.s_id=s_downs.s_id)
) AS votes

FROM stories

I'd like to apply the following mathematical function to it for upcoming stories (I think it's what reddit uses) -
http://redflavor.com/reddit.cf.algorithm.png

I can perform the function on the application side (which I'm doing now), but I can't sort it by the ranking which the function provides.

Any advise?

Answer:
y and z are the tricky ones. You want a specific return based on x's value. That sounds like a good reason to make a function.
http://dev.mysql.com/doc/refman/5.0/en/if-statement.html
You should make 1 function for y and one for z. pass in x, and expect a number back out.
```
```
DELIMINATOR //

CREATE FUNCTION y_element(x INT)
  RETURNS INT

BEGIN
    DECLARE y INT;

IF x > 0 SET y =  1;
ELSEIF x = 0 SET y =  0;
ELSEIF x < 0 SET y = -1;
END IF;

RETURN y;

END //;

DELIMINATOR;
```
```
There is y. I did it by hand without checking so you may have to fix a few typo's.
Do z the same way, and then you have all of the values for your final function.


Question:
When I want to validate my XML docuemnts against a schema in my server-side Java, I use the built-in JRE Xerces implementation and javax.xml.validation.Schema.  It works fine, but when validation fails, Xerces gives error messages that are very close to useless, for example:

cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type 'PopulatedStringType'

These can take an age to diagnose and track down to the particular part of the XML document that fails validation, and all because of a poor error message.

So my question is, do you use an alternative means of validating XML against Schema, that gives a more useful output on validation failure?

Please not that this is server-side Java, so please don't say "use XML Spy" or similar.

Answer:
We use
Oracle's XDK (XML Development Kit)
which includes xmlparserv2.jar with a validating parser and XSLT 2.0.  It uses the JAXB API so you should only have to add it to your classpath and change your imports.  It throws errors that aren't perfect, but I would say more easily understood than your example.


Question:
I am playing with a CAD application using MFC. I was thinking it would be nice to save the document (model) as an SQLite database.

Advantages:

I avoid file format changes (SQLite takes care of that)

Free query engine

Undo stack is simplified (table name, column name, new value
and so on...)

Opinions?

Answer:
This is a fine idea.  Sqlite is very pleasant to work with!
But remember the old truism (I can't get an authoritative answer from Google about where it originally is from) that storing your data in a relational database is like parking your car by driving it into the garage, disassembling it, and putting each piece into a labeled cabinet.
Geometric data, consisting of points and lines and segments that refer to each other by name, is a good candidate for storing in database tables.  But when you start having composite objects, with a heirarchy of subcomponents, it might require a lot less code just to use serialization and store/load the model with a single call.
So that would be a fine idea too.
But serialization in MFC is not nearly as much of a win as it is in, say, C#, so on balance I would go ahead and use SQL.


Question:
What do the brackets do in a sql statement?

For example, in the statement:

insert into table1 ([columnname1], columnname2) values (val1, val2)

Also, what does it do if the table name is in brackets?

Answer:
They are meant to escape reserved keywords or invalid column identifiers.
```
```
CREATE TABLE test
(
  [select] varchar(15)
)

INSERT INTO test VALUES('abc')

SELECT [select] FROM test
```
```


Question:
See: Understanding Pointers

In many C flavoured languages, and some older languages like Fortran, one can use Pointers.

As someone who has only really programmed in basic, javascript, and actionscript, can you explain to me what a Pointer is, and what it is most useful for?

Thanks!

Answer:
A pointer is a variable that contains the address of another variable.  This allows you to reference another variable indirectly.  For example, in C:
```
```
// x is an integer variable
int x = 5;
// xpointer is a variable that references (points to) integer variables
int *xpointer;
// We store the address (& operator) of x into xpointer.
xpointer = &x;
// We use the dereferencing operator (*) to say that we want to work with
// the variable that xpointer references
*xpointer = 7;
if (5 == x) {
    // Not true
} else if (7 == x) {
    // True since we used xpointer to modify x
}
```
```


Question:
As part of a build setup on a windows machine I need to add a registry entry and I'd like to do it from a simple batch file.

The entry is for a third party app so the format is fixed.

The entry takes the form of a REG_SZ string but needs to contain newlines ie. 0xOA characters as separators.

I've hit a few problems.

First attempt used regedit to load a generated .reg file.  This failed as it did not seem to like either either long strings or strings with newlines.  I discovered that export works fine import fails.  I was able to test export as the third party app adds similar entries directly through the win32 api.

Second attempt used the command REG ADD but I can't find anyway to add the newline characters everything I try just ends up with a literal string being added.

Answer:
You could create a VBScript(.vbs) file and just call it from a batch file, assuming you're doing other things in the batch other than this registry change.  In vbscript you would be looking at something like:
```
```
set WSHShell = CreateObject("WScript.Shell")
WSHShell.RegWrite "HKEY_LOCAL_MACHINE\SOMEKEY", "value", "type"
```
```
You should be able to find the possible type values using Google.


Question: Assuming a MySQL datastore, when would you NOT want to use memcached in a Ruby on Rails app?

Answer:
Don't use memcached if your application is able to handle all requests quickly. Adding memcached is extra mental overhead when it comes to coding your app, so don't do it unless you need it.
Scaling's "
one swell problem to have
".


Question:
I'm trying to find a good way to print leading 0, such as 01001 for a ZIP Code. While the number would be stored as 1001, what is a good way to do it?

I thought of using either case statements or if to figure out how many digits the number is and then convert it to an char array with extra 0's for printing, but I can't help but think there may be a way to do this with the printf format syntax that is eluding me.

Answer:
```
```
printf("%05d", zipCode);
```
```
The
```
0
```
indicates what you are padding with and the
```
5
```
shows the width of the integer number.
Example 1: If you use
```
"%02d"
```
(useful for dates) this would only pad zeros for numbers in the ones column. E.g.,
```
06
```
instead of
```
6
```
.
Example 2:
```
"%03d"
```
would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to
```
007
```
and number 17 padded to
```
017
```
.


Question:
I have a link that I dynamically create which looks something like the following:

<a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a>

with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there is a single quote in the text being passed. The obvious problem being that the link then looks something like:

<a onclick="Edit('I'm a jelly donut')" href="javascript:void(null);">Edit</a>

Any suggestions on what I can do? I'd rather not stray too far from the structure I am currently using because it is something of a standard (and maybe the standard sucks, but that's another question altogether).

Note: I am using ASP as my server side language.

Answer:
Convert quote charaters to their HTML equivalents,
```
"
```
etc. before you insert them into the HTML. There's a
long list
of HTML/XML character codes on wikipedia.
There may well be a function to do this for you, depending on how you're dynamically generating the code: PHP has
htmlspecialchars
, and though I'm not familiar with ASP etc, I'm sure there are similar routines.


Question:
My Django app has a Person table, which contains the following text in a field named details:

<script>alert('Hello');</script>

When I call PersonForm.details in my template, the page renders the script accordingly (a.k.a., an alert with the word "Hello" is displayed).  I'm confused by this behavior because I always thought Django 1.0 autoescaped template content by default.

Any idea what may be going on here?

UPDATE: Here's the snippet from my template. Nothing terribly sexy:

{{ person_form.details }}

UPDATE 2: I have tried escape, force-escape, and escapejs.  None of these work.

Answer:
You need to mark the values as | safe I think (I'm guessing that you're filling in the value from the database here(?)):
```
```
{{ value|safe }}
```
```
Could you post a sample of the template? Might make it easier to see what's wrong
[Edit]
..or are you saying that you
want
it to escape the values (make them safe)? Have you tried manually escaping the field:
```
```
{{ value|escape }}
```
```
[Edit2]
Maybe
escapejs from the Django Project docs
is relevent:
```
```
escapejs

New in Django 1.0.

Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.
```
```
[Edit3]
What about force_escape:
```
```
{{ value|force_escape }}
```
```
...and I know it's an obvious one, but you're absolutely certain you've not got any caching going on in your browser? I've tripped over that one a few times myself ;-)


Question:
Pattern pattern = Pattern.compile("^[a-z]+$");
String string = "abc-def";
assertTrue( pattern.matcher(string).matches() ); // obviously fails

Is it possible to have the character class match a "-" ?

Answer:
Escape the minus sign
```
```
[a-z\\-]
```
```


Question: Is there a string.Empty in JavaScript, or is it just a case of checking for ""?

Answer:
Empty string, undefined, null, ...
To check for a
truthy value
:
```
```
if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}
```
```
To check for a
falsy value
:
```
```
if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}
```
```
Empty string (only!)
To check for exactly an empty string, compare for strict equality against
```
""
```
using the
```
===
```
operator
:
```
```
if (strValue === "") {
    // strValue was empty string
}
```
```
To check for not an empty string strictly, use the
```
!==
```
operator
:
```
```
if (strValue !== "") {
    // strValue was not an empty string
}
```
```


Question:
I have a Virtual Machine in Virtual PC 2007.

To start it from the desktop, I have the following command in a batch file:

"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch

But that leaves a dos prompt on the host machine until the virtual machine shuts down, and I exit out of the Virtual PC console.  That's annoying.

So I changed my command to use the START command, instead:

start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch

But it chokes on the parameters passed into Virtual PC.

START /? indicates that parameters do indeed go in that location.  Has anyone used START to launch a program with multiple command-line arguments?

Answer:
have you tried:
```
```
start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" "-pc MY-PC -launch"
```
```
?


Question:
When I open a file in eclipse it shows with the improper line spacing showing an extra line break between every line. When I open the file with notepad or wordpad it doesn't show these extra line breaks that only eclipse shows. How do I get eclipse to read these files like notepad and wordpad without those line breaks?

-edit: I don't have this problem with all files but only a select few where I have made local changes > uploaded them to our sun station > then pulled those files back to my local workstation for future modifications.

Answer:
Eclipse should have a
```
File -> Convert Line Delimiters To...
```
option that may correct this for you. (If it doesn't work on your file,
this article
may help.)
Really, though, you should have your file transfer program treat your source files as ascii instead of binary. Then your line ending problem should be moot.


Question: Anyone know how to programmatically mute the Windows XP Volume using C#?

Answer:
Declare this for P/Invoke:
```
```
private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
private const int WM_APPCOMMAND = 0x319;

[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
```
```
And then use this line to mute/unmute the sound.
```
```
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE);
```
```


Question:
I've switched computers a few times recently, and somewhere along the way I lost my .emacs.  I'm trying to build it up again, but while I'm at it, I thought I'd pick up other good configurations that other people use.

So, if you use Emacs, what's in your .emacs?

Mine is pretty barren right now, containing only:

Global font-lock-mode! (global-font-lock-mode 1)

My personal preferences with respect to indentation, tabs, and spaces.

Use cperl-mode instead of perl-mode.

A shortcut for compilation.

What do you think is useful?

Answer:
```
```
(put 'erase-buffer 'disabled nil)
(put 'downcase-region 'disabled nil)
(set-variable 'visible-bell t)
(set-variable 'tool-bar-mode nil)
(set-variable 'menu-bar-mode nil)

(setq load-path (cons (expand-file-name "/usr/share/doc/git-core/contrib/emacs") load-path))
 (require 'vc-git)
 (when (featurep 'vc-git) (add-to-list 'vc-handled-backends 'git))
 (require 'git)
 (autoload 'git-blame-mode "git-blame"
           "Minor mode for incremental blame for Git." t)
```
```


Question:
We have a fairly large .NET solution with multiple executable projects (winforms and command line programs). Currently each of these projects has its own app.config that contains connection strings, mail server settings and the like. As you can imagine it's not that convenient to make a change in every app.config file whenever a particular setting needs to be updated.

What do you reckon is the best practice for centralized management of these settings? So far I've thought about two different approaches. The first is using a custom class (or classes) that contains the settings and is serialized into and deserialized from XML. The second approach is defining an app.config file only for a single project and using ConfigurationManager.OpenExeConfiguration() to access it.

Answer:
Create the App.config on your startup project and link statically to it on the other projects.
You can link statically by going to Add->Existing Item, and when clicking the Add button on the File Browser Window, there is a small down arrow on the Add button. Click there and the "Add as link" option will be shown. That will place the same App.Config on both projects, with only one actual file.
If your projects have different App.Config with only 'some' settings that are the same, consider checking the file parameter; I mean, you can have more than one App.Config in a project:
http://weblogs.asp.net/pwilson/archive/2003/04/09/5261.aspx
Just create a central common.config file and point to it.