q:
I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django.

I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block.

How should I do this? It's a fairly large project, so adding code to every view is far from ideal.

That solution works well. The Middleware Class I ended up with this this:

from django.http import HttpResponseRedirect

class BetaMiddleware(object):
    """
    Require beta code session key in order to view any page.
    """
    def process_request(self, request):
        if request.path != '/beta/' and not request.session.get('in_beta'):
            return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path))

[A]
You should be able to add
```
@login_required
```
decorators across the board and be done with it.  Unless you have a boat-load of view functions, it shouldn't be too horrible.


q: I'm trying to get a sampling of what people think are the best sign-up forms.  Good design, usability.  Smart engineering.  Helpful feedback.

[A]
One of my all-time fave sign-up forms was the original
Vox
one, which has since been changed; there was
a great break-down
of it published online, and it goes into the things that made it so great to me.  How they implemented the CSS layout of their forms, how they used in-form validation with pop-up tips, etc. -- it was nice.

s: huggingface

c: devops

d: intermediate


q:
How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC?

I have a CDialog based Windows Mobile 6 (touchscreen) Professional app that I am workign on.

The default behavior of a CDialog based app in WM6 Professional is to not use any softkeys by default... I want to map the softkeys to "Cancel" and "OK" functionality that sends IDOK and IDCANCEL to my Main Dialog class.

I have been trying to work with CCommandBar with no luck, and SHCreateMenuBar was not working out for me either.

Does anyone have a sample of how to get this to work?

[A]
What's "not working" with the CCommandBar for you?  You should be able to add a CCommandBar member to your dialog class, then in teh DIalog's InitDialog you call Create and InsertMenuBar on the command bar - something like this:
```
```
m_cmdBar.Create(this);
m_cmdBar.InsertMenuBar(IDR_MENU_RESRC_ID);
```
```
Your menu resource might look something like this:
```
```
IDR_MENU_RESRC_ID MENU DISCARDABLE
BEGIN
MENUITEM "OK", IDOK
MENUITEM "Cancel", IDCANCEL
END
```
```


q:
We are currently using Apache 2.2.3 and Tomcat 5 (Embedded in JBoss 4.2.2) using mod_proxy_jk as the connector.

Can someone shed some light on the the correct way to calculate / configure the values below (as well as anything else that may be relevant).  Both Apache and Tomcat are running on separate machines and have copious amounts of ram (4gb each).

Relevant server.xml portions:

<Connector port="8009"
    address="${jboss.bind.address}"
    protocol="AJP/1.3"
    emptySessionPath="true"
    enableLookups="false"
    redirectPort="8443"
    maxThreads="320"
    connectionTimeout="45000"
/>

Relevant httpd.conf portions:

<IfModule prefork.c>
  StartServers       8
  MinSpareServers    5
  MaxSpareServers   20
  ServerLimit      256
  MaxClients       256
  MaxRequestsPerChild  0
</IfModule>

[A]
MaxClients
This is the fundamental cap of parallel client connections your apache should handle at once.
With prefork, only one request can be handled per process. Therefore the whole apache can process
at most
$MaxClients requests in the time it takes to handle a
single
request. Of course, this ideal maximum can only be reached if the application needs less than 1/$MaxClients resources per request.
If, for example, the application takes a second of cpu-time to answer a single request, setting MaxClients to four will limit your throughput to four requests per second: Each request uses up an apache connection and apache will only handle four at a time. But if the server has only two CPUs, not even this can be reached, because every wall-clock second only has two cpu seconds, but the requests would need four cpu seconds.
MinSpareServers
This tells apache how many idle processes should hang around. The bigger this number the more burst load apache can swallow before needing to spawn extra processes, which is expensive and thus slows down the current request.
The correct setting of this depends on your workload. If you have pages with many sub-requests (pictures, iframes, javascript, css) then hitting a single page might use up many more processes for a short time.
MaxSpareServers
Having too many unused apache processes hanging around just wastes memory, thus apache uses the MaxSpareServers number to limit the amount of spare processes it is holding in reserve for bursts of requests.
MaxRequestsPerChild
This limits the number of requests a single process will handle throughout its lifetime. If you are very concerned about stability, you should put an actual limit here to continually recycle the apache processes to prevent resource leaks from affecting the system.
StartServers
This is just the amount of processes apache starts by default. Set this to the usual amount of running apache processes to reduce warm-up time of your system. Even if you ignore this setting, apache will use the Min-/MaxSpareServers values to spawn new processes as required.
More information
See also
the documentation for apache's multi-processing modules
.


q:
I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.

I tried using MySQL Administrator, but I got the following error:

The selected file was generated by
  mysqldump and cannot be restored by
  this application.

How do I get this working?

[A]
It should be as simple as running this:
```
```
mysql -u <user> -p < db_backup.dump
```
```
If the dump is of a single database you may have to add a line at the top of the file:
```
```
USE <database-name-here>;
```
```
If it was a dump of many databases, the use statements are already in there.
To run these commands, open up a command prompt (in Windows) and
```
cd
```
to the directory where the
```
mysql.exe
```
executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP).  Once you're in that directory, you should be able to just type the command as I have it above.


q:
Part of our app parses RTF documents and we've come across a special character that is not translating well.  When viewed in Word the character is an elipsis (...), and it's encoded in the RTF as ('85).

In our vb code we converted the hex (85) to int(133) and then did Chr(133) to return (...)

Here's the code in C# - problem is this doesn't work for values above 127.  Any ideas?

Calling code :

// S is Hex number!!!
return Convert.ToChar(HexStringToInt(s)).ToString();

Helper method:

private static int HexStringToInt(string hexString)
{
    int i;

    try
    {
        i = Int32.Parse(hexString, NumberStyles.HexNumber);
    }
    catch (Exception ex)
    {
        throw new ApplicationException("Error trying to convert hex value: " + hexString, ex);
    }

    return i;
}

[A]
```
```
private static int HexStringToInt(string hexString)
{
    try
    {
        return Convert.ToChar(hexString);
    }
    catch (FormatException ex)
    {
        throw new ArgumentException("Is not a valid hex character.", "hexString", ex);
    }
    // Convert.ToChar() will throw an ArgumentException also
    // if hexString is bad
}
```
```


q:
I saw this quote on the question: What is a good functional language on which to build a web service?

Scala in particular doesn't support tail-call elimination except in self-recursive functions, which limits the kinds of composition you can do (this is a fundamental limitation of the JVM).

Is this true?  If so, what is it about the JVM that creates this fundamental limitation?

[A]
This post:
Recursion or Iteration?
might help.
In short, tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available. These requirements could in theory be supported, but it would probably require a new bytecode (see
John Rose's informal proposal
).
There is also more discussion in
Sun bug #4726340
, where the evaluation (from 2002) ends:
I believe this could be done nonetheless, but it is not a small task.
Currently, there is some work going on in the
Da Vinci Machine
project. The tail call subproject's status is listed as "proto 80%"; it is unlikely to make it into Java 7, but I think it has a very good chance at Java 8.


q:
What are real-world problems where a recursive approach is the natural solution besides depth-first search (DFS)?

(I don't consider Tower of Hanoi, Fibonacci number, or factorial real-world problems. They are a bit contrived in my mind.)

[A]
How about anything involving a directory structure in the file system.  Recursively finding files, deleting files, creating directories, etc.
Here is a Java implementation that recursively prints out the content of a directory and its sub-directories.
```
```
import java.io.File;

public class DirectoryContentAnalyserOne implements DirectoryContentAnalyser {

    private static StringBuilder indentation = new StringBuilder();

    public static void main (String args [] ){
        // Here you pass the path to the directory to be scanned
        getDirectoryContent("C:\\DirOne\\DirTwo\\AndSoOn");
    }

    private static void getDirectoryContent(String filePath) {

        File currentDirOrFile = new File(filePath);

        if ( !currentDirOrFile.exists() ){
            return;
        }
        else if ( currentDirOrFile.isFile() ){
            System.out.println(indentation + currentDirOrFile.getName());
            return;
        }
        else{
            System.out.println("\n" + indentation + "|_" +currentDirOrFile.getName());
            indentation.append("   ");

            for ( String currentFileOrDirName : currentDirOrFile.list()){
                getPrivateDirectoryContent(currentDirOrFile + "\\" + currentFileOrDirName);
            }

            if (indentation.length() - 3 > 3 ){
                indentation.delete(indentation.length() - 3, indentation.length());
            }
        }
    }

}
```
```


q:
It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list:

Window position same as it was

Unless the screen has resized and the old position is now off screen.

Splitters should retain their position

Tab containers should retain their selection

Some dropdowns should retain their selection

Window state (maximize, minimize, normal) is the same as it was.

Maybe you should never start minimized, I haven't decided.

I'll add my current solutions as an answer along with the limitations.

[A]
The simplest solution I've found is to use data binding with the application settings. I bind the location and clientSize properties on the window along with the splitterDistance on the splitter.
Drawbacks:
If you close the window while minimized, it opens hidden the next time. It's really hard to get the window back.
If you close the window while maximized, it opens filling the whole screen, but not maximized (minor issue).
Resizing the window using the top-right corner or the bottom-left corner is just ugly. I guess the two databound properties are fighting each other.
If you'd like to experiment with the strange behaviour, I posted a
sample solution
using this technique.


q: This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control.

[A]
Unfortunately there is no more efficient way than a linear search, unless you know that your listbox is sorted or indexed in some particular fashion.
```
```
For i = 1 To TheComboBoxControl.ListCount
  if TheComboBoxControl.ItemData(i) = "Item to search for" Then do_something()
Next i
```
```


q: I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.

[A]
from:
http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm
```
```
sp_defaultdb [@loginame =] 'login' , [@defdb =] 'database'
```
```


q:
According to what I have found so far, I can use the following code:

    LocalSessionFactoryBean sessionFactory = (LocalSessionFactoryBean)super.getApplicationContext().getBean("&sessionFactory");
    System.out.println(sessionFactory.getConfiguration().buildSettings().getJdbcBatchSize());

but then I get a Hibernate Exception:

org.hibernate.HibernateException: No local DataSource found for
  configuration - dataSource property must be set on
  LocalSessionFactoryBean

Can somebody shed some light?

[A]
Try the following (I can't test it since I don't use Spring):
```
```
System.out.println(sessionFactory.getConfiguration().getProperty("hibernate.jdbc.batch_size"))
```
```


q:
I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list?

I have been searching for awhile but I cannot seem to find a comprehensive list.

Thanks :)


q:
In java, which regular expression can be used to replace these,
for example:

before:
aaabbb
after:
ab

before:
14442345
after:
142345

thanks!

[A]
In perl
```
```
s/(.)\1+/$1/g;
```
```
Does the trick, I assume if java has perl compatible regexps it should work too.
Edit: Here is what it means
```
```
s {
    (.)  # match any charater ( and capture it )
    \1   # if it is followed by itself
    +    # One or more times
}{$1}gx;  # And replace the whole things by the first captured character (with g modifier to replace all occurences)
```
```
Edit: As others have pointed out, the syntax in Java would become
```
```
original.replaceAll("(.)\\1+", "$1");
```
```
remember to escape the \1


q:
In the spirit of being helpful, this is a problem I had and solved, so I will answer the question here.

Problem

I have:

An application that has to be installed on on Redhat or SuSE enterprise.

It has huge system requirements and requires OpenGL.

It is part of a suite of tools that need to operate together on one machine.

This application is used for a time intensive task in terms of man hours.

I don't want to sit in the server room working on this application.

So, the question came up... how do I run this application from a remote windows machine?

I'll outline my solution. Feel free to comment on alternatives. This solution should work for simpler environments as well. My case is somewhat extreme.

[A]
Solution
I installed two pieces of software:
PuTTY
XMing-mesa
The mesa part is important.
PuTTY configuration
```
```
Connection->Seconds Between Keepalives: 30
Connection->Enable TCP Keepalives: Yes

Connection->SSH->X11->Enable X11 forwarding: Yes
Connection->SSH->X11->X display location: localhost:0:0
```
```
Lauching
Run
Xming
which will put simply start a process and put an icon in your system tray.
Launch putty, pointing to your linux box, with the above configuration.
Run program
Hopefully,
Success!


q:
I've read on Wikipedia and other sites about OSGi, but I don't really see the big picture. It says that it's a component-based platform, and that you can reload modules at runtime. Also the "practical example" given everywhere is the Eclipse Plugin Framework.

My questions are:

What is the clear and simple definition of OSGi?

What common problems does it solve?

By "common problems" I mean problems we face everyday, like "What can OSGi do for making our jobs more efficient/fun/simple?"

[A]
edited for clarity. OSGi page gave a better simple answer than mine
A simple answer: An OSGi Service Platform provides a standardized, component-oriented computing environment for cooperating networked services. This architecture significantly reduces the overall complexity of building, maintaining and deploying applications.
The OSGi Service Platform provides the functions to change the composition dynamically on the device of a variety of networks, without requiring a restarts.
In a single application structure, say the Eclipse IDE, it's not a big deal to restart when you install a new plugin. Using the OSGi implementation completely, you should be able to add plugins at runtime, get the new functionality, but not have to restart eclipse at all.
Again, not a big deal for every day, small application use.
But, when you start to look at multi-computer, distributed application frameworks, that's where it starts to get interesting. When you have to have 100% uptime for critical systems, the capability to hotswap components or add new functionality at runtime is useful. Granted, there are capabilities for doing this now for the most part, but OSGi is trying to bundle everything into a nice little framework with common interfaces.
Does OSGi solve common problems, I'm not sure about that. I mean, it can, but the overhead may not be worth it for simpler problems. But it's something to consider when you are starting to deal with larger, networked, applications.


q:
lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data.

What are some of the most common and useful ways of using lsof, and which command-line switches are used for that?

[A]
```
lsof -i
```
will provide a list of open network sockets. The
```
-n
```
option will prevent DNS lookups, which is useful when your network connection is slow or unreliable.


q:
I have an application where a Hilbert R-Tree (wikipedia) (citeseer) would seem to be an appropriate data structure.  Specifically, it requires reasonably fast spatial queries over a data set that will experience a lot of updates.

However, as far as I can see, none of the descriptions of the algorithms for this data structure even mention how to actually calculate the requisite Hilbert Value; which is the distance along a Hilbert Curve to the point.

So any suggestions for how to go about calculating this?

[A]
Fun question!
I did a bit of googling, and the good news is, I've found an implementation of Hilbert Value.
The potentially bad news is, it's in Haskell...
http://www.serpentine.com/blog/2007/01/11/two-dimensional-spatial-hashing-with-space-filling-curves/
It also proposes a Lebesgue distance metric you might be able to compute more easily.


q:
In my model I have:

validate :my_custom_validation

def my_custom_validation
 errors.add_to_base("error message") if condition.exists?
end

I would like to add some parameters to mycustomer vaildation like so:

validate :my_custom_validation, :parameter1 => x, :parameter2 => y

How do I write the mycustomvalidation function to account for parameters?

[A]
You can just do something like this:
```
```
def validate
  errors.add('That particular field', 'can not be the value you presented') if !self.field_to_check.blank? && self.field_to_check == 'I AM COOL'
end
```
```
No need to call reference it, as I believe the validate method is processed (if it exists) after any validates_uniqueness_of -like validations.
Added: More information in the Rails API docs
here
.


q:
I'm at a point in my freelance career where I've developed several web applications for small to medium sized businesses that support things such as project management, booking/reservations, and email management.

I like the work but find that eventually my applications get to a point where the overhear for maintenance is very high. I look back at code I wrote 6 months ago and find I have to spend a while just relearning how I originally coded it before I can make a fix or feature additions. I do try to practice using frameworks (I've used Zend Framework before, and am considering Django for my next project)

What techniques or strategies do you use to plan out an application that is capable of handling a lot of users without breaking and still keeping the code clean enough to maintain easily?
If anyone has any books or articles they could recommend, that would be greatly appreciated as well.

[A]
You should consider maybe using SharePoint. It's an environment that is already designed to do all you have mentioned, and has many other features you maybe haven't thought about (but maybe you will need in the future :-) )
Here
's some information from the official site.
There are 2 different SharePoint environments you can use: Windows Sharepoint Services (WSS) or Microsoft Office Sharepoint Server (MOSS). WSS is free and ships with Windows Server 2003, while MOSS isn't free, but has much more features and covers almost all you enterprise's needs.


q: Anyone have a good set of sqlplus configuration directives to help transform a given sql query into nicely tab separated output for pulling into a spreadsheet or further processing?

[A]
Check out the Oracle documentation:
Formatting SQLPlus Reports
Generating HTML Reports from SQLPlus
You can generate a tab in Oracle by using the tab's ASCII value 9 and the chr function:
```
```
select chr(9) from dual;
```
```


q:
With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.

Any place where we still have to use delegates and lambda expressions won't work?

[A]
lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:
```
```
delegate(int i) { Console.WriteLine(i.ToString()) }
```
```
can be replaced with
```
```
f => Console.WriteLine(f.ToString())
```
```


q:
I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?

FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.

[A]
Just call
```
.getClass()
```
on each
```
Object
```
in a loop.
Unfortunately, Java doesn't have
```
map()
```
. :)


q:
I have a list of ranked users, and would like to select the top 50. I also want to make sure one particular user is in this result set, even if they aren't in the top 50. Is there a sensible way to do this in a single mysql query? Or should I just check the results for the particular user and fetch him separately, if necessary?

Thanks!

[A]
If I understand correctly, you could do:
```
```
select * from users order by max(rank) desc limit 0, 49
union
select * from users where user = x
```
```
This way you get 49 top users plus your particular user.


q:
The built-in PHP extension for SOAP doesn't validate everything in the incoming SOAP request against the XML Schema in the WSDL. It does check for the existence of basic entities, but when you have something complicated like simpleType restrictions the extension pretty much ignores their existence.

What is the best way to validate the SOAP request against XML Schema contained in the WSDL?

[A]
Typically one doesn't validate against the WSDL.  If the WSDL is designed properly there should be an underlying xml schema (XSD) to validate the body of the request against.  Your XML parser should be able to do this.
The rest is up to how you implement the web service and which SOAP engine you are using.  I am not directly familiar with the PHP engine.  For WSDL/interface level "validation" I usually do something like this:
Does the body of the request match a known request type and is it valid (by XSD)?
Does the message make sense in this context and can i map it to an operation/handler?
If so, start processing it
Otherwise: error


q: How can I load an external JavaScript file using a bookmarklet?  This would overcome the URL length limitations of IE and generally keep things cleaner.

[A]
2015 Update
Content security policy
will prevent this from working in many sites now. For example, the code below won't work on Facebook.
2008 answer
Use a bookmarklet that creates a script tag which includes your external JS.
As a sample:
```
```
javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})();
```
```


q:
Before you answer: Yes I have read the jtable tutorial over at Sun. No, it did not help me. Yes, I am a dolt. Please don't answer with a reference to that document. What I am specifically interested in is how to dynamically add rows and columns to my Jtable via the Netbeans IDE. I already have an object that contains a hashmap with my data. I can't figure out where or what object I should be passing that object to. Thanks for your time!

I have a vector that contains a series (of length l) of objects (each one corresponding to a row). How do I get that vector object to display on the JTable?

[A]
A
```
JTable
```
uses a
```
TableModel
```
to hold its data. Your hash/vector of data will need to be adapted to be used; you can write a
```
TableModel
```
implementation, using the hash/vector as backing data, or, if you won't be dynamically updating the hash/vector and needing it to show automatically, you can simply copy everything into an instance of
```
DefaultTableModel
```
, and use that.
If you do use an adapter, and dynamically update the hash/vector, remember that all updates must be done in the event dispatch thread. :-)


q:
I have a setup executable that I need to install. When I run it, it launches a msi to do the actual install and then dies immediately. The side effect of this is it will return control back to any console you call it from before the install finishes. Depending on what machine I run it on, it can take from three to ten minutes so having the calling script sleep is undesirable. I would launch the msi directly but it complains about missing components.

I have a WSH script that uses WMI to start a process and then watch until it's pid is no longer running. Is there some way to determine the pid of the MSI the initial executable is executing, and then watch for that pid to end using WMI? Is the launching process information even associated with a process?

[A]
Would doing a WMI lookup of processes that have the initial setup as the parent process do the trick?  For example, if I launch an MSI from a command prompt with process id 4000, I can execute the following command line to find information about msiexec process:
```
```
c:\>wmic PROCESS WHERE ParentProcessId=4000 GET CommandLine, ProcessId
CommandLine                                                 ProcessId
"C:\Windows\System32\msiexec.exe" /i "C:\blahblahblah.msi"  2752
```
```
That may be one way to find the information you need.  Here is a demo of looking up that information in vbs:
```
```
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("select * from Win32_Process where ParentProcessId = 4000")
For Each objProcess in colProcesses
    Wscript.Echo "Process ID: " & objProcess.ProcessId
Next
```
```
I hope this helps.


q:
I have this line in a javascript block in a page:

res = foo('<%= @ruby_var %>');

What is the best way to handle the case where @ruby_var has a single-quote in it? Else it will break the JavaScript code.

[A]
```
```
@ruby_var.gsub(/[']/, '\\\\\'')
```
```
That will escape the single quote with an apostrophe, keeping your Javascript safe!
Also, if you're in Rails, there are a bunch of
Javascript-specific tools
.


q: What is a smart pointer and when should I use one?

[A]
http://en.wikipedia.org/wiki/Smart_pointer
In computer science, a smart pointer
  is an abstract data type that
  simulates a pointer while providing
  additional features, such as automatic
  garbage collection or bounds checking.
  These additional features are intended
  to reduce bugs caused by the misuse of
  pointers while retaining efficiency.
  Smart pointers typically keep track of
  the objects that point to them for the
  purpose of memory management. The
  misuse of pointers is a major source
  of bugs: the constant allocation,
  deallocation and referencing that must
  be performed by a program written
  using pointers makes it very likely
  that some memory leaks will occur.
  Smart pointers try to prevent memory
  leaks by making the resource
  deallocation automatic: when the
  pointer to an object (or the last in a
  series of pointers) is destroyed, for
  example because it goes out of scope,
  the pointed object is destroyed too.


q:
The default rails XML builder escapes all HTML, so something like:

atom_feed do |feed|
  @stories.each do |story|
    feed.entry story do |entry|
      entry.title story.title
      entry.content "<b>foo</b>"
    end
  end
end

will produce the text:

<b>foo</b>

instead of: foo

Is there any way to instruct the XML builder to not escape the XML?

[A]
turns out you need to do
```
```
entry.content "<b>foo</b>", :type => "html"
```
```
althought wrapping it in a CDATA stops it working.


q:
I use this code in my Windows Service to be notified of USB disk drives being inserted and removed:

WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent",
    "TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2");
query.WithinInterval = TimeSpan.FromSeconds(1);
_deviceWatcher = new ManagementEventWatcher(query);
_deviceWatcher.EventArrived += new EventArrivedEventHandler(OnDeviceEventArrived);
_deviceWatcher.Start();

It works on XP and Vista, but on XP I can hear the very noticeable sound of the hard drive being accessed every second. Is there another WMI query that will give me the events without the sound effect?

[A]
Not sure if this applies to your case but we've been using RegisterDeviceNotification in our C# code (which I can't post here) to detect when USB devices are plugged in. There's a handful of native functions you have to import but it generally works well. Easiest to make it work in C++ first and then see what you have to move up into C#.
There's some stuff on koders Code search that appears to be a whole C# device management module that might help:
http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx


q:
I have a Perl script where I maintain a very simple cache using a hash table. I would like to clear the hash once it occupies more than n bytes, to avoid Perl (32-bit) running out of memory and crashing.

I can do a check on the number of keys-value pairs:

if (scalar keys %cache > $maxSize)
 {
 %cache = ();
 }

But is it possible to check the actual memory occupied by the hash?

[A]
You're looking for
Devel::Size
NAME
Devel::Size - Perl extension for finding the memory usage of Perl variables
SYNOPSIS
```
```
use Devel::Size qw(size total_size);

my $size = size("A string");
my @foo = (1, 2, 3, 4, 5);
my $other_size = size(\@foo);
my $foo = {a => [1, 2, 3],
        b => {a => [1, 3, 4]}
       };
my $total_size = total_size($foo);
```
```


q:
There is a lot of relativity involved in working with exceptions. Beyond low level APIs where exceptions cover errors raised from hardware and the OS there is a shady area where the programmer decides what constitutes an exception and what is a normal condition.

How do you decide when to use exceptions? Do you have a consistent policy regarding exceptions?

[A]
Exceptions are expensive in processing time, so they should only be thrown when something happens that really shouldn't happen in your app.
Sometimes you can predict what kind of things might happen and code to recover from them, in which case it is appropriate to throw and catch an exception, log and recover, then continue.  Otherwise they should just be used to handle the unexpected and exit gracefully, while capturing as much information as possible to help with debugging.
I'm a .NET developer, and for catch and throw, my approach is:
Only try/catch in public methods (in general; obviously if you are trapping for a specific error you would check for it there)
Only log in the UI layer right before suppressing the error and redirecting to an error page/form.


q:
At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.

Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?

[A]
“… the volatile modifier guarantees that any thread that reads a field will see the most recently written value.”
- Josh Bloch
If you are thinking about using
```
volatile
```
, read up on the package
```
java.util.concurrent
```
which deals with atomic behaviour.
The Wikipedia post on a
Singleton Pattern
shows volatile in use.


q:
Possible Duplicates:

  Learn Obj-C Memory Management

  Where are the best explanations of memory management for iPhone?

I come from a C/C++ background and the dynamic nature of Objective-C is somewhat foreign to me, is there a good resource anyone can point me to for some basic memory management techniques in Objective-C? ex. retaining, releasing, autoreleasing

For instance, is it completely illegal to use a pointer to an Objective-C object and treat it as an array? Are you forced to use NSArray and NSMutableArray for data structures?

I know these are pretty newbie questions, thanks for any help you can offer me.

[A]
Here you go
:
Application memory management is the process of allocating memory during your program’s runtime, using it, and freeing it when you are done with it. A well-written program uses as little memory as possible. In Objective-C, it can also be seen as a way of distributing ownership of limited memory resources among many pieces of data and code. When you have finished working through this guide, you will have the knowledge you need to manage your application’s memory by explicitly managing the life cycle of objects and freeing them when they are no longer needed.
Although memory management is typically considered at the level of an individual object, your goal is actually to manage object graphs. You want to make sure that you have no more objects in memory than you actually need...


q:
Strange question, but: Sharepoint 2007 greets you with the Administrator Tasks on the Central Administration after installation.

I just wonder if this list is "safe" to be used for my own Administration Tasks? The reason why i'm asking is because I found that Sharepoint uses a lot of "black magic" and unlogical behaviour and breaks rather easily, so I do not want risk breaking anything if i'm entering my own tasks into the task list.

[A]
```
unicode
```
does not guess the encoding of your text. If your object can print itself as
```
unicode
```
, define the
```
__unicode__()
```
method that returns a Unicode string.
The secret is that
```
unicode(r)
```
is not actually calling
```
__str__()
```
itself. Instead, it's looking for a
```
__unicode__()
```
method. The default implementation of
```
__unicode__()
```
will call
```
__str__()
```
and then attempt to decode it using the
```
ascii
```
charset. When you pass the encoding,
```
unicode()
```
expects the first object to be something that can be decoded -- that is, an instance of
```
basestring
```
.
Behavior is weird because it tries to decode as ascii if I don't pass 'utf-8'. But if I pass 'utf-8' it gives a different error...
That's because when you specify "utf-8", it treats the first parameter as a string-like object to be decoded. Without it, it treats the parameter as an object to be coerced to unicode.
I do not understand the confusion. If you know that the object's
```
text
```
attribute will always be UTF-8 encoded, just define
```
__unicode__()
```
and then everything will work fine.


q: What I'm trying to do with MRS is to teach myself some basic AI; what I want to do is to make a rocket entity, with things such as vectored exhaust, and staging. Anyone have an idea on how to make an entity that can fly? Or do I just need to constantly apply a force upwards?

[A]
Hey TraumaPony, your question looked lonely :)
I took a look at an MSDN article about MRS 2.0
here
I believe you'll actually need to create a Rocket entity of some kind and then a Thruster entity that it can use. In the article they were able to reuse a DifferentialDrive entity to propel their bot forward. I hope that helps. I'm more or less shooting in the dark since no else has tried to help ya out yet. Cheers! :)


q:
I have a VB.NET Windows Forms project that at one point paints text directly to onto the form at runtime. Before I paint with the font though, I want to make sure that the font and font-size exists on the user's machine. If they don't, I'll try a few other similar fonts, eventually defaulting with Arial or something.

What's the best way to test and validate a font on a user's computer?

[A]
From an MSDN article titled "How To: Enumerate Installed Fonts", I found this code:
```
```
InstalledFontCollection installedFontCollection = new InstalledFontCollection();

// Get the array of FontFamily objects.
FontFamily[] fontFamilies = installedFontCollection.Families;
```
```


q:
It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam.  The web is littered with similar, yet still slightly different implementations of this type of solution.

Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)?  Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution?

[A]
As toolkit mentions above, Apache Commons IO is the way to go, specifically
FileUtils
.
copyFile()
; it handles all the heavy lifting for you.
And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files;
NIO can significantly increase file-copying performance
, in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer.  So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.


q:
Intel's Threading Building Blocks (TBB) open source library looks really interesting.  Even though there's even an O'Reilly Book about the subject I don't hear about a lot of people using it.  I'm interested in using it for some multi-level parallel applications (MPI + threads) in Unix (Mac, Linux, etc.) environments.  For what it's worth, I'm interested in high performance computing / numerical methods kinds of applications.

Does anyone have experiences with TBB?  Does it work well?  Is it fairly portable (including GCC and other compilers)?  Does the paradigm work well for programs you've written?  Are there other libraries I should look into?

[A]
I've looked into TBB but never used it in a project. I saw no advantages (for my purposes) over
ZThread
. A brief and somewhat dated overview can be found
here
.
It's fairly complete with several thread dispatch options, all the usual synchronization classes and a very handy exception based  thread "interrupt" mechanism . It's easily extendable, well written and documented. I've used it on 20+ projects.
It also plays nice with any *NIX that supports POSIX threads as well as Windows.
Worth a look.


q:
I am using Adobe Captivate 3 and am having trouble disabling the typing noise when using a recording.  Sometimes when I have this 'feature' disabled and make a recording, it doesn't make the typing sound, but when I publish the project, the typing sound returns.  Also, I have other projects I am working on where the typing sound wasn't initially disabled during the recording and I can't get it to stop making that typing noise.

Any suggestions on how to disable the typing sound permanently within a new or existing Captivate project?


q:
I have a table that is dynamically created using DIVs. Each row of the table has two images. I want to set the height for the div (that represents a particular row) to the height of image that is greater of the two images being displayed in that particular row. The images to displayed will always change, and they are from an external server.

How do I set the height for my div so that I can fit images?

[A]
Pre-load them into javascript image objects then just reference the height and width.
Might take some clever devilry to work in all browsers...
```
```
function getSize(imgSrc){

    var aImg = new Image();

    aImg.src = imgSrc;

    aHeight = newImg.height;
    aWidth = newImg.width;

}
```
```


q:
How do you draw a custom button next to the minimize, maximize and close buttons within the Titlebar of the Form?

I know you need to use Win32 API calls and override the WndProc procedure, but I haven't been able to figure out a solution that works right.

Does anyone know how to do this? More specifically, does anyone know a way to do this that works in Vista?

[A]
Drawing seems to be the easy part, the following will do that:
[Edit: Code removed, see my other answer]
The real problem is changing the state and detecting clicks on the button... for that you'll need to hook into the global message handler for the program, .NET seems to hide the mouse events for a form while not in the actual container areas (ie. mouse moves and clicks on the title bar). I'm looking for info on that, found it now, I'm working on it, shouldn't be too hard... If we can figure out what these messages are actually passing.


q:
I'm a pretty new C# and .NET developer. I recently created an MMC snapin using C# and was gratified by how easy it was to do, especially after hearing a lot of horror stories by some other developers in my organisation about how hard it is to do in C++.

I pretty much went through the whole project at some point and made every instance of the "public" keyword to "internal", except as required by the runtime in order to run the snapin. What is your feeling on this, should you generally make classes and methods public or internal?

[A]
I believe in blackboxes where possible. As a programmer, I want a well defined blackbox which I can easily drop into my systems, and have it work. I give it values, call the appropriate methods, and then get my results back out of it.
To that end, give me only the functionality that the class needs to expose to work.
Consider an elevator. To get it to go to a floor, I push a button. That's the public interface to the black box which activates all the functions needed to get the elevator to the desired floor.


q: I have been using IoC for a little while now and I am curious if I should use Microsoft's Unity framework (official name "Unity Application Block").  Does anyone have experience using it?  So for I have been copying my IoC container code from project to project, but I think it would be better to using something standard.  I think IoC can make a HUGE difference in keeping component based applications loosely coupled and therefore changeable but I am by no means an expert on IoC, so I am nervous to switch to a framework that will just paint me into a corner as a dependency I will one day want to walk away from.

[A]
I've played with CompositeWPF (aka Prism) - successor of Composite app block. From my experience Unity works much better as compared with previous version of ObjectBuilder. However it's up to you to evaluate IoC frameworks and choose one suited for your needs.
Unity tutorials & samples
Unity IoC Screencast


q:
I'm trying to implement an outdent of the first letter of the first paragraph of the body text. Where I'm stuck is in getting consistent spacing between the first letter and the rest of the paragraph.

For example, there is a huge difference in spacing between a "W" and an "I"

Anyone have any ideas about how to mitigate the differences? I'd prefer a pure CSS solution, but will resort to JavaScript if need be.

PS: I don't necessarily need compatibility in IE or Opera

[A]
I tried using a fix-width font like 'courier new' and since the characters are more or less the same width it made it a lot less noticeable.
Edit - this font is decent but might only work for windows
```
```
p.outdent:first-letter {
    font-family: ms mincho;
    font-size: 8em;
    line-height: 1;
    font-weight: normal;
    float: left;
    margin: -0.1em 0 0 -.55em;
    letter-spacing: 0.05em;
}
```
```


q: I noticed that you can call Queue.Synchronize to get a thread-safe queue object, but the same method isn't available on Queue<T>.  Does anyone know why?  Seems kind of weird.

[A]
(I assume you mean Queue<T> for the second one.)
I can't specifically answer the question, except that the IsSynchronized and SyncRoot properties (but not Synchronise() explicitly) are inherited from the ICollection interface. None of the generic collections use this and the ICollection<T> interface does not include SyncRoot.
As to why it is not included, I can only speculate that they weren't being used either in the way intended by the library designers or they simply weren't being used enough to justify retaining them in the newer collections.


q: It seems like you could use a mashup of Relector and a Debugger to be able to debug any .NET app WITHOUT having the source code at all.  Is this possible?  Has anyone seen this before?

[A]
I tried this a long time ago without success. Reflector has improved alot since then so I imagine it may be possible today.
It's actually kind of scary if you think about it. Someone could decompile your app and have the full code, then modify it and distribute their own version of it. All without being open source. But then again that's why "they" created obfuscators.


q:
As a follow up to "What are indexes and how can I use them to optimise queries in my database?" where I am attempting to learn about indexes, what columns are good index candidates? Specifically for an MS SQL database?

After some googling, everything I have read suggests that columns that are generally increasing and unique make a good index (things like MySQL's auto_increment), I understand this, but I am using MS SQL and I am using GUIDs for primary keys, so it seems that indexes would not benefit GUID columns...

[A]
In general (I don't use mssql so can't comment specifically), primary keys make good indexes. They are unique and must have a value specified. (Also, primary keys make such good indexes that they normally have an index created automatically.)
An index is effectively a copy of the column which has been sorted to allow binary search (which is much faster than linear search). Database systems may use various tricks to speed up search even more, particularly if the data is more complex than a simple number.
My suggestion would be to not use any indexes initially and profile your queries. If a particular query (such as searching for people by surname, for example) is run very often, try creating an index over the relevate attributes and profile again. If there is a noticeable speed-up on queries and a negligible slow-down on insertions and updates, keep the index.
(Apologies if I'm repeating stuff mentioned in your other question, I hadn't come across it previously.)


q:
How do I capture the event of the clicking the Selected Node of a TreeView?
It doesn't fire the SelectedNodeChanged since the selection has obviously not changed but then what event can I catch so I know that the Selected Node was clicked?

UPDATE:
When I have some time, I'm going to have to dive into the bowels of the TreeView control and dig out what and where it handles the click events and subclass the TreeView to expose a new event OnSelectedNodeClicked.

I'll probably do this over the Christmas holidays and I'll report back with the results.

UPDATE:
I have come up with a solution below that sub-classes the TreeView control.

[A]
Easiest way - if it doesn't interfere with the rest of your code - is to simply set the node as not selected in the SelectedNodeChanged method.
```
```
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e){
  // Do whatever you're doing
  TreeView1.SelectedNode.Selected = false;
}
```
```


q:
I'm asking more about what this means to my code.  I understand the concepts mathematically, I just have a hard time wrapping my head around what they mean conceptually.  For example, if one were to perform an O(1) operation on a data structure, I understand that the number of operations it has to perform won't grow because there are more items.  And an O(n) operation would mean that you would perform a set of operations on each element.  Could somebody fill in the blanks here?

Like what exactly would an O(n^2) operation do?

And what the heck does it mean if an operation is O(n log(n))?

And does somebody have to smoke crack to write an O(x!)?

[A]
A lot of these are easy to demonstrate with something non-programming, like shuffling cards.
Sorting a deck of cards by going through the whole deck to find the ace of spades, then going through the whole deck to find the 2 of spades, and so on would be worst case n^2, if the deck was already sorted backwards. You looked at all 52 cards 52 times.
In general the really bad algorithms aren't necessarily intentional, they're commonly a misuse of something else, like calling a method that is linear inside some other method that repeats over the same set linearly.


q: Has anyone out there got a good set of instructions for building/compiling Ruby from source of windows XP ?

[A]
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/184380
I normally get a binary installable for windows.. much faster if you just need Ruby installed. But you may be modifying ruby source.. anyways..
Update:
I ended up compiling Ruby from source today... here is what worked for me
http://madcoderspeak.blogspot.com/2009/06/how-to-compile-ruby-from-source-on.html


q:
I want to debug an application in Visual Studio but I ONLY have the source code for 1 class.  I only need to step through a single function in that file, but I don't understand what I need to do it.  I think the steps are normally something like this:

Open a file in VS

Load in the "symbols" (.PDB file)

Attach to the running process

I know how to do #1 and #3, but I don't how to do #2 without the .PDB file.  Is it possible to generate the .PDB file for this to make it work?  Thanks!

[A]
You need the symbol file (.PDB) file that belongs to the application you are trying to debug.
MSDN: PDB Files
The Visual Studio debugger uses the path to the PDB in the EXE or DLL file to find the project.pdb file. If the debugger cannot find the PDB file at that location, or if the path is invalid, for example, if the project was moved to another computer, the debugger searches the path containing the EXE followed by the symbol paths specified in the Options dialog box. This path is generally the Debugging folder in the Symbols node. The debugger will not load a PDB that does not match the binary being debugged.


q: Most of the implementations I find require a hardware instruction to do this.  However I strongly doubt this is required (if it is, I can't figure out why...)

[A]
You don't need a test and set instruction to get mutual exclusion locking, if thats what you're asking.
Dijkstra described the first mutual exclusion algorithm I am aware of, in 1965. The title of the paper was "Solution of a problem in concurrent programming control", search Google for a copy near you. The original algorithm required no special support from the hardware at all, but providing an atomic instruction in the CPU dramatically improves the performance.
Test-and-set, atomic swap, and load-linked + store-conditional are all common primitives for CPUs to provide. All can be used to implement mutual exclusion, which can then be used to implement whatever locking semantics you want.


q:
I was reading Andrew Kennedy's blog post series on units of measurement in F# and it makes a lot of sense in a lot of cases.  Are there any other languages that have such a system?

Edit: To be more clear, I mean the flexible units of measurement system where you can define your own arbitrarily.

[A]
I'm not sure if this really counts, but the
```
RPL
```
system on my HP-48 calculator does have similar features. I can write
```
40_gal 5_l +
```
and get the right answer of  156.416 liters.


q:
How often should I commit changes to source control ? After every small feature, or only for large features ?

I'm working on a project and have a long-term feature to implement. Currently, I'm committing after every chunk of work, i.e. every sub-feature implemented and bug fixed. I even commit after I've added a new chunk of tests for some feature after discovering a bug.

However, I'm concerned about this pattern. In a productive day of work I might make 10 commits. Given that I'm using Subversion, these commits affect the whole repository, so I wonder if it indeed is a good practice to make so many ?

[A] I like to commit changes every 30-60 minutes, as long as it compiles cleanly and there are no regressions in unit tests.


q:
I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use new I am dynamically allocating memory.

My question is the following:

If i were to use cout << &p, it would display the "virtual memory location" of p.
Is there a way in which I could manipulate this "virtual memory location?"

For example, the following code shows an array of ints.

If I wanted to show the value of p[1] and I knew the "virtual memory location" of p, could I somehow do "&p + 1" and obtain the value of p[1] with cout << *p, which will now point to the second element in the array?

int *p;
p = new int[3];

p[0] = 13;
p[1] = 54;
p[2] = 42;

[A]
Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself.
```
```
int *p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;

cout << *p << ' ' << *(p+1) << ' ' << *(p+2);
```
```
Each addition (or subtraction) mean the subsequent (prior) element in the array. If p points to a 4 byte variable (e.g.
int
on typical 32-bits PCs) at address say 12345, p+1 will point to 12349, and not 12346. Note you want to change the value of what p contains before dereferencing it to access what it points to.


q: They both seem to be sending data to the server inside the body, so what makes them different?

[A]
PUT is meant as a a method for "uploading" stuff to a particular URI, or overwriting what is already in that URI.
POST, on the other hand, is a way of submitting data RELATED to a given URI.
Refer to
the HTTP RFC


q: What are the down sides of using a composite/compound primary key?

[A]
Need more specificity.
Taken too far, it can overcomplicate Inserts (Every key MUST exist) and documentation and your joined reads could be suspect if incomplete.
Sometimes it can indicate a flawed data model (is a composite key REALLY what's described by the data?)
I don't believe there is a performance cost...it just can go really wrong really easily.


q: What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if http://somedomain/foo/ will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this?

[A]
edit
: This answer works, but nowadays you should just use the
requests
library as mentioned by other answers below.
Use
httplib
.
```
```
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
```
```
There's also a
```
getheader(name)
```
to get a specific header.


q:
I have a 3d object that I wish to be able to rotate around in 3d.  The easiest way is to directly translate X and Y mouse motion to rotation about the Y and X axes, but if there is some rotation along both axes, the way the model rotates becomes highly counterintuitive (i.e. if you flip the object 180 degrees about one axis, your motion along the other axis is reversed).

I could simply do the above method, but instead of storing the amount to rotate about the two axes, I could store the full rotation matrix and just further rotate it along the same axes for each mouse drag, but I'm concerned that that would quickly have precision issues.

[A]
Create an accumulator matrix and initialize it with the identity.
Each frame, apply that to your modelview/world matrix state before drawing the object.
Upon mouse motion, construct a rotation matrix about the X axis with some sensitivity_constant * delta_x.  Construct another rotation matrix about the Y axis for the other component.  Multiply one, then the other onto the accumulator.
The accumulator will change as you move the mouse.  When drawing, it will orient the object as you expect.
Also, the person talking about quaternions is right; this will look good only for small incremental changes.  If you drag it quickly on a diagonal, it won't rotate quite the way you expect.


q:
As a base SAS programmer, you know the drill:

You submit your SAS code, which contains an unbalanced quote, so now you've got not only and unclosed quote, but also unclosed comments, macro function definitions, and a missing run; or quit; statement.

What's your best trick for not having those unbalanced quotes bother you?

[A]
As for myself, I usually
Google for "SAS unbalanced quote"
, and end up with submitting something like
this
:
```
```
*); */; /*’*/ /*”*/; %mend;
```
```
... to break out of unclosed comments, quotes and macro functions.


q:
There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO."

Is JavaScript an object-oriented language?

[A]
The short answer is Yes. For more information:
From
Wikipedia
:
JavaScript is heavily object-based.
  Objects are associative arrays,
  augmented with prototypes (see below).
  Object property names are associative
  array keys: obj.x = 10 and obj["x"] =
  10 are equivalent, the dot notation
  being merely syntactic sugar.
  Properties and their values can be
  added, changed, or deleted at
  run-time. The properties of an object
  can also be enumerated via a for...in
  loop.
Also, see
this series of articles
about OOP with Javascript.


q:
When we compile a dll using __stdcall inside visual studio 2008 the compiled function names inside the dll are.

FunctionName

Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like.

FunctionName@numberOfParameters or == FunctionName@8

How do you tell GCC compiler to remove @nn from exported symbols in the dll?

[A]
__stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters to the end (separated by @).
So, a function:
```
```
void __stdcall Foo(int a, int b);
```
```
...would become _Foo@8.
If you list the function name (undecorated) in the EXPORTS section of your .DEF file, it is exported undecorated.
Perhaps this is the difference?


q:
How do you unit test a large MFC UI application?

We have a few large MFC applications that have been in development for many years, we use some standard automated QA tools to run basic scripts to check fundamentals, file open etc. These are run by the QA group post the daily build.

But we would like to introduce procedures such that individual developers can build and run tests against dialogs, menus, and other visual elements of the application before submitting code to the daily build.

I have heard of such techniques as hidden test buttons on dialogs that only appear in debug builds, are there any standard toolkits for this.

Environment is C++/C/FORTRAN, MSVC 2005, Intel FORTRAN 9.1, Windows XP/Vista x86 & x64.

[A]
Well we have one of these humongous MFC Apps at the workplace. Its a gigantic pain to maintain or extend... its a huge ball of mud now but it rakes in the moolah.Anyways
We use
Rational Robot
for doing smoke tests and the like.
Another approach that has had some success is to create a small product-specific language and
script tests
that use VBScript and some Control handle spying magic. Turn common actions into commands.. e.g. OpenDatabase would be a command that in turn will inject the required script blocks to click on Main Menu > File > "Open...". You then create excel sheets which are a series of such commands. These commands can take parameters too. Something like a FIT Test.. but more work. Once you have most of the common commands identified and scripts ready. It's pick and assemble scripts (tagged by CommandIDs) to write new tests. A test-runner parses these Excel sheets, combines all the little script blocks into a test script and runs it.
OpenDatabase "C:\tests\MyDB"
OpenDialog "Add Model"
AddModel "M0001", "MyModel", 2.5, 100
PressOK
SaveDatabase
HTH


q: I need to load some fonts temporarily in my program. Preferably from a dll resource file.

[A]
I found
this
with Google. I have cut & pasted the relevant code below.
You need to add the font to your resource file:
```
```
34 FONT "myfont.ttf"
```
```
The following C code will load the font from the DLL resource and release it from memory when you are finished using it.
```
DWORD   Count;
HMODULE Module   = LoadLibrary("mylib.dll");
HRSRC   Resource = FindResource(Module,MAKEINTRESOURCE(34),RT_FONT);
DWORD   Length   = SizeofResource(Module,Resource);
HGLOBAL Address  = LoadResource(Module,Resource);
HANDLE  Handle   = AddFontMemResourceEx(Address,Length,0,&Count);

/* Use the font here... */

RemoveFontMemResourceEx(Handle);
FreeLibrary(Module);
```


q:
So the official XML-RPC standard doesn't support 64-bit values.  But in these modern times, 64-bit values are increasingly common.

How do you handle these?  What XML-RPC extensions are the most common?  What language bindings are there?  I'm especially interested in Python and C++, but all information is appreciated.

[A]
I don't know anything about how XMLRPC could be extended but I did find
this mail
about the subject:
In XML-RPC, everything is transmitted
  as a string, so I don't think that
  choice is really that bad - except of
  course for the additional clumsiness
  for invoking explicit conversion
  functions.
But no, XML-RPC doesn't have a data
  type that can represent integers above
  2**32. If you can accept losing
  precision, you can use doubles (but
  you still would have to convert
  explicitly on the sender).


q:
What is the best (regarding performance) way to compute the critical path of a directional acyclic graph when the nodes of the graph have weight?

For example, if I have the following structure:

            Node A (weight 3)
               /            \
     Node B (weight 4)      Node D (weight 7)
     /               \
Node E (weight 2)   Node F (weight 3)

The critical path should be A->B->F (total weight: 10)

[A]
I have no clue about "critical paths", but I assume you mean
this
.
Finding the longest path in an acyclic graph with weights is only possible by traversing the whole tree and then comparing the lengths, as you never really know how the rest of the tree is weighted. You can find more about tree traversal at
Wikipedia
. I suggest, you go with pre-order traversal, as it's easy and straight forward to implement.
If you're going to query often, you may also wish to augment the edges between the nodes with information about the weight of their subtrees at insertion. This is relatively cheap, while repeated traversal can be extremely expensive.
But there's nothing to really save you from a full traversal if you don't do it. The order doesn't really matter, as long as you do a
traversal
and never go the same path twice.


q:
I'd like to build a real quick and dirty administrative backend for a Ruby on Rails application I have been attached to at the last minute. I've looked at activescaffold and streamlined and think they are both very attractive and they should be simple to get running, but I don't quite understand how to set up either one as a backend administration page. They seem designed to work like standard Ruby on Rails generators/scaffolds for creating visible front ends with model-view-controller-table name correspondence.

How do you create a admin_players interface when players is already in use and you want to avoid, as much as possible, affecting any of its related files?

The show, edit and index of the original resource are not usuable for the administrator.

[A]
I have used Streamlined pretty extensively.
To get Streamline working you create your own controllers - so you can actually run it completely apart from the rest of your application, and you can even run it in a separate 'admin' folder and namespace that can be secured with
.
Here is the Customers controller from a recent app:
```
```
class CustomersController < ApplicationController
  layout 'streamlined'
  acts_as_streamlined

  Streamlined.ui_for(Customer) do
    exporters :csv
    new_submit_button :ajax => false
    default_order_options :order => "created_at desc"
    list_columns :name, :email, :mobile, :comments, :action_required_yes_no
  end
end
```
```


q:
I'd like to unit test responses from the Google App Engine webapp.WSGIApplication, for example request the url '/' and test that the responses status code is 200, using GAEUnit. How can I do this?

I'd like to use the webapp framework and GAEUnit, which runs within the App Engine sandbox (unfortunately WebTest does not work within the sandbox).

[A]
Actually WebTest does work within the sandbox, as long as you comment out
```
```
import webbrowser
```
```
in webtest/__init__.py


q:
Is output buffering enabled by default in Python's interpreter for sys.stdout?

If the answer is positive, what are all the ways to disable it?

Suggestions so far:

Use the -u command line switch

Wrap sys.stdout in an object that flushes after every write

Set PYTHONUNBUFFERED env var

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Is there any other way to set some global flag in sys/sys.stdout programmatically during execution?

[A]
From
Magnus Lycka answer on a mailing list
:
You can skip buffering for a whole
python process using
```
python -u
```
or by
setting the environment variable
PYTHONUNBUFFERED.
You could also replace sys.stdout with
some other stream like wrapper which
does a flush after every call.
```
```
class Unbuffered(object):
   def __init__(self, stream):
       self.stream = stream
   def write(self, data):
       self.stream.write(data)
       self.stream.flush()
   def writelines(self, datas):
       self.stream.writelines(datas)
       self.stream.flush()
   def __getattr__(self, attr):
       return getattr(self.stream, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'
```
```


q:
Are there any import and export tools that would let us move projects into and out of team system with full history and log? Our current SCM is SVN.

PS - Sorry, I know it's a repost, but I didn't get an answer before... :)

[A]
Unfortunately, you probably didn't get an answer because there isn't a good one on offer...
I've looked into this a couple of times before, initially for the first TFS Betas.
(At the time we were eager to move away from VSS while waiting for TFS to be ready... the compromise we ended up with then was to use SVN in the interim, but used a post commit hook that kept a VSS repository in sync to allow for that migration path to TFS.)
These guys (ComponentSource)
were around back then with a VSS to TFS converter, and added a SVN to TFS one, but appear to have since discontinued the product.
These guys (Kyrosoft)
might have some promise, but I'm concerned that they don't post prices, and do post a customer list (of two).  If anyone has experience with the product, please let us all know.
More recently the TFS Migration and Synchronization Toolkit has been released on CodePlex, but to date no one has release a SVN plugin for it (there are 66 votes for the
request
)
So, you can look at rolling your own plugin for the toolkit, but even then you won't get the original dates for commits, as to my knowledge the TFS team haven't allowed a mechanism for importers to set this, so all migrated revisions will have the date of migration.
(The discontinued first tool above purportedly used to allow this, but how they got around the limitation (secret API? adjusting system time? database manipulation?) I don't know.)
In the end, I suspect most teams end up deciding to just switch systems at an appropriate time (eg new version or project), and manually deal with the bifurcated history lookup for the 6-12 months it remains particularly problematic...


q:
(Jeopardy-style question, I wish the answer had been online when I had this issue)

Using Java 1.4, I have a method that I want to run as a thread some of the time, but not at others. So I declared it as a subclass of Thread, then either called start() or run() depending on what I needed.

But I found that my program would leak memory over time. What am I doing wrong?

[A]
This is a known bug in Java 1.4:
http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=5869e03fee226ffffffffc40d4fa881a86e3:WuuT?bug_id=4533087
It's fixed in Java 1.5 but Sun doesn't intend to fix it in 1.4.
The issue is that, at construction time, a
```
Thread
```
is added to a list of references in an internal thread table. It won't get removed from that list until its start() method has completed. As long as that reference is there, it won't get garbage collected.
So, never create a thread unless you're definitely going to call its
```
start()
```
method. A
```
Thread
```
object's
```
run()
```
method should not be called directly.
A better way to code it is to implement the
```
Runnable
```
interface rather than subclass
```
Thread
```
. When you don't need a thread, call
```
```
myRunnable.run();
```
```
When you do need a thread:
```
```
Thread myThread = new Thread(myRunnable);
myThread.start();
```
```


q: I don't want PHP errors to display /html, but I want them to display in /html/beta/usercomponent. Everything is set up so that errors do not display at all. How can I get errors to just show up in that one folder (and its subfolders)?

[A]
I don't believe there's a simple answer to this
, but I'd certainly want to  be proven wrong.
edit: turns out this can be controlled from .htaccess files. Thanks people! :)
You can use error_reporting()
http://docs.php.net/manual/en/function.error-reporting.php
to switch the setting on a script by script basis, though. If you happen to have a single script which is included every time at /html/beta/usercomponent, this will do the trick.


q:
I've encrypted the connectionstring in my web.config file using the steps in the link below:
http://www.codeproject.com/KB/database/WebFarmConnStringsNet20.aspx

However, whenever I call my application, it will give the following error:

Failed to decrypt using provider
  'CustomProvider'. Error message from
  the provider: The RSA key container
  could not be opened.

The server where I perform the encryption is a 64-bit Windows Server 2003 R2 SP2. Because of that I assign the ACL to NT Authority\Network Service. Yet it still doesn't work.

Hope someone has some ideas what else do I need to check to get this working.

PS. If I used the default rsa key NetFrameworkConfigurationKey for encryption, then the connection string will not have an access problem.

[A]
Did you remember to add the
```
```
<configProtectedData>
```
```
to your web.config?


q: How many lines of code can a .java file contain? Does it depend on the JVM being used?

[A] I believe there is a 64kb limit on bytecode size per method.


q: I have Laconica (self hosted twitter) configured on my local intranet and would like to integrate the public stream into SharePoint site with a web part.  How can I do this?

[A]
You can point an RSS Viewer web part at the laconi.ca public stream RSS feed and use this XSLT to ensure attractive output.
Result screen shot:
XSL transform:
```
```
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" version="1.0" exclude-result-prefixes="xsl ddwrt msxsl rssaggwrt"
               xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
               xmlns:rssaggwrt="http://schemas.microsoft.com/WebParts/v3/rssagg/runtime"
               xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xmlns:msxsl="urn:schemas-microsoft-com:xslt"
               xmlns:rssFeed="urn:schemas-microsoft-com:sharepoint:RSSAggregatorWebPart"
               xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
               xmlns:dc="http://purl.org/dc/elements/1.1/"
               xmlns:rss="http://purl.org/rss/1.0/"
               xmlns:atom="http://www.w3.org/2005/Atom"
               xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
               xmlns:atom2="http://purl.org/atom/ns#"
               xmlns:ddwrt2="urn:frontpage:internal"
               xmlns:laconica="http://laconi.ca/ont/">
  <xsl:param name="rss_FeedLimit">5</xsl:param>
  <xsl:param name="rss_ExpandFeed">false</xsl:param>
  <xsl:param name="rss_LCID">1033</xsl:param>
  <xsl:param name="rss_WebPartID">RSS_Viewer_WebPart</xsl:param>
  <xsl:param name="rss_alignValue">left</xsl:param>
  <xsl:param name="rss_IsDesignMode">True</xsl:param>
  <xsl:template match="rdf:RDF">
    <xsl:call-template name="RDFMainTemplate"/>
  </xsl:template>
  <xsl:template name="RDFMainTemplate" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
    <xsl:variable name="Rows" select="rss:item"/>
    <xsl:variable name="RowCount" select="count($Rows)"/>

      <xsl:call-template name="RDFMainTemplate.body">
        <xsl:with-param name="Rows" select="$Rows"/>
        <xsl:with-param name="RowCount" select="count($Rows)"/>
      </xsl:call-template>

  </xsl:template>
  <xsl:template name="RDFMainTemplate.body" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
    <xsl:param name="Rows"/>
    <xsl:param name="RowCount"/>
    <xsl:for-each select="$Rows">
      <xsl:variable name="CurPosition" select="position()" />
      <xsl:variable name="RssFeedLink" select="$rss_WebPartID" />
      <xsl:variable name="CurrentElement" select="concat($RssFeedLink,$CurPosition)" />
      <xsl:if test="($CurPosition <= $rss_FeedLimit)">
        <xsl:element name="div">
          <xsl:if test="($CurPosition mod 2 = 1)">
            <xsl:attribute name="style"><![CDATA[background-color:#F9F9F9;]]></xsl:attribute>
          </xsl:if>
          <xsl:element name="table">
            <xsl:attribute name="cellpadding">0</xsl:attribute>
            <xsl:attribute name="border">0</xsl:attribute>
            <xsl:attribute name="style"><![CDATA[margin:0px;padding:0px;border-spacing:0px;background-color:transparent;]]></xsl:attribute>
            <xsl:element name="tr">
              <xsl:element name="td">
                <xsl:attribute name="style"><![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]></xsl:attribute>
                <xsl:attribute name="rowspan">2</xsl:attribute>
                <xsl:element name="img">
                  <xsl:attribute name="src"><xsl:value-of select="laconica:postIcon/@rdf:resource"/></xsl:attribute>
                  <xsl:attribute name="style"><![CDATA[margin:3px;height:48px;width:48px;]]></xsl:attribute>
                </xsl:element>
              </xsl:element>
              <xsl:element name="td">
                <xsl:attribute name="style"><![CDATA[vertical-align:top;padding:0px;background-color:transparent;]]></xsl:attribute>

                  <xsl:value-of select="substring-before(rss:title, ':')"/>

                    <xsl:value-of select="substring-after(rss:title, ':')"/>

              </xsl:element>
            </xsl:element>
            <xsl:element name="tr">
              <xsl:element name="td">
                <xsl:attribute name="style"><![CDATA[padding:0px;background-color:transparent;]]></xsl:attribute>
                <xsl:element name="a">
                  <xsl:attribute name="href"><xsl:value-of select="rss:link"/></xsl:attribute>
                  <xsl:value-of select="ddwrt:FormatDate(dc:date,number($rss_LCID),15)"/>
                </xsl:element>
              </xsl:element>
            </xsl:element>
          </xsl:element>
        </xsl:element>
      </xsl:if>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
```
```


q:
I have a legacy web site in ColdFusion MX 2004.  I'm re-writing it in .Net, so I don't want to pay $600+ for an upgrade to the latest version of ColdFusion, nor do I want to go through the (very large) site fixing version incompatibilities.

I often have to track down and fix bugs in the site.

A source-level debugger that would let me step through the code line-by-line and examine variables would be a HUGE time-saver.

Does anyone have experience using any of the third-party ColdFusion source-level debuggers?

[A]
There's no such thing as ColdFusion MX 2004, neither in name nor release year (CFMX 6.1 was released in 2003, and CFMX 7 was released in 2005).
FusionDebug
supports all versions of CFMX from 6.1 onwards.
You may want to investigate
BlueDragon.NET
, which allows you to run CFML code on the .NET platform, and may make the transition easier for you.


q:
On Linux/GCC I can use the -rpath flag to change an executables search path for shared libraries without tempering with environment variables.

Can this also  be accomplished on Windows? As far as I know, dlls are always searched in the executable's directory and in PATH.

My scenario: I would like to put shared libraries into locations according to their properties (32/64bit/Debug/Release) without taking care of unique names. On Linux, this is easily be done via rpath, but I haven't found any way doing this on Windows yet.

Thanks for any hints!

[A]
The search order for DLLs in Windows is described on
this page
on MSDN. If you're using
run-time dynamic linking
, you can specify the folder when you call
```
LoadLibrary
```
.


q:
I am using YUI reset/base, after the reset it sets the ul and li tags to list-style: disc outside;

My markup looks like this:

<div id="nav">
     <ul class="links">
         <li><a href="">Testing</a></li>
     </ul>

</div>

My CSS is:

#nav {}
#nav ul li {
    list-style: none;
 }

Now that makes the small disc beside each li disappear.

Why doesn't this work though?

 #nav {}
 #nav ul.links
 {
      list-style: none;
 }

It works if I remove the link to the base.css file, why?.

Updated: sidenav -> nav

[A]
shouldn't it be:
```
```
#nav ul.links
```
```


q:
The unzip command doesn't have an option for recursively unzipping archives.

If I have the following directory structure and archives:

/Mother/Loving.zip
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes.zip

And I want to unzip all of the archives into directories with the same name as each archive:

/Mother/Loving/1.txt
/Mother/Loving.zip
/Scurvy/Sea Dogs/2.txt
/Scurvy/Sea Dogs.zip
/Scurvy/Cures/Limes/3.txt
/Scurvy/Cures/Limes.zip

What command or commands would I issue?

It's important that this doesn't choke on filenames that have spaces in them.

[A]
Here's one solution that extracts all zip files to the
working directory
and involves the find command and a while loop:
```
```
find . -name "*.zip" | while read filename; do unzip -o -d "`basename -s .zip "$filename"`" "$filename"; done;
```
```


q:
I'm working on a simple multiplayer game in which 2-4 players are placed at separate entrypoints in a maze and need to reach a goal point.  Generating a maze in general is very easy, but in this case the goal of the game is to reach the goal before everyone else and I don't want the generation algorithm to drastically favor one player over others.

So I'm looking for a maze generation algorithm where the optimal path for each player from the startpoint to the goal is no more than 10% more steps than the average path.  This way the players are on more or less an equal playing field.  Can anyone think up such an algorithm?

(I've got one idea as it stands, but it's not well thought out and seems far less than optimal -- I'll post it as an answer.)

[A] The easiest solution I can come up with is to randomly generate an entire maze like normal, then randomly pick the goal point and player startpoints.  Once this is done, calculate the shortest path from each startpoint to the goal.  Find the average and start 'smoothing' (remove/move barriers -- don't know how this will work) the paths that are significantly above it, until all of the paths are within the proper margin.  In addition, it could be possible to take the ones that are significantly below the average and insert additional barriers.


q:
We are looking for a reliable "current weather" web service for Europe, with city resolution. We only need the current weather.

Since it is for a commercial web site, we don't mind paying a reasonable fee for the service.

What are our options? What service would you recommend or avoid based on previous experience?

Note: SOAP Web Service, XML RPC, REST, all are fine.

[A]
You should be able to interface with
Yahoo weather Europe
like the team of the
weather plasmoid
did.
Or if you only need to add it to a web page you could use directly
this gadget


q:
Could anybody explain in plain words how Cloud computing works?
I have read the Wikipedia article, but still not sure that I understand how cloud actually works.

[A]
Aside from the latest marketing term?
Basically all the resources your program needs are held "somewhere" on the internet. You interact with them via a defined service contract; SOAP, REST, POX or whatever and what happens after that is up to the service provider. You don't care about how your information is stored or how the service is provided, just that it is.
If, for example, you wanted to store files, you may choose to use Amazon's S3 cloud system. You connect to the service and upload your files; you don't know or care where the files are stored, only the location of the entry point to that service.
If you have an application then it may also be ran in the cloud, assuming it's suitable. Live Mesh for example is a virtual machine which you can code against and run your software both locally and within the cloud, so your user simply goes to a URI and finds your program, you don't care where it is beyond it being available somewhere on the cloud.


q: When I create a socket using accept() and make a FILE out of it using fdopen(), what do I have to do to clean everything up? Do I need to do fclose() on the FILE, shutdown() and close() on the socket, or only the shutdown() and or close() or fclose()? If I don't do fclose(), do I have to free() the FILE pointer manually?

[A]
You have 2 things here you need to clean up: the stream represented by
```
FILE
```
and the file descriptor represented by the socket. You need to close the stream first, then the file descriptor. So, in general you will need to
```
fclose()
```
any
```
FILE
```
objects, then
```
close()
```
any file descriptors.
Personally I have never used
```
shutdown()
```
when I want to cleanup after myself, so I can't say.
edit
Others have correctly pointed out that
```
fdclose()
```
will also close the underlying file descriptor, and since calling
```
close()
```
on a close file descriptor will lead to an error, in this case you only need
```
fdclose()
```
.


q:
I'm working on a large application (300K LOC) that is causing a memory leak in the Sun 1.6 JVM (1.6_05). Profiling the Java shows no leak. Are there any diagnostics available from the JVM that might detect the cause of the leak?

I haven't been able to create a simple, isolated Java test case. Is the only way to figure this out by using a C heap analyzer on the JVM?

The application creates a pool of sockets and does a significant amount of network I/O.

[A]
Some profiler like profiler4j can show the managed and the unmanaged memory (live curve). Then you can see if you has a leak and when the leak occur. But you does not find more informations.
After this there are 2 possible solutions:
You can with the live curve isolate the problem and create a simpler test until you have find the cause of the problem.
You search your code for the typical problems like:
Instances of the class Thread that are never start.
Images or Graphics that never are dispose
ODBC Bridge Objects that are never close


q: when they say the action controller in the struts framework is multi threaded, does it mean that there are multiple instances of the servlet taking the request and forwarding it to the model. OR does it mean that there is one single instance taking all the requests? Any visuals will be appreciated


q: Are there any good, cross platform (SBCL and CLISP at the very least) easy to install GUI libraries?

[A]
Ltk
is quite popular, very portable, and reasonably well documented through the Tk docs.  Installation on SBCL is as easy as saying:
```
```
(require :asdf-install)
(asdf-install:install :ltk)
```
```
There's also
Cells-Gtk
, which is reported to be quite usable but may have a slightly steeper learning curve because of its reliance on Cells.
EDIT: Note that ASDF-INSTALL is integrated this well with SBCL
only
.  Installing libraries from within other Lisp implementations may prove harder.  (Personally, I always install my libraries from within SBCL and then use them from all implementations.)  Sorry about any confusion this may have caused.


q:
Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"

So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?

So I have

typeof(int)
typeof(DateTime)
System.Type t = something;

and I want

int?
DateTime?

or

Nullable<int> (which is the same)
if (t is primitive) then Nullable<T> else just T

Is there a built-in method?

[A]
Here is the code I use:
```
```
Type GetNullableType(Type type) {
    // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.
    type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null
    if (type.IsValueType)
        return typeof(Nullable<>).MakeGenericType(type);
    else
        return type;
}
```
```


q: What problems does MEF (Managed Extensibility Framework) solves that cannot be solved by existing IoC/DI containers?

[A]
The principle purpose of MEF is extensibility; to serve as a 'plug-in' framework for when the author of the application and the author of the plug-in (
extension
) are different and have no particular knowledge of each other beyond a published interface (
contract
) library.
Another problem space MEF addresses that's different from the usual IoC suspects, and one of MEFs strengths, is [extension] discovery. It has a lot of, well, extensible discovery mechanisms that operate on metadata you can associate with extensions. From the MEF CodePlex site:
"MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering"
Combined with an ability to delay-load tagged extensions, being able to interrogate extension metadata
prior
to loading opens the door to a slew of interesting scenarios and substantially enables capabilities such as [plug-in] versioning.
MEF also has 'Contract Adapters' which allow extensions to be 'adapted' or 'transformed' (
from type > to type
) with complete control over the details of those transforms. Contract Adapters open up another creative front relative to just what 'discovery' means and entails.
Again, MEFs 'intent' is tightly focused on anonymous plug-in extensibility, something that very much differentiates it from other IoC containers. So while MEF can be used for composition, that's merely a small intersection of its capabilities relative to other IoCs, with which I suspect we'll be seeing a lot of incestuous interplay going forward.


q:
I am using pyexcelerator Python module to generate Excel files.
I want to apply bold style to part of cell text, but not to the whole cell.
How to do it?

[A]
This is an example from Excel documentation:
```
```
With Worksheets("Sheet1").Range("B1")
    .Value = "New Title"
    .Characters(5, 5).Font.Bold = True
End With
```
```
So the Characters property of the cell you want to manipulate is the answer to your question. It's used as Characters(
start
,
length
).
PS: I've never used the module in question, but I've used Excel COM automation in python scripts. The Characters property is available using win32com.


q:
I know that it's possible to replace the browse button, which is generated in html, when you use input tag with type="file.

I'm not sure what is the best way, so if someone has experience with this please contribute.

[A]
The best way is to make the file input control
almost
invisible (by giving it a very low opacity - do not do "
visibility: hidden
" or "
display: none
") and absolutely position something under it - with a lower
z-index
.
This way, the actual control will not be visible, and whatever you put under it will show through. But since the control is positioned above that button, it will still capture the click events (this is why you want to use opacity, not visibility or display - browsers make the element unclickable if you use those to hide it).
This article
goes in-depth on the technique.


q:
Given a list, how would I select a new list, containing a slice of the original list (Given offset and number of elements) ?

EDIT:

Good suggestions so far. Isn't there something specified in one of the SRFI's? This appears to be a very fundamental thing, so I'm surprised that I need to implement it in user-land.

[A]
The following code will do what you want:
```
```
(define get-n-items
    (lambda (lst num)
        (if (> num 0)
            (cons (car lst) (get-n-items (cdr lst) (- num 1)))
            '()))) ;'

(define slice
    (lambda (lst start count)
        (if (> start 1)
            (slice (cdr lst) (- start 1) count)
            (get-n-items lst count))))
```
```
Example:
```
```
> (define l '(2 3 4 5 6 7 8 9)) ;'
()
> l
(2 3 4 5 6 7 8 9)
> (slice l 2 4)
(3 4 5 6)
>
```
```


q:
class Tag(models.Model):
  name = models.CharField(maxlength=100)

class Blog(models.Model):
  name = models.CharField(maxlength=100)
  tags =  models.ManyToManyField(Tag)

Simple models just to ask my question.

I wonder how can i query blogs using tags in two different ways.

Blog entries that are tagged with "tag1" or "tag2":
Blog.objects.filter(tags_in=[1,2]).distinct()

Blog objects that are tagged with "tag1" and "tag2" : ?

Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : ??

Tag and Blog is just used for an example.

[A]
You could use Q objects for #1:
```
```
# Blogs who have either hockey or django tags.
from django.db.models import Q
Blog.objects.filter(
    Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')
)
```
```
Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these.  The following examples are from a Django application called called
django-tagging
that provides the functionality.
Line 346 of models.py
:
For part two, you're looking for a union of two queries, basically
```
```
def get_union_by_model(self, queryset_or_model, tags):
    """
    Create a ``QuerySet`` containing instances of the specified
    model associated with *any* of the given list of tags.
    """
    tags = get_tag_list(tags)
    tag_count = len(tags)
    queryset, model = get_queryset_and_model(queryset_or_model)

    if not tag_count:
        return model._default_manager.none()

    model_table = qn(model._meta.db_table)
    # This query selects the ids of all objects which have any of
    # the given tags.
    query = """
    SELECT %(model_pk)s
    FROM %(model)s, %(tagged_item)s
    WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
      AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
      AND %(model_pk)s = %(tagged_item)s.object_id
    GROUP BY %(model_pk)s""" % {
        'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
        'model': model_table,
        'tagged_item': qn(self.model._meta.db_table),
        'content_type_id': ContentType.objects.get_for_model(model).pk,
        'tag_id_placeholders': ','.join(['%s'] * tag_count),
    }

    cursor = connection.cursor()
    cursor.execute(query, [tag.pk for tag in tags])
    object_ids = [row[0] for row in cursor.fetchall()]
    if len(object_ids) > 0:
        return queryset.filter(pk__in=object_ids)
    else:
        return model._default_manager.none()
```
```
For part #3 I believe you're looking for an intersection. See
line 307 of models.py
```
```
def get_intersection_by_model(self, queryset_or_model, tags):
    """
    Create a ``QuerySet`` containing instances of the specified
    model associated with *all* of the given list of tags.
    """
    tags = get_tag_list(tags)
    tag_count = len(tags)
    queryset, model = get_queryset_and_model(queryset_or_model)

    if not tag_count:
        return model._default_manager.none()

    model_table = qn(model._meta.db_table)
    # This query selects the ids of all objects which have all the
    # given tags.
    query = """
    SELECT %(model_pk)s
    FROM %(model)s, %(tagged_item)s
    WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
      AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
      AND %(model_pk)s = %(tagged_item)s.object_id
    GROUP BY %(model_pk)s
    HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
        'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
        'model': model_table,
        'tagged_item': qn(self.model._meta.db_table),
        'content_type_id': ContentType.objects.get_for_model(model).pk,
        'tag_id_placeholders': ','.join(['%s'] * tag_count),
        'tag_count': tag_count,
    }

    cursor = connection.cursor()
    cursor.execute(query, [tag.pk for tag in tags])
    object_ids = [row[0] for row in cursor.fetchall()]
    if len(object_ids) > 0:
        return queryset.filter(pk__in=object_ids)
    else:
        return model._default_manager.none()
```
```


q:
I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.

BTW, this is an on-page Ajax search, so it has no button.

[A]
You can add and remove a special CSS class and modify the input value
```
onfocus
```
/
```
onblur
```
with JavaScript:
```
```
<input type="text" class="hint" value="Search..."
    onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
    onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">
```
```
Then specify a
hint
class with the styling you want in your CSS for example:
```
```
input.hint {
    color: grey;
}
```
```


q:
I want to add a column to an existing legacy database and write a procedure by which I can assign each record a different value. Something like adding a column and autogenerate the data for it.

Like, if I add a new column called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID column will have records from say 1 to 1000.

How do I do that?

[A]
This will depend on the database but for SQL Server, this could be achieved as follows:
```
```
alter table Example
add NewColumn int identity(1,1)
```
```


q:
As a novice, I've spent time learning a smattering of C and a fair bit of PHP. I've looked at writing desktop applications for Windows, but there seems to be a fair barrier to entry due to complexity of APIs. Is it worth learning this, or will native applications become less common in the future?

The way I see it, the only desktop application I ever use is a web browser and a text editor as well as the obviously the OS itself. Everything I need is online now.

Is learning to write non-web applications a useful skill going forwards? If so, what should I learn?

[A]
You should learn whatever you
want
to learn.  If you don't you'll probably find it harder going than you need to.
I personally started writing desktop applications for Windows, because I used it at the time.  These days I do think that you're correct - you can produce a website / online-application without investing so much into the process.
But even writing a decent web application is going to be hard if you're new to programming.  A standalone page is simple, but when you add databases, security, and administration into the mix then things can grow.


q:
I come from the Microsoft world (and I come in peace). I want to rapidly prototype a web app and if it works out, take it live - and I don't want to use ASP.Net.

I am not sure which web application toolkit to use though. Should I use GWT, DOJO...other recommendations?  I am open to any server-side language but am looking at RoR, Php or even Java (J2EE to be precise). I am not much of a Javascript/CSS guy so a toolkit that might make it relatively easy on me on those fronts would be preferable.

Also, I am a mac user at home. What IDEs go along with the framework you would recommend?

Any recommendations guys?

[A]
If you're open to doing Java, GWT is the way to go. It allows you to have a relatively uniform codebase across client-server, and to only use one language on both.
There are some limitations to doing very off-the-beaten-path AJAXy things (which GWT makes difficult, but not impossible), but it doesn't sound like that's your use case anyway.
GWT will allow you to scale up by using more of its features as your app gets more complex - and your prototype won't be throwaway code.