q:
I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:

import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

class TestSequence(unittest.TestCase):
    def testsample(self):
        for name, a,b in l:
            print "test", name
            self.assertEqual(a,b)

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

The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?

[A]
This is called "parametrization".
There are several tools that support this approach. E.g.:
pytest's decorator
parameterized
The resulting code looks like this:
```
```
from parameterized import parameterized

class TestSequence(unittest.TestCase):
    @parameterized.expand([
        ["foo", "a", "a",],
        ["bar", "a", "b"],
        ["lee", "b", "b"],
    ])
    def test_sequence(self, name, a, b):
        self.assertEqual(a,b)
```
```
Which will generate the tests:
```
```
test_sequence_0_foo (__main__.TestSequence) ... ok
test_sequence_1_bar (__main__.TestSequence) ... FAIL
test_sequence_2_lee (__main__.TestSequence) ... ok

======================================================================
FAIL: test_sequence_1_bar (__main__.TestSequence)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in <lambda>
    standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)
  File "x.py", line 12, in test_sequence
    self.assertEqual(a,b)
AssertionError: 'a' != 'b'
```
```
For historical reasons I'll leave the original answer circa 2008):
I use something like this:
```
```
import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

class TestSequense(unittest.TestCase):
    pass

def test_generator(a, b):
    def test(self):
        self.assertEqual(a,b)
    return test

if __name__ == '__main__':
    for t in l:
        test_name = 'test_%s' % t[0]
        test = test_generator(t[1], t[2])
        setattr(TestSequense, test_name, test)
    unittest.main()
```
```


q: I'd like to render to svg data in a swf at runtime (not in Flex - not using degrafa) - how would I go about doing that?

[A]
The Ajaxian blog had a post about this today.
http://ajaxian.com/archives/the-state-of-svg-browser-support-using-flash-for-svg-in-internet-explorer

s: huggingface

c: devops

d: intermediate


q:
I'd like to add dvd burning functionality to my .Net app (running on Windows Server 2003), are there any good components available?  I've used the NeroCOM sdk that used to come with Nero but they no longer support the sdk in the latest versions of Nero.  I learned that Microsoft has created an IMAPI2 upgrade for Windows XP/2003 and there is an example project at CodeProject but not having used it myself I can't say how easy/reliable it is to use.

I'm not really worried about burning audio/video to DVD as this is for file backup purposes only.

[A]
At my last job I was tasked with finding a cross platform and preferably free way to write our application specific files to cd/dvd.  I quickly found that writing CD's wasn't hard on windows, but I couldn't write DVD's easily, and that only worked on windows.
I ended up writing a wrapper around
cdrecord
cdrecord is an open source project that builds easily with cygwin.  I would create a staging directory where I added the files that needed to be written, called mkisofs on that directory to make a cd iso, and then called cdrecord to burn the image.  This may not be the best solution if you have a strictly windows audience, but it was the only thing I could find that did window, Linux, and OS X.
Another option worht checking out is the
StarBurn SDK
, I download the trial and used it, it worked well, but in the end it wasn't free so it was too expensive for my purposes.


q:
In C# is there a shorthand way to write this:

public static bool IsAllowed(int userID)
{
    return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}

Like:

public static bool IsAllowed(int userID)
{
    return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}

I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.

[A]
I would encapsulate the list of allowed IDs as
data
not
code
. Then it's source can be changed easily later on.
```
```
List<int> allowedIDs = ...;

public bool IsAllowed(int userID)
{
    return allowedIDs.Contains(userID);
}
```
```
If using .NET 3.5, you can use
```
IEnumerable
```
instead of
```
List
```
thanks to extension methods.
(This function shouldn't be static. See this posting:
using too much static bad or good ?
.)


q:
I'm using Ruby on Rails for an internal site. Different users of the site have access to a wide variety of data and highly disparate perspectives of the data. Within those different classes of users, there needs to be levels of access. Within the levels of access I need to be able to add features from other classes of users.

In the released "Version 1.0" of the intranet site I have implemented the general classes of users. I am now needed to implement much finer-grained control of a users access.

The question is how?

What is the generally accepted practice for coding up user preferences (display the map (or not); access to this feature, but not this feature) without exploding the database schema and populating the view code with <% if feature_allowed %> tags everywhere.

[A]
Another totally different approach would be to use acts_as_authenticated and authorization plugins. The tables will be built by the plugins (ie
users
,
roles
and
roles
_users). From the doc:
The authorization plugin provides the following:
A simple way of checking authorization at either the class or instance method
level using #permit and #permit?
Authorization using roles for the entire application, a model class, or an
instance of a model (i.e., a particular object).
Some english-like dynamic methods that draw on the defined roles. You will be
able to use methods like "user.is_fan_of angelina" or "angelina.has_fans?",
where a 'fan' is only defined in the roles table.
Pick-and-choose a mixin for your desired level of database complexity. For
all the features, you will want to use "object roles table" (see below)


q: I know that if you have a loop that modifies the count of the items in the loop, using the NSEnumerator on a set is the best way to make sure your code blows up, however I would like to understand the performance tradeoffs between the NSEnumerator class and just an old school for loop

[A]
They are very similar. With Objective-C 2.0 most enumerations now default to
```
NSFastEnumeration
```
which creates a buffer of the addresses to each object in the collection that it can then deliver. The one step that you save over the classic for loop is not having to call
```
objectAtIndex:i
```
each time inside the loop. The internals of the collection you are enumerating implement fast enumeration with out calling
```
objectAtIndex:i method
```
.
The buffer is part of the reason that you can't mutate a collection as you enumerate, the address of the objects will change and the buffer that was built will no longer match.
As a bonus the format in 2.0 looks as nice as the classic for loop:
```
```
for ( Type newVariable in expression ) {
    stmts
}
```
```
Read the following documentaion to go deeper:
NSFastEnumeration Protocol Reference


q:
The leaving your wireless network open question reminded me of this.

I typically share the root drive on my machines across my network, and tie login authorization to the machines NT ID, so there is at least some form of protection.

My question, how easy is it to gain access to these drives for ill good? Is the authorization enough, or should I lock things down more?

[A]
I can't answer the main question, but do keep in mind that Windows, by default, is always sharing the roots of your drives. Try:
```
```
\\yourmachine\c$
```
```
(And then try not to freak out.)


q:
I have a very large code base that contains extensive unit tests (using CppUnit). I need to work out what percentage of the code is exercised by these tests, and (ideally) generate some sort of report that tells me on a per-library or per-file basis, how much of the code was exercised.

Here's the kicker: this has to run completely unnatended (eventually inside a continuous integration build), and has to be cross platform (well, WIN32 and *nix at least).

Can anyone suggest a tool, or set of tools that can help me do this? I can't change away from CppUnit (nor would I want to - it kicks ass), but otherwise I'm eager to hear any recommendations you might have.

Cheers,

[A]
Which tool should I use?
This
article describes
another developers frustrations searching for C++ code coverage tools.  The author's final solution was
Bullseye Coverage
.
Bullseye Coverage
features:
Cross Platform Support
(win32, unix, and embedded), (supports linux gcc compilers and MSVC6)
Easy to use
(up and running in a few hours).
Provides "best" metrics
: Function Coverage and Condition/Decision Coverage.
Uses source code instrumentation.
As for hooking into your continuous integration, it depends on which CI solution you use, but you can likely hook the instrumentation / coverage measurement steps into the make file you use for automated testing.
Testing Linux vs Windows?
So long as all your tests run correctly in both environments, you should be fine measuring coverage on one or the other.  (Though Bullseye appears
to support both platforms
).  But why aren't you doing continuous integration builds in both environments??  If you deliver to clients in both environments then you
need
to be testing in both.
For that reason, it sounds like you might need to have two continuous build servers set up, one for a linux build and one for a windows build.  Perhaps this can be easily accomplished with some virtualization software like
vmware
or
virtualbox
.  You may not need to run code coverage metrics on both OSs, but you should definitely be running your unit tests on both.


q: Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?

[A]
Disclaimer: I've never actually done this on a production site, but it looks like a reasonable way would be to use mock objects,
```
should_receive
```
and friends, and invoke methods on the observer directly
Given the following model and observer:
```
```
class Person < ActiveRecord::Base
  def set_status( new_status )
    # do whatever
  end
end

class PersonObserver < ActiveRecord::Observer
  def after_save(person)
    person.set_status("aha!")
  end
end
```
```
I would write a spec like this (I ran it, and it passes)
```
```
describe PersonObserver do
  before :each do
    @person = stub_model(Person)
    @observer = PersonObserver.instance
  end

  it "should invoke after_save on the observed object" do
    @person.should_receive(:set_status).with("aha!")
    @observer.after_save(@person)
  end
end
```
```


q:
How do I make diff ignore temporary files like foo.c~? Is there a configuration file that will make ignoring temporaries the default?

More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it...

EDIT: OK, the short answer is

diff -ruN -x *~ ...

Is there a better answer? E.g., can this go in a configuration file?

[A]
This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directory to keep the backup files in. There are different implementations for Emacs or XEmacs.
In GNU Emacs
```
(defvar user-temporary-file-directory
      (concat temporary-file-directory user-login-name "/"))
    (make-directory user-temporary-file-directory t)
    (setq backup-by-copying t)
    (setq backup-directory-alist
      `(("." . ,user-temporary-file-directory)
        (,tramp-file-name-regexp nil)))
    (setq auto-save-list-file-prefix
      (concat user-temporary-file-directory ".auto-saves-"))
    (setq auto-save-file-name-transforms
      `((".*" ,user-temporary-file-directory t)))
```
In XEmacs
```
(require 'auto-save)
    (require 'backup-dir)

    (defvar user-temporary-file-directory
      (concat (temp-directory) "/" (user-login-name)))
    (make-directory user-temporary-file-directory t)
    (setq backup-by-copying t)
    (setq auto-save-directory user-temporary-file-directory)
    (setq auto-save-list-file-prefix
         (concat user-temporary-file-directory ".auto-saves-"))
    (setq bkup-backup-directory-info
      `((t ,user-temporary-file-directory full-path)))
```
You can also remove them all with a simple find command
```
find . -name “*~” -delete
```
Note that the asterisk and tilde are in double quotes to stop the shell expanding them.
By the way, these aren't strictly
temporary
files. They are a backup of the previous version of the file, so you can manually "undo" your last edit at any time in the future.


q:
In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.

I need an auto-height for the object.  The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen.  I have a max height for the container DIV, so there would have to be minimum-height for the div.  I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.

My javascript isn't nearly as good as it should be.  Is there an easy script I could write that would do this for me?

Edit:
The DIV houses a control that does it's own overflow handling (implements its own scroll bar).

[A]
What should happen in the case of overflow?  If you want it to just get to the bottom of the window, use absolute positioning:
```
```
div {
  position: absolute;
  top: 300px;
  bottom: 0px;
  left: 30px;
  right: 30px;
}
```
```
This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom.  Add an
```
overflow:auto;
```
to handle cases where the content is larger than the div.
Edit: @Whoever marked this down, an explanation would be nice... Is something wrong with the answer?


q: I'm using the ASP.NET Login Controls and Forms Authentication for membership/credentials for an ASP.NET web application.  It keeps redirecting to a Login.aspx page at the root of my application that does not exist.  My login page is within a folder.

[A]
I found the answer at
CoderSource.net
.  I had to put the correct path into my web.config file.
```
```
<?xml version="1.0"?>
<configuration>
    <system.web>
        ...
        <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
        <authentication mode="Forms">
            <forms loginUrl="~/FolderName/Login.aspx" />
        </authentication>
        ...
    </system.web>
    ...
</configuration>
```
```


q: I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?

[A]
Probably using the
```
onpaste
```
event, and either
```
return false
```
from it or use
```
e.preventDefault()
```
on the Event object.
Note that
```
onpaste
```
is
non standard
, don't rely on it for production sites, because it will not be there forever.
```
```
$(document).on("paste",function(e){
  console.log("paste")
  e.preventDefault()
  return false;
})
```
```


q:
I would like to extend some existing applications' drag and drop behavior, and I'm wondering if there is any way to hack on drag and drop support or changes to drag and drop behavior by monitoring the app's message loop and injecting my own messages.

It would also work to monitor for when a paste operation is executed, basically to create a custom behavior when a control only supports pasting text and an image is pasted.

I'm thinking Detours might be my best bet, but one problem is that I would have to write custom code for each app I wanted to extend.  If only Windows was designed with extensibility in mind!

On another note, is there any OS that supports extensibility of this nature?

[A]
With jQuery newer than 1.2 you can use
JSONP


q:
Would it be possible to print Hello twice using single condition?

if  "condition"
  printf ("Hello");
else
  printf("World");

[A]
The
```
if
```
statement executes one or the other of the controlled statements (both
```
printf
```
in your example). No matter what you use for
```
condition
```
, that snippet will either print "Hello", or "World", but never both.
Edit: Okay, so it's a trick question and you can put whatever you like in the condition (including a call to an entire other function that does anything you want). But that's hardly interesting. I can't believe I got downmodded for giving a correct answer.


q: How can you implement trackbacks on a custom-coded blog (written in C#)?

[A]
If you're custom coding your own blog you have too much time on your hands.  Start with something like
dasBlog
or
SubText
and customize that to your needs.  Then you get trackbacks for free.


q:
Winform on CF is a bit heavy, initialising a lot of windows handles takes serious time and memory. Another issue is the lack of inbuilt double buffering and lack of control you have over the UI rendering means that during processor intensive operations the UI might leave the user staring at a half rendered screen. Nice!

To alleviate this issue I would seek a lightweight control framework, is there one kicking about already or would one have to homebrew?

By lightweight I mean a control library that enables one to fully control painting of controls and doesn't use many expensive windows handles.

NOTE: Please don't suggest that I am running too much on the UI thread. That is not the case.

[A]
Actually, you can override the paint event.
And the idea is that you offload long-running operations to a separate thread.  That's no different from any other event-driven framework, really.
Anything
that relies on a handling a Paint event is going to be susceptible to that.
Also, there's no system that lets you determine when the paint event is raised. That kind of event is generally raised by the window manager layer, which is outside of the application (or even the framework). You can handle the event yourself and just do no work some of the time, but I wouldn't recommend it.


q:
Assuming such a query exists, I would greatly appreciate the help.

I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database.  My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database.

[A]
```
```
select * from information_schema.tables
where table_type = 'view'
```
```


q:
Imagine you homebrew a custom gui framework that doesn't use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer.

So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the InitialiseComponent() method?


q:
Within an application, I've got Secret Keys uses to calculate a hash for an API call.  In a .NET application it's fairly easy to use a program like Reflector to pull out information from the assembly to include these keys.

Is obfuscating the assembly a good way of securing these keys?

[A]
Probably not.
Look into cryptography and Windows' built-in information-hiding mechanisms (DPAPI and storing the keys in an ACL-restricted registry key, for example). That's as good as you're going to get for security you need to keep on the same system as your application.
If you are looking for a way to stop someone physically sitting at the machine from getting your information, forget it. If someone is determined, and has unrestricted access to a computer that is not under your control, there is no way to be 100% certain that the data is protected under all circumstances. Someone who is determined will get at it if they want to.


q:
I have a JavaScript method that I need to run on one of my pages, in particular, the onresize event.

However, I don't see how I can set that event from my content page.  I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page.

Any help would be appreciated.

[A]
Place the following in your content page:
```
```
<script type="text/javascript">

// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
    if(element.attachEvent) {
       element.attachEvent(eventToHandle, eventHandler);
    } else if(element.addEventListener) {
       element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false);
    } else {
    element[eventToHandle] = eventHandler;
  }
}

attachEventHandler(window, "onresize", function() {
    // the code you want to run when the browser is resized
});

</script>
```
```
That code should give you the basic idea of what you need to do. Hopefully you are using a library that already has code to help you write up event handlers and such.


q:
When trying to execute from within Visual Studio 2008 your application and you get the (uninformative) message "The operation could not be completed".

The solution to this is to turn off the "Visual Studio Hosting Process".

The problem with turning off this "hosting process" is that all the "run and rewrite" functionality is no longer available. OK, so this isn't a big deal, but I'm always getting this message no matter what machine I use (and it might be nice once in a while to use the rewrite and execute functionality).

Am I doing something wrong? How come this "feature" within VS seems to complain so readily? Do other people have success with enabling the hosting process and making use of it?

[A] I honestly have never seen this message and I work with Visual Studio for at least 8 hours a day.  Is this reproducible on other machines?  If so is there anything weird or abnormal in your code that could cause this to crash?


q:
I'm considering developing a website similar to stackoverflow, but the answers may also consist of drawings (schematics, in this case).  I want to have an area in the answer form where they can make this schematic without requiring special plugins, etc.

Are we to the point where SVG has or should have critical mass soon (1-2 years) such that designing a website where script-run SVG as a primary feature is reasonable (ie, requiring Firefox or another SVG/AJAX compliant browser)?

What are some good resources for learning cross platform SVG scripting (likely in javascript)?

-Adam Davis

[A]
1/ probably never - if IE wanted to add it, then I would have though it would have done so by now; but there are workarounds using
SilverLight
and
Gecko
to provide rendering. On the other hand, there are cross-browser graphics APIs available. I've done largish front ends using XULRunner and SVG, but nothing on the web which had to cater for IE.
2/ The two I referred to most often were the
SVG pages on mozilla.org
and this
SVG DOM reference
. All of my SVG links are here on
delicious
There's one existing editor at
http://www.bpel4chor.org/editor/
; also if all you want is schematics where all arcs are on a grid, you can do that quite well using divs and images without SVG. Or you could just go the
lo-fi route


q:
I using SharePoint Designer to create a workflow. I'm trying to get at a sub-folder in a document library in the "Define Workflow Lookup" dialog.  There are two issues with this:

I can't look up items by URL Path. If I look up by Title, I can
output the URL Path, but selecting by path doesn't work.  What
fields can/can't I use?

I can't get at any sub-folders.  I can get at the top-level folder,
but the sub-folders don't seem to be available. Noticed the same
things is true when looking at the data for a document library in
the "Data Source Library" in Designer.

To clarify, the workflow is on a different list, not on the document library.

UPD: Also, I know how to do this through the object model, the question is how to do it in SharePoint Designer without deploying code to the server.

[A]
I really don't have much experience with Sharepoint, but I thought I could at least provide
some
answer - even if it's the wrong one.
From another dev I've spoken to it sounds like it's tough to get into any subfolders, so you might need to look at making your own custom workflow.
Maybe something like LINQ to Sharepoint might be able to help you with actually getting in and enumerating the subfolders and getting to the data that you need?
LINQ to Sharepoint


q: What's the best lifetime model for a DataContext? Should I just create a new one whenever I need it (aka, function level), should I keep one available in each class that would use it (class level), or should I create a static class with a static DataContext (app-domain level)? Are there any considered best practices on this?

[A]
I think Jeff Atwood talked about this in the
Herding Code podcast
, when he was questioned about the exact same thing. Listen to it towards the last 15-20 minutes or so.
I think in SO, the datacontext is created in the Controller class. Not sure about a lot of details here. But that's what it looked like.


q:
After reading Jeff's blog post on Protecting Your Cookies: HttpOnly. I'd like to implement HttpOnly cookies in my web application.

How do you tell tomcat to use http only cookies for sessions?

[A]
For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report
Need to add support for HTTPOnly session cookie parameter
. A somewhat involved work-around for now can be found
here
, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.
To summarize the work-around, it involves downloading the 5.5
source
, and then change the source in the following places:
org.apache.catalina.connector.Request.java
```
```
//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}
```
```
org.apache.catalina.connectorResponse.addCookieInternal
```
```
public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}
```
```


q:
I am using Hibernate in a Java application to access my Database and it works pretty well with MS-SQL and MySQL. But some of the data I have to show on some forms has to come from Text files, and by Text files I mean Human-Readable files, they can be CSV, Tab-Delimited, or even a key, value pair, per line since my data is as simple as this, but my preference of course is XML files.

My question is: Can I use hibernate to read those files using HQL, Query , EntityManager and all those resources Hibernate provides me to access files. Which file format should I use and How I configure My persistence.xml file to recognize files as Tables?

[A]
Hibernate is written against the JDBC API. So, you need a JDBC driver that works with the file format you are interested in. Obviously, even for read-only access, this isn't going to perform well, but it might still be useful if that's not a high priority. On a Windows system, you can set up ODBC datasources for delimited text files, Excel files, etc. Then you can set up the JdbcOdbcDriver in your Java application to use this data source.
For most of the applications I work on, I would not consider this approach; I would use an import/export mechanism to convert from a real database (even if it's an in-process database like Berkeley DB or Derby) to the text files. Yes, it's an extra step, but it could be automated, and the performance isn't likely to be much worse than trying to use the text files directly (it will likely be much better, overall), and it will be more robust and easy to develop.


q: Is there a way to call out from a TSQL stored procedure or function to a webservice?

[A]
Not in T-SQL code itself, but with SQL Server 2005 and above, they've enabled the ability to write CLR stored procedures, which are essentially functions in .NET code and then expose them as stored procedures for consumption. You have most of the .NET framework at your fingertips for this, so I can see consumption of a web service possible through this.
It is a little lengthy to discuss in detail here, but here's a link to an
MSDN article
on the topic.


q:
Does anyone have a definitive answer to whether Sql Server Management Objects is compatible with Sql Server 7.0?
The docs state:

Because SMO is compatible with SQL Server version 7.0, SQL Server 2000, SQL Server 2005, and SQL Server 2008, you easily manage a multi-version environment.

But trying to connect to a Sql 7 instance gets me:

"This SQL Server version (7.0) is not supported."

Has anyone been successful in getting these 2 to play nice?

[A]
you can use SMO to connect to SQL Server versions 7, 2000, and 2005, but SMO does not support databases set to compatibility levels 60, 65, and 70.
for SQL Server 7.0 the compatibility level is 70
Obviously this is conflicting information...I assume if your compatibility level of your DB is 70 you can not connect.
To check run: EXEC sp_dbcmptlevel '
databasename
'
Looking through this link
, it seems you might be able to change the compatibility level by running this:
EXEC sp_dbcmptlevel '
databasename
', 80
Obviously make a back up before changing anything.


q:
Is it possible to use a flash document embedded in HTML as a link?

I tried just wrapping the object element with an a like this:

<a href="http://whatever.com">
    <object ...>
        <embed ... />
    </object>
</a>

In Internet Explorer, that made it show the location in the status bar like a link, but it doesn't do anything.

I just have the .swf file, so I can't add a click handler in ActionScript.

[A]
Though the object really should respond to being wrapped in an a href tag, you could open the swf in vim and just throw in an
```
_root.onPress=function(){getURL("http://yes.no/");};
```
or if it's AS3, something like
```
_root.addEventHandler(MouseEvent.PRESS, function (e:event) {getURL("http://yes.no/");});
```
But if editing the swf is your route, you'd likely have more success with
a tool for the purpose
.


q: I'm starting a new web project and I am considering two presentation frameworks. I am thinking either about ASP.NET MVC or Silverlight. I would tend toward Silverlight since I'm quite experienced .NET developer while I have just a basic knowledge of ASP.NET controls.

[A]
It's hard to recommend one over the other without knowing what your application is.  Whatever you do decide, make sure you keep your target audience in mind; not everyone is going to have Silverlight installed on their computers.
Personally, unless I was designing an incredibly interactive and beautiful web app, I would go with ASP.NET (with or without the MVC framework) if only for the fact that there is a
ton
of reference material for it while Silverlight is still relatively new territory.


q:
Right now, I keep all of my projects on my laptop. I'm thinking that I shouldn't do this, but instead use a version control system and check them in/out from an external hosting repository (Google Code, SourceForge, etc). I see several benefits here - first, I don't have to worry about losing my code if my computer crashes and burns or my external HDD crashes and burns; second, I can share my code with the world and perhaps even get more help when I need it.

Is this a good idea? If so, what are some other project hosts that I should investigate (other than Google Code and SourceForge)?

[A]
Assembla
is
awesome.
EDIT: Yes, this is a good idea - I used to use a personal copy of
Vault
and found it was more than I cared to manage (in case my server went down or hard drive crashed - not only was it painful to worry about losing and backing up data, but the downtime). Of course, it doesn't hurt to have your own backup as well. Cover all your bases!


q:
Inspired by this CodingHorror article, "Protecting Your Cookies: HttpOnly"

How do you set this property? Somewhere in the web config?

[A]
With props to Rick (second comment down in the blog post mentioned), here's the
MSDN article
on httpOnlyCookies.
Bottom line is that you just add the following section in your system.web section in your web.config:
```
```
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
```
```


q:
I want to check out all files in all subdirectories of a specified folder.

(And it is painful to do this using the GUI, because there is no recursive checkout option).

[A]
```
```
cleartool find somedir -exec "cleartool checkout -nc \"%CLEARCASE_PN%\""
```
```
Also an article "
ClearCase: The ten best scripts
" might be helpful


q:
Obviously, that's 64-bit windows.

Also, what's the maximum amount of memory a single 64-bit process can use?
I was kind of counting on using it all...
(Yes, I know what I'm doing, please don't tell me that if I need that much RAM i must be doing something wrong)

Also, is this the same for a .Net 2.0 process? Or is there a lower limit for .Net?

[A] Something we found out recently: with MySQL running on Win32, you can only use up to 2GB per process. On Win64, the memory is not managed as well and a single MySQL instance will run your memory into the ground. Ours used up all 16GB we have. So regarding how much memory 1 64-bit process can use: the answer is however much the OS allows.


q: I assume it doesn't connect to anything (other than the satelite I guess), is this right? Or it does and has some kind of charge?

[A]
There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing.  Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.
If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.
Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.
Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.


q:
As you develop an application database changes inevitably pop up.  The trick I find is keeping your database build in step with your code.  In the past I have added a build step that executed SQL scripts against the target database but that is dangerous in so much as you could inadvertanly add bogus data or worse.

My question is what are the tips and tricks to keep the database in step with the code?  What about when you roll back the code?  Branching?

[A]
Version numbers embedded in the database are helpful.  You have two choices, embedding values into a table (allows versioning multiple items) that can be queried, or having an explictly named object (such as a table or somesuch) you can test for.
When you release to production, do you have a rollback plan in the event of unexpected catastrophe?  If you do, is it the application of a schema rollback script?  Use your rollback script to rollback the database to a previous code version.


q:
I'm a PHP developer, and I use the MVC pattern and object-oriented code. I really want to write applications for the iPhone, but to do that I need to know Cocoa, but to do that I need to know Objective-C 2.0, but to do that I need to know C, and to do that I need to know about compiled languages (versus interpreted).

Where should I begin?
Do I really need to begin with plain old "C", as Joel would recommend?

Caveat: I like to produce working widgets, not elegant theories.

[A]
I think starting with C would be a smart thing to do. After all, Objective-C is C language with some extensions.
To develop in Cocoa you are required to know well how pointers and memory allocation work (there's no garbage collection on the iPhone), plus you will have to use some standard C libraries,
because a lot of the frameworks that are used to develop for the iPhone are C libraries
not Cocoa libraries. Take for example CoreGraphics, the library you have to use to draw on the screen on the iPhone. That's a C framework, meaning that it is not written in Objective-C.
Of course after learning C to a modest level, you could start reading about Objective-C and Cocoa, and in that case I would start with the
Objective-C language specification
(link to PDF)
and the Aaron Hillegas book on Cocoa.


q:
I'm working on a visual studio 2005 vb.net windows forms project that's been around for several years.  It's full of default textboxes, labels, dropdowns, datagrids, datetime pickers -- all the standard stuff.  The end result is a very gray, old-looking project.

What would be the best approach to making this project look fresh and snazzy?  I'd rather not rewrite the entire solution with all brand new forms objects, but would that be avoidable?

[A]
This depends on how the existing "gray old looking" project is structured in terms of code.  For example, is data access code separated from the UI in a Data Access Layer, is the business logic in a Business Logic Layer?  If yes, then cleaning the UI for a snazzy look should be relatively simple.
If everything is all there in the "Button Click" event, then a rewrite is the only way in my humble opinion as otherwise it will just be too time consuming trying to work with the existing code base.
Cheers


q:
How would I change the initial templates created by Xcode when creating a new Cocoa Class.

I am referring to the comments and class name created when using Xcode's new class wizard.

[A]
You wouldn't change the existing templates.  In other words, don't
modify
anything under the
```
/Developer
```
hierarchy (or wherever you installed your developer tools).
Instead, clone the templates you want to have customized variants of.  Then change their names and the information in them.  Finally, put them in the appropriate location in your account's
```
Library/Application Support
```
folder, specifically:
File templates:
```
~/Library/Application Support/Developer/Shared/Xcode/File Templates/
```
Target templates:
```
~/Library/Application Support/Developer/Shared/Xcode/Target Templates/
```
Project templates:
```
~/Library/Application Support/Developer/Shared/Xcode/Project Templates/
```
That way they won't be overwritten when you install new developer tools, and you can tweak them to your heart's content.
Update
For newer versions of Xcode the updated path will be:
```
~/Library/Developer/Xcode/Templates/File Templates/Source
```


q:
I would like to add the following MIME type to a site run by Apache:

<mime-mapping>
  <extension>jnlp</extension>
  <mime-type>application/x-java-jnlp-file</mime-type>
</mime-mapping>

That is the Tomcat format.

I'm on a shared host, so I can only create an .htaccess file. Would someone please specify the complete contents of such a file?

[A]
You should be able to just add this line:
```
```
AddType application/x-java-jnlp-file     .jnlp
```
```


q:
Using C# and System.Data.SqlClient, is there a way to retrieve a list of parameters that belong to a stored procedure on a SQL Server before I actually execute it?

I have an a "multi-environment" scenario where there are multiple versions of the same database schema. Examples of environments might be "Development", "Staging", & "Production". "Development" is going to have one version of the stored procedure and "Staging" is going to have another.

All I want to do is validate that a parameter is going to be there before passing it a value and calling the stored procedure. Avoiding that SqlException rather than having to catch it is a plus for me.

Joshua

[A]
```
```
SqlCommandBuilder.DeriveParameters(command)
```
```
This statement does what I need it to.
Here is a full code sample for the way I solved this problem.
```
```
Public Sub GetLogEntriesForApplication(ByVal settings As FilterSettings,
                              Optional ByVal RowGovernor As Integer = -1)

    Dim command As New SqlCommand("GetApplicationActions",
        New SqlConnection(m_environment.LoggingDatabaseConnectionString))
    Dim adapter As New SqlDataAdapter(command)

    Using command.Connection

        With command

            .Connection.Open()
            .CommandType = CommandType.StoredProcedure

            SqlCommandBuilder.DeriveParameters(command)

            With .Parameters

                If settings.FilterOnLoggingLevel Then
                    If .Contains("@loggingLevel") Then
                        .Item("@loggingLevel").Value = settings.LoggingLevel
                    End If
                End If

                If settings.FilterOnApplicationID Then
                    If .Contains("@applicationID") Then
                        .Item("@applicationID").Value = settings.ApplicationID
                    End If
                End If

                If settings.FilterOnCreatedDate Then
                    If .Contains("@startDate") Then
                        .Item("@startDate").Value = settings.CreatedDate.Ticks
                    End If
                End If

                If settings.FilterOnEndDate Then
                    If .Contains("@endDate") Then
                        .Item("@endDate").Value = settings.EndDate.Ticks
                    End If
                End If

                If settings.FilterOnSuccess Then
                    If .Contains("@success") Then
                        .Item("@success").Value = settings.Success
                    End If
                End If

                If settings.FilterOnProcess Then
                    If settings.Process > -1 Then
                        If .Contains("@process") Then
                            .Item("@process").Value = settings.Process
                        End If
                    End If
                End If

                If RowGovernor > -1 Then
                    If .Contains("@topRows") Then
                        .Item("@topRows").Value = RowGovernor
                    End If
                End If

            End With

        End With

        adapter.TableMappings.Clear()
        adapter.TableMappings.Add("Table", "ApplicationActions")
        adapter.TableMappings.Add("Table1", "Milestones")

        LogEntries.Clear()
        Milestones.Clear()
        adapter.Fill(m_logEntryData)

    End Using

End Sub
```
```


q: I run Flex Builder 3 on a mac and as my project grows - the compile time gets longer and longer and longer.  I am using some SWC's and there is a fair amount of code but it shouldn't take minutes to build and crash daily should it?

[A]
You may want to explore the command-line compiler found in the Flex SDK,
```
mxmlc
```
. As I recall, Flex Builder 3 seems to hide all the compiler details, but perhaps there are arguments you can append that will help you speed up the compilation.
For example, you may want to set
```
optimize=false
```
which will skip the step of optimizing the bytecode (perhaps reducing compilation time)?  This of course comes at the price of performance and file size of the actual application.
More documentation on
```
mxmlc
```
can be found at:
http://livedocs.adobe.com/flex/3/html/compilers_13.html
.
Good luck!


q:
I am currently using the following command to upload my site content:

scp -r web/* user@site.com:site.com/

This works great except that the .htaccess file is not sent. Presumably, this is because it's hidden.

I have tried adding a second line to send the file explicitely:

scp -r web/.htaccess user@site.com:site.com/.htaccess

This works great except now I have to enter my password twice.

Any thoughts on how to make this deploy with only 1 or 0 entries of my password?

[A]
Just combine the two commands:
```
```
scp -r web/* web/.htaccess user@site.com:site.com/
```
```
If you want 0 entries of your password you can set up
public key authentication
for ssh/scp.


q:
I'm writing a PHP script that involves scraping web pages. Currently, the script analyzes the page line by line, but it breaks if there is a tag that spans multiple lines, like

<img src="example.jpg"
alt="example">

If worse comes to worst, I could possibly preprocess the page by removing all line breaks, then re-inserting them at the closest >, but this seems like a kludge.

Ideally, I'd be able to detect a tag that spans lines, conjoin only those to lines, and continue processing.

So what's the best method to detect this?

[A]
Well, this doesn't answer the question and is more of an opinion, but...
I think that the best scraping strategy (and consequently, to eliminate this problem) is not to analyze an HTML line by line, which is unnatural to HTML, but to analyze it by its natural delimiter: <> pairs.
There will be two types of course:
Tag elements that are immediately closed, e.g., < br />
Tag elements that need a separate closing tag, e.g., < p > text < /p >
You can immediately see the advantage of using this strategy in the case of paragraph(p) tags: It will be easier to parse mutiline paragraphs instead of having to track where the closing tag is.


q:
I have an application which really should be installed, but does work fine when deployed using JNLP.

However, it would seem that some Java functions such as Runtime.exec don't work using the default security options.

I would like to therefore disable UI functionality that relies upon such functions.

So my question is, how do I detect at runtime whether certain functions are available or not?

The case study, here of course, is Runtime.exec.

[A]
You want to ask to the
SecurityManager
if you have Exec right with the checkExec method.


q:
I'm planning on doing more coding from home but in order to do so, I need to be able to edit files on a Samba drive on our dev server. The problem I've run into with several editors is that the network latency causes the editor to lock up for long periods of time (Eclipse, TextMate). Some editors cope with this a lot better than others, but are there any file system or other tweaks I can make to minimize the impact of lag?

A few additional points:

There's a policy against having company data on personal machines, so I'd like to avoid checking out the code locally.

The mount is over a PPTP VPN connection.

Mounting to Linux or OS X client

[A]
Use a source control system — Subversion, Perforce, Git, Mercurial, Bazaar, etc. — so you're never editing code on a shared server.  Instead you should be editing a local work area and committing changes to a repository located on the network.
Also, convince your company to adapt their policy such that company code is allowed on personal machines
if
it's on an encrypted volume.  Encrypted disk images that you can use for this are
trivial
to create using Disk Utility, and can use strong cryptography.  You can get even more security by not storing your encryption passphrase in your keychain, and instead typing it every time you mount the encrypted volume; this means that even if your local user account is compromised, as long as you don't have the volume mounted, nobody else will be able to mount it.
I did this all the time when I was consulting and none of my clients — some of whom had similar rules about company code — ever had a problem with it once I explained how things worked.  (I think some of them even started using encrypted disk images even within their offices.)


q:
In my (PHP) web app, I have a part of my site that keeps a history of recent searches. The most recent queries get shown in a side box. If the query text is too long, I truncate it and show ellipses. Eg: "My very long query is..."

Currently, I truncate after a certain number of characters. Since the font is not monotype, a query of all I's is more narrow than a query of all W's. I'd like them to all be about the same width prior to the ellipses. Is there a way to get the approximate width of the resulting string so that the ellipses for any given string will occur in about the same number of pixels from the beginning? Does CSS have a way? Does PHP? Would this be better handled by JavaScript?

[A]
Does CSS have a way?
No
Does PHP?
No
-
To do that you'd have to get the font metrics for each character, and apply them to all your letters in your string. While you could do this by using a drawing/rendering library like ImageMagick on the server, it wouldn't really work because different browser on different OS's render fonts differently.
Even if it did work, you wouldn't want to do it, because it would also take forever to render. Your server would be able to push 1 page per second (if that) instead of several thousand.
If you can live without the trailing ..., then you can nicely fake it using
```
div
```
tags and css
```
overflow: hidden
```
, like this:
```
```
.line_of_text {
    height:1.3em;
    line-height:1.3em;
    overflow:hidden;
}

 Some long text which will arbitrarily be cut off at whatever word fits best

```
```


q:
Today I was listening to the Hanselminutes show about .NET 3.5 SP1...What's inside, and they twice mentioned the Office 2007-like Ribbon control that is included in Visual Studio 2008 Service Pack 1.

I am very interested about this, as I was previously looking at purchasing this from a 3rd party vendor (likely DevComponent's DotNetBar).  However, I did some research this morning and have found nothing about this control being included for use with C# and WPF.  Does anyone know more about the included Ribbon control and whether or not it is available for C# or WPF?

[A]
Yeah I did a double-take when I heard them say that too.
The ribbon control, along with a DatePicker and DataGrid, are being developed out of band
over here
on CodePlex. I'm not sure why Carl and Scott were suggesting that it was part of the SP1 release.
Vincent Sibal
posts about DataGrid (which is available already in some form) on his blog.


q: Whilst starting to learn lisp, I've come across the term tail-recursive. What does it mean exactly?

[A]
I'm not a Lisp programmer, but I think
this
will help.
Basically it's a style of programming such that the recursive call is the last thing you do.


q:
I have the following textarea in a table:

<table width="300"><tr><td>

<textarea style="width:100%">
longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring
</textarea>

</td></tr></table>

With a long string in the textarea, the textarea stretches out to accommodate it in one line in IE7, but retains its 300px width in other browsers.

Any ideas as to how to fix this in IE?

[A]
did you try...
```
overflow: hidden;
```
??
I'm not sure if it should be in the table of the textarea... experiment a bit


q:
What is the minimum I need to add to a .NET 2.0 WebSite's web.config to make it .NET 3.5?

Visual Studio adds all the config sections and script handlers, but if you aren't using those are they are really necessary?

Is there a command line tool to "upgrade" a .NET 2.0 web.config to 3.5?

[A]
There is a good description of the 3.5 web.config available here:
https://web.archive.org/web/20211020153237/https://www.4guysfromrolla.com/articles/121207-1.aspx
The assemblies and config sections are important because they tell the runtime to use the new 3.5 dlls instead of the 2.0 dlls
The
codedom
section tells the compiler to use 3.5.
If you're not using ASP.Net Ajax you can probably skip the rest.  I've never tested that though.


q:
Could someone tell me what the units the SetTimeout(int) method in the ICriteria interface uses?

Is it milliseconds, seconds, minutes or other?

[A]
I think it's seconds.  The NHibernate API closely mirrors Hibernate Core for Java, where the
Criteria.setTimeout(int)
method uses seconds as the units (see also
Statement.setQueryTimeout(int)
).
Also, after looking at some NHibernate source, it appears that it's using that value to set the timeout for the underlying ADO.NET query, which uses seconds.


q:
Assume that I have a field called price for the documents in Solr and I have that field faceted. I want to get the facets as ranges of values (eg: 0-100, 100-500, 500-1000, etc). How to do it?

I can specify the ranges beforehand, but I also want to know whether it is possible to calculate the ranges (say for 5 values) automatically based on the values in the documents?

[A]
There may well be a better Solr-specific answer, but I work with straight Lucene, and since you're not getting much traction I'll take a stab. There, I'd create a populate a
```
Filter
```
with a
```
FilteredQuery
```
wrapping the original
```
Query
```
. Then I'd get a
```
FieldCache
```
for the field of interest. Enumerate the hits in the filter's bitset, and for each hit, you get the value of the field from the field cache, and add it to a SortedSet. When you've got all of the hits, divide the size of the set into the number of ranges you want (five to seven is a good number according the user interface guys), and rather than a single-valued constraint, your facets will be a range query with the lower and upper bounds of each of those subsets.
I'd recommend using some special-case logic for a small number of values; obviously, if you only have four distinct values, it doesn't make sense to try and make 5 range refinements out of them. Below a certain threshold (say 3*your ideal number of ranges), you just show the facets normally rather than ranges.


q:
I would like to retrieve the ethernet address of the network interface that is used to access a particular website.

How can this be done in Java?

Solution Note that the accepted solution of getHardwareAddress is only available in Java 6. There does not seem to be a solution for Java 5 aside from executing i(f|p)confing.

[A]
You can get the address that connects to your ServerSocket using
http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getInetAddresses()
However if your client is connecting via a NAT, then you will get the address of the router and NOT the Ethernet address. If it is on your local network (via a hub/switch, no router with NAT) the it wil work as intended.


q:
I've switched over to a Mac recently and, although things have been going quite well, the very different text-editing behaviours across applications is driving me insane.

Home, End, Page Up, Page Down, Apple-arrow, Ctrl-arrow, alt-arrow etc. quite often do different things depending on the application.

Is there a way to standardise this behaviour?

[A]
There are standards, but they are not based around what you're used to from windows. It drove me mad until I got over myself and decided to learn what the actual standards were. Since then I've been sold.
The ones I use:
Command
-
Left
/
Right
- Jump to start/end of line
Can also do this with
ctrl
-
a
/
e
which is great if you're used to ssh
Command
-
Up
/
Down
- Jump to top/bottom of text field or document
Option
-
Left
/
Right
- Jump to start/end of word or previous/next word
These basically replace
home
/
end
/
pgup
/
pgdown
, and
ctrl
-
left
/
right
from the windows world.
I find this to be a massive win due to the fact I have a macbook pro and almost no laptops have proper
home
/
end
/
pgup
/
pgdown
keys - not needing them in OSX is a godsend
Here's a big list of the rest of them


q: How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.

[A]
I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:
PySizer, "a memory profiler for Python," found at
http://pysizer.8325.org/
.  However the page seems to indicate that the project hasn't been updated for a while, and refers to...
Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at
http://guppy-pe.sourceforge.net/#Heapy
.
Hope that helps.


q:
How can you allow a PHP script to write to a file with high-security restrictions, such as only allowing a single user to write to it?

The difficulty seems to be that a PHP script is running as a low-permissions user (maybe apache, or www, or nobody?), and even if I chown apache the_writable_file, the directory it's in might not be writable for the low-level user.  In general, what's the usual way that PHP can work with local files in a secure way?

[A]
Sure,
```
chgrp apache the_writable_file
```
and
```
chmod g+w the_writable_file
```
.  After that, only your secure user and the apache user will be able to write to the file.  Since the apache user is typically forbidden from logging in, you only have to worry about web users writing to your secure file using through the http daemon.


q: A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether.  What can said about this rumor?

[A] I've used it in several applications and have never had nor heard of threading being anything other than 100% reliable, as long as you know its limits.  You can't spawn 1000 threads at the same time and expect your program to run properly on Windows, however you can easily write a worker pool and just feed it 1000 operations, and keep everything nice and under control.


q:
Given the key for some registry value (e.g. HKEY_LOCAL_MACHINE\blah\blah\blah\foo) how can I:

Safely determine that such a key exists.

Programmatically (i.e. with code) get its value.

I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly.

Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is.

[A]
RegQueryValueEx
This gives the value if it exists, and returns an error code ERROR_FILE_NOT_FOUND if the key doesn't exist.
(I can't tell if my link is working or not, but if you just google for "RegQueryValueEx" the first hit is the msdn documentation.)


q: What's the best way to specify a proxy with username and password for an http connection in python?

[A]
This works for me:
```
```
import urllib2

proxy = urllib2.ProxyHandler({'http': 'http://
username:password@proxyurl:proxyport'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)

conn = urllib2.urlopen('http://python.org')
return_str = conn.read()
```
```


q: I've been given a job of 'translating' one language into another. The source is too flexible (complex) for a simple line by line approach with regex. Where can I go to learn more about lexical analysis and parsers?

[A]
I've recently been working with
PLY
which is an implementation of lex and yacc in Python. It's quite easy to get started with it and there are some simple examples in the documentation.
Parsing can quickly become a very technical topic and you'll find that you probably won't need to know all the details of the parsing algorithm if you're using a parser builder like PLY.


q:
<xsl:for-each select="./node [position() &lt;= (count(*) div 2)]">
    <li>foo</li>
</xsl:for-each>
<xsl:for-each select="./node [count(*) div 2 &lt; position()]">
    <li>bar</li>
</xsl:for-each>

My list has 12 nodes, but the second list is always 8 and the first is always 4. What's wrong with my selects?

[A]
I'm not at all sure, but it seems to me that
```
count(*)
```
is not doing what you think it is.  That counts the number of children of the current node, not the size of the current node list.  Could you print it out to check that it's 8 or 9 instead of 12?
Use
```
last()
```
to get the context size.


q: I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.

[A]
I found a possible answer here:
http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
From the article:
```
```
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
```
```
Edit:
But my trusty compiler says,
```
XslTransform
```
is obsolete: Use
```
XslCompiledTransform
```
instead:
```
```
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
```
```


q:
MS CRM Dynamics 4.0 incorporates the MS WF engine.  The built in designer allows the creation of sequential workflows whos activities have native access to CRM entities.

Is it possible to:

Create a state machine workflow
outside of CRM (i.e. in visual studio) and import it into CRM?

Have this workflow access the CRM
entities?

[A]
I don't know the answer to your specific question, but hopefully this information will point you in the right direction.
The "native" format for WF workflows is ".xoml" files.  These are basically identical to XAML files, and both are nothing more than generic persistence formats for a .NET object tree.  If you can access the saved data that is output by the Dynamics designer, it should be in the same format.  If it is, you should be able to open it from the Visual Studio designer.
The key here is that CRM undoubtedly defines its own set of custom activities that you'll need to be able to reference from within the alternate designer.  With any luck, these will be in assemblies with obvious names and/or in the GAC.


q:
I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.

To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that.

[A]
Using the
Maven Dependency Plugin
:
```
```
mvn dependency:tree
```
```


q:
Is the following safe?

I am new to threading and I want to delegate a time consuming process to a separate thread in my C++ program.
Using the boost libraries I have written code something like this:

thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);

Where finished_flag is a boolean member of my class. When the thread is finished it sets the value and the main loop of my program checks for a change in that value.
I assume that this is okay because I only ever start one thread, and that thread is the only thing that changes the value (except for when it is initialised  before I start the thread)
So is this okay, or am I missing something, and need to use locks and mutexes, etc

[A]
You never mentioned the type of finished_flag...
If it's a straight
bool
, then it might work, but it's certainly bad practice, for several reasons. First, some compilers will cache the reads of the
finished_flag
variable, since the compiler doesn't always pick up the fact that it's being written to by another thread. You can get around this by declaring the
bool
volatile
, but that's taking us in the wrong direction. Even if reads and writes are happening as you'd expect, there's nothing to stop the OS scheduler from interleaving the two threads half way through a read / write. That might not be such a problem here where you have one read and one write op in separate threads, but it's a good idea to start as you mean to carry on.
If, on the other hand it's a thread-safe type, like a
CEvent in MFC
(or
equivilent in boost
) then you should be fine. This is the best approach: use thread-safe synchronization objects for inter-thread communication, even for simple flags.


q: I have the following situation: I built an Access form with a subform (which records are linked to the records of main form via certain key). When I try to delete any record in the subform, I get the following message: “Access has suspended the action because you and another user tried to change the data” (approximate translation from German). Does anyone know how to delete those records from the subform (and, respectively, from the table behind the form).

[A]
If you are currently 'editing' the current form then it will not allow the action. Editing a record can sometimes be triggered by simply clicking inside a field, or other simple actions you wouldn't normally consider 'editing'.
This is usually avoided in Access by using the RunCommand method to undo any edits before deleting the record:
```
```
DoCmd.RunCommand acCmdUndo
```
```


q: I want to get an overview of files that are updated in TFS (that someone else checked in) that I don't have the latest version for.

[A]
if they checked them in as part of a single changeset then you can find them that way.
(right click file in solution explorer, view history, double-click on the relevant changeset and you'll see all the related files for that checkin)
Is your question about finding this info via the TFS API via the website, or via the visual studio interface?


q:
I've been asked to create a Delphi compatible dll in C++ to do simple 64bit memory management.

The background is that the system in Delphi needs to allocate a lots of chunks of memory that would go well outside 32bit addressable space. The Delphi developer explained to me that he could not allocate memory with the Delphi commands available to him. He says that he can hold a 64bit address, so he just wants to call a function I provide to allocate the memory and return a 64bit pointer to him. Then another function to free up the memory later.

Now, I only have VS 2008 at my disposal so firstly I'm not even sure I can create a Delphi compatible dll in the first place.

Any Delphi experts care to help me out. Maybe there is a way to achieve what he requires without re-inventing the wheel. Other developers must have come across this before in Delphi.

All comments appreciated.

[A]
Only 64 bit processes can address 64 bit memory. A 64 bit process can only load 64 bit dlls and 32 bits processes can only load 32 bits dlls. Delphi's compiler can only make 32 bits binaries.
So a 32 bits Delphi exe can not load your 64 bit c++ dll. It could load a 32 bit c++ dll, but then that dll wouldn't be able to address the 64 bit memory space. You are kind of stuck with this solution.
Delphi could, with the right compiler options and Windows switches address 3GB of memory without problems. Even more memory could be accessed by a 32 bits process if it uses
Physical Address Extension
. It then needs to swap memory pages in and out of the 32 bits memory through the use of
Address Windowing Extensions
.


q:
I was wondering if anyone that has experience in both this stuff can shed some light on the significant difference between the two if any?

Any specific strength of each that makes it suitable for any specific case?

[A]
I found SimpleTest was even easier than PHPUnit to set up. Just extract it and you are good to go. A benefit of this is if you are working at more than one machine, since you can store the whole testing framework the same way as your source code, and thereby know that you are using the same framework code. Especially if you modify it in any way.
So, I would say that a strength of SimpleTest is that it is very light weight and portable.
SimpleTest also ships with a very simple HTML GUI, which is quite easy to extend if you want to. As far as I know, PHPUnit does not include a HTML GUI, but there are GUI:s available to download, such as
Cool
.


q:
I want to implement search functionality for a website (assume it is similar to SO). I don't want to use Google search of stuff like that.

My question is:

How do I implement this?

There are two methods I am aware of:

Search all the databases in the application when the user gives his query.

Index all the data I have and store it somewhere else and query from there (like what Google does).

Can anyone tell me which way to go? What are the pros and cons?

Better, are there any better ways to do this?

[A]
Use lucene,
http://lucene.apache.org/java/docs/
Apache Lucene is a high-performance, full-featured text search engine library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform.
It is available in java and .net. It is also in available in php in the form of a zend framework module.
Lucene does what you wanted(indexing of the searched items), you have to keep track of a lucene index but it is much better than doing a database search in terms of performance. BTW, SO search is powered by lucene. :D


q:
I have a multi dimensional OLAP cube with a number of dimensions. Some of these dimensions have hierarchies. The users would like to perform 'what-if' analysis on the measures in the cube by changing the hierarchies in the dimensions.

For example, they want to know the impact on departmental resource budgets by moving employees between departments or the movement in cost of manufacture if a product is moved from one factory to another.

Does anyone have a straight forward way to do this in a modern OLAP engine?

[A]
There may be tools that allow this sort of analysis, but I only have experience of writing MDX, which ought to be able to help you.
Typical 'what if' analysis is more about changing values in the OLAP cube (e.g. change net sales from 845.45 to 700.00 and see what happens to gross profit). Your case is a bit different as you want to move members within a hierarhy, but keep the same values.
I haven't worked through a full solution, but the way I would approach it would be to create a new 'calculated member' or set (on the fly) and use that to build up the new hierarchy that you want. Your query can then use that on one axis.
Look carefully into 'visual totals' as there may be potential pitfalls there!


q: Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to HttpContext.Current.Request.QueryString. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module?

[A]
Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object in order to modify the querystring.
Using an
IHttpModule
, it might look something like:
```
```
context.RewritePath(context.Request.Path, context.Request.PathInfo, newQueryStringHere!);
```
```
Hope this helps!


q:
Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?

Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView?

[A]
If you are creating composite UserControl, then you can set the
CSSClass
property on the child controls..
If not, then you need to expose properties that are either of the
Style
type, or (as I often do) string properties that apply CSS at the render type (i.e. take them properties and add a
style
attribute to the HTML tags when rendering).


q:
How would you programmacially abbreviate XHTML to an arbitrary number of words without leaving unclosed or corrupted tags?

i.e.

<p>
    Proin tristique dapibus neque. Nam eget purus sit amet leo
    tincidunt accumsan.
</p>
<p>
    Proin semper, orci at mattis blandit, augue justo blandit nulla.
    <span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget,
    hendrerit, <em>justo</em>.
</p>

Abbreviated to 25 words would be:

<p>
    Proin tristique dapibus neque. Nam eget purus sit amet leo
    tincidunt accumsan.
</p>
<p>
    Proin semper, orci at mattis blandit, augue justo blandit nulla.
    <span>Quisque ante congue...</span>
</p>


q: I would like to put a string into a byte array, but the string may be too big to fit.  In the case where it's too large, I would like to put as much of the string as possible into the array.  Is there an efficient way to find out how many characters will fit?

[A]
In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this:
```
```
static string Truncate(string s, int maxLength) {
    if (Encoding.UTF8.GetByteCount(s) <= maxLength)
        return s;
    var cs = s.ToCharArray();
    int length = 0;
    int i = 0;
    while (i < cs.Length){
        int charSize = 1;
        if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))
            charSize = 2;
        int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);
        if ((byteSize + length) <= maxLength){
            i = i + charSize;
            length += byteSize;
        }
        else
            break;
    }
    return s.Substring(0, i);
}
```
```
The returned string can then be safely transferred to a byte array of length maxLength.


q: I have an html file with an unordered list.  I want to show the list items horizontally but still keep the bullets.  No matter what I try, whenever I set the style to inline to meet the horizontal requirement I can't get the bullets to display.

[A]
Did you try
```
float: left
```
on your
```
<li/>
```
? Something like this:
```
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

test

test2

```
```
I only tested Firefox 3.0.1, works there. The
```
margin
```
is set because else your bullet overlaps the previous item.
addition:
Be wary that when you float the items you remove them from the normal flow, which in turn causes the
```
<ul/>
```
to have no height. If you want to add a border or something, you'll get weird results.
One way to fix that is to add the following to your styles:
```
```
ul {
    overflow: auto;
    background: #f0f;
}
```
```


q: I always tend to forget these built-in Symfony functions for making links.

[A]
This advice is for symfony 1.0. It probably will work for later versions.
Within your sfAction class
:
string  genUrl($parameters = array(), $absolute = false)
eg.
$this->getController()->genUrl('yourmodule/youraction?key=value&key2=value', true);
In a template
:
This will generate a normal link.
string link_to($name, $internal_uri, $options = array());
eg.
link_to('My link name', 'yourmodule/youraction?key=value&key2=value');


q: Is there a simple way to format numbers in a Winforms 1.1 datagrid?  The Format property of the DataGridTextBoxColumn seems to be completely ignored.  I know there is a solution that involves subclassing a Column control, and it's fairly simple, but was hoping there might be some trick to making the Format property just work.

[A]
My personal opinion is that a datagridcolumnstyle is the way to go.  Without seeing the code that you have, I can't say for certain why your formatting isn't taking hold when no style is defined - but mixing in formatting with data calculations and other parts of the code can get very messy very quickly.
Creating a new column style class is very clean, and if you have to use the same formatting again in another datagrid, it's as easy as pie to reuse it.
Here's the
Microsoft Documentation
that may get you started in the right direction.


q:
Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?

Or,

if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?

[A]
For many objects
, you can use this code, replacing 'object' with the object you're interested in:
```
```
object_methods = [method_name for method_name in dir(object)
                  if callable(getattr(object, method_name))]
```
```
I discovered it at
diveintopython.net
(now archived), that should provide some further details!
If you get an
```
AttributeError
```
, you can use this instead
:
```
getattr()
```
is intolerant of pandas style Python 3.6 abstract virtual sub-classes.  This code does the same as above and ignores exceptions.
```
```
import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
                  columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
  methodList = []
  for method_name in dir(object):
    try:
        if callable(getattr(object, method_name)):
            methodList.append(str(method_name))
    except Exception:
        methodList.append(str(method_name))
  processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
  for method in methodList:
    try:
        print(str(method.ljust(spacing)) + ' ' +
              processFunc(str(getattr(object, method).__doc__)[0:90]))
    except Exception:
        print(method.ljust(spacing) + ' ' + ' getattr() failed')

get_methods(df['foo'])
```
```


q: SHA Hash functions

[A]
```
```
require 'digest/sha1'
Digest::SHA1.hexdigest 'foo'
```
```


q:
When writing multithreaded applications, one of the most common problems experienced is race conditions.

My questions to the community are:

What is the race condition?

How do you detect them?

How do you handle them?

Finally, how do you prevent them from occurring?

[A]
A race condition is a kind of bug, that happens only with certain temporal conditions.
Example:
Imagine you have two threads, A and B.
In Thread A:
```
```
if( object.a != 0 )
    object.avg = total / object.a
```
```
In Thread B:
```
```
object.a = 0
```
```
If thread A is preempted just after having check that object.a is not null, B will do
```
a = 0
```
, and when thread A will gain the processor, it will do a "divide by zero".
This bug only happen when thread A is preempted just after the if statement, it's very rare, but it can happen.


q:
When writing multi-threaded applications, one of the most common problems experienced are deadlocks.

My questions to the community are:

What is a deadlock?

How do you detect them?

Do you handle them?

And finally, how do you prevent them from occurring?

[A]
A
lock
occurs when multiple processes try to access the same resource at the same time.
One process loses out and must wait for the other to finish.
A
deadlock
occurs when the waiting process is still holding on to another resource that the first needs before it can finish.
So, an example:
Resource A and resource B are used by process X and process Y
X starts to use A.
X and Y try to start using B
Y 'wins' and gets B first
now Y needs to use A
A is locked by X, which is waiting for Y
The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can.
In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible.


q: Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?

[A]
```
```
/// <summary>
///
/// </summary>
/// <param name="strFilePath"></param>
```
```
http://msdn.microsoft.com/en-us/magazine/cc302121.aspx


q: How do you sort an array of strings naturally in different programming languages? Post your implementation and what language it is in in the answer.

[A]
JavaScript
```
```
Array.prototype.alphanumSort = function(caseInsensitive) {
  for (var z = 0, t; t = this[z]; z++) {
    this[z] = [], x = 0, y = -1, n = 0, i, j;

    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        this[z][++y] = "";
        n = m;
      }
      this[z][y] += j;
    }
  }

  this.sort(function(a, b) {
    for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
      if (caseInsensitive) {
        aa = aa.toLowerCase();
        bb = bb.toLowerCase();
      }
      if (aa !== bb) {
        var c = Number(aa), d = Number(bb);
        if (c == aa && d == bb) {
          return c - d;
        } else return (aa > bb) ? 1 : -1;
      }
    }
    return a.length - b.length;
  });

  for (var z = 0; z < this.length; z++)
    this[z] = this[z].join("");
}
```
```
Source


q:
A mutex is a programming concept that is frequently used to solve multi-threading problems.  My question to the community:

What is a mutex and how do you use it?

[A]
When you have a multi-threaded application, the different threads sometimes share a common resource, such as a variable or similar. This shared source often cannot be accessed at the same time, so a construct is needed to ensure that only one thread is using that resource at a time.
The concept is called "mutual exclusion" (short Mutex), and is a way to ensure that only one thread is allowed inside that area, using that resource etc.
How to use them is language specific, but is often (if not always) based on a operating system mutex.
Some languages doesn't need this construct, due to the paradigm, for example functional programming (Haskell, ML are good examples).


q: Additionally, how can I format it as a string padded with zeros?

[A]
To generate the number call rand with the result of the expression "10 to the power of 10"
```
```
rand(10 ** 10)
```
```
To pad the number with zeros you can use the string format operator
```
```
'%010d' % rand(10 ** 10)
```
```
or the
```
rjust
```
method of string
```
```
rand(10 ** 10).to_s.rjust(10,'0')
```
```


q:
I've recently been working with a MySQL database, and using MySQL workbench to design the Database.

When I use the export to SQL function, so I can actually get the layout in to the Database, I get:

"Error 1005: Cannot create table"

This appears to be related to Foreign Keys in the create table statement.

Does anybody have a work around for this that doesn't involve taking the constraints out and putting them back in later?  That's a less than ideal solution given the size of the database.

[A]
I ran into this situation recently when I attempted (in InnoDB tables) to make a foreign key reference to a column that had a different data type.
MySQL 5.1 Documentation


q:
I would like to have an iframe take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?

Are there any workarounds?

[A]
This CSS snippet should remove the vertical scrollbar:
```
```
body {
  overflow-x: hidden;
  overflow-y: hidden;
}
```
```
I'm not sure yet about having it take up as much vertical space as it needs, but I'll see if I can't figure it out.


q:
We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question.

What is the reccomended approach for dealing with a large number of forms that all have different data. Right now were are trying to take a structured approach in setting up a js "class" for each page, with an init, wireClickEvents etc.. to try to have everything conformed.

Is there any "best practices" with creating repetitive jQuery code or any type of reccomended structure other than just throwing a bunch of functions in a js file?

[A]
Not 100% sure example what you are asking, but personally, and I use MochiKit, I create JavaScript "classes" (or widgets, if you prefer) for every significant client-side UI structure. These know, of course, how to populate themselves with data.
I don't know what more there is to say - writing UI code for the browser in JavaScript is no different than writing UI code for other types of apps, as far as I am concerned. Build classes and instantiate them as needed, populate them with data, have them throw events, etc. etc.
Am I up in the night on this? :)
EDIT: In other words, yes - do what you are doing, for the most part. I see too many novice JavaScript hackers write a bunch of poorly-cohesive functions that don't appear to be a part of anything specific other than they are all in a single file. Hope that makes sense.


q:
Is it possible to embed an audio object (mp3, wma, whatever) in a web-enabled InfoPath form ?

If it is, how do you do it ?

[A]
Edit:  My apologies, I missed that the question was about Web forms - for which the below does not work.  Must learn to read the question fully!
Go to menu View
Click on Design Tasks
Select Controls in the 'Design Tasks' Task pane
Click on the 'add or remove custom controls' button to install your custom
control
Click on the Add button and select ActiveX Control
Select the Windows Media Player control
Select the necessary properties for databinding and finish the wizard.
After you have added the control, you can drag and drop the control on your screen.
Right-Click on the control and select the 'Windows Media Player properties'
Fill in the URL to automatically embed the file to play.


q:
I am deploying new versions of java servlets with JRun as the host. I am having difficulty finding good sources for information about JRun and tutorials about how to configure and manage it.

After installing JRun and opening the launcher it can't start the admin server that it creates by default...so obviously I'm running into some issues just getting started.

edit for clarity: I'm not looking for an answer or help with a specific error but if anyone knows of good sources for information about JRun and how to work with it so I can quickly bring myself up to speed on it.

[A]
This is probably going to be difficult to resolve unless you post either the error message from the log file or the list of steps that you took so far.
I have JRun 3.1 configured on my machine so maybe I can duplicate your issue if you give us more information.


q:
How do I list the symbols being exported from a .so file?  If possible, I'd also like to know their source (e.g. if they are pulled in from a static library).

I'm using gcc 4.0.2, if that makes a difference.

[A]
You can use the
```
nm -g
```
tool from the binutils toolchain. However, their source is not always readily available. and I'm not actually even sure that this information can always be retrieved. Perhaps
```
objcopy
```
reveals further information.
/EDIT: The tool's name is of course
```
nm
```
. The flag
```
-g
```
is used to show only exported symbols.


q:
I've tried two different methods of reusing code. I have a solution full of just class library projects with generic code that I reuse in almost every project I work on. When I get to work on a new project, I will reuse code from this code library in one of two ways:

I have tried bringing the projects I need from this code library into my project.

I have also tried compiling down to a .dll and referencing the .dll from a folder in the root of my current solution.

While the second method seems easier and lighter to implement, I always find myself making small tweaks to the original code to fit it into the context of my current project.

I know this is a bit of a vague question, but has anyone had success with other methods of reusing class libraries on new solutions?

[A]
In short, what you are doing is right, you want to move the common code into a class library (DLL) and then reference that in any projects that require its logic.
Where you are going wrong is that you are not
maintaining
it. If you need to make little "tweaks",
subclass
your existing code and extend it, dont change it.. If there are major changes needed, then re-think the design.


q:
I have recently installed .net 3.5 SP1.  When I deployed a compiled web site that contained a form with its action set:

<form id="theForm" runat="server" action="post.aspx">

I received this error.

Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set_Action(System.String)'.

If a fellow developer who has not installed SP1 deploys the compiled site it works fine.  Does anyone know of any solutions for this?

[A]
I don't know the specific solution, but HtmlForm.set_Action() is a function the compiler creates that acts as the setter for a property called Action.
When you do:
```
```
public String Action { set { DoStuff(); } }
```
```
The
set
code actually becomes a function called
set_Action
.
I know it's not the best answer, but I hope it helps you find the source of your problems!


q:
What is a good setup for .hgignore file when working with Visual Studio 2008?

I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it.

I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include?

Thanks!

p.s.: at the moment I do the following : ignore all .pdb files and all obj folders.

# regexp syntax.
syntax: glob
*.pdb

syntax: regexp
/obj/

[A]
This is specific to a C# project, but I ignore these files/directories:
```
*.csproj.user
```
```
/obj/*
```
```
/bin/*
```
```
*.ncb
```
```
*.suo
```
I have no problems running the code in the depot on other machines after I ignore all of these files. The easiest way to find out what you need to keep is to make a copy of the folder and start deleting things you think aren't necessary. Keep trying to build, and as long as you can build successfully keep on deleting. If you delete too much, copy it from the source folder.
In the end you'll have a nice directory full of the only files that have to be committed.


q: I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this?

[A]
First, I'd create a simple DependencyObject class to hold your collection:
```
```
class YourCollectionType : DependencyObject {

    [PROPERTY DEPENDENCY OF ObservableCollection<YourType> NAMED: BoundList]

}
```
```
Then, on your ValidationRule-derived class, create a property:
```
```
YourCollectionType ListToCheck { get; set; }
```
```
Then, in the XAML, do this:
```
```
<Binding.ValidationRules>
    <YourValidationRule>
       <YourValidationRule.ListToCheck>
          <YourCollectionType BoundList="{Binding Path=TheCollectionYouWantToCheck}" />
       </YourValidationRule.ListToCheck>
    </YourValidationRule>
</Binding.ValidationRules>
```
```
Then in your validation, look at ListToCheck's BoundList property's collection for the item that you're validating against. If it's in there, obviously return a false validation result. If it's not, return true.


q:
In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date() function, the manual reads:

string date ( string $format [, int $timestamp = time() ] )

Where $timestamp is an optional parameter, and when left blank it defaults to the time() function's return value.

How do you go about creating optional parameters like this when defining a custom function in PHP?

[A]
Much like the manual, use an equals (
```
=
```
) sign in your definition of the parameters:
```
```
function dosomething($var1, $var2, $var3 = 'somevalue'){
    // Rest of function here...
}
```
```


q:
I need debug some old code that uses a Hashtable to store response from various threads.

I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.

How can this be done?

[A]
```
```
foreach(string key in hashTable.Keys)
{
   Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
```
```


q:
The manual page for XML::Parser::Style::Objects is horrible.  A simple hello world style program would really be helpful.

I really wanted to do something like this: (not real code of course)

use XML::Parser;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
$tree->doSomething();

MyNode::doSomething() {
  my $self = shift;
  print "This is a normal node";
  for $kid ($self->Kids)
  {
    $kid->doSomething();
  }
}

MyNode::special::doSomething() {
  my $self = shift;
  print "This is a special node";
}

[A]
When ever I need to do something similar, usually I end up using
XML::Parser::EasyTree
it has better documentation and is simpler to use.
I highly recommend it.


q: Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model.

[A]
I hear you, I've followed the Pylons mailing list for a while looking for something similar. There have been some attempts in the past (see
AdminPylon
and
Restin
) but none have really kept up with SQLAlchemy's rapidly developing orm api.
Since DBSprockets is likely to be incorporated into TurboGears it will likely be maintained. I'd bite the bullet and go with that.


q:
Is it possible to do 3.1 or 5.1 audio using Flash?  We're starting a project here for an interactive kiosk, and we've been told to use Flash.  However, we also have a requirement to support either 3.1 or 5.1 audio (where 5.1 is the most wanted feature).

I haven't done any high-tech audio stuff using Flash, so I was wondering if anyone knew if it was possible to do?

Thanks.

[A]
A quick google search gave me this forum
http://board.flashkit.com/board/showthread.php?t=715062
where they state that Flash is unable to handle 5.1 audio and the alternative is to use another application that can communicate with Flash to handle the audio side of things.
I also found this blog entry from Summit Projects
http://summitprojectsflashblog.wordpress.com/2008/08/07/wave-theory-in-actionscript-3-part-4/
where they go into great detail about byte handling and processing audio samples. I'm not sure if they are using their own actionscript libraries for this, or if they are using Adobe's libraries. I'm not too up to speed on the audio side of Flash with respects to surround sound.
I think your two options might have to be either using a separate application to run your audio(which may be less stressful) or maybe getting in touch with the Summit people if you are as lost as I am over some of the concepts they touch on, heh. Good luck!


q: When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code.  What strategies do people use for debugging and fixing linking errors?

[A]
One of the common linking errors I've run into is when a function is used differently from how it's defined.  If you see such an error you should make sure that every function you use is properly declared in some .h file.
You should also make sure that all the relevant source files are compiled into the same lib file.  An error I've run into is when I have two sets of files compiled into two separate libraries, and I cross-call between libraries.
Is there a failure you have in mind?


q:
The company I work for is starting to have issues with their current branching model and I was wondering what different kinds of branching strategies the community has been exposed to?

Are there any good ones for different situations?  What does your company use?  What are the advantages and disadvantages of them??

[A]
We currently have one branch for ongoing maintenance, one branch for "new initiatives" which just means "stuff that will come out sometime in the future; we're not sure when." We have also occasionally had two maintenance branches going on: one to provide fixes for what is currently in production and one that is still in QA.
The main advantage we've seen is the ability to react to user requests and emergencies more rapidly.  We can do the fix on the branch that is in production and release it without releasing anything extra that may have already been checked in.
The main disadvantage is that we end up doing a lot of merging between branches, which increases the chance that something will get missed or merged incorrectly. So far, that hasn't been a problem, but it is definitely something to keep in mind.
Before we instituted this policy, we generally did all development in the trunk and only branched when we released code. We then did fixes against that branch as needed. It was simpler, but not as flexible.