q:
http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx

This post shows how to test setting a cookie and then seeing it in ViewData. What I what to do is see if the correct cookies were written (values and name). Any reply, blog post or article will be greatly appreciated.

[A]
```
```
function ReadCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return "";
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length;
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
```
```


q:
Suppose we have two stacks and no other temporary variable.

Is to possible to "construct" a queue data structure using only the two stacks?

[A]
The time complexities would be worse, though.  A good queue implementation does everything in constant time.
Edit
Not sure why my answer has been downvoted here.  If we program, we care about time complexity, and using two standard stacks to make a queue is inefficient.  It's a very valid and relevant point.  If someone else feels the need to downvote this more, I would be interested to know why.
A little more detail
: on why using two stacks is worse than just a queue: if you use two stacks, and someone calls dequeue while the outbox is empty, you need linear time to get to the bottom of the inbox (as you can see in Dave's code).
You can implement a queue as a singly-linked list (each element points to the next-inserted element), keeping an extra pointer to the last-inserted element for pushes (or making it a cyclic list).  Implementing queue and dequeue on this data structure is very easy to do in constant time.  That's worst-case constant time, not amortized.  And, as the comments seem to ask for this clarification, worst-case constant time is strictly better than amortized constant time.

s: huggingface

c: devops

d: intermediate


q:
In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.

Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.

In "release" mode, you usually have all sorts of optimizations turned on.

Why the difference?

[A]
Without any optimization on, the flow through your code is linear.  If you are on line 5 and single step, you step to line 6.  With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.
For example:
```
```
void foo() {
1:  int i;
2:  for(i = 0; i < 2; )
3:    i++;
4:  return;
```
```
In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4
With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...)
Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions.
Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case.
While the optimized and non-optimized code should be "functionally" equivalent, under certain circumstances, the behavior will change.
Here is a simplistic example:
```
```
int* ptr = 0xdeadbeef;  // some address to memory-mapped I/O device
    *ptr = 0;   // setup hardware device
    while(*ptr == 1) {    // loop until hardware device is done
       // do something
    }
```
```
With optimization off, this is straightforward, and you kinda know what to expect.
However, if you turn optimization on, a couple of things might happen:
The compiler might optimize the while block away (we init to 0, it'll never be 1)
Instead of accessing memory, pointer access might be moved to a register->No I/O Update
memory access might be cached (not necessarily compiler optimization related)
In all these cases, the behavior would be drastically different and most likely wrong.


q:
I have an Enumerable array

int meas[] = new double[] {3, 6, 9, 12, 15, 18};

On each successive call to the mock's method that I'm testing I want to return a value from that array.

using(_mocks.Record()) {
  Expect.Call(mocked_class.GetValue()).Return(meas);
}
using(_mocks.Playback()) {
  foreach(var i in meas)
    Assert.AreEqual(i, mocked_class.GetValue();
}

Does anyone have an idea how I can do this?

[A]
IMHO, yield will handle this.
Link
.
Something like:
```
```
get_next() {
  foreach( float x in meas ) {
    yield x;
  }
}
```
```


q:
Is it possible to query the Crystal CMS database and get meaningful data back?  The data appears to be encrypted.

I am running Business Objects Crystal Report Server version 11.5

[A]
I had a similar problem on my workstation at the office.  It sounds like you need to reinstall (that's what worked for me). This is a known bug according BussinessObjects (I had to call them and use our maintenance support).  Hopefully you can find more information by searching for, 'Crystal Business query corruption' instead of calling them if the reinstall doesn't work for you.
They told me the data is not encrypted, but occasionally components don't install correctly and the queries come back in a binary form that is all garbled.
Good luck!


q: What are the biggest pros and cons of Apache Thrift vs Google's Protocol Buffers?

[A]
Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper.  In their own words:
We decided against some extreme storage optimizations (i.e. packing
  small integers into ASCII or using a 7-bit continuation format)
  for the sake of simplicity and clarity in the code. These alterations
  can easily be made if and when we encounter a performance-critical
  use case that demands them.
Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning.  Thrift does have some versioning support, but it takes a bit of effort to make it happen.


q: What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form.

[A]
```
```
FormName.WindowState = FormWindowState.Minimized;
```
```


q: In OS X, in order to quickly get at menu items from the keyboard, I want to be able to type a key combination, have it run a script, and have the script focus the Search field in the Help menu.  It should work just like the key combination for Spotlight, so if I run it again, it should dismiss the menu.  I can run the script with Quicksilver, but how can I write the script?

[A]
Here is the script I came up with.
```
```
tell application "System Events"
    tell (first process whose frontmost is true)
        click menu "Help" of menu bar 1
    end tell
end tell
```
```


q:
I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.

I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.

[A]
Absolutely position divs over the text area with a z-index higher and give these divs a transparent
GIF
background graphic.
Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to
```
display:box
```
, width and height set as well as the transparent background image.


q:
I am using VS2008 and Resharper.  Resharper creates a directory _Resharper.ProjectName.  These files provide no value for source control that I am aware of and cause issues when committing changes.  How can I get SVN to ignore them?  I am using TortoiseSVN as my interface for SVN.

EDIT: You guys are fast.

[A]
SVN only controls what you put into it when creating your repository. Don't just import your entire project folder but import a "clean" folder BEFORE doing a build. After the build you get all the object files or your _Resharper folder etc. but they are not version controlled.
I forgot: the
```
svn:ignore
```
command is another possibility to tell SVN to exclude certain files. You can add this as a property to the version controlled folders, e.g. with TortoiseSVN.


q:
We have a small embedded system without any video or serial ports (i.e. we can't output text via printf).

We would like to track the progress of our code through the initialization sequence.

Is there some simple things we can do to help with this.

It is not running any OS, and the hardware platform is somewhat customizable.

[A]
There are a few strategies you can employ to help with debugging:
If you have Output Pins available, you can hook them up to LEDs (or an oscilloscope) and toggle the output pins high/low to indicate that certain points have been reached in the code.
For example, 1 blink might be program loaded, 2 blink is foozbar initialized, 3 blink is accepting inputs...
If you have multiple output lines available, you can use a 7 segment LED to convey more information (numbers/letters instead of blinks).
If you have the capabilities to read memory and have some RAM available, you can use the sprint function to do printf-like debugging, but instead of going to a screen/serial port, it is written in memory.


q: I am curious if anyone have used UnderC, Cint, Cling, Ch, or any other C++ interpreter and could share their experience.

[A] Long ago, I used a C++ interpreter called CodeCenter.  It was pretty nice, although it couldn't handle things like bitfields or fancy pointer mangling.  The two cool things about it were that you could watch when variables changed, and that you could evaluate C/C++ code on the fly while debugging.  These days, I think a debugger like GDB is basically just as good.


q:
I have a multi-frame layout. One of the frames contains a form, which I am submitting through XMLHttpRequest. Now when I use document.write() to rewrite the frame with the form, and the new page I am adding contains any javascript then the javascript is not exectuted in IE6?

For example:

document.write("<html><head><script>alert(1);</script></head><body>test</body></html>");

In the above case the page content is replaced with test but the alert() isn't executed. This works fine in Firefox.

What is a workaround to the above problem?

[A]
Workaround is to programmatically add
```
<script>
```
blocks to head DOM element in JavaScript at Callback function or call eval() method. It's only way you can make this work in IE 6.


q: I think the best part of flash is the possibility to create not squared user interfaces, so I like the idea to create desktop apps using flash. I know AIR is for that but it doesn't allow real access to OperatingSystem apis and dlls and the commercial options are kind of difficult to customize.

[A]
You can try ScreenweaverHX:
http://haxe.org/com/libs/swhx
It's the Haxe-based successor of the old Screenweaver. However, it's not as simple as the old version used to be. Most likely you need to take a look to the basics of Haxe and Neko, the 2 technologies it's based on.
There's another project on top of SWHX that it's called HippoHX. It aims to "complete" SWHX providing that extra functionality you might miss (simple ActionScript APIs and a GUI). However, it's in its early stages:
http://hippohx.com
DISCLAIMER: I'm the owner of HippoHX, so my point is obviously biased.
As far as I know SWHX is the only Open Source alternative at this point.


q:
I am trying to use a stringstream object in VC++ (VStudio 2003) butI am getting an error when I use the overloaded << operator to try and set some manipulators.

I am trying the following:

int SomeInt = 1;
stringstream StrStream;
StrStream << std::setw(2) << SomeInt;

This will not compile (error C2593: 'operator <<' is ambiguous).

Does VStudio 2003 support using manipulators in this way?

I know that I can just set the width directly on the stringstream object e.g. StrStream.width(2);

I was wondering why the more usual method doesn't work?

[A]
Are you sure you included all of the right headers? The following compiles for me in VS2003:
```
```
#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
   int SomeInt = 1;
   std::stringstream StrStream;
   StrStream << std::setw(2) << SomeInt;
   return 0;
}
```
```


q:
public static void main(String[] args) {

    List<? extends Object> mylist = new ArrayList<Object>();

    mylist.add("Java"); // compile error

}

The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing.
In this case what purpose does the above fulfil ??

[A]
With java generics using wildcards, you are allowed the above declaration assuming you are only going to read from it.
You aren't allowed to add/write to it, because all generic types must be stripped at compile time, and at compile time there isn't a way the compiler knows List are only strings, (it could be any object including strings!)
You are however allowed to read from it since they are going to be at least objects.  Mixing different types are not allowed in java collections to keep things clean and understandable, and this helps ensure it.


q:
I have a dl containing some input boxes that I "clone" with a bit of JavaScript like:

var newBox = document.createElement('dl');
var sourceBox = document.getElementById(oldkey);
newBox.innerHTML = sourceBox.innerHTML;
newBox.id = newkey;
document.getElementById('boxes').appendChild(columnBox);

In IE, the form in sourceBox is duplicated in newBox, complete with user-supplied values.  In Firefox, last value entered in the orginal sourceBox is not present in newBox.  How do I make this "stick?"

[A]
You could try the
```
cloneNode
```
method. It might do a better job of copying the contents. It should also be faster in most cases
```
```
var newBox;
var sourceBox = document.getElementById(oldkey);
if (sourceBox.cloneNode)
    newBox = sourceBox.cloneNode(true);
else {
    newBox = document.createElement(sourceBox.tagName);
    newBox.innerHTML = sourceBox.innerHTML;
}
newBox.id = newkey;
document.getElementById('boxes').appendChild(newBox);
```
```


q: What are in your opinion big differences between areas of usage for "Astoria" (ADO.NET data services) and SQL Server Data Services?

[A]
They are similiar but very different technologies. Astoria or what is now called at
Microsoft ADO.NET Data Services
is a programming library that will allow data to be passed through RESTful web services.  You develop these web services to be run against data you have access to.  ADO.NET Data Services is now included in the .NET 3.5 SP1 updates.
SQL Server Data Services
is a new service provided by Microsoft.  The following is a decription:
"SQL Server Data Services (SSDS) are highly scalable, on-demand data
  storage and query processing utility
  services. Built on robust SQL Server
  database and Windows Server
  technologies, these services provide
  high availability, security and
  support standards-based web interfaces
  for easy programming and quick
  provisioning."
SQL Server Data Services is very similair to Amazon S3 service.


q:
I am trying to populate a string with a double value using a sprintf like this:

sprintf(S, "%f", val);

But the precision is being cut off to six decimal places. I need about 10 decimal places for the precision.

How can that be achieved?

[A]
What you want is a modifier:
```
```
sprintf(S, "%.10f", val);
```
```
man sprintf will have many more details on format specifiers.


q:
Another easy one hopefully.

Let's say I have a collection like this:

List<DateTime> allDates;

I want to turn that into

List<List<DateTime>> dividedDates;

where each List in 'dividedDates' contains all of the dates in 'allDates' that belong to a distinct year.

Is there a bit of LINQ trickery that my tired mind can't pick out right now?

Solution

The Accepted Answer is correct.

Thanks, I don't think I was aware of the 'into' bit of GroupBy and I was trying to use the .GroupBy() sort of methods rather than the SQL like syntax.  And thanks for confirming the ToList() amendment and including it in the Accepted Answer :-)

[A]
```
```
var q  = from date in allDates
         group date by date.Year into datesByYear
         select datesByYear.ToList();
q.ToList(); //returns List<List<DateTime>>
```
```


q: Mac OS X ships with apache pre-installed, but the files are in non-standard locations.  This question is a place to collect information about where configuration files live, and how to tweak the apache installation to do things like serve php pages.

[A]
Apache Config file is: /private/etc/apache2/httpd.conf
Default DocumentRoot is: /Library/Webserver/Documents/
To enable PHP, at around line 114 (maybe) in the /private/etc/apache2/httpd.conf file is the following line:
```
```
#LoadModule php5_module     libexec/apache2/libphp5.so
```
```
Remove the pound sign to uncomment the line so now it looks like this:
```
```
LoadModule php5_module     libexec/apache2/libphp5.so
```
```
Restart Apache: System Preferences -> Sharing -> Un-check "Web Sharing" and re-check it.
OR
```
```
$ sudo apachectl restart
```
```


q: When is it a good idea to use factory methods within an object instead of a Factory class?

[A] It's really a matter of taste. Factory classes can be abstracted/interfaced away as necessary, whereas factory methods are lighter weight (and also tend to be testable, since they don't have a defined type, but they will require a well-known registration point, akin to a service locator but for locating factory methods).


q:
What is the reason browsers do not correctly recognize:

<script src="foobar.js" /> <!-- self-closing script element -->

Only this is recognized:

<script src="foobar.js"></script>

Does this break the concept of XHTML support?

Note: This statement is correct at least for all IE (6-8 beta 2).

[A]
The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:
С.3. Element Minimization and Empty Element Content
Given an empty instance of an element whose content model is not
```
EMPTY
```
(for example, an empty title or paragraph) do not use the minimized form (e.g. use
```
<p> </p>
```
and not
```
<p />
```
).
XHTML DTD
specifies script elements as:
```
```
<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
```
```


q:
I have a JSF application that I am converting over to use webservices instead of straight up database queries. There are some extremely long lists that before could be returned easily with a simple SQL query. I'd like to figured out how implement the paging using JSF/web services. Is there a good design pattern for doing paged web services?

If it matters, I'm currently using the Apache MyFaces reference implementation of JSF with the Tomahawk extensions (a set of JSF components created by the MyFaces development team prior to its donation to Apache).

[A]
I like Seam's Query objects:
http://docs.jboss.com/seam/2.1.0.BETA1/reference/en-US/html_single/#d0e7527
They basically abstract all the SQL/JPA in a Seam component that JSF can easily use.
If you don't want to use Seam and/or JPA you could implement a similar pattern.


q:
I've been unsuccessful in getting Emacs to switch from 8 space tabs to 4 space tabs when pressing the TAB in buffers with the major mode text-mode. I've added the following to my .emacs:

(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)

;;; And I have tried
(setq indent-tabs-mode nil)
(setq tab-width 4)

No matter how I change my .emacs file (or my buffer's local variables) the TAB button always does the same thing.

If there is no text above, indent 8 spaces

If there is text on the previous line, indent to the beginning of the second word

As much as I love Emacs this is getting annoying. Is there a way to make Emacs to at least indent 4 space when there's not text in the previous line?

[A]
Have you tried
```
```
(setq  tab-width  4)
```
```


q:
My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible?

If it's not, how would you do it with POST? Just out of curiosity.

Cheers!

[A]
You could use HTTP Authentication, if supported.
You'd have to add SSL, as all methods, POST, GET and HTTP Auth (well, except Digest HHTP authentication) send plaintext.
GET is basically just like POST, it just has a limit on the amount of data you can send which is usually a lot smaller than POST and a semantic difference which makes GET not a good candidate from that point of view, even if technically they both can do it.
As for examples, what are you using? There are many choices in Python, like the cgi module or some framework like Django, CherryPy, and so on


q:
How do I prevent vim from replacing spaces with tabs when autoindent is on?

An example: if I have two tabs and 7 spaces in the beginning of the line, and tabstop=3, and I press Enter, the next line has four tabs and 1 space in the beginning, but I don't want that...

[A]
Maybe the bottom of this can help you?
Standard vi interprets the tab key literally, but there are popular vi-derived alternatives that are smarter, like vim. To get vim to interpret tab as an ``indent'' command instead of an insert-a-tab command, do this:
```
```
set softtabstop=2
```
```


q: PL/SQL is not my native tongue. Oracle supports writing stored procedures in Java. What are the advantages of doing this over writing the stored procedures in PL/SQL

[A]
I have used Oracle emmbedded java for two problems:
1) To do a PLSQL procedure which bulks the results of a query in a text file and send it over FTP. This file was very large and i use Java to Zip it.
2) In a client-server aplication with direct connection with the DB, to compare the user sent password to the application (not the DB user password) hashed with MD5, so that the password not travel by the net in plain text. I'm not sure if this was the better solution for this problem, i'm going to ask it now. :)


q: How can I visually customize autocomplete fields in Wicket (change colors, fonts, etc.)?

[A]
You can use CSS to modify the look of this component.  For the Ajax auto-complete component in 1.3 the element you want to override is div.wicket-aa, so for example you might do:
```
```
div.wicket-aa {
    background-color:white;
    border:1px solid #CCCCCC;
    color:black;
}
div.wicket-aa ul {
   list-style-image:none;
   list-style-position:outside;
   list-style-type:none;
   margin:0pt;
   padding:5px;
}
div.wicket-aa ul li.selected {
    background-color:#CCCCCC;
}
```
```


q:
I am looking for attributes I can use to ensure the best runtime performance for my .Net application by giving hints to the loader, JIT compiler or ngen.

For example we have DebuggableAttribute which should be set to not debug and not disable optimization for optimal performance.

[Debuggable(false, false)]

Are there any others I should know about?

[A]
I found another:
NeutralResourcesLanguageAttribute
. According to
this
blog post it helps the loader in finding the right satellite assemblies faster by specifying the culture if the current (neutral) assembly.
```
```
[NeutralResourcesLanguageAttribute("nl", UltimateResourceFallbackLocation.MainAssembly)]
```
```


q: I have an Java desktop application which connects directly with the DB (an Oracle). The application has multiple user accounts. What is the correct method to send the user's password (not DB password) over the network? I don't want to send it in plain text.

[A]
If you don't want to send the data in plain text, use encryption !!!
Use some encryption algorithm such as AES, Twofish etc.
You must also take into consideration where your client and server are. If they both are in the same machine, there is no use of using an encryption. If they are in different machines, use some encryption algorithm to send sensitive data.
If YOU are checking the validity of the passwords, you can just send the hash of the password. Beware that this method will work only if you are comparing the password yourself. If some other application (out of your control) is doing the validation job, you cannot hash the password.


q: How do I declare "as any" in VB.NET, or what is the equivalent?

[A]
VB.NET
doesn't support the "As Any" keyword. You'll need to explicitly specify the type.


q:
I was wondering if there are any code or class libraries out there on how to implement multithreading or "green threading" in ActionScript.

As you've might seen, Scott Peterson is developing some kind of toolset, but I haven't found any more info on this other than his performance on the Adobe MAX Chicago event.

Regards Niclas

[A]
There's no built-in way to do green threading in ActionScript. You have to write code to handle it.
Make a function that performs one iteration of whatever operation you want to do. It should return true or false depending on if its job is done or not. Now, you have to compute the time interval left to the next screen update on the ENTER_FRAME event. This can be done using flash.utils.getTimer.
```
```
start = getTimer();
//thread is a ui component added to system manager that is redrawn each frame
var fr:Number = Math.floor(1000 / thread.systemManager.stage.frameRate);
due = start + fr;
```
```
Keep on executing your function while checking the function's return value each time and checking if due time has been crossed by comparing getTimer() with due.
This has been implemented into a usable class by Alex Harui in the blog entry -
Threads in ActionScript


q:
I have an application with one form in it, and on the Load method I need to hide the form.

The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.

Any suggestions?

[A]
Here is a simple approach:
It's in C# (I don't have VB compiler at the moment)
```
```
public Form1()
{
    InitializeComponent();
    Hide(); // Also Visible = false can be used
}

private void Form1_Load(object sender, EventArgs e)
{
    Thread.Sleep(10000);
    Show(); // Or visible = true;
}
```
```


q:
I have a structure in C#:

public struct UserInfo
{
   public string str1
   {
     get;
     set;
   }

   public string str2
   {
     get;
     set;
   }
}

The only rule is that  UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA"))

How to override the GetHashCode function for this structure?

[A]
Many possibilities. E.g.
```
return str1.GetHashCode() ^ str1.GetHashCode()
```


q:
Working on implementing TFS throughout our organization.  It is easy to integrate with .NET projects and any platform that uses Eclipse or a derivative of Eclipse for editing.

What's the best way to use TFS version control with Xcode (now that I find out we need to write some iPhone apps)?

[A]
One way would be to use the Team Foundation System client under Windows in VMWare, and check out (or whatever TFS calls it) your sources to a directory on your Mac that's shared with the virtual machine.  It also looks like
Teamprise
has a Team Foundation client for Mac OS X built atop Eclipse that would be worth looking into.
That said, I'd very strongly encourage you to use a
natively
cross-platform source code management system like Subversion or Perforce instead of a platform-specific silo like Team Foundation System for your company's soruce code, especially since you're going to be doing multi-platform development.
While you're not likely to share code between a .NET application and an iPhone application, having full cross-platform access to things like design documents can be really important.  Mac OS X 10.5 and later include Subversion, Perforce is readily available, and both Perforce and Subversion are natively supported by the Xcode IDE.  Subversion in particular is also more likely to be familiar to experienced Mac and iPhone developers you might bring onto your projects as you ramp up.


q: What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?

[A]
Ummm… An inner class
is
a nested class… Do you mean anonymous class and inner class?
Edit: If you actually meant inner v.s. anonymous: an inner class is just a class defined within a class, such as:
```
```
public class A {
    public class B {
    }
}
```
```
…whereas an anonymous class is an extension of a class defined anonymously, so no actual "class" is defined, as in:
```
```
public class A {
}

A anon = new A() { /* You could change behavior of A here */ };
```
```
Further edit:
Wikipedia
claims there is a difference
in Java, but I've been working with Java for eight years, and it's the first time I heard such a distinction – not to mention there are no references there to back up the claim… Bottom line, an inner class is a class defined within a class (static or not), and nested is just another term to mean the same thing.
There is a subtle difference between static and non-static nested classes… Basically, non-static inner classes have implicit access to instance fields and methods of the enclosing class (thus they cannot be constructed in a static context, it will be a compiler error). On the other hand, static nested classes don't have implicit access to instance fields and methods and
can
be constructed in a static context.


q: Are System.IO.Compression.GZipStream or System.IO.Compression.Deflate compatible with zlib compression?

[A] They just compressing the data using zlib or deflate algorithms , but does not provide the output for some specific file format. This means that if you store the stream as-is to the hard drive most probably you will not be able to open it using some application (gzip or winrar) because file headers (magic number, etc ) are not included in stream an you should write them yourself.


q: Is there any way to prevent Visual Studio from creating a VSMacros80 folder in my default project directory?

[A]
I could not find the previous thread, because I was searching for "vsmacros" instead of "vsmacros80".
There are currently 5 different entries in
```
Tools->Options->Addin/Macro Security
```
```
```
%ALLUSERSPROFILE%\Application Data\Microsoft\MsEnvShared\Addins
%APPDATA%\Microsoft\MsEnvShared\Addins
%VSAPPDATA%\Addins
%VSCOMMONAPPDATA%\Addins
%VSMYDOCUMENTS%\Addins
```
```
Can you tell me which one I have to delete?


q:
I have apache 2.2 and tomcat 5.5 running on a Windows XP machine.

Which tomcat/apache connector is the easiest to set up and is well documented?

[A]
```
mod_jk
```
, or simply just use
```
mod_proxy
```
even though it's not really a Tomcat connector.


q:
So I'm working on a Rails app to get the feeling for the whole thing. I've got a Product model that's a standard ActiveRecord model. However, I also want to get some additional product info from Amazon ECS. So my complete model gets some of its info from the database and some from the web service. My question is, should I:

Make two models a Product and a ProductAWS, and then tie them together at the controller level.

Have the Product ActiveRecord model contain a ProductAWS object that does all the AWS stuff?

Just add all the AWS functionality to my Product model.

???

[A]
You can use the
```
composed_of
```
relationship in ActiveRecord. You make a regular class with all the attributes that you manage through AWS and specify that your Product-class is composed_of this class. ActiveRecord will handle the delegation of the mapped attributes to and from this class.
See
the documentation of composed_of


q: I was asked this question during an interview. They're both O(nlogn) and yet most people use Quicksort instead of Mergesort. Why is that?

[A]
Actually, QuickSort is O(n
2
).  Its
average case
running time is O(nlog(n)), but its
worst-case
is O(n
2
), which occurs when you run it on a list that contains few unique items.  Randomization takes O(n).  Of course, this doesn't change its worst case, it just prevents a malicious user from making your sort take a long time.
QuickSort is more popular because it:
Is in-place (MergeSort requires extra memory linear to number of elements to be sorted).
Has a small hidden constant.


q: I'm doing simple string input parsing and I am in need of a string tokenizer. I am new to C# but have programmed Java, and it seems natural that C# should have a string tokenizer. Does it? Where is it? How do I use it?

[A]
I think the nearest in the .NET Framework is
```
string.Split()
```


q: Can we achieve 100% decoupling between components of a system or different systems that communicate with each other? I don't think its possible. If two systems communicate with each other then there should be some degree of coupling between them. Am I right?

[A] You can achieve that. Think of two components that communicate with each other through network. One component can run on Windows while other on Unix. Isn't that 100% decoupling?


q:
So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties!

Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something?

[A]
My Java experience is not that high either, so anyone feel free to correct me. But AFAIK, the general convention is to write two methods like so:
```
```
public string getMyString() {
    // return it here
}

public void setMyString(string myString) {
    // set it here
}
```
```


q:
In order to know how many times a pattern exists in current buffer, I do:

:%s/pattern-here/pattern-here/g

It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status.

Is there a more elegant way to count?

[A]
To avoid the substitution, leave the second pattern empty, and add the “n” flag:
```
```
:%s/pattern-here//gn
```
```
This is described as
an official tip
.


q:
I have heard there is a way to cheat single inheritance and implement multiple inheritance in Java. Does anyone know how to implement this(with out using interface)?

Just out of curiosity ;-)

[A]
JAVA doesn't support multiple Inheritence.
You can get it to implement multiple interfaces and some see this as a way round the problem. Personally I have yet to use multiple inheritence, so I can't really understand its appeal.
Normally when someone suggests multiple inheritence within c# or JAVA its due to the fact that 'they could' in c++. Im a fan of 'just because you can doens't mean you should'. As c# & JAVA doesn't support it, why try and force it to do something it wasn't designed to do. This is not to say that there are unique cases where it is a valid technique to empoly, just the code can usually be refactored to not need it.


q:
What's the best, crossplatform way to perform blackbox tests on AJAX web applications?

Ideally, the solution should have the following attributes:

Able to integrate into a continuous integration build loop

Cross platform so I you can run it on Windows laptops and Linux continuous integration servers

Easy way to script the interactions

Free-as-in-freedom so you can adapt it into your tool chain if necessary

I've looked into HttpUnit but I'm not conviced it can handle AJAX-heavy websites.

[A]
Selenium might be what you're looking for:
http://selenium.openqa.org/
It allows you to script actions and evaluate the results. It's open-source (Apache 2.0), cross platform, and has nice tools.


q:
When entering a question, stackoverflow presents you with a list of questions that it thinks likely to cover the same topic. I have seen similar features on other sites or in other programs, too (Help file systems, for example), but I've never programmed something like this myself. Now I'm curious to know what sort of algorithm one would use for that.

The first approach that comes to my mind is splitting the phrase into words and look for phrases containing these words. Before you do that, you probably want to throw away insignificant words (like 'the', 'a', 'does' etc), and then you will want to rank the results.

Hey, wait - let's do that for web pages, and then we can have a ... watchamacallit ... -  a "search engine", and then we can sell ads, and then ...

No, seriously, what are the common ways to solve this problem?

[A]
One approach is the so called bag-of-words model.
As you guessed, first you count how many times words appear in the text (usually called document in the NLP-lingo). Then you throw out the so called stop words, such as "the", "a", "or" and so on.
You're left with words and word counts. Do this for a while and you get a comprehensive set of words that appear in your documents. You can then create an index for these words:
"aardvark" is 1, "apple" is 2, ..., "z-index" is 70092.
Now you can take your word bags and turn them into vectors. For example, if your document contains two references for aardvarks and nothing else, it would look like this:
```
```
[2 0 0 ... 70k zeroes ... 0].
```
```
After this you can count the "angle" between the two vectors with
a dot product
. The smaller the angle, the closer the documents are.
This is a simple version and there other more advanced techniques. May the
Wikipedia be with you
.


q:
I have successfully connected to an Oracle database (10g) from C# (Visual Studio 2008) by downloading and installing the client administration tools and Visual Studio 2008 on my laptop.

The installation footprint for Oracle Client tools was over 200Mb, and quite long winded.

Does anyone know what the minimum workable footprint is? I am hoping that it's a single DLL and a register command, but I have the feeling I need to install an oracle home, and set various environment variables.

I am using Oracle.DataAccess in my code.

[A]
ODAC xcopy will get you away with about 45MB.
http://www.oracle.com/technology/software/tech/windows/odpnet/index.html


q:
I am looking for details of the VTable structure, order and contents, and the location of the vtable pointers within objects.

Ideally, this will cover single inheritance, multiple inheritance, and virtual inheritance.

References to external documentation would also be appreciated

Documentation of GCC 4.0x class layout is here and the Itanium, and more broadly GNU, ABI layout documents are here.

[A]
Most of the compiler implementations that I have seen just "embed" the base object into the derived object. It becomes irrelevant where the vtable is kept because the relative offset into the object will just be added at compile time as references are evaluated.
Multiple and virtual inheritance are more complicated and can require a different offset depending on what is being accessed.
I highly recommend reading this article on Code Project:
The Impossibly Fast C++ Delegates
It brilliantly gives a broad picture of how different compilers handle various aspects of inheritance. Fantastic read if you are interested in the low level workings of different compilers.
Edit: I linked the wrong article over there. Corrected.


q: What is an efficient way to implement a singleton design pattern in Java?

[A]
Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.
There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found
dependency injection
(DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.


q:
I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night.  This is a temporary solution until I can diagnose the stoppage.

I created a task to run under my admin user, and to start the program, cmd with the arguments /c net start mssqlserver.  When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped:

action "C:\Windows\system32\cmd.EXE" with return code 2.

Any suggestions?


q:
I administrate several Oracle Apps environment, and currently check profile options in lots of environments by loading up forms in each environment, and manually checking each variable, which requires a lot of time.

Is there a snippet of code which will list profile options and at what level and who they are applied to?

[A]
You'll want to query
```
APPLSYS.FND_PROFILE_OPTIONS
```
and
```
FND_PROFILE_OPTION_VALUES
```
.
For a comprehensive script that you can pick up the SQL from, look here:
http://tipsnscripts.com/?p=16


q:
And if you do, can you give some background information on the implementation and the reasons for implementing this pattern?

The pattern is described in more detail in these articles:

Microsoft Inductive User Interface
Guidelines

IUIs and Web-Style
Navigation in Windows Forms, Part 1 & Part 2

[A]
Yes - we had a problem in that many of the administrators of our software found it too difficult to use. To solve this we used Microsoft's WinForms IUI framework build a new configuration and management tool for our software.
User feedback has been extremely positive, particularly with everything being task driven - i.e. the links on our home page include thing like "Create new user", "Create new department" - rather then the user having to discover how to do this by clicking through a series of menus. Since the inductive interface is more similar to a web-browser (hypertext links, back/forward buttons) it seems much easier for new users to learn.


q:
This confusion arises as most people are trained to evaluate arithmetic expressions as per PEDMAS or BODMAS rule whereas arithmetic expressions in programming languages like C# do not work in the same way.

What are your takes on it?

[A]
I am not sure there really is a difference.  The traditional BODMAS (brackets, orders, division, multiplication, addition, subtraction) or PEDMAS (parentheses, exponents, division, multiplication, addition, subtraction) are just subsets of all the possible operations and denote the order that such operations should be applied in.  I don't know of any language in which the BODMAS/PEDMAS rules are violated, but each language typically adds various other operators - such as ++, --, = etc.
I always keep a list of operator precedence close to hand in case of confusion.  However when in doubt it is usually worth using some parentheses to make the meaning clear.  Just be aware that parentheses do not have the highest precedence - see
http://msdn.microsoft.com/en-us/library/126fe14k.aspx
for an example in C++.


q:
Suppose I've found a “text” somewhere in open access (say, on public network share). I have no means to contact the author, I even don't know who is the author.

What can I legally do with such “text”?

Update: I am not going to publish that “text”, but rather learn from it myself.

Update: So, if I ever see an anonymous code, article, whatever, shouldn't I even open it, because otherwise I'd copy its contents to my brain?

[A]
As far as I
know
(without any legal training) - if you list the text or code or whathaveyou as "anonymous", you're OK.
I believe that by listing it as anonymous you're indicating you do not know where it came from, but you're admitting you didn't create it as original work.
Extending from that, you should be open to the actual author being able to prove they are the author, and changing your usage to reflect their name/license/copyright/whatever.
You should check with an Intellectual Property lawyer for details and corrections to my understanding.


q:
What are the pros / cons of using pthread_cond_wait or using a semaphore ?
I am waiting for a state change like this :

pthread_mutex_lock(&cam->video_lock);
while(cam->status == WAIT_DISPLAY) {
    pthread_cond_wait(&cam->video_cond, &cam->video_lock);
}
pthread_mutex_unlock(&cam->video_lock);

Using a properly initialised semaphore, I think I could do it like this :

while(cam->status == WAIT_DISPLAY) {
    sem_wait(&some_semaphore);
}

What are the pros and cons of each method ?

[A]
In your second snippet, you're getting the lock multitude of times, never releasing it.
In general, the state you're waintin on can be completely expressed by a semaphore, then you can use just that.  A lock structure is smaller in size, and it requires less atomic operations to check/set/release.
Otherwise, if the state is complex, and different parts of the code wait on different conditions of the same variable (eg, here you want x<10; there you want y>x), use cond_wait.


q: How to get a file's creation date or file size, for example this Hello.jpg at http://www.mywebsite.com/now/Hello.jpg(note: This URL does not exist)? The purpose of this question is to make my application re-download the files from the any website when it has detected that the website has an updated version of the files and the files in my local folder are out of date. Any ideas?

[A]
If you use the HEAD request it will send the headers for the resource, there you can check the cache control headers which will tell you if the resource has been modified, last modification time, size (content-length) and date.
```
```
$ telnet www.google.com 80
Trying 216.239.59.103...
Connected to www.l.google.com.
Escape character is '^]'.
HEAD /intl/en_ALL/images/logo.gif HTTP/1.0

HTTP/1.0 200 OK
Content-Type: image/gif
Last-Modified: Wed, 07 Jun 2006 19:38:24 GMT
Expires: Sun, 17 Jan 2038 19:14:07 GMT
Cache-Control: public
Date: Tue, 16 Sep 2008 09:45:42 GMT
Server: gws
Content-Length: 8558
Connection: Close

Connection closed by foreign host.
```
```
Note that you'll probably have to decorate this basic and easy approach with many heuristics depending on the craziness of each webserver's admin, as each can send whatever headers they like. If they do not provide caching headers (Last-Modified, Expires, Cache-Control) nor Content-Length nor etag, you'd be stuck with redownloading it to test.


q: How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?

[A]
```
```
var = raw_input("Please enter something: ")
print "you entered", var
```
```
Or for Python 3:
```
```
var = input("Please enter something: ")
print("You entered: " + var)
```
```


q:
For best performance, is it better to use a virtual IDE HDD or virtual SCSI HDD?
If, SCSI, does it matter whether you use an BusLogic or LSILogic?

[A]
Go for the SCSI and LSILogic. IDE and BusLogic are for compatibility reasons. Like when you do physical2virtual...
There's a whitepaper from vmware showing the difference between LSILogic and BusLogic, which in my opinion is rather small:
http://www.vmware.com/pdf/ESX2_Storage_Performance.pdf
Edit after like three years:
With current ESX environments it's best to use the Paravirtual SCSI device.


q: Is it possible to use the Asp.Net MVC framework within SharePoint sites?

[A] I don't believe so, although you can upload standard ASPX files into SharePoint and have them operate I'm pretty sure that the URL rewritting is where it would come unstuck.


q:
Say I have the following C++:

char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;

Is this safe according to the C++ standard? Do I need to cast back to a char* and then use delete[]? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?

[A]
No, it's undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that
thudbang
linked to says,
```
operator delete[]
```
might be overloaded to do something different to
```
operator delete
```
. You can sometimes get away with it, but it's also good practice to get into the habit of matching delete[] with new[] for the cases where you can't.


q: I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA?

[A]
Yes.
```
```
ThisWorkbook.RefreshAll
```
```
Or, if your Excel version is old enough,
```
```
Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next
```
```


q:
Is there a good way to exclude certain pages from using a HTTP module?

I have an application that uses a custom HTTP module to validate a session. The HTTPModule is set up like this in web config:

<system.web>
  <!-- ... -->
  <httpModules>
    <add name="SessionValidationModule"
       type="SessionValidationModule, SomeNamespace" />
  </httpModules>
</system.web>

To exclude the module from the page, I tried doing this (without success):

<location path="ToBeExcluded">
  <system.web>
    <!-- ... -->
    <httpModules>
      <remove name="SessionValidationModule" />
    </httpModules>
  </system.web>
</location>

Any thoughts?

[A]
You could use an HTTPHandler instead of an HTTPModule.  Handlers let you specify a path when you declare them in Web.Config.
```
```
<add verb="*" path="/validate/*.aspx" type="Handler,Assembly"/>
```
```
If you must use an HTTPModule, you could just check the path of the request and if it's one to be excluded, bypass the validation.


q:
Originally I am looking for a solution in Actionscript. The point of this question is the algorithm, which detects the exact Minute, when a clock has to switch the Daylight Saving Time.

So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...

[A]
There is no real algorithm for dealing with Daylight Saving Time. Basically every country can decide for themselves when -and if- DST starts and ends. The only thing we can do as developers is using some sort of table to look it up. Most computer languages integrate such a table in the language.
In Java you could use the
```
inDaylightTime
```
method of the
TimeZone
class. If you want to know the exact date and time when DST starts or ends in a certain year, I would recommend to use
Joda Time
. I can't see a clean way of finding this out using just the standard libraries.
The following program is an example: (Note that it could give unexpected results if a certain time zone does not have DST for a certain year)
```
```
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class App {
    public static void main(String[] args) {
        DateTimeZone dtz = DateTimeZone.forID("Europe/Amsterdam");

        System.out.println(startDST(dtz, 2008));
        System.out.println(endDST(dtz, 2008));
    }

    public static DateTime startDST(DateTimeZone zone, int year) {
        return new DateTime(zone.nextTransition(new DateTime(year, 1, 1, 0, 0, 0, 0, zone).getMillis()));
    }

    public static DateTime endDST(DateTimeZone zone, int year) {
        return new DateTime(zone.previousTransition(new DateTime(year + 1, 1, 1, 0, 0, 0, 0, zone).getMillis()));
    }
}
```
```


q:
We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system.

The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though.

[A]
The verification of "logical" systems in the IC design arena is known as "Design Verification", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality.
Ladder logic can be transformed to one of the modern HDL's like Verilog..
transform each ladder
```
```
|---|R15|---+---|/R16|---------(R18)--------|
|           |
|---|R12|---+
```
```
to an expression like
```
```
always @(*) R18 = !R16 && ( R15 | R12);
```
```
or you could use an assign statement
```
```
assign R18 = R16 && (R15 | R12);
```
```
a latching relay
```
```
assign R18 = (set condition) || R18 && !(break condition);
```
```
Then use a free verilog simulator like
Icarus
to develop a testbench and test your system.
Make sure you're testcases give good CODE coverage of your logic!  And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn.
(Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials.
Verilog will be an easier language to develop your tests and testbenches in!
It may be helpful to program in some unit delays.
Sorry, I have never looked for ladder logic to/from verilog translators..
but ladder logic in my day was only just being put into a computer for programming PLC's - most of the relay systems I used were REAL Relays, wired into the cabinets!!
Good luck.
jbd
There are a couple of ladder logic editors (with simultors) available for free..
here is one that runs on windows supposedly:
http://cq.cx/ladder.pl


q:
How do you return 1 value per row of the max of several columns:

TableName

[Number, Date1, Date2, Date3, Cost]

I need to return something like this:

[Number, Most_Recent_Date, Cost]

Query?

[A]
This is an old answer and broken in many way.
See
https://stackoverflow.com/a/6871572/194653
which has way more upvotes and works with sql server 2008+ and handles nulls, etc.
Original but problematic answer
:
Well, you can use the CASE statement:
```
```
SELECT
    CASE
        WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
        WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
        WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
        ELSE                                        Date1
    END AS MostRecentDate
```
```


q:
I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like:

mvn install -Dmaven.repository=http://example.com/maven2

The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle.

[A]
I am not sure if you can do it using the command line. You can on the other hand add repositories in the
pom.xml
as in the following example. Using this approach you do not need to change the
~/.m2/settings.xml
file.
```
```
<?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ...
    <repositories>
            <repository>
                <id>MavenCentral</id>
                <name>Maven repository</name>
                <url>http://repo1.maven.org/maven2</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
...
            <repository>
                <id>Codehaus Snapshots</id>
                <url>http://snapshots.repository.codehaus.org/</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </repository>
        </repositories>

    ...

        <pluginRepositories>
            <pluginRepository>
                <id>apache.snapshots</id>
                <name>Apache Snapshot Repository</name>
                <url>
                    http://people.apache.org/repo/m2-snapshot-repository
                </url>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </pluginRepository>
            <pluginRepository>
                <id>Codehaus Snapshots</id>
                <url>http://snapshots.repository.codehaus.org/</url>
                <snapshots>
                    <enabled>true</enabled>
                </snapshots>
                <releases>
                    <enabled>false</enabled>
                </releases>
            </pluginRepository>
        </pluginRepositories>

    ...

    </project>
```
```


q:
Does anyone know of a good code obsfucator for Perl? I'm being ask to look into the option of obsfucating code before releasing it to a client. I know obsfucated code can still be reverse engineered, but that's not our main concern.

Some clients are making small changes to the source code that we give them and it's giving us nightmares when something goes wrong and we have to fix it, or when we release a patch that doesn't work with what they've changed. So the intention is just to make it so that it's difficult for them to make their own changes to the code(they're not supposed to be doing that anyway).

[A]
Please don't do that. If you don't want people to alter your Perl code then put it under an appropriate licence and enforce that licence. If people change your code when you licence says that they shouldn't do that, then it's not your problem when your updates not longer work with their installation.
See
perlfaq3's answer to "How Can I hide the source for my Perl programs?
for more details.


q:
Maven spews out far too many lines of output to my taste (I like the Unix way: no news is good news).

I want to get rid of all [INFO] lines, but I couldn't find any mention of an argument or config settings that controls the verbosity of Maven.

Is there no LOG4J-like way to set the log level?

[A]
You can try the
```
-q
```
switch
.
```
-q
```
,
```
--quiet
```
Quiet output - only show errors


q:
I can make Firefox not display the ugly dotted focus outlines on links with this:

a:focus {
    outline: none;
}

But how can I do this for <button> tags as well? When I do this:

button:focus {
    outline: none;
}

the buttons still have the dotted focus outline when I click on them.

(and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots)

[A]
There's no way to remove these dotted focus in Firefox using CSS.
If you have access to the computers where your webapplication works, go to about:config in Firefox and set
```
browser.display.focus_ring_width
```
to 0. Then Firefox won't show any dotted borders at all.
The following bug explains the topic:
https://bugzilla.mozilla.org/show_bug.cgi?id=74225


q:
I want to compress some files (into the ZIP format) and encrypt them if possible using C#. Is there some way to do this?

Can encryption be done as a part of the compression itself?

[A]
For compression, look at the
```
System.IO.Compression
```
namespace and for encryption look at
```
System.Security.Cryptography
```
.


q: What is the difference, what is the official terms, are any terms obsolete in ASP.NET 3.5?

[A]
UserControl
:  A custom control, ending in .ascx, that is composed of other web controls.  Its almost like a small version of an aspx webpage.  It consists of a UI (the ascx) and codebehind.  Cannot be reused in other projects by referencing a DLL.
WebControl
:  A control hosted on a webpage or in a UserControl.  It consists of one or more classes, working in tandem, and is hosted on an aspx page or in a UserControl.  WebControls don't have a UI "page" and must render their content directly.  They can be reused in other applications by referencing their DLLs.
RenderedControl
:  Does not exist.  May be synonymous to WebControl.  Might indicate the control is written directly to the HttpResponse rather than rendered to an aspx page.
CompositeControl
:  Inbetween UserControls and WebControls.  They code like UserControls, as they are composed of other controls.  There is not any graphical UI for control compositing, and support for UI editing of CompositeControls must be coded by the control designer.  Compositing is done in the codebehind.  CompositeControls can be reused in other projects like WebControls.


q: Can you suggest a tool for testing accessibility and section 508/ADA compliance of a Website with MS Share Point and .Net 2.0 as the underlying platform?

[A]
In my experience, testing Sharepoint for accessibility is not worth it. Even if you've used the Accessibility Toolkit for Sharepoint (AKS) with Sharepoint 2007, the end result is far from accessible.
The trouble is that accessibility was not, and still is not a big consideration for MS when they made Sharepoint. Everything depends on table layout, and screenreaders are given a nightmare to deal with.
There are a few online tools - some will help validate your output, others pretend to test you for accessibility (
TAW
).
The problem is that many of the guidelines under WCAG are just too arbitrary, and will never be testable by an automated tool. This may change with WCAG 2.
Anyway, wish you the best trying to make Sharepoint accessible.
EDIT:
As a side not, I can highly recommend the following tools/resources for anyone interested in accessible development:
Chris Pederick's
Web Accessibility
Toolbar
NDA's Web Accessibility IT
Guidelines


q: Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in Foo **) in C++?

[A]
IMO most common usage is to pass reference to pointer variable
```
```
void test(int ** var)
{
 ...
}

int *foo = ...
test(&foo);
```
```
You can create multidimensional jagged array using double pointers:
```
```
int ** array = new *int[2];
array[0] = new int[2];
array[1] = new int[3];
```
```


q:
What's the best value for money c# code protection? Some just use obfuscation, others add win32 wrapping, some cost a fortune. So far I've come up with http://www.eziriz.com/ who's Intellilock looks promising. Any other suggestions? Any reasons why this is not a good idea?

I know its impossible to completely protect but I'd prefer the ability to protect my code so that it would require a lot of effort in order to recover it. I do hope to sell my products eventually, while also releasing some for free.

[A]
First of all, no matter what kind of protection you'll employ,a truly dedicated cracker will, eventually, get through all of the protective barriers. It might simply not worth it employing high-level code obfuscation; rather focus that time into making a better application.
One way to look at this problem, is that people pirating your software are not your target audience; focus on paying customers instead.
With that said, Visual Studio includes the community edition of
Dotfuscator
, which is fairly decent (for it's value); I would look into that, if needed.


q: Using the Python Documentation I found the HTML parser but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).

[A]
Try:
```
```
import HTMLParser
```
```
In Python 3.0, the HTMLParser module has been renamed to html.parser
you can check about this
here
Python 3.0
```
```
import html.parser
```
```
Python 2.2 and above
```
```
import HTMLParser
```
```


q: How can I find the last row that contains data in a specific column and on a specific sheet?

[A]
```
```
Function LastRow(rng As Range) As Long
    Dim iRowN As Long
    Dim iRowI As Long
    Dim iColN As Integer
    Dim iColI As Integer
    iRowN = 0
    iColN = rng.Columns.count
    For iColI = 1 To iColN
        iRowI = rng.Columns(iColI).Offset(65536 - rng.Row, 0).End(xlUp).Row
        If iRowI > iRowN Then iRowN = iRowI
    Next
    LastRow = iRowN
End Function
```
```


q: Why can I not see an option for copying database objects when I right click > tasks on my database?

[A]
MS Sql Server Express doesn't come with SSIS which is what you will need to import/export objects out of your database.
You can also manually script this process. One way is to use BCP (
http://msdn.microsoft.com/en-us/library/ms162802.aspx
)


q:
I'm currently writing a TYPO3 extension which is configured with a list of tt_content UID's.
These point to content elements of type "text" and i want to render them by my extension.

Because of TYPO3s special way of transforming the text you enter in the rich text editing when it enters the database, and again transforming it when it is rendered to the frontend, i can not just output the database contents of the bodytext field.

I want to render these texts as they would usually get rendered by TYPO3.
How do I do that?

[A]
I had the same problem a couple of months ago. Now I must say that I am no typo3 developer, so I don't know if this is the right solution.
But I used something like this:
```
$output .= $this->pi_RTEcssText( $contentFromDb );
```
in my extension and it works.


q:
I am using a .NET Windows Forms DataGridView and I need to edit a DataBound column (that binds on a boolean DataTable column). For this I specify the cell template like this:

DataGridViewColumn column = new DataGridViewColumn(new DataGridViewCheckBoxCell());

You see that I need a CheckBox cell template.

The problem I face is that this column is constantly readonly/disabled, as if it would be of TextBox type. It doesn't show a checkbox at all.

Any thoughts on how to work with editable checkbox columns for DataGridView?

Update: For windows forms, please.

Thanks.

[A]
Create a TemplateField and bound the id to it, something like this:
```
```
<asp:TemplateField HeaderText="Whatever" SortExpression="fieldname" ItemStyle-HorizontalAlign="Center">
    <ItemTemplate>
        <asp:CheckBox runat="server" ID="rowCheck" key='<%# Eval("id") %>' />
    </ItemTemplate>
</asp:TemplateField>
```
```


q:
How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.

I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.

[A]
See this CodeProject article for the win32 basics :
http://www.codeproject.com/KB/threads/pausep.aspx
.  This sample code makes use of the ToolHelp32 library from the SDK, so I would recommend turning this sample code into an unmanaged C++/CLI library with a simple interface like "SuspendProcess(uint processID).
Process.Start will return you a Process object, from which you can get the process id, and then pass this to your new library based on the above.
Dave


q:
Is it possible to have one application binary build for multiple mobile devices (on BREW platform), rather than making a separate build for each device using build script with conditional compilation.

In particular is is possible to use single BREW application build for multiple screen resolutions?

Note that the goal is to have a single binary build. If it would be just to have a single codebase, than conditional compilation and smart build script would do the trick.

[A]
Yes, it is possible, we were able to do this at my previous place of work. What's required is tricky though:
Compile for the lowest common denominator BREW version. Version 1.1 is the base for all current handsets out there.
Your code must be able to handle multiple resolutions. The methods for detecting screen width and height are accurate for all handsets in my experience.
All your resources must load on all devices. This would require making your own custom image loader to work around certain device issues. For sound, I know simple MIDI type 0 works on all but QCP should also work (no experience of it myself).
Use bitmap fonts. There are too many device issues with fonts to make it worthwhile using the system fonts.
Design your code structure as a finite state machine. I cannot emphasise this enough - do this and many, many problems never materialise.
Have workarounds for every single device issue. This is the hard part! It's possible but this rabbit hole is incredibly deep...
In the end, the more complex and advanced the application, the less likely you can go this route. Some device properties simply cannot be detected reliably at runtime (such as platform ID) and so multiple builds are then required.


q:
I am using git on a project, that generates lots of data-files (simulation-results).
I am "forced" to version and track all those results in the same repository. (This is a hard requirement and can not be changed)

However I don't need them. We have about 50 MB for the project and 5 GB results in the repository.

Is it feasible for me to create a branch, delete all the results, check this branch out and only work on that branch?

How hard would it be (what would I have to do), to push my local changes back into the fat branch?

Is there a better solution to get rid of those 5 GB for my work?

[A]
If you were to make a branch and delete the result files from the branch, then merging your branch back into master would also try to delete the results from master. A file delete is a change just like any other.
Perhaps you could use the git submodule support to manage your code changes as a submodule of the fat repository. In this way, the fat repository would appear to contain everything, but you could work on just the small code bits independently. This may take some fiddling around to work smoothly.


q:
I'm trying to replace each , in the current file by a new line:

:%s/,/\n/g

But it inserts what looks like a ^@ instead of an actual newline. The file is not in DOS mode or anything.

What should I do?

If you are curious, like me, check the question Why is \r a newline for Vim? as well.

[A]
Use
```
\r
```
instead of
```
\n
```
.
Substituting by
```
\n
```
inserts a null character into the text. To get a newline, use
```
\r
```
. When
searching
for a newline, you’d still use
```
\n
```
, however. This asymmetry is due to the fact that
```
\n
```
and
```
\r
```
do slightly different things
:
```
\n
```
matches an end of line (newline), whereas
```
\r
```
matches a carriage return. On the other hand, in substitutions
```
\n
```
inserts a null character whereas
```
\r
```
inserts a newline (more precisely, it’s treated as the input
CR
). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it).
```
xxd
```
shows a hexdump of the resulting file.
```
```
echo bar > test
(echo 'Before:'; xxd test) > output.txt
vim test '+s/b/\n/' '+s/a/\r/' +wq
(echo 'After:'; xxd test) >> output.txt
more output.txt
```
```
```
```
Before:
0000000: 6261 720a                                bar.
After:
0000000: 000a 720a                                ..r.
```
```
In other words,
```
\n
```
has inserted the byte 0x00 into the text;
```
\r
```
has inserted the byte 0x0a.


q:
I have PHP configured so that magic quotes are on and register globals are off.

I do my best to always call htmlentities() for anything I am outputing that is derived from user input.

I also occasionally seach my database for common things used in xss attached such as...

<script

What else should I be doing and how can I make sure that the things I am trying to do are always done.

[A]
Escaping all user input is enough for most sites. Also make sure that session IDs don't end up in the URL so they can't be stolen from the
```
Referer
```
link to another site. Additionally, if you allow your users to submit links, make sure no
```
javascript:
```
protocol links are allowed; these would execute a script as soon as the user clicks on the link.


q:
I'm making a method combining Scrum with the OpenUP lifecycle and deliverables. I also want to keep the OpenUP disciplines apart from "Project Management".  I can "hide" it so that it's not immediately obvious in my generated method site. But when you then navigate to the "Risk List" artefact for example the PM is still seen as contributing, and if you click on the link, you get taken to the PM Discipline page.

How can I remove it completely from my method without deleting it from the OpenUP library which I'm consuming?

[A]
I've never used EPF Composer.
I did a little bit of google searches and I understand what you are looking for can be done through Configurations (select OpenUP in your Library view) and published View definitions.
See slide 83 and 84 of this PPT document. You should be able to take it from there.
An Introduction to the Eclipse Process Framework
.
In case the link does not work, I searched for "EPF Composer" "Standard categories" on google and the document is at the bottom of the first results page.
Good luck.


q:
I'm not sure if many people know about this text-editor?

jEdit was kinda big in 2004, but now, Notepad++ seems to have taken the lead(on Windows)
Many of the plugins haven't been updated since 2003 and the overal layout and usage is confusing...

I'm sure jEdit has many nifty features, but I'll be damned if I can find out where to find them and how to use them. Reading that manual is a fulltime job on it's own.

[A]
I had to use during my vocational education for XML and XSLT. It had a lot of bugs and didn't work always. I couldn't get to like it, but if I had to test some XSLT I'd give it another shot. I found Notepad++ and I am more than happy with it for what I need.
To your question: Did you take a look at
jEdit's plugin list
? There are some plugins released 2008 and the latest version was released on 8th August 2008.


q:
Given a table of votes (users vote for a choice, and must supply an email address):

votes
--
id: int
choice: int
timestamp: timestamp
ip: varchar
email: varchar

What's the best way to count "unique" votes (a user being a unique combination of email + ip) given the constraint they may only vote twice per hour?

It's possible to count the number of hours between first and last vote and determine the maximum number of allowed votes for that timeframe, but that allows users to compress all their votes into say, a single hour-long window, and still have them counted.

I realize anonymous online voting is inherently flawed, but I'm not sure how to do this with SQL. Should I be using an external script or whatever instead? (For each choice, for each email+ip pair, get a vote, calculate the next +1h timestamp, count/discard/tally votes, move on to the next hour, etc...)

[A]
Something like
```
```
select email, ip, count(choice)
from votes
group by email, ip, datepart(hour, timestamp)
```
```
If I understand correctly


q:
From question How to replace a character for a newline in Vim?. You have to use \r when replacing text for a newline, like this

:%s/%/\r/g

But when replacing end of lines and newlines for a character, you can do it like:

:%s/\n/%/g

What section of the manual documents these behaviors, and what's the reasoning behind them?

[A]
```
:help NL-used-for-Nul
```
Technical detail:
```
<Nul>
```
characters in the file are stored as
```
<NL>
```
in memory. In the display
  they are shown as "
```
^@
```
".  The translation is done when reading and writing
  files.  To match a
```
<Nul>
```
with a search pattern you can just enter
CTRL-@
or
  "
CTRL-V
000".  This is probably just what you expect.  Internally the
  character is replaced with a
```
<NL>
```
in the search pattern.  What is unusual is
  that typing
CTRL-V
CTRL-J
also inserts a
```
<NL>
```
, thus also searches for a
```
<Nul>
```
in the file.  {Vi cannot handle
```
<Nul>
```
characters in the file at all}


q:
I want to disable the selection of certain rows in a datagridview.

It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)

Thankx,

[A]
If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected.
If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell.
Here's an example:
```
```
public class MyDataGridView : DataGridView
{
    protected override void SetSelectedRowCore(int rowIndex, bool selected)
    {
        if (selected && WantRowSelection(rowIndex))
        {
            base.SetSelectedRowCore(rowIndex, selected);
        }
     }

     protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)
     {
         if (selected && WantRowSelection(rowIndex))
         {
            base.SetSelectedRowCore(rowIndex, selected);
          }
     }

     bool WantRowSelection(int rowIndex)
     {
        //return true if you want the row to be selectable, false otherwise
     }
}
```
```
If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class.


q:
I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up?

class MyControl : System.Web.UI.UserControl {
  // Attribute to prevent property from showing in VS Property Window?
  public bool SampleProperty { get; set; }

  // other stuff
}

[A]
Use the following attribute ...
```
```
using System.ComponentModel;

[Browsable(false)]
public bool SampleProperty { get; set; }
```
```
In VB.net, this
will be
:
```
```
<System.ComponentModel.Browsable(False)>
```
```


q:
I have created a namespace extension that is rooted under Desktop. The main purpose of the extension is to provide a virtual list of ZIP files that represent a list of configurable directories. When the user clicks one of the those items the contents of the related directory are zipped in place and the resulting ZIP file is stored in a cache folder.

All this works well aside a minor issue. If we go to Windows Explorer, open the extension and double click an item the opened file is the one from the cache. [CORRECT]

If on the other hand we open it by an Open Dialog the opened file is one from a Temporary Internet files directory. [INCORRECT]

What do I have to change for the Open Dialog (when used for example trough notepad.exe) to open the file from the cache folder and not from Temporary Internet files. I have tried to send allways the qualified file name in IShellFolder::GetDisplayNameOf but without any luck.

[A]
What would be wrong with doing something like the following:
Defining a 'Maintainer' interface with the addListener(Listener, Enum) method.
Create a DefaultMaintainer class (as above) which implements Maintainer.
Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer.
other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)


q:
The win32.perl.org web site provides references to several Perl distributions for MS Windows.

For a long time I have been using ActivePerl from
ActiveState but recently I switched to
Strawberry Perl.

IMHO The only advantage that Active Perl still has over Strawberry Perl is the fact that it comes with Perl Tk which means its easy to install
Devel::ptkdb the graphical debugger. Other than that, I think Strawberry Perl has all the advantages.

[A]
Strawberry Perl
is just getting better and better.  One problem I've repeatedly had with ActiveState is that my modules sometimes fail to install because I need an upgrade to a core module, but they won't allow that.  Thus, everybody who
doesn't
use Windows can use my code, but they can't do that with ActiveState's Perl.
ActiveState also has a very dodgy build system which often fails to report exactly why a module failed to build.  I got so tired of emailing and asking for this information that I eventually gave up.  I want my code to run on Windows, but if ActiveState doesn't provide me with that information and doesn't give me any option for upgrading core modules, I just can't use it.  Some of my modules have NO build failures on any operating system -- except those with ActiveState Perl.  Support Strawberry Perl and just don't worry about ActiveState.
If ActiveState has fixed their build system and their 'no upgrade to core modules' policy, it's worth revisiting.


q:
I have just found a static nested interface in our code-base.

class Foo {
    public static interface Bar {
        /* snip */
    }
    /* snip */
}

I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:

What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?

[A]
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with
```
Foo.Bar
```
, like so:
```
```
public class Baz implements Foo.Bar {
   ...
}
```
```
In most ways, this isn't different from a static inner class.


q:
I have an ASP.Net 2.0 application in which the Session_Start event is not firing in my Global.asax file. Can anyone tell why this is happening and how I can get it working?

The application worked fine on my Windows XP development machine, but stopped working when deployed to the server (Win Server 2003/IIS 6/ASP.Net 2.0).

I'm not sure if this is relevant, but the server also hosts a SharePoint installation (WSS 3.0) which I know does change some settings at the default web site level.

[A] Are you sure the website in IIS is set to use ASP.NET 2.0 rather than 1.1?


q: Is there an api to bring the vista side bar to the front (Win+Space) programatically and to do the reverse (send it to the back ground).

[A]
Probably using SetWindowPos you can change it to be placed the top / bottom of the z-order or even as the top-most window. You would need to find the handle to the sidebar using FindWindow or an application like WinSpy.
But after that something like.
Sets the window on top, but not top most.
```
```
SetWindowPos(sidebarHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE);
```
```
Sets the window at the bottom.
```
```
SetWindowPos(sidebarHandle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE);
```
```
This is my best guess on achieving what you asked, hopefully it helps.


q:
I've been using OpenGL for years, but after trying to use D3D for the first time, I wasted a significant amount of time trying figure out how to make my scene lights stay fixed in the world rather than fixed on my objects.

In OpenGL light positions get transformed just like everything else with the MODELVIEW matrix, so to get lights fixed in space, you set up your MODELVIEW the way you want for the lights, and call glLightPosition then set it up for your geometry and make geometry calls.   In D3D that doesn't help.

(Comment -- I eventually figured out the answer to this one, but I couldn't find anything helpful on the web or in the MSDN.  It would have saved me a few hours of head scratching if I could have found this answer then.)

[A]
The answer I discovered eventually was that while OpenGL only has its one amalgamated
```
MODELVIEW
```
matrix, in D3D the "world" and "view" transforms are kept separate, and placing lights seems to be the major reason for this.  So the answer is you use
```
D3DTS_VIEW
```
to set up matrices that should apply to your lights, and
```
D3DTS_WORLD
```
to set up matrices that apply to the placement of your geometry in the world.
So actually the D3D system kinda makes more sense than the OpenGL way.  It allows you to specify your light positions whenever and wherever the heck you feel like it once and for all, without having to constantly reposition them so that they get transformed by your  current "view" transform.  OpenGL has to work that way because it simply doesn't know what you think your "view" is vs your "model".  It's all just a modelview to GL.
(Comment - apologies if I'm not supposed to answer my own questions here, but this was a real question that I had a few weeks ago and thought it was worth posting here to help others making the shift from OpenGL to D3D.  Basic overviews of the D3D lighting and rendering pipeline seem hard to come by.)


q: How effective is merging when folders and projects have been renamed in your solution?

[A]
In my experience TFS can track renames, as long as you do all the renaming within the SourceControlExplorer (TFS).
The problems tend to occur when you have other people making changes to the original files while someone else is doing massive renames/moves, while someone else is editing the renamed version.
Where possible I would say that if you are doing large scale renaming and moving it is worth informing team mates, and if possible get them to hold off making changes until you've checked yours in.
As with all branch/merge issues the problem is greatly reduced by checking in and merging little and often.


q:
in our application we have a Java applet running inside a .NET browser control. It is a know issue from Sun that running an applet this way may crash the control.

Has anyone come across the same problem and solved it?

Atm we are running the applet in a Webbrowser but we need to run it in a browser control.

Thx for any help.

[A]
If you wrote the applet and have source, then you could try to migrate the Java Applet to a J# Browser control and stuff that in your .net application.
```
```
Here is a link - http://msdn.microsoft.com/en-us/library/aa290083(VS.71).aspx
```
```


q:
In Delphi, I want to be able to create an private object that's associated with a class, and access it from all instances of that class.  In Java, I'd use:

public class MyObject {
    private static final MySharedObject mySharedObjectInstance = new MySharedObject();
}

Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block.

(You might have guessed...  I know my Java but I'm rather new to Delphi...)

Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject.  (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.)

What's the neatest way to do something like this in Delphi?

[A]
Before version 7, Delphi didn't have static variables, you'd have to use a global variable.
To make it as private as possible, put it in the
```
implementation
```
section of your unit.


q:
I have to read data from some files and insert the data into different tables in a database. Is Unix shell script powerful enough to do the job?

Is it easy to do the job in shell script or should I go about doing this in Java?

[A]
Can't test it right now, but something like:
```
```
echo "INSERT INTO foo (b,a,r) VALUES (1,2,3);" |
    mysql -u user -psecret -h host database
```
```
in a shell script should work. Don't know about getting Data out of it though


q:
The problem: I have a class which contains a template method execute which calls another method _execute. Subclasses are supposed to overwrite _execute to implement some specific functionality. This functionality should be documented in the docstring of _execute.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use execute, so he won't see the correct docstring if he uses help(execute).

Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of execute is automatically replaced with that of _execute. Any ideas how this might be done?

I was thinking of metaclasses to do this, to make this completely transparent to the user.

[A]
Well the doc-string is stored in
```
__doc__
```
so it wouldn't be too hard to re-assign it based on the doc-string of
```
_execute
```
after the fact.
Basically:
```
```
```
class MyClass(object):
    def execute(self):
        '''original doc-string'''
        self._execute()

class SubClass(MyClass):
    def _execute(self):
        '''sub-class doc-string'''
        pass

    # re-assign doc-string of execute
    def execute(self,*args,**kw):
        return MyClass.execute(*args,**kw)
    execute.__doc__=_execute.__doc__
```
Execute has to be re-declared to that the doc string gets attached to the version of execute for the
```
SubClass
```
and not for
```
MyClass
```
(which would otherwise interfere with other sub-classes).
That's not a very tidy way of doing it, but from the POV of the user of a library it should give the desired result.  You could then wrap this up in a meta-class to make it easier for people who are sub-classing.


q: Does anyone know if the Infragistics UltraGrid control provides functionality similar to that of DataGridView.HitTestInfo?

[A]
There's a
```
.MousePosition
```
property which returns
```
System.Drawing.Point
```
and "Gets the position of the mouse cursor in screen coordinates" but I'm using an older version of their UltraWinGrid (2003).
They have a
free trial download
, so you could see if they've added it to their latest and greatest  :o)


q: Anyone know uf there's a dll/runner anywhere that returns TAP output from an NUnit test suite?

[A] Seems unlikely to me, since there is an impedance mismatch. TAP has no concept for what NUnit calls a test, and what TAP calls a test usually corresponds to an NUnit assertion, but not precisely. So I’m not sure how the thing you’re looking for would work at all. (But maybe a heuristic could work well enough.)


q:
I'm using an Xml field in my Sql Server database table. I'm trying to search a word using the XQuery contains method but it seems to search only in case sensitive mode. The lower method isn't implemented on Sql Server XQuery implementation also.
¿Is there a simple solution to this problem?

[A]
First
link from google points to MSDN page:
contains Function (XQuery)
In order to get case-insensitive
  comparisons, the
upper-case
or
  lower-case functions can be used.


q:
I'm missing the boat on something here, kids.  This keeps rearing its head and I don't know what's going on with it, so I hope my homeys here can help.

When working in Silverlight, when I create bindings in my c# code, they never hold up when the application is running.  The declarative bindings from my xaml seem ok, but I'm doing something wrong when I create my bindings in C#.  I'm hoping that there is something blindingly obvious I'm missing.  Here's a typical binding that gets crushed:

TextBlock tb = new TextBlock();
Binding b = new Binding("FontSize");
b.Source = this;
tb.SetBinding(TextBlock.FontSizeProperty, b);

[A]
I've just tried the exact code you just posted and it worked fine, with some changes. I believe the problem is the element you are using for the SetBinding call is not the textblock you want to bind. It should be:
```
```
TextBlock tb = new TextBlock();
Binding b = new Binding("FontSize");
b.Source = this;
tb.SetBinding(TextBlock.FontSizeProperty, b);
```
```
Make sure you also have a FontSize public property of type double on "this". If "this" is a user control, I would recommend renaming the property so you don't hide the inherited member.


q:
I am using <input type="file" id="fileUpload" runat="server"> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions).

Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).

[A]
Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.
I think you may be able to do it on the client using JavaScript.  Personally, I use a third party component called
radUpload by Telerik
.  It has a good client-side and server-side API, and it provides a progress bar for big file uploads.
I'm sure there are open source solutions available, too.


q:
I find I can do more with NHibernate, and even Castle than with the Linq to Entities, or linq to SQL.

Am I crazy?

[A]
No you're not crazy. nHibernate is a full OR Mapper, Linq to SQL and Linq to Entities don't implement everything you'd expect from an OR mapper and targeted at a slightly different group of developers.
But don't let that put you off linq though. Linq is still a pretty good idea.. Try Linq to nHibernate :-)


q:
Given the following example, why do I have to explicitly use the statement b->A::DoSomething() rather than just b->DoSomething()?

Shouldn't the compiler's overload resolution figure out which method I'm talking about?

I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)

class A
{
  public:
    int DoSomething() {return 0;};
};

class B : public A
{
  public:
    int DoSomething(int x) {return 1;};
};

int main()
{
  B* b = new B();
  b->A::DoSomething();    //Why this?
  //b->DoSomething();    //Why not this? (Gives compiler error.)
  delete b;
  return 0;
}

[A]
The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done
afterwards
. In your case this means that the compiler sees
```
B::DoSomething
```
. It then tries to match the argument list, which fails.
One solution would be to pull down the overload from
```
A
```
into
```
B
```
's scope:
```
```
class B : public A {
public:
    using A::DoSomething;
    // …
}
```
```


q:
What are some important practices to follow when creating a .NET assembly that is going to be embedded to SQL Server 2005?

I am brand new to this, and I've found that there are significant method attributes like:

[SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "letter nchar(1)")]

I'm also looking for common pitfalls to avoid, etc.

[A]
Some that I remember:
Keep its usage to a minimum, only use it when T-SQL proved too complex.
Avoid pointers/cursors at all costs because a for loop is so easily abusable in CLR context.
Only use the SQL-Server native data types unless totally necessary.
Can't remember where I've found the information, but those are some that I do remember.
Basically, only use it when declarative T-SQL is too complex or is impossible to do (such as registry editing etc.).


q: I want to create cursor rsrc files on the Mac from png files. The application that uses the cursors requires it to be in a .rsrc format and I cannot change that. Does anybody know of any way I can create the cursor .rsrc files from png images.

[A]
Its been a long time since I've thought about MacOS resource forks. Are you using the classic MacOS (i.e. before MacOS X)?
As I recall,
ResEdit
was the application most often used to manipulate the resource fork of a classic Mac application. I know it can edit cursor resources, but I don't recall if it can read PNG files. You may need to convert the files to GIF.
ResEdit is a Classic MacOS application. MacOS X prior to 10.5 could run Classic apps in emulation, but in 10.5 this support has been removed. You'd need to find a system either running the classic MacOS directly, or running 10.4 with Classic installed.


q: I would like to have a Guile script, which implements functions, which output test result messages according to the TAP protocol.

[A]
The following script, to be named guiletap.scm, implements the frequently-needed functions for using the TAP protocol when running tests.
```
; Define functions for running Guile-written tests under the TAP protocol.
; Copyright © 2008 by Omer Zak
; Released under the GNU LGPL 2.1 or (at your option) any later version.
;;;
;;; To invoke it:
;;; (use-modules (guiletap))
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-module (guiletap))
(export plan)
(export ok)
(export bail_out)
(export diag)
(export is_ok)

(use-modules (ice-9 format))

; n is the number of tests.
(define plan
  (lambda (n) (display (format "1..~d~%" n))))

; n -        test number
; testdesc - test descriptor
; res -      result which is #f at failure, other at success.
(define ok
  (lambda (n testdesc res)
    (if (not res)(display "not "))
    (display (format "ok ~d - ~a~%" n testdesc))))

; testdesc - test descriptor
(define bail_out
  (lambda (testdesc)
    (display (format "Bail out! - ~a~%" testdesc))))

; diagmsg - diagnostic message
(define diag
  (lambda (diagmsg)
    (display (format "# ~a~%" diagmsg))))

; n -        test number
; testdesc - test descriptor
; expres -   expected test result
; actres -   actual test result
(define is_ok
  (lambda (n testdesc expres actres)
    (ok n testdesc (equal? expres actres))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; !!! TODO:
; !!! To be implemented also:
; plan_no_plan
; plan_skip_all [REASON]
;
; is RESULT EXPECTED [NAME]
; isnt RESULT EXPECTED [NAME]
; like RESULT PATTERN [NAME]
; unlike RESULT PATTERN [NAME]
; pass [NAME]
; fail [NAME]
;
; skip CONDITION [REASON] [NB_TESTS=1]
; Specify TODO mode by setting $TODO:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; End of guiletap.scm
```