q:
How would you design a database to support the following tagging features:

items can have a large number of tags

searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search)

creating/writing items may be slower to enable quick lookup/reading

Ideally, the lookup of all items that are tagged with (at least) a set of n given tags should be done using a single SQL statement. Since the number of tags to search for as well as the number of tags on any item are unknown and may be high, using JOINs is impractical.

Any ideas?

Thanks for all the answers so far.

If I'm not mistaken, however, the given answers show how to do an OR-search on tags. (Select all items that have one or more of n tags). I am looking for an efficient AND-search. (Select all items that have ALL n tags - and possibly more.)

[A]
I don't see a problem with a straightforward solution: Table for items, table for tags, crosstable for "tagging"
Indices on cross table should be enough optimisation. Selecting appropriate items would be
```
```
SELECT * FROM items WHERE id IN
    (SELECT DISTINCT item_id FROM item_tag WHERE
    tag_id = tag1 OR tag_id = tag2 OR ...)
```
```
AND tagging would be
```
```
SELECT * FROM items WHERE
    EXISTS (SELECT 1 FROM item_tag WHERE id = item_id AND tag_id = tag1)
    AND EXISTS (SELECT 1 FROM item_tag WHERE id = item_id AND tag_id = tag2)
    AND ...
```
```
which is admittedly, not so efficient for large number of comparing tags. If you are to maintain tag count in memory, you could make query to start with tags that are not often, so AND sequence would be evaluated quicker. Depending on expected number of tags to be matched against and expectancy of matching any single of them this could be OK solution, if you are to match 20 tags, and expect that some random item will match 15 of them, then this would still be heavy on a database.


q:
Does anyone know of a similar product to Citrix Server that'll run on the Mac OS?

Essentially, I'm looking to allow multiple remote users to log in to the same OSX Server at the same time (with full visual desktop, not SSH).

[A]
OS X's Quartz window server has no remoting abilities, unlike
its predecessor
. X11
does
, but 'native' OS X applications don't use that; of the few Mac apps typically run in X11 (such as GIMP or CrossOver), none are specific to the Mac, so you might as well run them on a different OS.
That said, if all you want is to visually remote-control a session, it is possible to use VNC or a derivative, such as Apple Remote Desktop. Since 10.4, this allows for multiple simultaneous sessions,
as implemented with Vine Server
. Remote Desktop also has other abilities such as remotely installing and updating software.
(Unlike Citrix and X11, VNC does
not
send drawing commands over the network; it instead transmits a compressed image representation pixel-per-pixel.)
You should specify your exact needs.
You will not get a Citrix-like experience where you can run single Mac apps in their own remote session.
You will, however, get remote graphical control, and that
may
be more than enough for you.

s: huggingface

c: devops

d: intermediate


q:
I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this ?

The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though.

[A]
Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does.
So to do this, just wrap your single object in an IEnumerable.
Even this would work:
```
```
DataBindObject.DataSource = new List<YourObject>().Add(YourObjectInstance);
```
```


q:
I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target;

<target name="publish-artifacts-to-build">
    <msbuild project="my-solution.sln" target="Publish">
      <property name="Configuration" value="debug" />
      <property name="OutDir" value="builds\" />
      <arg line="/m:2 /tv:3.5" />
    </msbuild>
</target>

and all I get is this as a response;

[msbuild]          Skipping unpublishable project.

Is it possible to publish web applications via the command line in this way?

[A]
The "Publish" target you are trying to invoke is for "OneClick" deployment, not for publishing a website...  This is why you are getting the seemingly bizarre message.
You would want to use the AspNetCompiler task, rather than the MSBuild task.  See
http://msdn2.microsoft.com/en-us/library/ms164291.aspx
for more info on this task.  Your "PublishDir" would correspond to the TargetPath property of the task.
Source


q: I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input.

[A]
You can use the WindowsIdentity.Impersonate method to
achieve this. This method allows code to impersonate a different Windows
user. Here is a link for more information on this method with a good sample:
http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx
Complete example:
```
```
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES:
// This sample can be run only on Windows XP.  The default Windows 2000 security policy
// prevents this sample from executing properly, and changing the policy to allow
// proper execution presents a security risk.
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked,
// it will be visible to anyone viewing the screen.
// The sample is intended to be executed in a .NET Framework 1.1 environment.  To execute
// this code in a 1.0 environment you will need to use a duplicate token in the call to the
// WindowsIdentity constructor. See KB article Q319615 for more information.

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Windows.Forms;

[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]
[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class ImpersonationDemo
{
    [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
    private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
        int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments);

    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

    // Test harness.
    // If you incorporate this code into a DLL, be sure to demand FullTrust.
    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public static void Main(string[] args)
    {
        IntPtr tokenHandle = new IntPtr(0);
        IntPtr dupeTokenHandle = new IntPtr(0);
        try
        {
            string userName, domainName;
            // Get the user token for the specified user, domain, and password using the
            // unmanaged LogonUser method.
            // The local machine name can be used for the domain name to impersonate a user on this machine.
            Console.Write("Enter the name of the domain on which to log on: ");
            domainName = Console.ReadLine();

            Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
            userName = Console.ReadLine();

            Console.Write("Enter the password for {0}: ", userName);

            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            tokenHandle = IntPtr.Zero;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);

            Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                throw new System.ComponentModel.Win32Exception(ret);
            }

            Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes" : "No"));
            Console.WriteLine("Value of Windows NT token: " + tokenHandle);

            // Check the identity.
            Console.WriteLine("Before impersonation: "
                + WindowsIdentity.GetCurrent().Name);
            // Use the token handle returned by LogonUser.
            WindowsIdentity newId = new WindowsIdentity(tokenHandle);
            WindowsImpersonationContext impersonatedUser = newId.Impersonate();

            // Check the identity.
            Console.WriteLine("After impersonation: "
                + WindowsIdentity.GetCurrent().Name);

            // Stop impersonating the user.
            impersonatedUser.Undo();

            // Check the identity.
            Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);

            // Free the tokens.
            if (tokenHandle != IntPtr.Zero)
                CloseHandle(tokenHandle);

        }
        catch(Exception ex)
        {
            Console.WriteLine("Exception occurred. " + ex.Message);
        }

    }
}
```
```


q:
I would like to implement something similar to a c# delegate method in PHP.  A quick word to explain what I'm trying to do overall:  I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised.

I am having some problems coming up with a mechanism to do callbacks in PHP.  I have come up with a method that works for now but I am unhappy with it.  Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be.  This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of?

[A]
How do you feel about using the
Observer
pattern? If not, you can implement a true callback this way:
```
```
// This function uses a callback function.
function doIt($callback)
{
    $data = "this is my data";
    $callback($data);
}

// This is a sample callback function for doIt().
function myCallback($data)
{
    print 'Data is: ' .  $data .  "\n";
}

// Call doIt() and pass our sample callback function's name.
doIt('myCallback');
```
```
Displays: Data is: this is my data


q:
Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship.

However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class?

[A]
Programming to an interface means respecting the "contract" created by using that interface. And so if your
```
IPoweredByMotor
```
interface has a
```
start()
```
method, future classes that implement the interface, be they
```
MotorizedWheelChair
```
,
```
Automobile
```
, or
```
SmoothieMaker
```
, in implementing the methods of that interface, add flexibility to your system, because one piece of code can start the motor of many different types of things, because all that one piece of code needs to know is that they respond to
```
start()
```
. It doesn't matter
how
they start, just that they
must start
.


q:
How do I set a property of a user control in ListView's LayoutTemplate from the code-behind?

<asp:ListView ...>
<LayoutTemplate>
<myprefix:MyControl id="myControl" ... />
</LayoutTemplate>
...
</asp:ListView>

I want to do this:

myControl.SomeProperty = somevalue;

Please notice that my control is not in ItemTemplate, it is in LayoutTemplate, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item.

[A]
Use the
FindControl
method on each ListViewItem.
```
```
var control = (MyControl)Item.FindControl("yourControlId");
```
```


q:
What is the maximum size for a MySQL table? Is it 2 million at 50GB? 5 million at 80GB?

At the higher end of the size scale, do I need to think about compressing the data? Or perhaps splitting the table if it grew too big?

[A]
About your first question, the effective maximum size for the
database
is usually determined by operating system, specifically the file size MySQL Server will be able to create, not by MySQL Server itself. Those limits play a big role in
table
size limits. And MyISAM works differently from InnoDB. So any tables will be dependent on those limits.
If you use InnoDB you will have more options on manipulating table sizes, resizing the tablespace is an option in this case, so if you plan to resize it, this is the way to go. Give a look at
The table is full
error page.
I am not sure the real record quantity of each table given all necessary information (OS, Table type, Columns, data type and size of each and etc...) And I am not sure if this info is easy to calculate, but I've seen simple table with around 1bi records in a couple cases and MySQL didn't gave up.


q:
I want to write a command that specifies "the word under the cursor" in VIM.  For instance, let's say I have the cursor on a word and I make it appear twice.  For instance, if the word is "abc" and I want "abcabc" then I could type:

:s/\(abc\)/\1\1/

But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef":

:s/\(def\)/\1\1/

How can I write the command in the commandline so that it does this?

:s/\(*whatever is under the commandline*\)/\1\1

[A]
```
<cword>
```
is the word under the cursor (:help
```
<cword>
```
).
Sorry, I should have been more complete in this answer.
You can nmap a command to it, or this series of keystrokes for the lazy will work:
```
```
b #go to beginning of current word
yw #yank to register
```
```
Then, when you are typing in your pattern you can hit
```
<control-r>0<enter>
```
which will paste in your command the contents of the 0-th register.
You can also make a command for this like:
```
```
:nmap <leader>w :s/\(<c-r>=expand("<cword>")<cr>\)/
```
```
Which will map hitting '\' and 'w' at the same time to replace your command line with
```
```
:s/\(<currentword>\)/
```
```


q: I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code?

[A]
It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a
```
catch
```
block is simply not true in C++ because RAII is an established idiom. Resource handling in C++
is
done by resource acquisition and garbage collection is done by implicit destructor calls.
On the other hand, explicit
```
catch
```
blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly.
RAII (including
```
ScopeGuard
```
s) isn't an obscure technique in C++ but firmly established best-practice.


q:
Anybody know of a way to copy a file from path A to path B and suppressing the Windows file system cache?

Typical use is copying a large file from a USB drive, or server to your local machine. Windows seems to swap everything out if the file is really big, e.g. 2GiB.
Prefer example in C#, but I'm guessing this would be a Win32 call of some sort if possible.

[A]
I am not sure if this helps, but take a look at
Increased Performance Using FILE_FLAG_SEQUENTIAL_SCAN
.
SUMMARY
There is a flag for CreateFile()
  called FILE_FLAG_SEQUENTIAL_SCAN which
  will direct the Cache Manager to
  access the file sequentially.
Anyone reading potentially large files
  with sequential access can specify
  this flag for increased performance.
  This flag is useful if you are reading
  files that are "mostly" sequential,
  but you occasionally skip over small
  ranges of bytes.


q:
Say I have a Textbox nested within a TabControl.

When the form loads, I would like to focus on that Textbox (by default the focus is set to the TabControl).

Simply calling textbox1.focus() in the Load event of the form does not appear to work.

I have been able to focus it by doing the following:

 private void frmMainLoad(object sender, EventArgs e)
 {
     foreach (TabPage tab in this.tabControl1.TabPages)
     {
         this.tabControl1.SelectedTab = tab;
     }
 }

My question is:

Is there a more elegant way to do this?

[A]
The following is the solution:
```
```
private void frmMainLoad(object sender, EventArgs e)
{
    ActiveControl = textBox1;
}
```
```
The better question would however be why... I'm not entirely sure what the answer to that one is.
Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.


q:
Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships.

We then have a separate jvm that is the server using this data.  As it is running continuously we just have one long db session (read only).

There is currently no intra-jvm cache involved - so we manually signal one jvm from the other.

Now when the webapp changes some data, it signals the server to reload the changed data.  What we have found is that we need to tell hibernate to purge the data and then reload it.  Just doing a fetch/merge with the db does not do the job - mainly in respect of the objects several layers down the hierarchy.

Any thoughts on whether there is anything fundamentally wrong with this design or if anyone is doing this and has had better luck with working with hibernate on the reloads.

Thanks,
Chris

[A]
Chris, I'm a little confused about your circumstances. If I understand correctly, you have a both a web app (read/write) a standalone application (read-only?) using Hibernate to access a shared database. The changes you make with the web app aren't visible to the standalone app. Is that right?
If so, have you considered using a different second-level cache implementation? I'm wondering if you might be able to use a clustered cache that is shared by both the web application and the standalone application. I believe that SwarmCache, which is integrated with Hibernate, will allow this, but I haven't tried it myself.
In general, though, you should know that the contents of a given cache will never be aware of activity by another application (that's why I suggest having both apps share a cache). Good luck!


q:
What's the "right" way to do the following as a boolean expression?

for i in `ls $1/resources`; do
    if [ $i != "database.db" ]
    then
        if [ $i != "tiles" ]
        then
            if [ $i != "map.pdf" ]
            then
                if [ $i != "map.png" ]
                then
                    svn export -q $1/resources/$i ../MyProject/Resources/$i
...

[A]
```
```
for i in `ls $1/resources`; do
    if [ $i != "database.db" ] && [ $i != "tiles" ] && [ $i != "map.pdf" ] && [ $i != "map.png" ]; then
        svn export -q $1/resources/$i ../MyProject/Resources/$i
```
```


q: I have to choose an online WYSIWYG editor. I'm pending between TinyMCE and Xinha. My application is developed in Asp.Net 3.5. Could you help me with with some pros and cons?

[A]
I've never used Xinha, but I can vouch for TinyMCE. It's fast, scales well, and is infinitely customizable. I particularly like the dynamic loading of functionality, which means you only take the performance hit for the stuff you use.
It also includes language-specific
compressors
to further increase performance (C# is supported, along with PHP, Java and ColdFusion) by GZipping components.


q:
Here is a scenario: Let's say I have site with two controllers responsible for displaying different type of content - Pages and Articles. I need to embed Partial View into my masterpage that will list pages and articles filtered with some criteria, and be displayed on each page. I cannot set Model on my masterpage (am I right?). How do I solve this task using Html.RenderPartial?

[EDIT]
Yes, I'd probably create separate partial views for listing articles and pages, but still, there is a barrier that I cannot and shouldn't set model on masterpage. I need somehow to say "here are the pages" as an argument to my renderpartial, and also for articles. Entire concept of renderpartial with data from database in masterpages is a bit blurry to me.

[A]
The ViewData Model property should only be used for the content that you're viewing/editing on the main section of the UI.
Other parts of the view may need some data present in ViewData, so just add those to the dictionary.
I'd just pass data from the dictionary like this:  ViewData["articles"] to the partial.  (or ViewData.Get() from MvcContrib).
You might also look at the recently implemented SubController pattern implemented in
MvcContrib
.


q:
Some e-Marketing tools claim to choose which web page to display based on where you were before. That is, if you've been browsing truck sites and then go to Ford.com, your first page would be of the Ford Explorer.

I know you can get the immediate preceding page with HTTP_REFERRER, but how do you know where they were 6 sites ago?

[A]
Javascript this should get you started:
http://www.dicabrio.com/javascript/steal-history.php
There are more nefarius means to:
http://ha.ckers.org/blog/20070228/steal-browser-history-without-javascript/
Edit:I wanted to add that although this works it is a sleazy marketing teqnique and an invasion of privacy.


q:
Ajax, Flex and Silverlight are a few ways to make more interactive web applications.  What kinds of factors would you consider when deciding which to use for a new web application?

Does any one of them offer better cross-platform compatibility, performance, developer tools or community support?

[A]
The web runtimes like Flex and Silverlight all offer enticing things, but come with two big costs:
They run only within a rectangle on the page, and don't interact with normal web widgets
They are only available to people who have that plug-in installed
Even the nearly-ubiquitous Flash isn't installed on every web browser, so by choosing to use a plug-in runtime you're excluding part of your audience.
In contrast, JavaScript (or Ajax) is available on pretty much every browser, and interacts better with normal web pages, but is a more primitive and restricting language. Using it for complex animations can be tricky, and you'll need to test your applications in more versions on more platforms to make sure it works.
Cross-platform compatibility isn't the issue it used to be, so the issue is this:
Will you gain more in the features of a plug-in library than you'll lose in the audience you exclude?
My own answer has so far always been JavaScript/Ajax, but I'd re-evaluate that in any new project.


q:
I am a bit confused about socket programming in C.

You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article <s>Network programming under Unix systems</s> to be very informative.

What confuses me is the timing of data arriving on the socket.

How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself?

My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that?

[A] When you do a read on the socket, you tell it how many maximum bytes to read, but if it doesn't have that many, it gives you however many it's got.  It's up to you to design the protocol so you know whether you've got a partial packet or not.  For instance, in the past when sending variable length binary data, I would put an int at the beginning that said how many bytes to expect.  I'd do a read requesting a number of bytes greater than the largest possible packet in my protocol, and then I'd compare the first int against however many bytes I'd received, and either process it or try more reads until I'd gotten the full packet, depending.


q: What is the JavaScript to scroll to the top when a button/link/etc. is clicked?


q:
Does anybody know of a way to list up the "loaded plugins" in Vim?
I know I should be keeping track of this kind of stuff myself but
it would always be nice to be able to check the current status.

[A]
Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following
VIM Tips
site:
```
```
" where was an option set
:scriptnames            : list all plugins, _vimrcs loaded (super)
:verbose set history?   : reveals value of history and where set
:function               : list functions
:func SearchCompl       : List particular function
```
```


q:
I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this:

procedure TForm1.CalculateGP(..)
const
   Price : money = 0;
begin
   ...
   Price := 1.0;
   ...
end;

So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, why? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time?

[A]
You need to turn assignable typed constants on.

Project -> Options -> Compiler -> Assignable typed Constants
Also you can add
```
{$J+}
```
or
```
{$WRITEABLECONST ON}
```
to the pas file, which is probably better, since it'll work even if you move the file to another project.


q:
I'm building an application in C# using WPF. How can I bind to some keys?

Also, how can I bind to the Windows key?

[A]
I'm not sure about WPF, but this may help. I used the solution described in
RegisterHotKey (user32)
(modified to my needs of course) for a C# Windows Forms application to assign a CTRL-KEY combination within Windows to bring up a C# form, and it worked beautifully (even on Windows Vista). I hope it helps and good luck!


q: How are callbacks written in PHP?

[A]
Implementation of a callback is done like so
```
```
// This function uses a callback function.
function doIt($callback)
{
    $data = "this is my data";
    $callback($data);
}

// This is a sample callback function for doIt().
function myCallback($data)
{
    print 'Data is: ' .  $data .  "\n";
}

// Call doIt() and pass our sample callback function's name.
doIt('myCallback');
```
```
Displays: Data is: this is my data


q: We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading.  Is there a way to get WatiN to click a link on the page before the page finishes rendering completely?

[A]
Here's the code we found to work:
```
```
IE browser = new IE(....);
browser.Button("SlowPageLoadingButton").ClickNoWait();
Link continueLink = browser.Link(Find.ByText("linktext"));
continueLink.WaitUntilExists();
continueLink.Click();
```
```


q:
I am wondering if anyone has any experience using a JQuery plugin that converts a html

<select>
  <option> Blah </option>
</select>

combo box into something (probably a div) where selecting an item acts the same as clicking a link.

I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.

Your advice, experience and recommendations are appreciated.

[A]
This bit of javascript in the 'select':
```
```
onchange="if(this.options[this.selectedIndex].value!=''){this.form.submit()}"
```
```
It's not ideal (because form submissions in ASP.NET MVC which I'm using don't appear to use the routing engine for URLs) but it does its job.


q: Why prefer composition over inheritance?  What trade-offs are there for each approach?  When should you choose inheritance over composition?

[A]
Think of containment as a
has a
relationship. A car "has an" engine, a person "has a" name, etc.
Think of inheritance as an
is a
relationship. A car "is a" vehicle, a person "is a" mammal, etc.
I take no credit for this approach. I took it straight from the
Second Edition of Code Complete
by
Steve McConnell
,
Section 6.3
.


q:
Why does n not equal to 8 in the following function?

void foo(char cvalue[8])
{
  int n = sizeof (cvalue);
}

But n does equal to 8 in this version of the function:

void bar()
{
  char cvalue[8];
  int n = sizeof (cvalue);
}

[A]
Because you can't pass entire arrays as function parameters in C.  You're actually passing a pointer to it; the brackets are syntactic sugar.  There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want.
```
```
// These all do the same thing
void foo(char cvalue[8])
void foo(char cvalue[])
void foo(char *cvalue)
```
```


q:
I am bit confused about ADO.Net Data Services.

Is it just meant for creating RESTful web services? I know WCF started in the SOAP world but now I hear it has good support for REST. Same goes for ADO.Net data services where you can make it work in an RPC model if you cannot look at everything from a resource oriented view.

At least from the demos I saw recently, it looks like ADO.Net Data Services is built on WCF stack on the server. Please correct me if I am wrong.

I am not intending to start a REST vs SOAP debate but I guess things are not that crystal clear anymore.

Any suggestions or guidelines on what to use where?

[A]
In my view ADO.Net data services is for creating restful services that are closely aligned with your domain model, that is the models themselves are published rather then say some form of DTO etc.
Using it for RPC style services seems like a bad fit, though unfortunately even some very basic features like being able to perform a filtered counts etc. aren't available which often means you'll end up using some RPC just to meet the requirements of your customers i.e. so you can display a paged grid etc.
WCF 3.5 pre-SP1 was a fairly weak RESTful platform, with SP1 things have improved in both Uri templates and with the availability of ATOMPub support, such that it's becoming more capable, but they don't really provide any elegant solution for supporting say JSON, XML, ATOM or even something more esoteric like payload like CSV simultaneously, short of having to make use of URL rewriting and different extension, method name munging etc. - rather then just selecting a serializer/deserializer based on the headers of the request.
With WCF it's still difficult to create services that work in a more a natural restful manor i.e. where resources include urls, and you can transition state by navigating through them - it's a little clunky - ADO.Net data services does this quite well with it's AtomPub support though.
My recommendation would be use web services where they're naturally are services and strong service boundaries being enforced, use ADO.Net Data services for rich web-style clients (websites, ajax, silverlight) where the composability of the url queries can save a lot of plumbing and your domain model is pretty basic... and roll your own REST layer (perhaps using an MVC framework as a starting point) if you need complete control over the information i.e. if you're publishing an API for other developers to consume on a social platform etc.
My 2ø worth!


q:
So I have a function that looks something like this:

float function(){
    float x = SomeValue;
    return x / SomeOtherValue;
}

At some point, this function overflows and returns a really large negative value.  To try and track down exactly where this was happening, I added a cout statement so that the function looked like this:

float function(){
    float x = SomeValue;
    cout << x;
    return x / SomeOtherValue;
}

and it worked!  Of course, I solved the problem altogether by using a double.  But I'm curious as to why the function worked properly when I couted it.  Is this typical, or could there be a bug somewhere else that I'm missing?

(If it's any help, the value stored in the float is just an integer value, and not a particularly big one.  I just put it in a float to avoid casting.)

[A]
Printing a value to cout should not change the value of the paramter in any way at all.
However, I have seen similar behaviour, adding debugging statements causes a change in the value. In those cases, and probably this one as well my guess was that the additional statements were causing the compiler's optimizer to behave differently, so generate different code for your function.
Adding the cout statement means that the vaue of x is used directly. Without it the optimizer could remove the variable, so changing the order of the calculation and therefore changing the answer.


q:
Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky.  What's the normal pattern to work around this?

For example, is there a clean way to implement swap( intA, intB ) in Actionscript?

[A]
If ActionScript works like Javascript,
```
```
[a,b] = [b,a]
```
```


q:
I'm looking at using OpenID for my authentication scheme and wanted to know what the best .NET library is to use for MVC specific applications?

thx

[A]
.Net OpenID project
is the best library to use right now that I know of.  I think SO used it also.  The source includes a sample ASP.NET MVC project using the library.
Scott Hanselman did a
post
on how to use the .Net OpenID project inside of ASP.NET MVC.


q:
I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition.

I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in

MessageBox("Hello, World!");

I received the following error:

MessageBox is a 'type' but used as a 'variable'

Fair enough, it seems in C# MessageBox is an Object. I tried the following

MessageBox a = new MessageBox("Hello, World!");

I received the following error:
MessageBox does not contain a constructor that takes '1' arguments

Now I am stumped. Please help.

[A]
Code summary:
```
```
using System.Windows.Forms;

...

MessageBox.Show( "hello world" );
```
```
Also (
as per this other stack post
): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select
```
System.Windows.Forms
```
on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.


q:
I have a .tag file that requires a JavaScript library (as in a .js file).

Currently I am just remembering to import the .js file in every JSP that uses the tag but this is a bit cumbersome and prone to error.

Is there a way to do the importing of the .js inside the JSP tag?

(for caching reasons I would want the .js to be a script import)

[A]
Short of just including the js in every page automatically, I do not think so. It really would not be something that tags are designed to to.
Without knowing what your tag is actually doing (presumably its its outputting something in the body section) then there is no way that it will be able to get at the head to put the declaration there.
One solution that might (in my head) work would be to have an include that copies verbatim what you have in the head after the place in the head to import tags right up to where you want to use the tag. This is really not something that you would want to do. You would have to have multiple 'header' files to import depending on the content and where you want to use the tag. Maintenance nightmare. Just a bad idea all round. Any solution I can think of would require more work than manually just adding in the declaration.
I think you are out of luck and stuck with manually putting it in.
edit: Just import it in every page. It will be cached and then this problem goes away.


q:
I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here.  I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication.

Is there a way I can use GreaseMonkey to log me into this site automatically?

Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page.  This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit

[A]
Why don't you use Firefox (I assume you're using Firefox) to remember your credentials using the Password Manager?
I found this link:
HTTP Authentication with HTML Forms
.  Looks like you can use javascript to do HTTP authentication.  I don't think you can have Greasemonkey interrupt when you are first navigating to a URL though.  You might have to setup some sort of launching point that you can use to have greasemonkey automatically redirect + login.  For example, you can have the local page that takes the destination URL in the query string, have Greasemonkey automatically do the authenticate + redirect.  The only problem is that you'll have to wrap the site bookmarks with your launching page for the bookmarks you use as entry points.


q: How do I turn a python program into an .egg file?

[A]
Setuptools
is the software that creates
.egg files
. It's an extension of the
```
distutils
```
package in the standard library.
The process involves creating a
```
setup.py
```
file, then
```
python setup.py bdist_egg
```
creates an .egg package.


q:
The first language I learnt  was PHP, but I have more recently picked up Python. As these are all 'high-level' languages, I have found them a bit difficult to pick up. I also tried to learn Objective-C but I gave up.

So, what language should I learn to bridge between Python to C

[A] It's not clear why you need a bridge language. Why don't you start working with C directly? C is a very simple language itself. I think that hardest part for C learner is pointers and everything else related to memory management. Also C lang is oriented on structured programming, so you will need to learn how to implement data structures and algorithms without OOP goodness. Actually, your question is pretty hard, usually people go from low level langs to high level and I can understand frustration of those who goes in other direction.


q:
Should libraries that the application relies on be stored in source control? One part of me says it should and another part say's no. It feels wrong to add a 20mb library that dwarfs the entire app just because you rely on a couple of functions from it (albeit rather heavily). Should you just store the jar/dll or maybe even the distributed zip/tar of the project?

What do other people do?

[A]
store everything you will need to build the project 10 years from now.I store the entire zip distribution of any library, just in case
Edit for 2017:
This answer did not age well:-). If you are still using something old like ant or make, the above still applies. If you use something more modern like maven or graddle (or Nuget on .net for example), with dependency management, you should be running a dependency management server, in addition to your version control server. As long as you have good backups of both, and your dependency management server does not delete old dependencies, you should be ok. For an example of a dependency management server, see for example
Sonatype Nexus
or
JFrog Artifcatory
, among many others.


q: I'm considering using Flash but I'm pretty addicted to autocomplete and Step-at-a-time debugging.

[A]
If you mean ActionScript I once heard that
PrimalScript
will do Intellisense. Never tested it though. As for debugging, MAYBE,
PrimalScope
will have that too. I'd recommend you try before you buy, though. (They both have trials.)


q:
For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object:

Object.variable_name= 'new value'

However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround:

Object.send('variable.name=', 'new value')

However, I am wondering is there a way to escape the period so that I can use

Object.variable.name= 'new value'

[A]
Don't do it!
Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:
```
```
attr_writer :bar
attr_reader :baz
attr_accessor :foo
```
```
Okay, now that you have been warned, here's how to do it.  Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.
```
```
class SillySetter
  def initialize path=nil
    @path = path
  end

  def method_missing name,value=nil
    new_path = @path ? "#{@path}.#{name}" : name
    if name.to_s[-1] == ?=
      puts "setting #{new_path} #{value}"
    else
      return self.class.new(path=new_path)
    end
  end
end

s = SillySetter.new
s.foo = 5              # -> setting foo= 5
s.foo.bar.baz = 4      # -> setting foo.bar.baz= 4
```
```
I didn't want to encourage ruby sillyness, but I just couldn't help myself!


q: I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I don't want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg .ini) file. Does anyone know a clean and simple way of doing this ? Thanks.


q:
I have a string, say '123', and I want to convert it to the integer 123.

I know you can simply do some_string.to_i, but that converts 'lolipops' to 0, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful Exception. Otherwise, I can't distinguish between a valid 0 and something that just isn't a number at all.

EDIT: I was looking for the standard way of doing it, without regex trickery.

[A]
Ruby has this functionality built in:
```
```
Integer('1001')                                    # => 1001
Integer('1001 nights')
# ArgumentError: invalid value for Integer: "1001 nights"
```
```
As noted in answer by
Joseph Pecoraro
, you might want to watch for strings that are valid non-decimal numbers, such as those starting with
```
0x
```
for hex and
```
0b
```
for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.
Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:
```
```
Integer('23')                                     # => 23
Integer('0x23')                                   # => 35
Integer('023')                                    # => 19
Integer('0x23', 10)
# => #<ArgumentError: invalid value for Integer: "0x23">
Integer('023', 10)                                # => 23
```
```


q:
We have some legacy code that needs to identify in the Page_Load which event caused the postback.
At the moment this is implemented by checking the Request data like this...

if (Request.Form["__EVENTTARGET"] != null

&& (Request.Form["__EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort)

       || Request.Form["btnSave"] != null            // Save button

This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this?

Rewriting each page so that it does not need to check this in Page_Load is not an option at the moment.

[A]
This should get you the control that caused the postback:
```
```
public static Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}
```
```
Read more about this on this page:
http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx


q:
Using the zip function, Python allows for loops to traverse multiple sequences in parallel.

for (x,y) in zip(List1, List2):

Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?

[A]
If I'm not mistaken the zip function you use in python
creates a pair of the items found in list1 and list2
. Basically it still is a for loop with the addition that it will retrieve the data from the two seperate lists for you, instead that you have to do it yourself.
So maybe your best option is to use a
standard
for loop like this:
```
```
for i=1:length(a)
  c(i) = a(i) + b(i);
end
```
```
or whatever you have to do with the data.
If you really are talking about parallel computing then you should take a look at the
Parallel Computing Toolbox
for matlab, and more specifically at
parfor


q:
Is it correct to link a static library (.lib) compiled with VS 2005 with a program which is compiled with VS 2008? Both library and my program are written in C++. This program is run on Windows Mobile 6 Professional emulator.

This seems to work, there are no linking errors. However the program crashes during startup because strange things happen inside the linked library. E.g. lib can return a vector of characters with size of big negative number.

There are no such problems when the program is compiled with VS 2005.

What is even more strange the problem is only when using release configuration for the build. When compiling using debug configuration the problem doesn't occur.

[A]
It's not incorrect to link to an older library in the way you describe, but it doesn't surprise me you're seeing some odd behavior. Couple sanity checks:
Are both files using the
same versions
of the
same run-time libraries
?
Is your .EXE application "seeing" the same header files that the .LIB was built against? Make sure that the _WIN32_WINNT (etc.) macros are
declared properly
.
And when you say .LIB, do you mean a true static library (mylib.lib) or an import library for a DLL (mylib.lib -> mylib.dll)?
And what are the compile/link settings for your VS2008 executable project?


q:
Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?

I know that marking it as disabled works but then it gets displayed differently (greyed out).

To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.

I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link.

[A]
If you merely want to modify the appearance of the link so as not to look like a link, you can set the CSS for your "a" tags to not have underlines:
```
```
a: link, visited, hover, active {
    text-decoration: none;
}
```
```
Though I would advise against including "hover" here because there will be no other way to know that it's a link.
Anyway I agree with @pilif here, this looks like a usability disaster waiting to happen.


q:
We have the standard Subversion trunk/branches/tags layout. We have several branches for medium- and long-term projects, but none so far for a release. This is approaching fast.

Should we:

Mix release branches and project branches together?

Create a releases folder? If so, is there a better name than releases?

Create a projects folder and move the current branches there? If so, is there a better name than projects? I've seen "sandbox" and "spike" in other repositories.

Something else altogether?

[A]
Releases is the same as tags... Have you got multiple projects inside your trunk? In that case, I would copy the same folders inside tags
So
```
```
trunk
     fooapp
         stuff...
     barapp
         stuff...
tags
     fooapp
         1.0.0
         1.0.1
     barapp
         1.0.0
```
```


q: Are the naming conventions similar in different languages? If not, what are the differences?

[A]
Of course there are some common guidelines but there are also differences due to difference in language syntax\design.
For .NET (C#, VB, etc) I would recommend following resource:
Framework Design Guidelines
-
definitive book on .NET coding
guidelines including naming
conventions
Naming Guidelines
- guidelines from Microsoft
General Naming Conventions
- another set of MS guidelines (C#, C++, VB)


q:
What all would be the requirements for the following scenario:

A GSM modem connected to a PC running
  a web based (ASP.NET) application. In
  the application the user selects a
  phone number from a list of phone nos.
  When he clicks on a button named the
  PC should call the selected phone
  number. When the person on the phone
  responds he should be able to have a
  conversation with the PC user.
  Similarly there should be a facility
  to send SMS.

Now I don't want any code listings. I just need to know what would be the requirements besides asp.net, database for storing phone numbers, and GSM modem.

Any help in terms of reference websites would be highly appreciated.

[A]
I'll pick some points of your very broad question and answer them. Note that there are other points where others may be of more help...
First, a GSM modem is probably not the way you'd want to go as they usually don't allow for concurrency. So unless you just want one user at the time to use your service, you'd probably need another solution.
Also, think about cost issues - at least where I live, providing such a service would be prohibitively expensive using a normal GSM modem and a normal contract - but this is drifting into off-topicness.
The next issue will be to get voice data from the client to the server (which will relay it to the phone system - using whatever practical means). Pure browser based functionality won't be of much help, so you would absolutely need something plugin based.
Flash may work, seeing they provide access to the microphone, but please don't ask me about the details. I've never done anything like this.
Also, privacy would be a concern. While GSM data is encrypted, the path between client and server is not per default. And even if you use SSL, you'd have to convince your users trusting you that you don't record all the conversations going on, but this too is more of a political than a coding issue.
Finally, you'd have to think of bandwidth. Voice uses a lot of it and also it requires low latency. If you use a SIP trunk, you'll need the bandwidth twice per user: Once from and to your client and once from and to the SIP trunk. Calculate with 10-64 KBit/s per user and channel.
A feasible architecture would probably be to use a SIP trunk (they optimize on using VoIP as much as possible and thus can provide much lower rates than a GSM provider generally does. Also, they allow for concurrency), an Asterisk box (
http://www.asterisk.org
- a free PBX), some custom made flash client and a custom made SIP client on the server.
All in all, this is quite the undertaking :-)


q:
I have a WCF service which includes UI components, which forces me to be in STA mode.

How do I set the service behaviour to STA-mode?

The service uses a reference to a WPF DLL file which opens a UI window (used as view port) for picture analysis. When the service is trying to create an instance of that item (inherits from window) it throws an exception:

The calling thread must be an STA

[A]
I would investigate using the [STAThread] attribute to switch the threading model.
e.g.
```
```
[STAThread]
static void Main()
{
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new Host() };
        ServiceBase.Run(ServicesToRun);
}
```
```
Description of the STAThread attribute
But I'm confused why you're using UI components in a web service at all. Can you explain a bit more about why you're trying to do this?


q:
I'm just about wrapped up on a project where I was using a commercial SVN provider to store the source code. The web host the customer ultimately picked includes a repository as part of the hosting package, so, now that the project is over, I'd like to relocate the repository to their web host and discontinue the commercial account.

How would I go about doing this?

[A]
Assuming you have the necessary privileges to run svnadmin, you need to use the
dump
and
load
commands.


q:
I deleted a branch in TFS and just found out that I need the changes that were on it.

How do I recover the branch or the changes done on it?

[A]
As described in the
TFS FAQ
:
Are Deletes physical or logical? Can accidental deletes be recovered?
Deletes are fully recoverable with the “undelete” operation. You wouldn’t want to do a SQL restore because that would roll back every change to the TFS in the time since the file was deleted.


q:
Is there a C# equivalent for the VB.NET FormatNumber function?

I.e.:

JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);

[A]
You can use string formatters to accomplish the same thing.
```
```
double MyNumber = inv.RRP * oCountry.ExchangeRate;
JSArrayString += "^" + MyNumber.ToString("#0.00");
```
```


q:
Is Bouncy Castle API Thread Safe ? Especially,

org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
org.bouncycastle.crypto.paddings.PKCS7Padding
org.bouncycastle.crypto.engines.AESFastEngine
org.bouncycastle.crypto.modes.CBCBlockCipher

I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here.

Please let me know if you have come across such situations using Bouncy Castle.

[A]
It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe.
Some terminology -
```
```
E(X) = Enctrypt message X
D(X) = Dectrypt X. (Note that D(E(X)) = X)
IV = Initialization vector. A random sequence to bootstrap the CBC algorithm
CBC = Cipher block chaining.
```
```
A really simple CBC implementation can look like:
P1, P2, P3 = Plain text messages
```
```
1. Generate an IV, just random bits.
2. Calculate E( P1 xor IV) call this C1
3. Calculate E( P2 xor C1) call this C2
4. Calculate E( P3 xor C2) call this C3.
```
```
As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order).
So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe.
You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe.


q:
I'm trying to redirect requests for a wildcard domain to a sub-directory.

ie. something.blah.example.com --> blah.example.com/something

I don't know how to get the subdomain name to use in the rewrite rule.

Final Solution:

RewriteCond %{HTTP_HOST} !^blah\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)
RewriteRule ^(.*) /%1/$1 [L]

Or as pointed out by pilif

RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$

[A]
You should have a look at the
URL Rewriting Guide
from the apache documentation.
The following is untested, but it should to the trick:
```
```
RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$
RewriteRule ^/(.*)$           http://blah.domain.com/%1/$1 [L,R]
```
```
This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer.


q:
How do you set your Cocoa application as the default web browser?

I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.).

[A]
There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes.
1) Add the URL schemes your app can handle to your application's info.plist file
To add support for
```
http://
```
and
```
https://
```
you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs.
```
```
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>http URL</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>http</string>
        </array>
    </dict>
    <dict>
        <key>CFBundleURLName</key>
        <string>Secure http URL</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>https</string>
        </array>
    </dict>
</array>
```
```
2) Write an URL handler method
This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this:
```
```
- (void)getUrl:(NSAppleEventDescriptor *)event
    withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
  // Get the URL
  NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
    stringValue];

  //TODO: Your custom URL handling code here
}
```
```
3) Register the URL handler method
Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed
```
self
```
as the event handler, assuming that we're calling
```
setEventHandler
```
from the same object that defines the
```
getUrl:withReplyEvent:
```
method.
You should add this code somewhere in your application's initialisation code.
```
```
NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];
[em
  setEventHandler:self
  andSelector:@selector(getUrl:withReplyEvent:)
  forEventClass:kInternetEventClass
  andEventID:kAEGetURL];
```
```
Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following:
```
```
[em
  setEventHandler:self
  andSelector:@selector(getUrl:withReplyEvent:)
  forEventClass:'WWW!'
  andEventID:'OURL'];
```
```
4) Set your app as the default browser
Everything we've done so far as told the OS that your application is
a browser
, now we need to make it
the default browser
.
We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links:
```
```
CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier];
OSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID);
OSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID);
//TODO: Check httpResult and httpsResult for errors
```
```
(It's probably best to ask the user's permission before changing their default browser.)
Custom URL schemes
It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is
```
com.example.MyApp
```
you should consider using
```
x-com-example-myapp://
```
URLs.


q:
Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner.

For security reasons we do not want certain pages in our application to be cached, ever, by the web browser. This must work for at least the following browsers:

Internet Explorer 6+

Firefox 1.5+

Safari 3+

Opera 9+

Chrome

Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages.

[A]
Setting the modified http header to some date in 1995 usually does the trick.
Here's an example:
```
Expires: Wed, 15 Nov 1995 04:58:08 GMT
Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
Cache-Control: no-cache, must-revalidate
```


q:
I'm still trying to get my head around LINQ and accessing a SQL Database.

I was always taught that you should only have execute permissions of stored procedures to your data.

You should never have select / insert / update / delete.

(This is because of performance and security)

To get the data out of LINQ you obviously need select permissions.  I know you can use stored procs with LINQ, but since I can't do joins what's the point?

Have I missed something???

[A]
1) We're programmers, not DBA fascists.  If your requirements state that the database must be locked down 100%, Linq is not for you.  I'm not a DBA, so I believe that most of the performance/security hype is just that.  Linq is for me.
2) You can do joins with linq.
@Philippe
:  Linq automatically transforms evaluations into query parameters, so it provides some sql injection protection.  However, you still have to closely evaluate your requirements to determine how much security you need and at what levels.  Linq makes dealing with the database much easier, but it makes it easier to put secuirty design on the back burner, which is a bad thing.


q:
What is the difference between

char str1[32] = "\0";

and

char str2[32] = "";

[A]
Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, you can see that the first declaration makes a larger string:
```
```
char a[] = "a\0";
char b[] = "a";

printf("%i %i\n", sizeof(a), sizeof(b));
```
```
prints
```
```
3 2
```
```
This is because a ends with two nulls (the explicit one and the implicit one) while b ends only with the implicit one.


q:
Jquery has a great language construct that looks like this:

$(document).ready(function() {
    $("a").click(function() {
        alert("Hello world!");
    });
});

As you might guess this, once the document has loaded, binds a custom function to the onClick event of all a tags.

The question is, how can I achieve this same kind of behavior in Prototype?

[A]
```
```
Event.observe(window, 'load', function() {
     Event.observe(element, 'click', function() {
         alert("Hello World!");
     });
});
```
```
Of course you need to "select" the elements first in Prototype.


q:
In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" rownum column. Consider the following example, which will return, at most, 10 rows.

SELECT * FROM all_tables WHERE rownum <= 10

Is there a simple, generic way to do something similar in Ingres?

[A]
Blatantly changing my answer. "Limit 10" works for MySql and others, Ingres uses
```
```
Select First 10 * from myTable
```
```
Ref


q:
For many years I have used two great tools BoundsChecker & Purify, but the developers of these applications have let me down, they no longer put effort into maintaining them or developing them. We have corporate accounts with both companies, and they both tell me that they have no intention of producing versions to support 64 bit applications.

Can anyone recommend either open source or commercial alternatives that support 64 bit native C++/MFC applications?

[A]
I've used bounds checking and other dynamic analysis tools, and while the architectures are different it's the code that you're checking - in theory you could run bounds checking on any backend and the result would be the same - the code either steps outside its bounds or it does not.
The only complications are addressing more than 4GB of memory space, dealing with pieces of code you can't cross-compile to a 32-bit architecture (64 bit object files for which you have no source, etc), and general 64 bit migration issues (platform specific code such as checking for 0xFFFFFFFF instead of -1)
What other problems are you running into doing bounds checking on your program?  Are you unable to compile a 32 bit version?
It's not your ideal solution, certainly, and one should always check the code they're going to run, but in this case you might not have a choice, unless you want to do your own bounds checking (which is a good idea in any case...).
-Adam


q: Can someone suggest some good automated test suite framework for Perl?

[A]
I'd go for Test::More, or in general, anything that outputs
TAP


q:
My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying.  We'd also like to make sure it can't be copied and distributed to our customers' customers.

One model we've seen is tying a license to a MAC address so the software will only work on one machine.

What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions?

[A]
I'd suggest you take the pieces of information you want in the key, and hash it with md5, and then just take the first X characters (where X is a key length you think is manageable).
Cryptographically, it's far from perfect, but this is the sort of area where you want to put in the minimum amount of effort which will stop a casual attacker - anything more quickly becomes a black hole.
Oh, I should also point out, you will want to provide the expiration date (and any other information you might want to read out yourself) in plain text (or slightly obfuscated) as part of the key as well if you go down this path - The md5 is just to stop the end user from changing he expiration date to extend the license.
The easiest thing would be a key file like this...
```
```
# License key for XYZZY
expiry-date=2009-01-01
other-info=blah
key=[md5 has of MAC address, expiry date, other-info]
```
```


q: Most of the work I do is with what could be considered enterprise Web applications. These projects have large budgets, longer timelines (from 3-12 months), and heavy customizations. Because as developers we have been touting the idea of the Web as the next desktop OS, customers are coming to expect the software running on this "new OS" to react the same as on the desktop. That includes easy to manage automatic upgrades. In other words, "An update is available. Do you want to upgrade?" Is this even a realistic expectation? Can anyone speak from experience on trying to implement this feature?

[A]
One of the primary reasons to implement an application as a web application is that you get automatic upgrades for free.  Why would users be getting prompted for upgrades on a web app?
For Windows applications, the "update is available, do you want to upgrade?" functionality is provided by Microsoft using ClickOnce, which I have used in an enterprise environment successfully -- there are a few gotchas but for the most part it is a good way to manage automatic deployment and upgrade of Windows apps.
For mobile apps, you can also implement auto-upgrades, although it is a little trickier.
In any case, to answer your question in a broad sense, I don't know if it is expected that all enterprise apps should make upgrading easy, but it certainly is worth the money from an IT support standpoint to architect them to allow for easy upgrading.


q: Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?

[A]
I think this pair of articles by Philip J. Eby does a great job discussing the differences between the two languages (mostly about philosophy/mentality rather than specific language features).
Python is Not Java
Java is Not Python, either


q:
Say I have this given XML file:

<root>
    <node>x</node>
    <node>y</node>
    <node>a</node>
</root>

And I want the following to be displayed:

ayx

Using something similar to:

<xsl:template match="/">
    <xsl:apply-templates select="root/node"/>
</xsl:template>
<xsl:template match="node">
    <xsl:value-of select="."/>
</xsl:template>

[A]
You can do this, using
```
xsl:sort
```
. It is important to set the
```
data-type="number"
```
because else, the position will be sorted as a string, end therefor, the 10th node would ge considered before the 2nd one.
```
```
<xsl:template match="/">
    <xsl:apply-templates select="root/node">
        <xsl:sort
            select="position()"
            order="descending"
            data-type="number"/>
    </xsl:apply-templates>
</xsl:template>
<xsl:template match="node">
    <xsl:value-of select="."/>
</xsl:template>
```
```


q:
We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case).  However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.

The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property.  Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name?  In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.

[A]
It is generally considered a bad idea to version control your binaries and I do not recommend doing so. But if you absolutely have to, you can use antcall combined with param to pass parameters and call a target.
```
```
<antcall target="reusable">
    <param name="some.variable" value="var1"/>
</antcall>

<target name="reusable">
    <!-- Do something with ${some.variable} -->
</target>
```
```
You can find more information about the
antcall task here
.


q:
I know I've seen this in the past, but I can't seem to find it now.

Basically I want to create a page that I can host on a dasBlog instance that contains the layout from my theme, but the content of the page I control.

Ideally the content is a user control or ASPX that I write.  Anybody know how I can accomplish this?

[A]
I did something similar setting up a handler to stream video files from the blog on my home server.  I ended up ditching it because it killed my bandwidth whenever someone would view a video, but I did have it up and working for a while.
To get it to work I had to check dasBlog out from source control and open it in visual studio.  I had VS2008 and it was built using VS2005, so it took some work to get everything to build.  Once I could get the unaltered solution to build I added a new class library project to hold my code.  This is to make sure my code stays separate across dasBlog updates.
I don't have access to the code here at work so I can't tell you exact names right now, but if you want your pages to be able to use the themes then they need to inherit from a class in the newtelligence.dasBlog.Web namespace, and I believe also implement an interface.  A good place to look is in FormatPage and FormatControl.


q: What is the difference between UNION and UNION ALL?

[A]
The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result set but union all returns all rows after joining.
from
http://zengin.wordpress.com/2007/07/31/union-vs-union-all/


q:
What is Dynamic Code Analysis?

How is it different from Static Code Analysis (ie, what can it catch that can't be caught in static)?

I've heard of bounds checking and memory analysis - what are these?

What other things are checked using dynamic analysis?

-Adam

[A]
Basically you instrument your code to analyze your software as it is running (dynamic) rather than just analyzing the software without running (static). Also see this
JavaOne presentation comparing the two
.
Valgrind
is one example dynamic analysis tool for C. You could also use code coverage tools like
Cobertura
or
EMMA
for Java analysis.
From Wikipedia's
definition of dynamic program analysis
:
Dynamic program analysis is the
  analysis of computer software that is
  performed with executing programs
  built from that software on a real or
  virtual processor (analysis performed
  without executing programs is known as
  static code analysis). Dynamic program
  analysis tools may require loading of
  special libraries or even
  recompilation of program code.


q: Is it necessary to set large objects to null when implementing a Dispose() method?

[A]
If a class has a Dispose method the best practice is to call it. the reason
behind that is that Dispose runs when called, whereas setting the object to
null simply adds a entry to the Finalize queue in GC, and we cannot
determine when GC will run.
There is no performance benefit in implementing the Dispose method on types that use only managed resources (such as arrays) because they are automatically reclaimed by the garbage collector. Use the Dispose method primarily on managed objects that use native resources and on COM objects that are exposed to the .NET Framework. Managed objects that use native resources (such as the FileStream class) implement the IDisposable interface.
An elegant means of inoking Dispose that have adopted is using the "using" construct. For those of you who may not be familiar with the construct, it provide a means to implicity invoke Dispose() on an instance that implements IDisposable even if an exception is thrown durring the operation. The following is an example of the using construct:
```
```
using(DisposableClass dc = new DisposableClass())
{
   dc.PerformActionOnUmanagedResources();
   dc.PerformAnotherActionOnUmanagedResources();
}
```
```
In the previous example, if an exception was thrown in the PerformActionOnUmanagedResources() method, although the PerformAnotherActionOnUmanagedResources() method would not be processed, the using block will still implicity invoke the Dispose method on dc ensuring the realese of any unmanaged resources.


q:
Each cell contains some text and a background color. So I have some cells that are blue and some that are red. What function do I use to count the number of red cells?

I have tried =COUNTIF(D3:D9,CELL("color",D3)) with no success (Where D3 is red).

[A]
Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:
http://www.cpearson.com/excel/colors.aspx
Example form the site:
The SumColor function is a color-based
  analog of both the SUM and SUMIF
  function. It allows you to specify
  separate ranges for the range whose
  color indexes are to be examined and
  the range of cells whose values are to
  be summed. If these two ranges are the
  same, the function sums the cells
  whose color matches the specified
  value. For example, the following
  formula sums the values in B11:B17
  whose fill color is red.
```
=SUMCOLOR(B11:B17,B11:B17,3,FALSE)
```


q:
When I turn an image (<img>) into a hyperlink (by wrapping it in <a>), Firefox adds a black border around the image.  Safari does not display the same border.

What CSS declaration would be best to eliminate the border?


q:
I know that the .NET framework looks for referenced DLLs in several locations

Global assembly cache (GAC)

Any private paths added to the AppDomain

The current directory of the executing assembly

What order are those locations searched? Is the search for a DLL ceased if a match is found or does it continue through all locations (and if so, how are conflicts resolved)?

Also, please confirm or deny those locations and provide any other locations I have failed to mention.

[A]
No longer is the current directory searched first when loading DLLs! This change was also made in Windows XP SP1. The default behavior now is to look in all the system locations first, then the current directory, and finally any user-defined paths.
(ref.
http://weblogs.asp.net/pwilson/archive/2003/06/24/9214.aspx
)
The default search order, which can be changed by the application, is also described on MSDN:
Dynamic-Link Library Search Order
.


q:
The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially).

Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line.

For more information on the bug, read it here.

This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0.

Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.

[A]
For this particular issue, the reason is because javascript generated by
ASP.NET 2.0 has some IE only notation: event.srcElement is not availabe in
FireFox (use event.target instead):
```
```
function WebForm_FireDefaultButton(event, target) {
if (!__defaultFired && event.keyCode == 13 && !(event.srcElement &&
(event.srcElement.tagName.toLowerCase() == "textarea"))) {
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof(defaultButton.click) !=
"undefined") {
__defaultFired = true;
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
return true;
}
```
```
If we change the first 2 lines into:
```
```
function WebForm_FireDefaultButton(event, target) {
var element = event.target || event.srcElement;
if (!__defaultFired && event.keyCode == 13 && !(element &&
(element.tagName.toLowerCase() == "textarea"))) {
```
```
Put the changed code in a file and then do
```
```
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptInclude("js1", "JScript.js");
}
```
```
Then it will work for both IE and FireFox.
Source:
http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html


q:
Pretty much what the title says really.

We have some code that is .NET 1.1 based and no real desire to up-convert it.  However, we are looking to add developers to the team and they will need copies of Visual Studio.

My understanding is that they will need VS 2003 - as this is the only IDE that supports .NET 1.1 but I am wondering if we are still able to purchase it!

[A]
You can build 1.1 projects in Visual Studio 2005:
http://www.hanselman.com/blog/BuildingNET11ProjectsUsingVisualStudio2005.aspx
The MSBuild Everett Environment (MSBEE) has been announced, and soon this will be a (reasonably) supported scenario and we'll all be able to build both 1.1 and 2.0 versions of .NET code on Visual Studio 2005.
Also read this post about this issue:
http://blogs.msdn.com/clichten/archive/2005/11/08/490541.aspx
And also:
MSBuild Extras
– Toolkit for .NET 1.1 “MSBee” is an addition to MSBuild that allows developers to build managed applications using Visual Studio 2005 projects that target .NET 1.1.


q:
This is pretty simple, I come from a swing/awt background.

I'm just wondering what the proper way to set the background color for a SWT widget is?

I've been trying:

widget.setBackground( );

Except I have no idea how to create the color Object in SWT?

[A]
To create a color, try this:
```
```
Device device = Display.getCurrent ();
Color red = new Color (device, 255, 0, 0);
```
```


q:
exact code will be helpful. I assume the DirectoryServices namespace does it but I can't find the method that does it.

I need actual C# code. All the samples I found so far are VB or VBScript. The C# examples I found are for reading/setting ADSI properties. A command like backup seems to have a certain .NET syntax which I am not clear how to use. In VB there's a straightforward backup command. Need an equivalent in .NET.

[A]
You'll need to use ADSI objects. The
IIsComputer.Backup
method is what you want.
As far as how to access ADSI objects from C#, check out this
MSDN page
.
EDIT:
Here's a
sample implementation in C#
.


q:
What options exist for accessing different databases from C++?
Put differently, what alternatives are there to ADO?
What are the pros and cons?

[A]
Microsoft ODBC
.
The MFC ODBC classes such as
CDatabase
.
OleDB
(via COM).
And you can always go through the per-RDBMS native libraries (for example, the
SQL Server native library
)
DAO
(don't).
3rd party ORM providers.
I would recommend going through ODBC or OleDB by default. Native libraries really restrict you, DAO is no fun, there aren't a lot of great 3rd-party ORM for C++/Windows.


q:
How would you describe and promote WCF as a technology to a non-technical client/manager/CEO/etc?

What are competing solutions or ideas that they might bring up(such as those they read about in their magazines touting new technology)?

What is WCF not good for that you've seen people try to shoehorn it into?

-Adam

[A]
In a single sentence, I'd say that WCF is "software that lets you set up and manage communication between systems a lot more efficiently than in the past".
I can see them bringing up BizTalk as a competitor, but of course you could say that WCF works with it and is in fact used as base technology for it in the more recent versions.
I'm not sure if I can think of any inappropriate shoe-horning of WCF that I have seen, although there are plenty of legacy apps that will probably be "upgraded" to WCF that don't really need to be for any real business reason.


q: I know that it does in PHP, and I'm pretty sure it does in Java. I haven't used the latest versions of .NET, so I won't speak for them. It seems very awkward, but I was wondering if there was an underlying reason for this.

[A]
One reason is compatibility - anyone who has done 'check for existence' knows to exclude directories; changing that behaviour may confuse those who rely on that behaviour.
Secondly, the underlying code often does a check on the operating system for existence in a catlog of filesystem entries - to the OS, a directory is the same as a file. In other words, it's looking for an entry of 'xyz' in the catalog not a file with name 'xyz' in the catalog.
Backwards compatability is the main reason, I suspect.


q: I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this?

[A]
to learn what libraries a binary uses, use ldd
```
```
ldd path/to/the/tool
```
```
You'd have to write a little shell script to get to your system-wide breakdown.


q: What kind of multi-threading issues do you have to be careful for in asp.net?

[A]
Programmatic Caching is one area which immediately comes to my mind. It is a great feature which needs to be used carefully. Since it is shared across requests, you have to put locks around it before updating it.
Another place I would check is any code accessing filesystem like writing to log files. If one request has a read-write lock on a file, other concurrent requests will error out if not handled properly.


q:
We're using Mercurial where I work and I want to have a setup similar to how I used SVN:

Trunk

Tags

Production

Branches

Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'.

Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial?

[A]
Something like
```
hg transplant
```
? That's what we use on our dev and prod branches.


q: Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect.  In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control.

[A]
I recently discovered that you can use SetWindowPos to accomplish this.  Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this:
```
```
SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
```
```
This changes the z-order of controls which, in turn, establishes the tab order.


q:
This is the text from MSDN comment: "According to the book ATL Internals (2ed) the use of attributes is deprecated and should not be used in new ATL projects."

But WHY?!!

[A]
In ATL these attributes were a compiler trick. They were not a core part of the platform like attributes in C#. They were also more confusing to debug than macros's and the method of dumping generated attribute code was a hassle.
I suspect another issue is likely to have been C++ compiler compatibility and standards-adherence. Attributes didn't make for more beautiful C++ code, and perhaps this syntax may be used in a future version of a real C++ standard.


q: It's really quite annoying as they are not part of the project.

[A]
The Visual Studio Web Deployment addin lets you exclude folders and more.
VS2005
VS2008
Also a decent writeup on the
Web Deployment addin


q:
I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:

Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))

The ItemDrag handler (where the exception takes place), looks like:

private void treeView_ItemDrag(object sender,
        System.Windows.Forms.ItemDragEventArgs e)
{

        this.DoDragDrop(e.Item, DragDropEffects.Move);
}

Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2)

[A]
```
FORMATETC
```
is a type of application clipboard, for lack of a better term.  In order to pull off some of the visual tricks of draging around the tree node, it has to be copied into this clipboard with its source description.  The source control loads its info into the
```
FORMATETC
```
clipboard and sends it to the target object.  It looks like the error occurs on the drop and not on the drag. The
```
DV
```
in
```
DV_E_FORMATETC
```
typically indicates the error occurrs on the drop step.
The destination doesn't look like it likes what you are droping on it. The clipboard may be corrupt or the drop destination may not be configured to understand it.
I recommend you try one of two things.
Remove the original tree structure and destination. Dump your dlls.  Close everything.  Open up and put the treeview and destination back on the form.  It may have just been poorly formed and not fully populating the
```
FORMATETC
```
structure.
Try putting another treeview and droping to that.  If you are droping to another tree and it works you know your oranges to oranges work and it isn't the treeview.  It may be the destination if it is a grid or listview.  You may need to change those structures to be able to receive the drop.
Not that it helps but the structure is something like this:
```
```
typedef struct tagFORMATETC
{
  CLIPFORMAT      cfFormat;
  DVTARGETDEVICE  *ptd;
  DWORD           dwAspect;
  LONG            lindex;
  DWORD           tymed;
} FORMATETC, *LPFORMATETC;
```
```


q: One of my co-workers claims that even though the execution path is cached, there is no way parameterized SQL generated from an ORM is as quick as a stored procedure. Any help with this stubborn developer?

[A]
I would start by reading this article:
http://decipherinfosys.wordpress.com/2007/03/27/using-stored-procedures-vs-dynamic-sql-generated-by-orm/
Here is a speed test between the two:
http://www.blackwasp.co.uk/SpeedTestSqlSproc.aspx


q:
I'm using WScript to automate some tasks, by using WScript.Shell to call external programs.

However, right now it does not wait for the external program to finish, and instead moves on. This causes issues because I have some tasks dependent on others finishing first.

I am using code like:

ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir

Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.run ZipCommand

Is there a way to do this so it blocks until the shell executed program returns?

[A]
If you use the "Exec" method, it returns a reference, so you can poll the "Status" property to determine when it is complete.  Here is a sample from
msdn
:
```
```
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec(ZipCommand)

Do While oExec.Status = 0
    WScript.Sleep 100
Loop
```
```


q: I'm currently working on putting together a fairly simple ORM tool to serve as a framework for various web projects for a client.  Most of the projects are internal and will not require massive amounts of concurrency and all will go against SQL Server.  I've suggested that they go with ORM tools like SubSonic, NHibernate, and a number of other open source projects out there, but for maintainability and flexibility reasons they want to create something custom.  So my question is this: What are some features that I should make sure to include in this ORM tool?  BTW, I'll be using MyGeneration to do the code generation templates.

[A]
You need to go the nHibernate style, in my experience, and have it so that you have some kind of map, between your objects and the database. This allows your objects to have some things that are hard to represent in a database but are easier represented in POCOs.
Generation gets you started, by giving you classes that meet your schema, but if you plan on maintaining anything or testing anything, mapping is pain now for pleasure later.
Subsonic is a great model, and its open source, if you must go generation, use their templates in myGeneration to get a leg up.
BTW: I've done what you are doing, and I ended up with something very similar to subsonic, and now advise my clients to take the subsonic source, and fork it for themselves.


q:
I know this isn't strictly speaking a programming question but something I always hear from pseudo-techies is that having a lot of entries in your registry slows down your Windows-based PC. I think this notion comes from people who are trying to troubleshoot their PC and why it's running so slow and they open up the registry at some point and see leftover entries from programs they uninstalled ages ago.

But is there any truth to this idea? I would not think so since the registry is essentially just a database and drilling down to an entry wouldn't take significantly longer on a larger registry. But does it?

EDIT: To be clear, I'm not looking for advice on how to make a PC run faster, or asking why my PC in particular is slow (it's not), I'm just curious if people who say "bigger registry means slower PC" are accurate or not.

[A]
In short, not really.
In the old days when machines were slower the answer was yes; but having a modern processor rip through even a 60MB registry is not a problem.
Typically, the real reason a modern machine starts running slow is due to everything from malware to virus scanners: Mcafee, Norton's, etc are prime targets in my mind.
Also, the WinSXS folder tends to grow as service packs and applications are installed.  This seems to have a negative impact on system performance.  There are only two possible solutions in this scenario.  First, if possible, reinstall the OS with the latest service pack already slipstreamed into the install.  Second, if that isn't possible AND you are running Vista with SP1, you can run the vsp1cln.exe tool (see
technet
) which will clean up a lot of the older versions of components.  Note that this tool can only be executed once and it does not allow you to roll back.


q:
As far as I can tell, this is isn't possible, so I'm really just hoping for a left field undocumented allocation hook function.

I want a way to track allocations like in _CrtSetAllocHook, but for C#/.NET.

The only visibility to the garbage collector/allocation appears to be GC.CollectionCount.

Anyone have any other .NET memory mojo?

[A]
The CLR has a 'profiling API' that hooks into pretty much everything - it is what the commercial .NET memory profiling products use, I believe. Here is an MSDN link to the top level of the documentation:
.NET Framework General Reference: About the Profiling API
See this MSDN magazine article for an introduction to the memory piece:
Inspect and Optimize Your Program's Memory Usage with the .NET Profiler API


q:
Does anyone have a good solution for integrating some C# code into a java application?

The code is small, so I could re-write in java, but I would rather reuse the code if possible. Don't repeat yourself, etc.

Also, I know I can expose the C# as a web service or whatever, but it has some security/encryption stuff in there, so I would rather keep it tightly integrated if possible.

Edit: It's going to be on a server-based app, so "downloading" another runtime is irrelevant.

[A] If it's short, I think you're better off re-writing the code in java.  Downloading one 50Mb runtime is bad enough.


q: When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows)

[A]
From
Joe Grossberg
's blog (no longer available):
But if you're using GNU Emacs 21.2
  (the latest version, which includes
  this as part of the standard distro),
  you can just put the following lines
  into your .emacs file
```
```
;; recentf stuff
(require 'recentf)
(recentf-mode 1)
(setq recentf-max-menu-items 25)
(global-set-key "\C-x\ \C-r" 'recentf-open-files)
```
```
Then, when you launch emacs, hit
CTRL
-
X
CTRL
-
R
. It will show a list of
  the recently-opened files in a buffer.
  Move the cursor to a line and press
ENTER
. That will open the file in
  question, and move it to the top of
  your recent-file list.
(Note: Emacs records file names.
  Therefore, if you move or rename a
  file outside of Emacs, it won't
  automatically update the list. You'll
  have to open the renamed file with the
  normal
CTRL
-
X
CTRL
-
F
method.)
Jayakrishnan Varnam has a
page
  including screenshots
of how this
  package works.
Note:
You don't need the
```
(require 'recentf)
```
line.


q: Does anyone know if silverlight plugs into chrome, or when they plan to support it?

[A]
This guy have had partial success with silverlight in chrome, but it does not seem to be supported:
http://wildermuth.com/2008/09/02/Silverlight_2_and_Google_Chrome
From The Microsoft Silverlight Team in the
silverlight forum
:
Hello, currently we don't have plans
  to support Chrome. We will support it
  in the future if it gains enough
  market share. Please understand, each
  browser implements the plug-in model
  differently, so it'll be a lot of
  effort to officially support a browser
  100%... By the way, IE 8 also runs
  each tab in its own process. If a tab
  crashes, other tabs will still work
  fine.
UPDATE:
Jon Galloway has just posted instructions on how to get silverlight successfully running on Chrome here:
http://weblogs.asp.net/jgalloway/archive/2008/09/17/silverlight-on-chrome.aspx


q:
This has been driving me crazy for a few days.  Why doesn't the following work?

    Dim arr(3, 3) As Integer

    For y As Integer = 0 To arr.GetLength(0) - 1
        For x As Integer = 0 To arr.GetLength(y) - 1
            arr(y, x) = y + x
        Next
    Next

Also, what if the array looked like this instead?

{ {1, 2, 3},
  {4, 5, 6, 7, 8, 9, 9, 9},
  {5, 4, 3, 2}
}

[A]
```
arr.GetLength(y)
```
should be
```
arr.GetLength(1)
```


q:
Is there a good way to adjust the size of a UITextView to conform to its content? Say for instance I have a UITextView that contains one line of text:

"Hello world"

I then add another line of text:

"Goodbye world"

Is there a good way in Cocoa Touch to get the rect that will hold all of the lines in the text view so that I can adjust the parent view accordingly?

As another example, look at the notes' field for events in the Calendar application - note how the cell (and the UITextView it contains) expands to hold all lines of text in the notes' string.

[A]
Did you try
```
[textView sizeThatFits:textView.bounds]
```
?
Edit: sizeThatFits returns the size but does not actually resize the component. I'm not sure if that's what you want, or if
```
[textView sizeToFit]
```
is more what you were looking for. In either case, I do not know if it will perfectly fit the content like you want, but it's the first thing to try.