q:
I have a web application with users and their documents. Each user can have many documents:

user.rb:

has_many :documents

document.rb:

belongs_to :user

document_controller.rb:

def index
    @documents = Document.find(:all)
end

I am using the restful_authentication plugin. Here is my question: How do I get the controller to only show documents that belongs to each user? Right now it shows all the documents for all the users.

I am using the latest version of Rails.

[A]
You set a relationship in your User class to your Document class. This will automatically add a method to your User objects that returns a list of all documents related to a particular user:
```
```
def index
  @documents = @current_user.documents
end
```
```
See the
documentation
for other automatically added methods.


q: Which types of objects fall into the domain of "subscriptable"?

[A]
It basically means that the object implements the
```
__getitem__()
```
method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

s: huggingface

c: devops

d: intermediate


q:
Say I want to copy the contents of a directory excluding files and folders whose names contain the word 'Music'.

cp [exclude-matches] *Music* /target_directory

What should go in place of [exclude-matches] to accomplish this?

[A]
One solution for this can be found with find.
```
```
$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt
```
```
Find has quite a few options, you can get pretty specific on what you include and exclude.
Edit: Adam in the comments noted that this is recursive.  find options mindepth and maxdepth can be useful in controlling this.


q: My AS3-heavy project tests fine in the IDE, but some parts don't work in the browser when published. Any ideas what could be causing this?

[A] It might help if you provide some more specific information on what's not working.  Can you post a link?  Furthermore, are any parts of your project referencing any remote objects?  If so, you might want to make sure your remote objects are located where your app expects them to be.  You may also need to add a crossdomain.xml to your server root if you're doing any cross site scripting.


q:
Is it possible to see the return value of a method after the line has been run and before the instruction pointer returns to the calling function?

I am debugging code I can't modify (read: don't want to re-compile a third party library), and sometimes it jumps to code I don't have source to or the return expression has side effects that stop me being able to just run the expression in the Display tab.

Often the return value is used in a compound statement, and so the Variables view will never show me the value (hence wanting to see the result before control returns to the calling function).

UPDATE: I can't use the expression viewer as there are side-effects in the statement.

[A]
Tough one.  My experience, outside of Eclipse, is that if you might need to see the return value, it is best to assign it to a local variable in the function so that the return statement is a simple
```
return varname;
```
and not
```
return(some * expression || other);
```
.  However, that's not dreadfully helpful to you since you say you can't (or don't want to) modify or even recompile the code.  So, I don't have a good answer for you - perhaps you need to reconsider your requirement.


q:
So I have an Access application, and I'd like some forms to be maximised when they are opened, and others to be medium-sized when they are opened.  However, if I try something like this:

Private Sub Form_Activate()
  DoCmd.Maximize
End Sub

or

Private Sub Form_Activate()
  DoCmd.Restore
End Sub

it has the effect of maximizing or restoring every open window, which isn't what I'm looking for.

Is there any way around this?

I'm using Access 2003.

[A]
Access is an MDI (Multiple Document Interface) application, and this is how they work: either all sub-windows are maximized, or none.
What you need to do, is find a way to discover the dimensions of the Access application window, and then programmatically set the form's .InsideWidth and .InsideHeight properties. The
```
Application
```
object has a
```
hwndAccessApp
```
that probably can be used with some Windows API call to find out its width and height.
addendum
Thanks to
Philippe Grondier
for finding a relevant code sample, the general idea from the
code sample
is:
declare the following Win32 API elements:
```
struct Rect
```
(
```
Type Rect…
```
in VBA)
```
const SW_SHOWNORMAL = 1
```
(for ShowWindow)
```
GetParent
```
(given a hwnd, get its parent's hwnd)
```
GetClientRect
```
(retrieve position and size from a hwnd)
```
IsZoomed
```
(boolean; true if window is maximized)
```
ShowWindow
```
(change the state of a window)
```
MoveWindow
```
(to change the position and size of a window)
if your form is maximized (
```
IsZoomed(frm.hWnd) = True
```
), then restore it (
```
ShowWindow frm.hWnd, SW_SHOWNORMAL
```
)
get the MDI clients area from your form's hWnd (
```
GetClientRect GetParent(frm.hWnd, rect)
```
)
use the rect data to change the position and size of your window (
```
MoveWindow frm.hWnd, 0, 0, rect.x2-rect.x1, rect.y2-rect.y1
```
)
(The above is basically the explanation of the code sample; I didn't copy-paste the code because I wasn't sure if the author allowed it).


q:
I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen.

I'd like to do this purely from (Py)GTK+, but I am amenable to calling platform-specific functions.  Ideally I'd like to call functions which have already been wrapped from Python, but if that's not possible, I'm not above a little bit of C or ctypes code, as long as I know what I'm actually looking for.

On Windows I think the function I want is GetLastInputInfo, but that doesn't seem to be wrapped by pywin32; I hope I'm missing something.

[A]
I got an answer regarding mouse-clicks suggesting to use
pyHook
:
Detecting Mouse clicks in windows using python
Here's some other code I did to detect mouse-position via ctypes:
http://monkut.webfactional.com/blog/archive/2008/10/2/python-win-mouse-position
A more round-about method to accomplish this would be via screen capture and comparing any change in images using PIL.
http://www.wellho.net/forum/Programming-in-Python-and-Ruby/Python-Imaging-Library-PIL.html


q:
Problem : I have multiple projects checked out in my depot. I also have multiple pending numbered change lists, each change list containing checked out files specific to its project. When I check out a new file, it appears in the default change list instead of in the change list that is relevant to its project and I need to manually move it to the relevant change list. This gets real tedious real quick.

Is there any way to automate this process? Sure, a shell script with regular expressions could work, but I want to know if there is any Perforce feature that does this. For example, is there a way to link my project folder to a numbered change list so that a newly checked out file automatically appears in the relevant change list?

[A]
The way I handle this is that each project I'm working on has a separate client workspace configuration.
However, this is a 6 of one, half dozen of the other situation - now I have to manage a bunch of workspaces. The problem I run into is that when I'm working on project A and want to do something quick in project B I have to switch my workspace to do it.
Perforce does have methods to help deal with that problem by using config files that you place in the proper parts of your directory hierarchy.  See the
Perforce User's Guide, Chapter 2 - the "Using config files" section
.


q: I have a revision that has been committed to SVN trunk which I would like to roll back.  However, I would like to retain the changes in some fashion such as a branch or even a patch file.  Any suggestions?

[A]
Reverse-merge (I think that was the term), commit and that's all.
For the "reverse-merge" part - TSVN has this cool feature called "Revert to this revision" (and "Revert changes from this revision"), accessible through the Log dialogue.
The main purpose of a VCS is to keep history of your changes. You could always go back to this particular revision by using "Update to revision..." or by using the aforementioned "shortcuts".


q:
Is there a way to make awk (gawk) ignore or skip missing files? That is, files passed on the command line that no longer exist in the file system (e.g. rapidly appearing/disappearing files under /proc/[1-9]*).

By default, a missing file is a fatal error :-(

I would like to be able to do the equivalent of something like this:

BEGIN { MISSING_FILES_ARE_FATAL = 0 }  # <- Wishful thinking!
      { count++ }
END   { print count }

A wrapper script cannot check that files exist befor awk is run as they may disappear between the time they are checked and awk then tries to open them, i.e., it is a race condition. (It is also a race condition to check-and-then-open within awk, although the timing is tighter)

[A]
In the finest of traditions, I will answer your awk question with a Perl program.
```
```
#!/usr/bin/perl -w

for my $file (@ARGV) {
    open my $fh, $file or next;
    while(<$fh>) {
        ...do your thing here...
    }
}
```
```
(It's not awk, but it is the only solution without a race condition.)


q:
I'm attempting to display some text in my program using (say) Windows GDI and some of the unicode characters are displayed as question marks? What is up?

See also: What does it mean when my text is displayed as boxes?

[A]
Basically you have corrupted the text. You are taking Unicode text in one encoding and then have converted it to another encoding without checking that target encoding includes all of the characters in the source text. Having done so you have got a bunch of gibberish.
Ways to do this include:
Treating UTF-8 text as ANSI (without converting into a valid code-page first)
Converting Unicode text into a code-page without checking if the code-page has the right characters in it.


q: I've run across this sort of thing on multiple websites and was wondering what it was called, does anyone know? Here's a screenshot.

[A]
I don't see anything obviously out of place.  If you're working with a very large database, you could try increasing your heap size by using the
```
-Xmx n
```
option in your JVM invocation.  This is usually not the best solution - only do with this when you know your working set size is actually bigger than the default heap size.
Are you using any complex data structures?  If you have circular references between objects, you might be preventing the garbage collector from cleaning up unreachable objects.  If you have any hand-written data structures, make sure that you explicitly null out references to objects that are removed instead of doing something like decrementing a size variable.


q:
I am using pseudo-code here, but this is in JavaScript. With the most efficient algorithm possible I am trying to find the high and low given an array of positive whole numbers. This is what I came up with, but I don't think it is probably best, and was just wondering if anyone has any other suggestions.

var low = 1;
var high = 1;
for ( loop numbers ) {
    if ( number > high ) {
        high = number;
    }
    if ( low == 1 ) {
        low = high;
    }
    if ( number < low ) {
        low = number;
    }
}


q:
What kind of collection I should use to convert NameValue collection to be bindable to GridView?
When doing directly it didn't work.

Code in aspx.cs

  private void BindList(NameValueCollection nvpList)
  {
     resultGV.DataSource = list;
     resultGV.DataBind();
  }

Code in aspx

<asp:GridView ID="resultGV" runat="server" AutoGenerateColumns="False" Width="100%">
    <Columns>
         <asp:BoundField DataField="Key" HeaderText="Key" />
         <asp:BoundField DataField="Value" HeaderText="Value" />
    </Columns>
</asp:GridView>

Any tip most welcome. Thanks. X.

[A]
Can you use Dictionary<string,string> instead of NameValueCollection.  Since Dictionary<T,T> implements IEnumerable you could use LINQ as so:
```
```
resultGV.DataSource = from item in nvpDictionary
                      select new { Key = item.Key, Value = item.Value };
resultGV.DataBind();
```
```
[EDIT] Actually you may be able to use Dictionary directly as:
```
```
resultGV.DataSource = nvpDictionary;
resultGV.DataBind();
```
```
If it doesn't map key/value the way you want you can always go back to LINQ.  LINQ would also allow you to rename the fields to whatever you want.
[EDIT]  If you can't change to use Dictionary<T,T>, make a copy of the NameValueCollection as a Dictionary in the method and bind to it.
```
```
private void BindList(NameValueCollection nvpList)
{
   Dictionary<string,string> temp = new Dictionary<string,string>();
   foreach (string key in nvpList)
   {
      temp.Add(key,nvpList[key]);
   }

   resultGV.DataSource = temp;
   resultGV.DataBind();
}
```
```
If you do this a lot, you could write an extension method to convert to a Dictionary, and use it so.
```
```
public static class NameValueCollectionExtensions
{
   public static Dictionary<string,string> ToDictionary( this NameValueCollection collection )
   {
      Dictionary<string,string> temp = new Dictionary<string,string>();
      foreach (string key in collection)
      {
          temp.Add(key,collection[key]);
      }
      return temp;
   }
}

private void BindList(NameValueCollection nvpList)
{
   resultGV.DataSource = nvpList.ToDictionary();
   resultGV.DataBind();
}
```
```


q:
Is there a way to spawn a new window via javascript in IE7 that hides the statusbar?

I've added the intranet app as a trusted site. Not sure what else I can use to try. This is my JS

window.open("http:/localhost/start.html", "MyApp", "left=0, top=0, width=" + screen.width + "," +
                              "height=" + screen.height + ", scrollbars=yes, " +
                              "resizable=yes, location=no, menubar=no, titlebar=no, " + "toolbar=no, status=no");

[A]
Your code worked for me,
and here's a screenshot.
Example of how IE7 renders popup without status bar. http://img511.imageshack.us/img511/7757/workshq7.th.png
Note that experment was done on local filesystem, with "Protected Mode" completly turned off. If it didn't work for you, my guess is that your security settings is somehow still to high. Tinkering with the browser UI trough JavaScript is usually blocked for security reasons and should not be relied on.


q:
I'm working on a C# program, and right now I have one Form and a couple of classes. I would like to be able to access some of the Form controls (such as a TextBox) from my class. When I try to change the text in the TextBox from my class I get the following error:

An object reference is required for the non-static field, method, or property 'Project.Form1.txtLog'

How can I access methods and controls that are in Form1.cs from one of my classes?

[A]
you have to have a reference to the form object in order to access its elements
the elements have to be declared public in order for another class to access them
don't do this - your class has to know too much about how your form is implemented; do not expose form controls outside of the form class
instead, make public properties on your form to get/set the values you are interested in
post more details of what you want and why, it sounds like you may be heading off in a direction that is not consistent with good encapsulation practices


q: Is there a standard way to convert an XSD to an input form (ASP.NET C#) so that later on whenever a new field is added / removed from the XSD the field on the page automatically shows up or goes away respectively, is this something which needs to be developed in-house I assume there must be a way to serializes / deserializes and generates a form? Any hel would be appreciated..

[A]
Assumption: You're using XML because it is simpler for you at the moment.
Idea: Since you want to create a form to manipulate the data, I'm guessing you might be open to SQL instead of XML. This may not be the case, but you will probably find more tools to help you if you have a database backend instead of an XML/XSD backend. (Plus there are ways you can convert your data from one to another).
There are tools that create forms from databases in ASP.NET. SubSonic, for example, has a auto-scaffolding module that lets you create a database manager knowing only its schema. If the schema changes, just have SubSonic regenerate its files and your forms will have been modified. It isn't perfect, but it may go a long way, depending on your needs.
Option 1) You can create the database schema from the XSD (
How can I create database tables from XSD files?
) and use SubSonic from that point on. This may be even more of a pain than you original question... only you know.
Option 2) Hack the SubSonic scaffolding so that it supports your underlying XSD/XML instead of a database. You can probably re-use lots of their infrastructure (SubSonic is open source) to generate the form from an XSD.
Good luck!


q:
I have a PHP form (mortgage app) that is about 400 fields, traffic on the site will be low.

What is the ideal Session size for 400 fields going into a MySQL db?

In php.ini what do I set?

Anything I should set that I am missing?

[A] Well, personally I have had very large sessions before with very little problems. Probably the largest size I've had before is ~10MB. It's not optimal, but I haven't had a problem with slow scripts even with that size. I wouldn't worry about sessions getting to large, but I would try to keep it under control. My theory is, if keeping it in the session makes it much faster than quering the database every time (such as in the case of a search) then I go for it.


q:
I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

I have the e-mailing of the link, MySQL query, etc. covered.

How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?

I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.

[A]
To have it send it as a CSV and have it give the file name, use header():
http://us2.php.net/header
```
```
header('Content-type: text/csv');
header('Content-disposition: attachment; filename="myfile.csv"');
```
```
As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.


q:
We are all talking about the efficiency of the algorithms and it depends on input size -basically.

How about the system specifications of current computer that runs the algorithm? does it make any difference to run a different sorting algorithm in a Core 2 Duo 2.6 GHZ, 4 GB RAM-computer or in a P-2, 256 MB RAM-computer?

I am sure that there must be a performance difference. But, I want to know what is the real relationship between algorithms and system specifications...

[A]
An increase in hardware performance will give you a constant C times the running time of your algorithm.   Meaning if you have computer A which is overall 2 times slower than computer B.  Than your algorithm will be twice as fast on computer B.   Twice as fast though really makes hardly no difference when you consider big input values to an algorithm though.
In big O notation
that is to say you will have something like O(n) compared to C
O(n) = O(c
n) = O(n).  The complexity of the algorithm and general running time for large values will be about the same on both Computer A and Computer B.
If you analyze an algorithm's running time using something like big O notation, then you will have a much better idea about how the algorithm really works.   Computer performance won't give you any kind of advantage when you are comparing an algorithm that is O(logn) compared to O(n^2).
Take a look at some of the data values for n:
I will assume 1 second per operation for the slow computer, and 2 operations for second for the fast computer.  I will compare the better algorithm with the slow computer with the worse algorithm with the fast computer.
for n = 10:
Algorithm 1: O(logn): 4 operations
  Slow computer: 4 seconds
Algorithm 2: O(n^2): 100 operations
  Fast computer: 50 seconds
for n = 100:
Algorithm 1: O(logn): 7 operations
  Slow computer: 7 seconds
Algorithm 2: O(n^2): 10,000
  operations  Fast computer: 1.4 hours
Large difference
for n = 1,000:
Algorithm 1: O(logn): 10 operations
  Slow computer: 10 seconds
Algorithm 2: O(n^2): 1,000,000
  operations  Fast computer: 5.8 days
Huge difference
As n increases, the difference gets bigger and bigger.
Now if you tried to run each of these algorithms on a faster/slower computer for a large input size.  It wouldn't matter.  Hands down the O(logn) would be faster.


q:
What is appropriate way to integrate SpringSecurity with Capcha ?

I have following use case :
When user will tries to login, if we he failed to login N times, captcha will be displayed, so authentication will be using three parameters : username, password, captcha. But Spring Security doesn't support built in Captcha handling.

I just start thinking about implementation. And have following variants:

Adding separate security filter in Spring Security filter stack,

Entirely rewrite AuthenticationProcessingFilter to support some Captcha

Use some programmatic authentication with interception captcha logic and then transfering username and password to Spring Security

As a Captcha implementation I think about JCaptcha, but what your thougths?

[A]
As an alternative to using JCaptcha, if you'd like to use the
reCAPTCHA Service
on your site, then check out the free Section 4.4 (
direct PDF link
) of the new
Spring in Practice
book (currently in beta).
This shows you integration with Spring MVC and Spring Validation. Since the integration is on the front-end, w/external APIs, Spring Security doesn't really come into the picture here.
I am not sure what your use case is? Are you hoping to use captchas as an alternative to authentication to prove "human"-ness?


q:
I'm creating an app that will have to put at max 32 GB of data into my database.  I am using B-tree indexing because the reads will have range queries (like from 0 < time < 1hr).

At the beginning (database size = 0GB), I will get 60 and 70 writes per millisecond.  After say 5GB, the three databases I've tested (H2, berkeley DB, Sybase SQL Anywhere) have REALLY slowed down to like under 5 writes per millisecond.

Questions:

Is this typical?

Would I still see this scalability issue if I REMOVED indexing?

What are the causes of this problem?

Notes:

Each record consists of a few ints

[A]
Yes; indexing improves fetch times at the cost of insert times. Your numbers sound reasonable - without knowing more.
You can benchmark it. You'll need to have a reasonable amount of data stored. Consider whether or not to index based upon the queries - heavy fetch and light insert? index everywhere a where clause might use it. Light fetch, heavy inserts? Probably avoid indexes. Mixed workload; benchmark it!
When benchmarking, you want as real or realistic data as possible, both in volume and on data domain (distribution of data, not just all "henry smith" but all manner of names, for example).


q:
How fast is php_uname() say doing php_uname('s n') or php_uname('a'). The reason I ask is because I'd like to use it to determine which server I'm on and therefore the configuration (paths, etc).

This is related to Is there a PHP function or variable giving the local host name?

[A]
I just did this:
```
```
<?php
  $tstart = microtime(true);

  php_uname('a');

  print 'it took '. sprintf("%f",microtime(true) - $tstart) ." seconds\n";
?>
```
```
And it produced this:
```
```
it took 0.000016 seconds
```
```
That is on a Core2Duo 2.4GHz Debian box.
I know it is an empirical test and all but I think that it shows that it will be fast enough for you.
I did not expect it to take a long time since uname only needs to make a very simple call to the kernel.


q: I'm trying to create a fast 2D point inside polygon algorithm, for use in hit-testing (e.g. Polygon.contains(p:Point)). Suggestions for effective techniques would be appreciated.

[A]
The trivial solution would be to divide the polygon to triangles and hit test the triangles as explained
here
If your polygon is
CONVEX
there might be a better approach though. Look at the polygon as a collection of infinite lines. Each line dividing space into two. for every point it's easy to say if its on the one side or the other side of the line. If a point is on the same side of all lines then it is inside the polygon.


q:
I have several xml files, the names of which are stored in another xml file.

I want to use xsl to produce a summary of the combination of the xml files. I remember there was a way to do this with the msxml extensions (I'm using msxml).

I know I can get the content of each file using select="document(filename)" but I'm not sure how to combine all these documents into one.

21-Oct-08 I should have mentioned that I want to do further processing on the combined xml, so it is not sufficient to just output it from the transform, I need to store it as a node set in a variable.

[A]
Have a look at the
```
document()
```
function documentation
.
You can use
```
document()
```
to load further XML documents during the transformation process. They are loaded as node sets. That means you would initially feed the XML that contains the file names to load to the XSLT, and take it from there:
```
```
<xsl:copy-of select="document(@href)/"/>
```
```


q:
I have an existing Perl program that uses Getopt package and Getopt::Long::Configure with permute as one of the options. However, now I need to keep the order of the options entered by the user. There is an option $RETURN_IN_ORDER mentioned in the Long.pm, however doesn't seem to be used anywhere at all.

When I pass return_in_order, I am getting the following error.

Getopt::Long: unknown config parameter "return_in_order" at C:/Program Files/IBM/RationalSDLC/common/lib/perl5/5.8.6/Getopt/Long.pm line 1199.

Can someone please tell me if this is supported at all and if so, the right way to use? If not, I would like to know the other alternatives I have.

Thanks.

[A]
It's called
```
require_order
```
, according to the manpage I have here. :-)


q:
I'm a little confused by some PHP syntax I've come across.  Here is an example:

$k = $this->_tbl_key;

if( $this->$k)
{
   $ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls );
}
else
{
    $ret = $this->_db->insertObject( $this->_tbl, $this, $this->_tbl_key );
}

My question is basically what does $this->$k mean?  I figured it might mean the member variable that goes by the name of whatever is in $this->_tbl_key, but how would that work?  Is it possible to add member variables to a class at run-time?

[A]
It'll look up whatever the value of "k" is, and treat it as a variable name. These two samples are the same:
```
```
echo ($obj->myvar);

####

$k = "myvar";
echo ($obj->$k);
```
```


q:
Is there any advantage to using __construct() instead of the class's name for a constructor in PHP?

Example (__construct):

class Foo {
    function __construct(){
        //do stuff
    }
}

Example (named):

class Foo {
    function Foo(){
        //do stuff
    }
}

Having the __construct method (first example) is possible since PHP 5.

Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.

[A]
```
__construct
```
was introduced in PHP5. It is the way you are supposed to do it now. I am not aware of any
advantages
per se, though.
From the PHP manual:
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics
If you're on PHP5 I would recommend using
```
__construct
```
to avoid making PHP look elsewhere.


q:
I'm using Entity Framework O/R mapper from Microsoft and using entity classes (generated classes that are mapped to DB objects) as a business objects.
Is this OK? Please state your cons or pros. What to do in a case of WCF communication between business layer and presentation, how to send those objects as data members?

[A]
The Entity framework was designed for the entity objects to be used as business objects, but you should keep in mind that the business objects will be tied to O/R technology as well as the EDM model. In EF 1.0, there wasn't any support for
persistence-ignorance
scenarios, but support was added in 4.0. You can implement
interfaces
, if you don't want to use any of their base classes.
As of .NET 3.5 SP1, they should also be usable as paramater and return types in WCF service methods without any additional code.


q:
I have faced this problem quite often during the last couple of months, during which I've been building this system. The scenario is this: I have this kind of object that essentially is a list of other objects, but has some other properties specific of its nature. For example:

Class Tests:

Contains many Test objects

Has properties:

DefaultTimeouts

DefaultNumberOfTries

Should I have this class subclass List<Test> or should I have it inheriting from Object, simply having the list as a property beside the other fields?

I know that this may be a bit subjective and personal taste might play a role here, but I'd wholeheartedly like to know your opinion on this.

[A]
If it literally does everything a
```
List
```
would do, and all the
```
List
```
functions would act on the
```
Tests
```
object in an intuitive way that gives the correct result, then in my opinion it should just subclass
```
List<Test>
```
.
Otherwise, you'll just have a class with a ton of methods which just call a method of the same name on the
```
List<Test>
```
variable in the instance. That'll just be an imperfect extension of the
```
List<Test>
```
class itself.


q: As you can see this is a question from a non web developer. I would like to have an ASPX page which, under certain circumstances, can generate a 401 error from code. Ideally it would show the IIS standard page.

[A]
You should be able to just use the following, according to
MSDN
.
```
```
Throw New HttpException(401, "Auth Failed")
```
```
Edit
After seeing the other responses setting the status code would be more appropriate.


q: Do these two keywords have exactly the same effect, or is there something I should be aware of?

[A]
According to this site:
http://en.csharp-online.net/CSharp_FAQ:_What_is_the_difference_between_CSharp_lock_and_Java_synchronized
, C#
```
lock
```
and Java
```
synchronized
```
code blocks are "semantically identical", while for methods, Java uses
```
synchronized
```
while C# uses an attribute:
```
[MethodImpl(MethodImplOptions.Synchronized)]
```
.


q:
What's the best way to format this for readability?

if (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false) {
  createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
  fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}

[A]
```
```
if ((strpos($file, '.jpg',1) ||
     strpos($file, '.gif',1) ||
     strpos($file, '.png',1))
    && file_exists("$thumbsdir/$file") == false)
{
  createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
  fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}
```
```


q:
I would really like to annotate a method with a reference to a single property in a property file for injection.

@Resource("${my.service.url}")
private String myServiceUrl;

Of course, this syntax does not work ;) Thats why I'm asking here.

I am aware that I can inject the full properties file, but that just seems excessive, I dont want the property file - I want the configured value.

Edit: I can only see PropertyPlaceholderConfigurer examples where XML is used to wire the property to the given field. I still cannot figure out how this can be achieved with an annotation ?

[A]
You could try injecting value of property "my.service.url" to a filed in your bean.
Take a look at:
http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer
HTH.


q:
With the asp.net MVC framework the blogs of the team members (Rob Conery, Phil Haack etc) really helped me on my way and made me feel comfortable the development was going in the right direction.
Is there something similar for Silverlight?

-Edit:
I would like to mention that I would like to find members of the dev team themselves.
Currently the support for Silverlight across OS and browser is just too poor to make me care and invest time in it.
But I would like to keep a spying eye out so I can start caring when the framework fulfils it's potentials.

[A]
Method ~ of ~ failed by Tim Heuer:
http://feeds.timheuer.com/timheuer-silverlight
Jesse Liberty - Silverlight Geek:
http://feeds.feedburner.com/JesseLiberty-SilverlightGeek
Community Silverlight content:
http://silverlight.net/blogs/community/rss.aspx
Silverlight Tips of the Day
http://silverlight.net/blogs/msnow/default.aspx
Podcasts:
http://www.sparklingclient.com/
Wynapse (Mining the Web for Silverlight so YOU don't have to):
http://geekswithblogs.net/WynApseTechnicalMusings/Default.aspx


q:
Can I access spring bean that exposed using http invoker (server) from GWT application (client)?

If so is there any example / tutorial for that?

[A]
There's an application template for Spring-GWT apps available
here
, that you may find useful. I haven't tried it out, but I believe it's implemented as a Maven archetype.
For more background on exactly what this template does for you, and how to integrate GWT with Spring, check out the following (video)
presentation
.


q:
Anyone have any idea how to get the value of "Language for Non-Unicode Programs" in Control Panel Regional Settings programmatically using c#?

Already tried CultureInfo, RegionInfo and getting the default encoding using the Encoding object, but I can only get the Standards and Formats value or the main code page.

[A]
IIRC,
```
Thread.CurrentUICulture
```
gets that value.


q:
What is the most efficient way to write the old-school:

StringBuilder sb = new StringBuilder();
if (strings.Count > 0)
{
    foreach (string s in strings)
    {
        sb.Append(s + ", ");
    }
    sb.Remove(sb.Length - 2, 2);
}
return sb.ToString();

...in LINQ?

[A]
Have you looked at the Aggregate extension method?
```
```
var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);
```
```


q: I build VBA applications for both Word and Excel, is there any way to access the progress bar that sometimes appears in the Office status bar.

[A]
I have not accessed the progress bar, but I have in the past used something like this to place task status text in the status bar...
```
```
Sub StatusBarExample()
    Application.ScreenUpdating = False
    ' turns off screen updating
    Application.DisplayStatusBar = True
    ' makes sure that the statusbar is visible
    Application.StatusBar = "Please wait while performing task 1..."
    ' add some code for task 1 that replaces the next sentence
    Application.Wait Now + TimeValue("00:00:02")
    Application.StatusBar = "Please wait while performing task 2..."
    ' add some code for task 2 that replaces the next sentence
    Application.Wait Now + TimeValue("00:00:02")
    Application.StatusBar = False
    ' gives control of the statusbar back to the programme
End Sub
```
```


q: Apart from just inserting and parsing text into a blank Word field, is there any way to programmatically build user-defined fields and field codes into my own templates with VBA? Furthermore, is there a way to make these fields show up in the list of available fields?

[A]
What had you in mind? It is possible to add custom document properties either manually or with VBA. These are the accessible as fields under DOCPROPERTY:
```
```
{ DOCPROPERTY "Test"  \* MERGEFORMAT }
```
```
You can use a macro to ensure that the custom property is added to documents:
```
```
Sub AutoNew()
Dim objCustomProperties As DocumentProperties

Set objCustomProperties = ActiveDocument.CustomDocumentProperties

objCustomProperties.Add Name:="Test", _
   Type:=msoPropertyTypeString, Value:="Blah", _
   LinkToContent:=False

End Sub
```
```
Further Information
Automacros:
http://msdn.microsoft.com/en-us/library/aa263747(office.10).aspx
Understanding Custom Document Properties in Microsoft Office Word 2003:
http://msdn.microsoft.com/en-us/library/aa537154.aspx


q: We are looking for a open source J2EE Application server for log budget deployments. We are considering JBoss and Glassfish. Which is the best open source application server? Any comparative study available?

[A]
A comparison table between JBoss, Geronimo and Tomcat for latter 2007.
This article
has many interesting points to aid your decision and is worth reading:
Geronimo 2 is the clear choice if your
  Java application needs are
  particularly extensive or if you just
  want to leverage total Java EE 5
  compliance.
Although JBoss 4.2 is not
  completely compatible with Sun's Java
  EE 5 standard, the JBoss 4.2 team is
  responsible for many of the
  cutting-edge technologies used by all
  of the servers and added to the
  standard Java EE 5 capabilities.
  Tomcat 6 by itself is a lightweight
  solution. It does not come with all
  the Java EE features and additional
  packages found in JBoss and Geronimo,
  but also doesn't require much memory
  and runs fast even on smaller servers.
In conclusion the author says:
Bottom line: JBoss, Geronimo, and
  Tomcat are reliable, fast, and
  definitely able to handle the traffic
  on large-scale enterprise
  applications. Furthermore, many of the
  high-demand Java server technologies
  presented in the features comparison
  originate from the open source world,
  not the commercial one.


q:
A page executes a number of tasks and takes a long time to process. We want to give the user feedback as each task is completed.

In ASP.NET webforms we used Response.Flush()

What way would you a approach this in ASP.NET MVC?

[A]
You can make it in client side. In each step, you set some session variable with the current step. Then, You make another action in your controller say called: "GetProgress" and assign a view and URI for it.
In the action, you will check this session and return the current progress of your task. In the client side, make a timer (i.e setTimeOut) and you invoke the URI of the later controller action every specific amount of time - 1 second or so. That is it.


q:
Could someone explain to me how Any-related annotations (@Any, @AnyMetaDef, @AnyMetaDefs and @ManyToAny) work in practice. I have a hard time finding any useful documentation (JavaDoc alone isn't very helpful) about these.

I have thus far gathered that they somehow enable referencing to abstract and extended classes. If this is the case, why is there not an @OneToAny annotation? And is this 'any' referring to a single 'any', or multiple 'any'?

A short, practical and illustrating example would be very much appreciated (doesn't have to compile).

Edit: as much as I would like to accept replies as answers and give credit where due, I found both Smink's and Sakana's answers informative. Because I can't accept several replies as the answer, I will unfortunately mark neither as the answer.

[A]
Have you read
the Hibernate Annotations documentation for @Any
? Haven't used that one myself yet, but it looks like some extended way of defining references. The link includes an example, though I don't know if it's enough to fully understand the concept...


q: In history-books you often have timeline, where events and periods are marked on a line in the correct relative distance to each other. How is it possible to create something similar in LaTeX?

[A]
The
tikz
package seems to have what you want.
```
```
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}

\begin{document}

  \begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm]
    % draw horizontal line
    \draw (0,0) -- (2,0);
    \draw[snake] (2,0) -- (4,0);
    \draw (4,0) -- (5,0);
    \draw[snake] (5,0) -- (7,0);

    % draw vertical lines
    \foreach \x in {0,1,2,4,5,7}
      \draw (\x cm,3pt) -- (\x cm,-3pt);

    % draw nodes
    \draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$   $};
    \draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};
    \draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};
    \draw (3,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};
    \draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};
    \draw (6,0) node[below=3pt] {$  $} node[above=3pt] {$  $};
    \draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};
  \end{tikzpicture}

\end{document}
```
```
I'm not too expert with tikz, but this does give a good timeline, which looks like:


q:
Heres a screenshot to make it clear. I'm trying to figure out a robust way of making the bullet images vertically aligned to my li content. As you can see my content is currently too high.

Many thanks 'over-flowers'...

http://dl.getdropbox.com/u/240752/list-example.gif

[A]
You can use something like this in your css...
```
```
#content li{

    list-style-image: url(../images/bullet.gif);

}
```
```


q:
Our 404 error logs show a lot of /SysVol http requests on our Windows Web Server 2008 for our website. It only has a webserver role and I believe that SysVol requests are meant for Domain Controllers? What's causing this and what would be the best solution to deal with these 404 requests?

I'm using code that access employee records via Active Directory (ldap) and the server is not trusted for delegaton in case this is related to the problem.


q:
What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string?

As an example, I need to convert this:

string = "*abc+de?"

to this:

string = ".*abc.+de.?"

Of course I could loop through the string and build up another string character by character, but that's surely an inefficient way of doing this?

[A]
I'd use
```
replace
```
:
```
```
def wildcard_to_regex(str):
    return str.replace("*", ".*").replace("?", .?").replace("#", "\d")
```
```
This probably isn't the most efficient way but it should be efficient enough for most purposes. Notice that some wildcard formats allow character classes which are more difficult to handle.


q:
Is there any good way to use a windows application written in C# to display/control a powerpoint slideshow? Ultimately I would like to show thumbnails in a form and clicking these thumbnails would advance the slides shown on a second monitor (similar to using Powerpoint itself to show a slideshow on a second monitor).

I would like to be able to use Powerpoint Viewer if Powerpoint is not installed.

There seems to be some ActiveX-controls that allows integration of Powerpoint in a form, but most of these seem to cost money, does anyone have experience using one of these controls?

Edit: I know that there is an object model accessable by adding a reference to Microsoft.Office.InterOp.Powerpoint, but I want to be able to distribute the resulting program without having Microsoft Office as a prerequisite, that was why I mentioned Powerpoint Viewer because it can be distributed freely.

[A]
One of our softwares here at work does that. Initially we used MS Office but recently we switched to use
OpenOffice.org Uno
since it offers better control than MS Office and is easier to work with. It has
.NET CLI-bindings
.
To answer your question, yes it can be done but our engineers would recommend you use OpenOffice.org instead.


q:
Suppose I have a hash_map and a code like

// i is an iterator
i = hash_map.erase(i)

But GCC's STL doesn't return iterator in erase, but a void. Now is a code like

hash_map.erase(i++)

safe (i.e. does not invalidate the iterator or does any other unexpected or unpleasant things)? Please note this is a hash_map.

[A]
Yes, this is safe, because the value of
```
i
```
will have been set to the next value, before the current value is erased.
According to the
SGI documentation about hashed containers
invalidation does not occur for non-erased elements, nor even for resizing (there is no word on whether insertions cause resizing, so to be careful I admit that as a possibility)---but in the latter case, the iteration order will be changed. But this doesn't apply here, unless you go out of your way to resize the container during traversal or something. :-)


q:
i want to write code for unit test to test my application code. I have different methods and now want to test these methods one by one in python script.
but i do not how to i write. can any one give me example of small code for unit testing in python.
i am thankful

[A]
Read the
unit testing framework section
of the
Python Library Reference
.
A
basic example
from the documentation:
```
```
import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def testshuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

    def testchoice(self):
        element = random.choice(self.seq)
        self.assert_(element in self.seq)

    def testsample(self):
        self.assertRaises(ValueError, random.sample, self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assert_(element in self.seq)

if __name__ == '__main__':
    unittest.main()
```
```


q:
Below are lines from "the c++ programming language"

template<class T > T sqrt(T );
template<class T > complex<T> sqrt(complex<T>);
double sqrt(double);
void f(complex<double> z )
{
s q r t (2 ); // sqrt<int>(int)
sqrt(2.0) ; // sqrt(double)
sqrt(z) ; // sqrt<double>(complex<double>)
}

I dont understand why sqrt(z) ; calls sqrt<double>(complex<double>) can any body please explain.

Author says,
T sqrt<complex<T>>  is more specialized than T sqrt <T> but there is a seperate declaration for template<class T > complex<T> sqrt(complex<T>); why not use that?

[A]
Well, the function used is the one you are talking about
```
sqrt<double>(complex<double>)
```
is an instance of the template
```
template <class T> complex<T> sqrt(complex<T>)
```
.
Your misunderstanding was in the signification of the template instance and not in the overloading process.


q:
Is there any class in the .NET framework that can read/write standard .ini files:

[Section]
<keyname>=<value>
...

Delphi has the TIniFile component and I want to know if there is anything similar for C#?

[A]
The creators of the .NET framework want you to use XML-based config files, rather than INI files. So no, there is no built-in mechanism for reading them.
There are third party solutions available, though.
INI handlers can be obtained as
NuGet packages
, such as
INI Parser
.
You can write your own INI handler, which is the old-school, laborious way. It gives you more control over the implementation, which you can use for bad or good. See e.g.
an INI file handling class using C#, P/Invoke and Win32
.


q:
I am a big fan of letting the compiler do as much work for you as possible.  When writing a simple class the compiler can give you the following for 'free':

A default (empty) constructor

A copy constructor

A destructor

An assignment operator (operator=)

But it cannot seem to give you any comparison operators - such as operator== or operator!=.  For example:

class foo
{
public:
    std::string str_;
    int n_;
};

foo f1;        // Works
foo f2(f1);    // Works
foo f3;
f3 = f2;       // Works

if (f3 == f2)  // Fails
{ }

if (f3 != f2)  // Fails
{ }

Is there a good reason for this?  Why would performing a member-by-member comparison be a problem?  Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?

[A]
I agree, for POD type classes then the compiler could do it for you. However what you might consider simple the compiler might get wrong. So it is better to let the programmer do it.
I did have a POD case once where two of the fields were unique - so a comparison would never be considered true. However the comparison I needed only ever compared on the payload - something the compiler would never understand or could ever figure out on it's own.
Besides - they don't take long to write do they?!


q:
I've got a text box bound to an object's property (in fact several text boxes) on a form. This for is an editor for an object. When i'm editing some objects and modify values in the one of the text boxes i can't exit from the text box (neither by tab nor clicking on another text box). However that's not always the case - when editing other objects (of the same type) it works fine.

Here's a code snipet:

txtValue.DataBindings.Add("Text", _SourceObject, "PlannedValue", True, DataSourceUpdateMode.OnPropertyChanged, Nothing, "c")
txtEstPlacements.DataBindings.Add("Text", _SourceObject, "EstimatedPlacementCount")
txtReference.DataBindings.Add("Text", _SourceObject, "Reference")

Any suggestions?

[A]
Sounds like a data validation issue.  Check if the controls on the form have their CausesValidation properties set to true or false.
Also check the AutoValidate property on the form.  It is probably set to EnablePreventFocusChange (which is the default).
It may also be the case that the value being supplied in the text box can not be converted to the type of the property it is bound to on the source data object.  I believe the Convert class is used for this (though I may be wrong here).
You may want to check out
this article
on MSDN that covers winforms validation in some detail.


q: Can I have multiple primary keys in a single table?

[A]
You can only have one primary key, but you can have multiple columns in your primary key.
You can also have Unique Indexes on your table, which will work a bit like a primary key in that they will enforce unique values, and will speed up querying of those values.


q:
How do I print debug messages in the Google Chrome JavaScript Console?

Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the print command in JavaScript Debugger will not work here. In the JavaScript Console, print() will send the parameter to the printer.

[A]
Executing following code from the browser address bar:
```
javascript: console.log(2);
```
successfully prints message to the "JavaScript Console" in Google Chrome.


q:
How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:

http://site/catalogue/BrowseByStyleLevel/1

The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.

For example, these two URLs will take you to the same place:

https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages

https://stackoverflow.com/questions/119323/

EDIT: The friendly part of the url is referred to as a slug.

[A]
you have a route on the global.asax
```
```
routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = ""}
                    // Parameter defaults )
```
```
you can  define your own route like :
controller is the cs class inside the the controllers folder.
you can define your id - with the name you choose.
the system will pass the value to your actionResult method.
you can read more about this step here :
http://www.asp.net/learn/mvc/tutorial-05-cs.aspx


q: Is there a way to Deserialize Expressions in C#, I would like to store Expressions in a Database and load them at run time.

[A]
Not in full; however, the
Dynamic LINQ
sample may help a bit. You can certainly serialize an expression to a string (to an extent - generics look a bit screwy), but there is no inbuilt parser.


q: I was trying to test code using com class to display Word files but I cannot seem to get the answer and still searching. I get errors and sometimes, programs do not display anything at all. Please give me some ideas. I'm working with PHP 4.

[A]
Do you mean you want to have the word plugin activated in the browser? Try the
```
<object>
```
tag with the correct mime type.


q:
In the documentation of hardware that allows us to control it via UDP/IP,
I found the following fragment:

In this communication protocol, DWORD is a 4 bytes data, WORD is a 2 bytes data,
  BYTE is a single byte data. The storage format is little endian, namely 4 bytes (32bits) data is stored as: d7-d0, d15-d8, d23-d16, d31-d24; double bytes (16bits) data is stored as: d7-d0 , d15-d8.

I am wondering how this translates to C#?
Do I have to convert stuff before sending it over?
For example, if I want to send over a 32 bit integer, or a 4 character string?

[A]
Re little-endian, the short answer (to do I need to do anything) is "probably not, but it depends on your hardware". You can check with:
```
```
bool le = BitConverter.IsLittleEndian;
```
```
Depending on what this says, you might want to reverse portions of your buffers. Alternatively, Jon Skeet has specific-endian converters
here
(look for EndianBitConverter).
Note that itaniums (for example) are big-endian. Most Intels are little-endian.
Re the specific UDP/IP...?


q:
I quite often see on the Internet various complaints that other peoples examples of currying are not currying, but are actually just partial application.

I've not found a decent explanation of what partial application is, or how it differs from currying. There seems to be a general confusion, with equivalent examples being described as currying in some places, and partial application in others.

Could someone provide me with a definition of both terms, and details of how they differ?

[A]
Interesting question. After a bit of searching,
"Partial Function Application is not currying"
gave the best explanation I found. I can't say that the
practical
difference is particularly obvious to me, but then I'm not an FP expert...
Another useful-looking page (which I confess I haven't fully read yet) is
"Currying and Partial Application with Java Closures"
.
It does look like this is widely-confused pair of terms, mind you.


q: If I switch on the generating of debug info with Javac then the class files are 20-25% larger. Has this any performance effects on running the Java program? If yes on which conditions and how many. I expect a little impact on loading the classes because the files are larger but this should be minimal.

[A]
In any language, debugging information is meta information. It by its nature increases the size of the object files, thus increasing load time. During execution outside a debugger, this information is actually completely ignored. As outlined (although not clearly) in the
JVM spec
the debug information is stored outside the bytecode stream. This means that at execution time there is no difference in the class file. If you want to be sure though, try it out :-).
Ps. Often for debugging there is value in turning off optimization. That
does
have a performance impact.


q: Guys, can someone give me a brief run through of how to change the background colour of a CEdit control at runtime? I want to be able to change the background to red if the field is zero length and the normal white otherwise.

[A]
You cannot do it with a plain CEdit, you need to override a few bits.
Implement your own ON_WM_CTLCOLOR_REFLECT handler, then return your coloured CBrush in the handler:
(roughly, you'll need to put the usual resource management in there, rememebr to delete your brush in the destructor)
```
```
class CColorEdit : public CEdit
{
  ....
  CBrush   m_brBkgnd;
  afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor)
  {
    m_brBkgnd.DeleteObject();
    m_brBkgnd.CreateSolidBrush(nCtlColor);
  }
}
```
```


q: I want to show the publish date in the About dialog.

[A]
Unfortunately, no. ApplicationDeployment class exposes only the
CurrentVersion
property, not the publish time.
You could use the revision field to store the date of the build to show in the About dialog.


q: Is there a class in the standard library of .NET that gives me the functionality to create random variables that follow Gaussian distribution?

[A]
Jarrett's suggestion of using a Box-Muller transform is good for a quick-and-dirty solution.  A simple implementation:
```
```
Random rand = new Random(); //reuse this if you are generating many
double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles
double u2 = 1.0-rand.NextDouble();
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
             Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
double randNormal =
             mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)
```
```


q:
I've recently searched how I could get the application's directory in Java. I've finally found the answer but I've needed surprisingly long because searching for such a generic term isn't easy. I think it would be a good idea to compile a list of how to achieve this in multiple languages.

Feel free to up/downvote if you (don't) like the idea and please contribute if you like it.

Clarification:

There's a fine distinction between the directory that contains the executable file and the current working directory (given by pwd under Unix). I was originally interested in the former but feel free to post methods for determining the latter as well (clarifying which one you mean).

[A]
In
Java
, there are two ways to find the application's path. One is to employ
```
System.getProperty
```
:
```
```
System.getProperty("user.dir");
```
```
Another possibility is the use of
```
java.io.File
```
:
```
```
new java.io.File("").getAbsolutePath();
```
```
Yet another possibilty uses reflection:
```
```
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
```
```


q:
I have a div with overflow:hidden, inside which I show a phone number as the user types it. The text inside the div is aligned to right and incoming characters are added to right as the text grows to left.

But once the text is big enough not to fit in the div, last characters of the number is automatically cropped and the user cannot see the new characters she types.

What I want to do is crop the left characters, like the div is showing the rightmost of its content and overflowing to the left side. How can I create this effect?

[A]
Have you tried using the following:
```
```
direction: rtl;
```
```
For more information see
http://www.w3schools.com/cssref/pr_text_direction.asp


q:
Today when I was in computer organization class, teacher talked about something interesting to me. When it comes to talk about Why cache memory works, he said that:

for (i=0; i<M; i++)
   for(j=0; j<N; j++)
      X[i][j] = X[i][j] + K; //X is double(8 bytes)

it is not good to change the first line with the second. What is your opinions on this? And why it is like that?

[A]
It is like that becauses caches like locality. The same number of memory accessed, but spaced further apart, will hit different "lines" of cache, or might even miss the cache altogether. It is therefore good, whenever you have the choice, to organize data so that accesses that are likely to happen close to each other in time, also do so in space. This increases the chance of a cache hit, and gives you more performance.
There is of course a wealth of information about this topic available, see for instance
this wikipedia entry on locality of reference
. Or, I guess, your own course text book. :)


q:
I want to deserialize an object but don't know the class up front.  So, consider the following code...

IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);

What could I do if I don't know the class up front?  Say, for example "MyFile.bin" was a MyObject or a MyFoo.  How do I determine which object to instantiate?

Something like...

if (magic happens here == typeof(MyObject))
    MyObject obj = (MyObject) formatter.Deserialize(stream);
else if (more magic happens here == typeof(MyFoo))
    MyFoo foo = (MyFoo)formatter.Deserialize(stream);

[A]
Just do:
```
```
object result = formatter.Deserialize(stream);
Type t = result.GetType();
```
```


q:
I'm wrapping up a Javascript widget in a Wicket component.  I want to let the JS side talk to the component.  What I've got so far:

Component in question goes like

talker = new GridAjaxBehavior();
this.add(talker);

in constructor

and then, later on, puts something like

"var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ");";

into the JS.

where GridAjaxBehavior extends AbstractDefaultAjaxBehavior.  I want GridAjaxBehavior to spit back some XML when the JS calls it.

Am I doing this the right way?  What should GridAjaxBehaviour do to spit back the XML?

Thanks

[A]
I don't really know what Wicket is or what it does, but there is a minor bug in your code (as it appears).
This:
```
"var MyGridTalker = new talker(" + this.talker.getCallbackUrl();
```
You seem to be missing your end parens:
```
"var MyGridTalker = new talker(" + this.talker.getCallbackUrl() + ")";
```
Anyway, not a big deal, but didn't know if it was intentional.


q: If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?

[A]
I use the
```
ArgumentException
```
(and its “friends”) regularly.
```
NotSupportedException
```
and
```
NotImplementedException
```
are also common.


q:
To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action.

So, what's the correct way of doing such a thing? I've tried

panel = new CustomJPanelWithComponentsOnIt();
parentFrameJPanelBelongsTo.pack();

but this won't work. What would you suggest?

[A]
```
```
frame.setContentPane(newContents());
frame.revalidate(); // frame.pack() if you want to resize.
```
```
Remember, Java use 'copy reference by value' argument passing. So changing a variable wont change copies of the reference passed to other methods.
Also note
```
JFrame
```
is very confusing in the name of usability. Adding a component or setting a layout (usually) performs the operation on the content pane. Oddly enough, getting the layout really does give you the frame's layout manager.


q:
The following code

number=1
if [[ $number =~ [0-9] ]]
then
  echo matched
fi

works. If I try to use quotes in the regex, however, it stops:

number=1
if [[ $number =~ "[0-9]" ]]
then
  echo matched
fi

I tried "\[0-9\]", too. What am I missing?

Funnily enough, bash advanced scripting guide suggests this should work.

Bash version 3.2.39.

[A]
It was changed
between 3.1 and 3.2
. Guess the advanced guide needs an update.
This is a terse description of the new
  features added to bash-3.2 since the
  release of bash-3.1.  As always, the
  manual page (doc/bash.1) is the place
  to look for complete descriptions.
New Features in Bash
snip
f.  Quoting the string argument to the
  [[ command's  =~ operator now forces
      string matching, as with the other pattern-matching operators.
Sadly this'll break existing quote using scripts unless you had the insight to store patterns in variables and use them instead of the regexes directly. Example below.
```
```
$ bash --version
GNU bash, version 3.2.39(1)-release (i486-pc-linux-gnu)
Copyright (C) 2007 Free Software Foundation, Inc.
$ number=2
$ if [[ $number =~ "[0-9]" ]]; then echo match; fi
$ if [[ $number =~ [0-9] ]]; then echo match; fi
match
$ re="[0-9]"
$ if [[ $number =~ $re ]]; then echo MATCH; fi
MATCH

$ bash --version
GNU bash, version 3.00.0(1)-release (i586-suse-linux)
Copyright (C) 2004 Free Software Foundation, Inc.
$ number=2
$ if [[ $number =~ "[0-9]" ]]; then echo match; fi
match
$ if [[ "$number" =~ [0-9] ]]; then echo match; fi
match
```
```


q:
Is there a nicer way of styling a <hr /> tag using CSS, that is cross-browser consistent and doesn't involve wrapping a div around it? I'm struggling to find one.

The best way I have found, is as follows:

CSS

.hr {
    height:20px;
    background: #fff url(nice-image.gif) no-repeat scroll center;
}
hr {
    display:none;
}

HTML

<div class="hr"><hr /></div>

[A]
If you set display to
```
block
```
it should behave more like a
```
<div>
```
.
Your answer you should remove hr altogether and just use the
```
div
```


q:
As web based designer who has designed web sites using tables but never with css, how can a novice get started with css?

Related SO posts

SO - Css Book & website for CSS

SO - Css blog

[A]
Get started by reading tutorial web site first. This way, he will see how to create simple CSS and see the benefits.
http://www.w3schools.com/css/
http://www.echoecho.com/css.htm
http://www.csstutorial.net/
http://www.w3.org/Style/Examples/011/firstcss
http://www.westciv.com/style_master/academy/css_tutorial/
Than, I suggest since he knows how to design website to check other website source and see their CSS files.
Zen Garden
is a good start.
If he requires more information, he can always get a book (I do not think it's necessary but if he wants a book), he could try
Core-Css
.


q:
I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts).

$array1 = array(1 => 'a', 2 => 'b');
$array2 = array(3 => 'c', 4 => 'd');

Essentially I want to combine the two arrays as if it were something like this

$array3 = array(1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd');

Thanks

[A]
Use
```
```
$array3 = $array1 + $array2;
```
```
See
Array Operators
By the way:
array_merge()
does something different with the arrays given in the example:
```
```
$a1=array(1 => 'a', 2 => 'b');
$a2=array(3 => 'c', 4 => 'd');
print_r($a1+$a2);
Array
(
    [1] => a
    [2] => b
    [3] => c
    [4] => d
)
print_r(array_merge($a1, $a2));
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)
```
```
Note the different indexing.


q: Is there a built-in way to URL encode a string in Excel VBA or do I need to hand roll this functionality?

[A]
No, nothing built-in (
until Excel 2013 -
see this answer
).
There are three versions of
```
URLEncode()
```
in this answer.
A function with UTF-8 support.
You should probably use this one
(or
the alternative implementation
by Tom) for compatibility with modern requirements.
For reference and educational purposes, two functions without UTF-8 support:
one found on a third party website, included as-is. (This was the first version of the answer)
one optimized version of that, written by me
A variant that supports UTF-8 encoding and is based on
```
ADODB.Stream
```
(include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):
```
```
Public Function URLEncode( _
   ByVal StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String
  Dim bytes() As Byte, b As Byte, i As Integer, space As String

  If SpaceAsPlus Then space = "+" Else space = "%20"

  If Len(StringVal) > 0 Then
    With New ADODB.Stream
      .Mode = adModeReadWrite
      .Type = adTypeText
      .Charset = "UTF-8"
      .Open
      .WriteText StringVal
      .Position = 0
      .Type = adTypeBinary
      .Position = 3 ' skip BOM
      bytes = .Read
    End With

    ReDim result(UBound(bytes)) As String

    For i = UBound(bytes) To 0 Step -1
      b = bytes(i)
      Select Case b
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Chr(b)
        Case 32
          result(i) = space
        Case 0 To 15
          result(i) = "%0" & Hex(b)
        Case Else
          result(i) = "%" & Hex(b)
      End Select
    Next i

    URLEncode = Join(result, "")
  End If
End Function
```
```
This function was
found on freevbcode.com
:
```
```
Public Function URLEncode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim CurChr As Integer
  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    Select Case Asc(Mid(StringToEncode, CurChr, 1))
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case Else
        TempAns = TempAns & "%" & _
          Right("0" & Hex(Asc(Mid(StringToEncode, _
          CurChr, 1))), 2)
    End Select

    CurChr = CurChr + 1
  Loop

  URLEncode = TempAns
End Function
```
```
I've corrected a little bug that was in there.
I would use more efficient (~2× as fast) version of the above:
```
```
Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String

  Dim StringLen As Long: StringLen = Len(StringVal)

  If StringLen > 0 Then
    ReDim result(StringLen) As String
    Dim i As Long, CharCode As Integer
    Dim Char As String, Space As String

    If SpaceAsPlus Then Space = "+" Else Space = "%20"

    For i = 1 To StringLen
      Char = Mid$(StringVal, i, 1)
      CharCode = Asc(Char)
      Select Case CharCode
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Char
        Case 32
          result(i) = Space
        Case 0 To 15
          result(i) = "%0" & Hex(CharCode)
        Case Else
          result(i) = "%" & Hex(CharCode)
      End Select
    Next i
    URLEncode = Join(result, "")
  End If
End Function
```
```
Note that neither of these two functions support UTF-8 encoding.


q:
I have a Makefile building many C files with long long command lines and we've cleaned up the output by having rules such as:

.c${MT}.doj:

        @echo "Compiling $<";\
         $(COMPILER) $(COPTS) -c -o $@ $<

Now this is great as the @ suppresses the compilation line being emitted.
But when we get an error, all we get is the error message, no command line.
Can anyone think of a "neat" way to emit the command line?
All I can think of doing is echoing it to a file and have a higher level make catch the error and cat the file. Hacky I know.

[A]
Tested and it worked (GNU make in Linux):
```
```
.c${MT}.doj:
     @echo "Compiling $<";\
          $(COMPILER) $(COPTS) -c -o $@ $<  \
          || echo "Error in command: $(COMPILER) $(COPTS) -c -o $@ $<" \
          && false
```
```


q:
I need to change in a text input the character '.' to ',' while typing.
In IE I change the keyCode event property in the keypress event, like this

document.getElementById('mytext').onkeypress =
 function (evt) {
  var e = evt || window.event;
  if (e.keyCode && e.keyCode==46)
   e.keyCode = 44;
  else if (e.which && e.which==46) {
   e.which = 44;
  }
 };

but it seemes that in Firefox it's impossible to change characters typed in key events.
Any suggestions?

[A]
Try this. It works on all browsers:
```
```
window.onload = function () {
    var input = document.getElementById("mytext");

    input.onkeypress = function () {
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is it a period?
        if (char == ".") {
            // Replace it with a comma
            input.value += ",";

            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};
```
```
Update:
Pier Luigi
pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.
The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.


q:
Is there support in Ruby for (for lack of a better word) non-escaped (verbatim) strings?

Like in C#:

@"c:\Program Files\"

...or in Tcl:

{c:\Program Files\}

[A]
Yes, you need to prefix your string with
```
%
```
and then a single character delineating its type.
The one you want is
```
%q{c:\program files\}
```
.
The pickaxe book covers this nicely
here,
section is General Delimited Input.


q: Looking for links to resources that will help me write a user guide for a software application. I'm after something that will help me to structure my guide, give it an appropriate writing style, and ensure that it has an excellent look and feel throughout.

[A]
This link has some strong points. Each point is presented with clear speech and with inline justifications.
When writing procedures, use the
  active voice (e.g. Click this) and
  address users directly (write "you"
  rather than "the user").
When explaining an action, use the
  "command" form of the verb:
"Choose an option from the menu and
  press [ENTER]."
http://www.klariti.com/technical-writing/User-Guides-Tutorial.shtml
Here is the complete list of the topics covered on the aforementioned article:
Front Page (cover pages)
Cover and Title Page
Disclaimer
Preface
Contents
Body of the guide
Procedures
Writing procedures
Chunking text
Number your steps
Using the If-Then Approach
Reference Materials
Back Matter
Glossary
Index
Establishing Standards
Document Format
Structure Style
Technical Language
Addressing the User
Presenting your material
Special Requirements


q: Is is possible to write MS SQL Server add-in? I'm thinking of some application integrated with database server available form SQL Server Enterprise Manager.

[A]
You can include a lot into MS SQL server 2005 and 2008 database. Including .Net code.
But there is no real way to extend (create plugin for) the Management Studio. (Formerly Enterprise Manager.)
However there are database management addins for Visual Studio (especially in Team System). Maybe there you can implement what you need.


q:
I have a custom class that implements that IComparable.  This class is stored in a Generic List.  I now need to compare to lists to see which objects are in list A but not in list B.

I thought the most simple way of doing this would be to iterate through list B and do A.contains().

I do not know how to get it to use my CompareTo() (or another method that I can override so that I can say if it contains a certain object or not).  I could be wrong but as I understand it the contains checks if the objects are actually the same (i.e. points to the same place in memory).

Could anyone help me please?

[A]
Why don't you just override the
```
Equals
```
method of your class to be consistent in meaning with
```
CompareTo(other) == 0
```
? This is the simplest way and also the most idiomatic since, as you've noticed,
```
Contains
```
compares equality rather than using
```
CompareTo
```
. However, this check is done via
```
Equals
```
. It does
not
check whether the objects point to the same memory location.
/EDIT: Additionally, if you're using .NET 3.5 you can use the
```
Contains
```
overload that accepts an
```
IEqualityComparer
```
argument. You can use this to provide a class that implements a custom equality relation for your class type. However, I think the first method is more appropriate in your case.


q:
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

[A]
```
NullPointerException
```
s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object.  Calling a method on a null reference or trying to access a field of a null reference will trigger a
```
NullPointerException
```
.  These are the most common, but other ways are listed on the
```
NullPointerException
```
javadoc page.
Probably the quickest example code I could come up with to illustrate a
```
NullPointerException
```
would be:
```
```
public class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}
```
```
On the first line inside
```
main
```
, I'm explicitly setting the
```
Object
```
reference
```
obj
```
equal to
```
null
```
.  This means I have a reference, but it isn't pointing to any object.  After that, I try to treat the reference as though it points to an object by calling a method on it.  This results in a
```
NullPointerException
```
because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location.  A null pointer is literally not pointing
anywhere
, which is subtly different than pointing to a location that happens to be invalid.)


q:
I want to stitch 2 pieces of png side by side. In Cocoa, I would use [NSImage initWithSize], and then just drawInRect.

But UIImage don't have initWithSize class, how would I do this now?

[A]
Use
```
UIGraphicsBeginImageContext()
```
, draw in it, then use
```
UIGraphicsGetImageFromCurrentImageContext()
```
. Remember to pop the context with
```
UIGraphicsEndImageContext()
```
afterwards.
You should avoid creating an extra image if you simply want to display the two images onscreen, due to the limited memory available on the device. Instead, display them using appropriate
```
drawInRect:
```
calls to avoid copying.


q:
What's the advantage of passing data as parameters vs part of the URL in an Ajax GET request?

Using parameters:

var ajax = new Ajax.Request('server.php',{
    parameters: 'store=11200&product=Meat',
    onSuccess: function(myData){whatever}
});

Using URL:

var ajax = new Ajax.Request('server.php?store=11200&product=Meat',{
    onSuccess: function(myData){whatever}
});

[A]
One advantage to using the
```
parameters
```
argument is that you can pass it a
```
Hash
```
-like object instead of as a string. (If you do this, though, make sure so set the
```
method
```
parameter to
```
"GET"
```
, as the default method for Prototype Ajax requests is POST; see
the Prototype Introduction to Ajax
for more details.)
Another advantage, which is more in-line with the example that you gave, is that you can separate the request URL from the options that are sent to it. This might be useful if, for example, you need to send a bunch of similar requests to several different URLs. (In that case, having a common parameters
```
Hash
```
that you modify for each request might be more useful, than using a parameter string, as well.)
For more information, see
the Prototype documentation of Ajax options
.


q:
I was wondering if there was a good way to monitor a document library on SharePoint for changes (new files added, files changed / checked-in, files deleted, etc.)

Basically, what System.IO.FileSystemWatcher does on local / network directories.

Are there events that get fired when documents are uploaded to document libraries?

Perhaps creating a workflow on the document library that fires onCreate / onModify would be better?

Any suggestions are welcome.

[A]
Take a look at event receivers for lists/document libraries.  There are both synchronous and asynchronous options built into the object model. (ItemAdded, ItemAdding, ItemUpdated, ItemUpdating ... and so on.)
The following site should give you a good start:
http://www.davehunter.co.uk/Blog/Lists/Posts/Post.aspx?List=f0e16a1a%2D6fa9%2D4130%2Dbcab%2Dbaeb97ccc4ff&ID=69


q:
Suppose we have the following code:

ExpressionHelper.GetRouteValuesFromExpression<AccountController>(ax => ax.MyAction("a", "b"));

(from ASP.NET MVC Futures assembly). Method is reasonably fast - it executes 10k iterations in 150ms.

Now, we change code to this:

string a = "a";
string b = "b";
ExpressionHelper.GetRouteValuesFromExpression<AccountController>(ax => ax.MyAction(a, b));

This code will execute 10k iterations in 15 seconds

The problem is the following code:

Expression<Func<object>> lambdaExpression = Expression.Lambda<Func<object>>(Expression.Convert(arg, typeof (object)));

Func<object> func = lambdaExpression.Compile();

value = func()

Is there a better way to get value from expression than compiling expression every time? This can greatly affect ASP.NET MVC link generation speed.

[A]
Why don't you just cache the value of the expression and its compiled value locally if this is such a bottleneck? I imagine a simply Dictionary could do the trick:
```
```
Dictionary<Expression<Action<T>>, Action<T>> m_Cache =
    new Dictionary<Expression<Action<T>>, Action<T>>();

public void GetRouteValuesFromExpression<T>(Expression<Action<T>> expr) {
    Action<T> compiled = null;
    if (!m_Cache.TryGetValue(expr, ref compiled)) {
        compiled = expr.Compile();
        m_Cached.Add(expr, compiled);
    }
    // execute …
}
```
```


q:
What is the best way to actively monitor if a .NET Windows service is still running (e.g not hung)?  The service needs to periodically respond to events raised by a timer.

Thanks

Jon

[A]
"Not hung" is always a hard condition to definitively detect, and will depend on the details of your service.
In general any form of interprocess communication can be used.  One simple approach is to create a
named
shared memory mapping and simply write information to it periodically from your service.  Another process can monitor the shared memory and see if its state stops changing.
The advantage of this approach is that you can extend the shared memory block to include other diagnostics which may help diagnose any issues.


q:
Part of my latest webapp needs to write to file a fair amount as part of its logging. One problem I've noticed is that if there are a few concurrent users, the writes can overwrite each other (instead of appending to file). I assume this is because of the destination file can be open in a number of places at the same time.

flock(...) is usually superb but it doesn't appear to work on NFS... Which is a huge problem for me as the production server uses a NFS array.

The closest thing I've seen to an actual solution involves trying to create a lock dir and waiting until it can be created. To say this lacks elegance is understatement of the year, possibly decade.

Any better ideas?

Edit: I should add that I don't have root on the server and doing the storage in another way isn't really feasible any time soon, not least within my deadline.

[A]
Another dirty hack would be to
```
flock()
```
a "local" file, and only open / write to the NFS file if you hold the lock on the local file.
Edit: from the
```
flock()
```
page:
flock() will not work on NFS and many
  other networked file systems. Check
  your operating system documentation
  for more details.
Edit 2:
Of course there's always using the database to synchonise access (I'm assuming your app uses a db).  This would be quite a performance hit if you're doing a lot of logging though.
If it's just for logging, do you actually need a centralised log file?  Could you log locally (and even combine the logs when they rotate at the end of the day if needed)?


q:
I would like to know what is the difference between initializing a static member inline as in:

class Foo
{
    private static Bar bar_ = new Bar();
}

or initializing it inside the static constructor as in:

class Foo
{
    static Foo()
    {
        bar_ = new Bar();
    }
    private static Bar bar_;
}

[A]
In this case I don't believe there si any practical difference. If you need some logic in initializing the static variables - like if you would want to use different concrete types of an interface given different conditions - you would use the static constructor. Else, the inline initialization is fine in my book.
```
```
class Foo
{
    private static IBar _bar;

    static Foo()
    {
        if(something)
        {
            _bar = new BarA();
        }
        else
        {
            _bar = new BarB();
        }
    }
}
```
```


q: Specifically, I want to copy a link (with text and location) and then to be able to paste it, e.g., into Word as a link.

[A]
dig around inside
Download of the Day: AutoCopy Firefox extension
or
Clipboard-Save-As 1.0.4


q:
At a new job I started, we have both a Java application that handles most of the heavy lifting in the core business logic, and we also have a Rails application that of course handles the web interface to this server.  Both of these access the same database.

Up until now, most of the focus has been on the Java application, and as such, there are no migrations in the Rails project.  The sql to update the shared database is managed in a file like changes.sql.

As you can imagine, this makes it somewhat difficult to develop.

My initial thought was to combine the codebases for the Java project and the Rails application, because there is a dependency there, and to manage that SQL file in the source.  However, I thought I'd ask here to see if anyone else had tackled this issue with some degree of success.

[A]
One approach is to use the rails migration tools, generate the DDL files for the database and use Hibernate to update the Java objects that relate to specific database entities.  You don't really say how you manage database changes on the Java side or whether you use an ORM, but you can certainly synchronize the two with a little work.
Or you can go the other way around and let the Java definitions control changes on the Rails side.
I think the key to doing this successfully is to select one of the two platforms as your "primary database modeller" and develop the process to migrate that model to the other platform.  Attempting to allow changes from both will only cause headaches.


q:
Is it possible to configure Windows Servers that reside on the same domain such that when a web service call is made from a web app using an IP address, the request does not go via a proxy server?

The web service is running on one of the servers on the domain.

I want to configure IP based security on the server that hosts the web service such that it only allows connections from specific servers.  Currently all requests go via the proxy server rendering IPSec problematic.

Within the browser I can specify that requests following a specific pattern should bypass the proxy server.  It's essentially this behaviour I want to replicate with the servers.

Thanks

[A]
With ASMX the proxy can be set on the Proxy property:
http://johnwsaundersiii.spaces.live.com/blog/cns!600A2BE4A82EA0A6!435.entry
With WCF, this is part of the binding configuration:
http://blogs.infosupport.com/porint/archive/2007/08/14/Configuring-a-proxy_2D00_server-for-WCF.aspx


q: I would like to use the ispell-buffer command in Emacs. It uses the English language by default. Is there an easy way to switch to another dictionary (for example, another language)?

[A]
From the file ispell.el you may specify some options for the
```
ispell
```
commands. This happens by adding a section to the end of your file like this:
```
```
;; Local Variables:
;; ispell-check-comments: exclusive
;; ispell-local-dictionary: "american"
;; End:
```
```
Note the double semicolon marks the start of comments in the current mode. It should probably be changed to reflect the way your file (programming language) introduces comments, like
```
//
```
for Java.


q:
Given the Python function:

def a_method(arg1, arg2):
    pass

How can I extract the number and names of the arguments. I.e., given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2").

The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the same order that they appear for the actual function as a key. I.e., how would the decorator look that printed "a,b" when I call a_method("a", "b")?

[A]
In CPython, the number of arguments is
```
```
a_method.func_code.co_argcount
```
```
and their names are in the beginning of
```
```
a_method.func_code.co_varnames
```
```
These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.
One portable way to admit "pass-through" arguments is to define your function with the signature
```
func(*args, **kwargs)
```
. This is used a lot in e.g.
matplotlib
, where the outer API layer passes lots of keyword arguments to the lower-level API.


q:
I've seen a couple of font topics on SO and it seems a majority of people use monospace fonts for programming tasks. I have been using Verdana for programming for a couple of years and I really like the enhanced readability, without missing anything monospace related.

Why do you use a monospace font?

[A]
In a monospace font:
Equal-length string literals look equal.
It's easier to see thin punctuation marks like : () {}
Similar characters look more different: Il 0O vs
```
Il 0O
```
You know whether or not a line will wrap on a window X characters wide. This means that your team can standardize on say 100 character lines and a line will always look like a line


q: How to create instance of AxHost abstract class

[A]
You cannot create an instance of an abstract class.
You typically do not use the AxHost class directly. You can use the Windows Forms ActiveX Control Importer (Aximp.exe) to generate the wrappers that extend AxHost.
See
http://msdn.microsoft.com/en-us/library/system.windows.forms.axhost.aspx
for an example.


q: I work for a custom cabinetry manufacturer and we write our own pricing program for our product.  I have a form that has a pop-up box so the user can select which side the hinge will be on for ambiguous doors on that cabinet.  I've got that to work so far, but when they copy an item and paste it at the bottom I don't want the pop-up box to come up.  Is there any way in Access VBA to know whether the new record is being pasted or entered manually?

[A]
Perhaps something on the lines of this would suit.
```
```
Option Compare Database
Public gvarPasted As Boolean

Private Sub txtText_AfterUpdate()
If Not gvarPasted Then
    'Open pop-up here
Else
    gvarPasted = False
End If
End Sub

Private Sub txtText_KeyDown(KeyCode As Integer, Shift As Integer)
'Detect ctrl-V combination
If Shift = acCtrlMask And KeyCode = vbKeyV Then
    gvarPasted = True
End If
End Sub
```
```


q:
I have been asked to audit any/all changes in a MySQL table. Does anyone know of any tools out there to help me do this or do I need to write my own solution?

If I write my own audting, my initial thought it to make a separate table and build a string of changes in the PHP code. Something like "fieldname1 -> oldvalue | fieldname2 -> oldvalue, ...". If you see a major problem with this method, please let me know.

[A]
Use a
trigger
to detect changes and to write before/after values to a log table.


q:
In .NET, Windows Forms have an event that fires before the Form is loaded (Form.Load), but there is no corresponding event that is fired AFTER the form has loaded.  I would like to execute some logic after the form has loaded.

Can anyone advise on a solution?

[A]
I sometimes use (in Load)
```
```
this.BeginInvoke((MethodInvoker) delegate {
  // some code
});
```
```
or
```
```
this.BeginInvoke((MethodInvoker) this.SomeMethod);
```
```
(change "this" to your form variable if you are handling the event on an instance other than "this").
This pushes the invoke onto the windows-forms loop, so it gets processed when the form is processing the message queue.
[updated on request]
The Control.Invoke/Control.BeginInvoke methods are intended for use with threading, and are a mechanism to push work onto the UI thread. Normally this is used by worker threads etc. Control.Invoke does a synchronous call, where-as Control.BeginInvoke does an asynchronous call.
Normally, these would be used as:
```
```
SomeCodeOrEventHandlerOnAWorkerThread()
{
  // this code running on a worker thread...
  string newText = ExpensiveMethod(); // perhaps a DB/web call

  // now ask the UI thread to update itself
  this.Invoke((MethodInvoker) delegate {
      // this code runs on the UI thread!
      this.Text = newText;
  });
}
```
```
It does this by pushing a message onto the windows message queue; the UI thread (at some point) de-queues the message, processes the delegate, and signals the worker that it completed... so far so good ;-p
OK; so what happens if we use Control.Invoke / Control.BeginInvoke on the UI thread? It copes... if you call Control.Invoke, it is sensible enough to know that blocking on the message queue would cause an immediate deadlock - so if you are already on the UI thread it simply runs the code immediately... so that doesn't help us...
But Control.BeginInvoke works differently: it
always
pushes work onto the queue, even it we are already on the UI thread. This makes a really simply way of saying "in a moment", but without the inconvenience of timers etc (which would still have to do the same thing anyway!).


q:
I have a GridView control in an Asp.net application, that has a <asp:buttonField> of type="image" and CommandName="Delete".

Is there any way to execute a piece of javascript before reaching the OnRowDelete event?

I want just a simple confirm before deleting the row.

Thanks!

EDIT: Please Note that <asp:ButtonField> tag does not have an OnClientClick attribute.

[A]
I would use a TemplateField instead, and populate the ItemTemplate with a regular asp:Button or asp:ImageButton, depending one what is needed. You can then execute the same logic that the RowCommand event was going to do when it intercepted the Delete command.
On either of those buttons I would then use the OnClientClick property to execute the JavaScript confirm dialog prior to this.
```
```
<script type="text/javascript">
   function confirmDelete()
   {
       return confirm("Are you sure you want to delete this?");
   }
</script>

...

<asp:TemplateField>
  <ItemTemplate>
     <asp:ImageButton ID="DeleteButton" runat="server"
        ImageUrl="..." AlternateText="Delete" ToolTip="Delete"
        CommandName="Delete" CommandArgument='<%# Eval("ID") %>'
        OnClientClick="return confirmDelete();" />
  </ItemTemplate>
</asp:TemplateField>
```
```


q:
I have a problem with Visual C++ 2008. I have installed opencv and I've created a new program and I build it with no errors. However, it complains about not finding MSVCR90D.dll when debugging. In release mode there is no problem at all.

I do have MSVCR90D.dll in one of Winsxs folders. Does anyone know a get-around to this problem? Is this a known bug?

Gerard

[A]
There are several potential solutions described in this
forum post
. See if any of those help.
One hint from there:
Go to %System Drive%\Windows\WinSxS
  and look for the directory
  x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_597c3456
If this doesn't exist, go to the VS
  setup and make sure you have all
  libraries installed under VC++.
And another one:
I had the same problem, but fixed it
  by turning off incremental linking
  (Project properties... Linker...
  General... Enable Incremental Linking:
  No).
Confirming the last one:
Projects built on a software-mounted
  drive complain about a missing
  MSVCR90D.dll.  The problem goes away
  if you turn off incremental linking
  (and rebuild all, of course).


q: Is there a special project type for creating a WCF to be hosted in IIS?

[A]
I assume you're talking about VS 2008.
I can't see a way to have the WCF Service Library template use IIS for hosting. My advice is to create an ASP.NET Web Application, configure it to be IIS hosted, delete the Default.aspx file, and then add the WCF Service to the project.


q:
I have a form that uses jQuery to submit an ajax post and it serializes the form that is sent up. The code looks like this:

var form = $("form");
var action = form.attr("action");
var serializedForm = form.serialize();
$.post(action, serializedForm, function(data)
{
  ...
});

The problem here is that if a field has trailing white space, the serialize function will turn those spaces to plus (+) signs, when they should be stripped.

Is there a way to get the fields trimmed without doing the following:

$("#name").val( jQuery.trim( $("#name") ) );

[A]
Trim all
<input>
and
<textarea></textarea>
element values in the DOM:
```
```
$('input, textarea').each(function(){
    $(this).val(jQuery.trim($(this).val()));
});
```
```


q: The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?

[A]
Is object:
```
```
function isObject ( obj ) {
   return obj && (typeof obj  === "object");
}
```
```
Is array:
```
```
function isArray ( obj ) {
  return isObject(obj) && (obj instanceof Array);
}
```
```
Because arrays are objects you'll want to test if a variable is an array first, and then if it is an object:
```
```
if (isArray(myObject)) {
   // do stuff for arrays
}
else if (isObject(myObject)) {
   // do stuff for objects
}
```
```