Question:
I have an Internet Explorer only web application.

I'm exploring what we can do to automate the testing.

Selenium looks like a good tool, but to be able to activate links etc. I need to tell it where they are. The application wasn't built with this kind of testing in mind, so there generally aren't id attributes on the key elements.

No problem, I think, I can use XPath expressions. But finding the correct XPath for, say, a button, is a royal pain if done by inspecting the source of the page.

With Firefox / Firebug, I can select the element then use "Copy XPath" to get the expression.

I have the IE Developer Toolbar and it's frustratingly close. I can click to select the element of interest and display all sorts of information about it. but I can't see any convenient way of determining the XPath for it.

So is there any way of doing this with IE?

Answer:
I would use bookmarklets. I have one XPath related, but I don't know if it works in IE. I gotta go but I will test it and give it if it works on IE.
Two bookmarklet sites for Web developers from my bookmarks:
Subsimple's bookmarklets
and
Squarefree's Bookmarklets
. Lot of useful things there...
[EDIT] OK, I am back. The bookmarklet I had was for FF only, and wasn't optimal. I finally rewrote it, although using ideas from the original one. Can't find back where I found it.
Expanded JS:
```
```
function getNode(node)
{
  var nodeExpr = node.tagName;
  if (nodeExpr == null)  // Eg. node = #text
    return null;
  if (node.id != '')
  {
    nodeExpr += "[@id='" + node.id + "']";
    // We don't really need to go back up to //HTML, since IDs are supposed
    // to be unique, so they are a good starting point.
    return "/" + nodeExpr;
  }
// We don't really need this
//~   if (node.className != '')
//~   {
//~     nodeExpr += "[@class='" + node.className + "']";
//~   }
  // Find rank of node among its type in the parent
  var rank = 1;
  var ps = node.previousSibling;
  while (ps != null)
  {
    if (ps.tagName == node.tagName)
    {
      rank++;
    }
    ps = ps.previousSibling;
  }
  if (rank > 1)
  {
    nodeExpr += '[' + rank + ']';
  }
  else
  {
    // First node of its kind at this level. Are there any others?
    var ns = node.nextSibling;
    while (ns != null)
    {
      if (ns.tagName == node.tagName)
      {
        // Yes, mark it as being the first one
        nodeExpr += '[1]';
        break;
      }
      ns = ns.nextSibling;
    }
  }
  return nodeExpr;
}

var currentNode;
// Standard (?)
if (window.getSelection != undefined)
  currentNode = window.getSelection().anchorNode;
// IE (if no selection, that's BODY)
else
  currentNode = document.selection.createRange().parentElement();
if (currentNode == null)
{
  alert("No selection");
  return;
}
var path = [];
// Walk up the Dom
while (currentNode != undefined)
{
  var pe = getNode(currentNode);
  if (pe != null)
  {
    path.push(pe);
    if (pe.indexOf('@id') != -1)
      break;  // Found an ID, no need to go upper, absolute path is OK
  }
  currentNode = currentNode.parentNode;
}
var xpath = "/" + path.reverse().join('/');
alert(xpath);
// Copy to clipboard
// IE
if (window.clipboardData) clipboardData.setData("Text", xpath);
// FF's code to handle clipboard is much more complex
// and might need to change prefs to allow changing the clipboard content.
// I omit it here as it isn't part of the original request.
```
```
You have to select the element and activate the bookmarklet to get its XPath.
Now, the bookmarklet versions (thanks to
Bookmarklet Builder
):
IE
(I had to break it in two parts, because IE doesn't like very long bookmarklets (max size varies depending on IE versions!). You have to activate the first one (function def) then the second one. Tested with IE6.)
```
```
javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}
javascript:function o__o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o__o();
```
```
FF
```
```
javascript:function o__o(){function getNode(node){var nodeExpr=node.tagName;if(nodeExpr==null)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps!=null){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns!=null){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}var currentNode=window.getSelection().anchorNode;if(currentNode==null){alert("No selection");return;}var path=[];while(currentNode!=undefined){var pe=getNode(currentNode);if(pe!=null){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');alert(xpath);}o__o();
```
```


Question:
I want to keep my website/s in version control (Subversion specifically) and use svn co to update it when there are stable versions to update, but I'm concerned about the security of doing so, as all the .svn folders will be public, and these include all sorts of private data, not least of which is complete source code to my website!

Is there anything I can I do to prevent this?

Answer:
This can be achieved server-wide (recommended), on a single virtual-host basis, or even inside
```
.htaccess
```
files if your server is somewhat permissive with what is allowed in them. The specific configuration you need is:
```
```
RewriteEngine On
RewriteRule /\.svn /some-non-existant-404-causing-page

<IfModule autoindex_module>
    IndexIgnore .svn
</IfModule>
```
```
The first section requires
```
mod_rewrite
```
. It forces any requests with "/.svn" in them (ie. any request for the directory, or anything inside the directory) to be
internally
redirected to a non-existant page on your website. This is completely transparent to the end-user and undetectable. It also forces a 404 error, as if your
```
.svn
```
folders just disappeared.
The second section is purely cosmetic, and will hide the
```
.svn
```
folders from the autoindex module if it is activated. This is a good idea too, just to keep curious souls from getting any ideas.


Question: Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc.

Answer:
I have no idea about exception safely here but I go this way. Let's imagine it's a templated array wrapper. Hope it helps :)
```
```
Array(const Array& rhs)
    {
        mData = NULL;
        mSize = rhs.size();
        *this = rhs;
    }

    Array& operator=(const Array& rhs)
    {
        if(this == &rhs)
        {
            return *this;
        }

        int len = rhs.size();

        delete[] mData;

        mData = new T[len];

        for(int i = 0; i < len; ++i)
        {
            mData[i] = rhs[i];
        }

        mSize = len;

        return *this;
    }
```
```


Question:
Is it possible, with Javascript or some other technology to determine which hyperlink a user has clicked on, without changing the hyperlink source code.

For example:
Can you click on a 'tag' button, then click on a hyperlink hosted in a different iframe, and be able to calculate which hyperlink the user clicked on, without changing any of the source code in that iframe?

Answer:
you need to put an event on each a link ,
and then you will get all the information about the specific click.
this will work only in the some document,
so if you try to do a test between the link inside an iframe and a link in your page you will not get an event for the iframe link.
in order to attach the event for all link you need to run on all the links in the page ,
the best way to do that is by jQuery selector. or other js framework like YUI
$("a").click(function () {
      alert('')
});
getElementsByTagName("a") - will give you all the links in the page.


Question:
I'm trying to assign application pool to one web site in IIS7 using vb script:

' Connect to the WMI WebAdministration namespace.'
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")

' Retrieve the application and display its Web site name and path.'
Set oApp = oWebAdmin.Get("Application.SiteName='Default Web Site',Path='/site'")

' Specify a new application pool name and save it.'
oApp.ApplicationPool = "NewAppPool"
oApp.Put_

the above script is not working!

Is there is a better way to assign application pool to web site under IIS (Using script)?

Answer:
Are you setting the app pool on a web site or a virtual directory?
i.e., "Default Web Site/site" (virtual directory) or just "Site" (web site).
If you trying to set it on a web site, not a virtual directory, you need to do something like:
```
```
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")
Set oSite = oWebAdmin.Get("Site.Name='Site'")
oSite.ApplicationDefaults.ApplicationPool = "NewAppPool"
oSite.Put_
```
```


Question:
When using C++ namespaces, do you prefer to explicitly name them, like this:

std::cout << "Hello, world!\n";

Or do you prefer using namespace:

using namespace std;
cout << "Hello, world!\n";

And if if you prefer the latter, do you declare your usings at file or function scope?

Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. std and boost) I find it more readable.

Answer:
I always use
```
using namespace
```
for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code.
In headers, I never use
```
using namespace
```
to avoid polluting the global namespace of the #including source.


Question: How to dynamically bind data to <%Html.Dropdownlist.... in ASP.NET MVC?

Answer:
Just pass the correct IEnumerable as the typed model or ViewData. Try something like this (out of my head):
```
```
<%= Html.DropDownList(string.Empty,
    "myDropDownList",
    new SelectList((IEnumerable)ViewData["stuff"],
        "DescriptionProperty",
        "ValueProperty"))
%>
```
```
With that drop down list helper in MVC, you do not really "bind" data to it in the way it is done in the old ASP.NET.


Question:
I am trying to connect to simple webparts in my sharepoint team site, i need one of the webparts to filter its information based on what it recieves from another webpart

I am using the query string filter webpart and the a list view webpart but no matter how i connect them always i am getting this error

"Web Part Error:  This page has exceeded its data fetch limit for connected Web Parts. Try disconnecting one or more Web Parts to correct the problem."

What should I do and what am I doing wrong

update:
 i can connect to web parts on some other pgae, but getting this error on the DispForm.aspx page of a certain item , is webpart connections not allowed there ??!!

Answer:
There is an issue with creating QueryString filter webparts in sharepoint, when you're not using the Web UI (I'm making an assumption that you aren't).
This fella here has a post about it and how he hacked around the issue.
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/0328f1b2-20cd-427f-887a-e2925bd695e3/
Another option is not using the QueryString filter web part at all, and just passing querystrings to a regular web part.
http://mo.notono.us/2008/04/moss-filter-views-through-url-query.html


Question:
I want to be able to use a function such as writefln() but without having to add import std.stdio at the top of the file.

Another way to explain it is the way you do it in C++. You can type std::cout << "Test"; and that will stop you from having to add using namespace std;. I want to do the same thing, but in D.

Answer:
I don't think you can do that. The
```
import
```
statement in D does more than the
```
using namespace
```
statement does in C++. It also replaces the
```
#include
```
preprocessor directive.


Question:
I am using running a simple find all and paginating with willpaginate, but I'd also like to have the query sorted by the user. The first solution that came to mind was just use a params[:sort]

http://localhost:3000/posts/?sort=created_at+DESC

@posts = Post.paginate :page => params[:page], :order => params[:sort]

But the problem with his approach is that the query is defaulting as sorting by ID and I want it to be created_at.

Is this a safe approach to sorting and is there a way to default to created_at?

Answer:
In general, the way to supply default values for Hash and Hash-like objects is to use
```
fetch
```
:
```
```
params.fetch(:sort){ :created_at }
```
```
A lot of people just use
```
||
```
though:
```
```
params[:sort] || :created_at
```
```
I prefer
```
fetch
```
myself as being more explicit, plus it doesn't break when
```
false
```
is a legitimate value.


Question:
I have an old ASP.NET 1.1 site that I am maintaining.  We are working with Google to place analytics code on all pages.  Since I can't take advantage of master pages in 1.1, I have my pages include headers/footers/sidebars with User Controls.

What came to mind first is to place the JavaScript in my footer ascx control so it appears on every page.  But I don't think I can link to a JavaScript file from a user control.

Any ideas on what I can do to get this js code placed on every page in my site?

Answer:
What keeps you from simply referencing your script in the user control?
```
```
<asp:SomeControl ID="SomeControl1" runat="server>
  <script src="some.js" type="text/javascript"></script>
</asp:SomeControl>
```
```
You could also do this:
```
```
protected void Page_Load(object sender, EventArgs e)
{
  Literal some_js = new Literal();
  some_js = "<script type='text/javascript' src='some.js'></script>";
  this.Header.Controls.Add(some_js);
}
```
```
(Obviously, the second approach would still force you to modify the pages themselves, unless they inherit from a common parent you control.)


Question: Sharepoint isn't the speediest of server applications, and I've read about a few tips to speed it up. What steps do you think are necessary to increase performance so it can be used to host a high traffic site?

Answer:
At the end of the day SharePoint is just a complicated web site with all the standard components.
In order to optimize performance you need to analyze each component and determine which one is a problem, and then adjust it accordingly.
We're in the process of implementing a 1000 concurrent user sharepoint website, which may or may not be large, however some steps we are taking are:
Implementing a detailed caching strategy, to cache webpart content intelligently.
Use load balanced servers to ensure all our hardware is utilised rather then lying idle.
We've undertaken capacity planning given the existing solution, so we have a good idea which component is the bottleneck for us. (The SQL Server), so we will ensure the server can cope with expected load and future growth of the site.
We're also using hardware load balancers which will ensure our network and the related servers operate as expected, and again this is something to investigate before you implement a sharepoint website.
We're also ensuring our webparts don't generate unnecessary html, and don't return unnecesary data, as this will slow down loading times.
Something which I definately think is a good idea is to have a goal to work towards, as you can spend a huge amount of money and time optimizing SharePoint, which may prove unnecessary.


Question:
Is the asp.net membership system used over wcf (transport security turned on) enough for high security internet scenarios with thousands of clients spread all over the internet?

I'm just evaluating possible solutions and wanted to know if this might fit in this category.

If not, what would be the best method to provide high security access over wcf for internet scenarios?

Answer:
Yes it will work; and with SSL/transport security the authentication will be protected by the transport. Will it scale? That's harder to say; it depends on too many factors.
OK so by high security you're looking for non-repudiation? That's trickier; because of course people can share usernames and passwords. But even if you also used client certificates, well people share certificates. I'd certainly look at
WCF auditing
in combination with the authentication and set SupressAuditFailure to be false.


Question:
I have a ListCtrl that displays a list of items for the user to select. This works fine except that when the ctrl is not large enough to show all the items, I want it to expand downwards with a vertical scoll bar rather than using a horizontal scroll bar as it expands to the right.

The ListCtrl's creation:

self.subjectList = wx.ListCtrl(self, self.ID_SUBJECT, style = wx.LC_LIST | wx.LC_SINGLE_SEL | wx.LC_VRULES)

Items are inserted using wx.ListItem:

item = wx.ListItem()
item.SetText(subject)
item.SetData(id)
item.SetWidth(200)
self.subjectList.InsertItem(item)

Answer:
Use the
wxLC_REPORT
style.
```
```
import wx

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.test = wx.ListCtrl(self, style = wx.LC_REPORT | wx.LC_NO_HEADER)

        for i in range(5):
            self.test.InsertColumn(i, 'Col %d' % (i + 1))
            self.test.SetColumnWidth(i, 200)

        for i in range(0, 100, 5):
            index = self.test.InsertStringItem(self.test.GetItemCount(), "")
            for j in range(5):
                self.test.SetStringItem(index, j, str(i+j)*30)

        self.Show()

app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()
```
```


Question:
Can someone tell me how i can change the .xml file that a flash movie loads using c#.  ie: i would like an ActionScript variable that defines the location of the flash movie. I would like to be able to change this variable using c# if possible.

i dont really know how it would look, but something like:

<object xmlpath='" + myCSharpVar + "'" ...></object>

I just starting this, but my ultimate goal is to create a .swf movie that can load an xml file that specifies images, etc.  However i want to use the same .swf file in multiple places and only have to change a ref to what xml file it uses - and my Flash/ActionScript skills are very rusty.

To clear it up a bit, in AS you can do something like:

loader.load( new URLRequest("IWantThisNameDynamic.xml") );

how can i define that xml file in my c# code?

Answer:
I'm quite sure you cannot "create" your own attributes for the object tag. At least not without consulting with the w3c ;-)
Passing values to flash is done via the "flashvar"-param:
```
```
<object ...>
    <param name="flashvars" value="&xmlpath=<path to xml>"/>
  </object>
```
```
In the flash-movie you can now access the path to your xml via the "xmlpath"-variable.


Question:
I have the following javascript:

$.ajax({
  type: "POST",
  dataType: "json",
  url: "/Home/Submit",
  data: {
    email: strEmail,
    message: strMessage
  },
  success: function(result) {
    //alert('here');
    alert(result.message);
  },
  error: function(error) {
    alert(error);
  }
});

This makes a call to this function:

public JsonResult Submit(string Email, string Message) {
  return Json(new {
    message = "yep"
  });
}

This works fine in debug mode on the inbuilt webserver.

However if I go to the virtual dir directly it does not and hits the error bit. I attached to the process and the code behind never gets hit.

I am using Vista.

Additionally how do you get the error description in the bit where it says  alert(error);

Thanks,

Alex

Answer:
Predicate is a delegate. You can not inherit from a delegate type.
If you want to get the inverted value, use the following:
```
```
Predicate<T> p;
Predicate<T> inverted = t => !p(t);
```
```


Question: For example, I want just the "filename" of a file in a field.  Say I have myimage.jpg  I only want to display "myimage"  How do I get just that?

Answer:
Use the List functions to your advantage.
```
```
<cfset FileName = ListDeleteAt(FileFullName, ListLen(FileFullName, "."), ".")>
```
```
Be aware that this only works for file names that actually
have
a file extension (that is defined as the thing after the last dot). To make it safer, the following is better:
```
```
<cfset ExtensionIndex = ListLen(FileFullName, ".")>
<cfif ExtensionIndex gt 1>
  <cfset FileExt  = ListGetAt(ExtensionIndex , ".")>
  <cfset FileName = ListDeleteAt(FileFullName, ExtensionIndex, ".")>
<cfelse>
  <cfset FileExt  = "">
  <cfset FileName = FileFullName>
</cfif>
```
```
To complicate things a bit further: There may be files that start with a dot. There may be file names that contain many adjacent dots. List functions return wrong results for them, as they ignore empty list elements. There may also be files that have dots, but no extension. These can only be handled if you provide an extension white list:
```
ListFindNoCase(FileExt, "doc,xls,ppt,jpg")
```
. If you want to account for all of this, you probably need to resign to a reguar expression:
```
```
<cfset FileExtRe = "(?:\.(?:doc|xls|ppt|jpg))?$">
<cfset FileName  = REReplaceNoCase(FileFullName, FileExtRe, "")>
```
```
To split file name from path, ColdFusion provides distinct functions that also handle platform differences:
```
GetFileFromPath()
```
and
```
GetDirectoryFromPath()
```


Question:
Is there a way to change the colors used by plain Win32 menus (background, text, and highlight) for a single process, without using SetSysColors?

(SetSysColors does a global change, which is bad, and if you crash or forget to set the colors back with SetSysColors again before exiting, they will not be restored until you logout.)

Answer:
The SetMenuInfo() API is your friend. It lets you apply any brush to paint your menu's background.
Something along these lines should solve your problem:
```
```
MENUINFO mi = { 0 };
mi.cbSize = sizeof(mi);
mi.fMask = MIM_BACKGROUND|MIM_APPLYTOSUBMENUS;
mi.hbrBack = hBrush;

HMENU hMenu = ::GetMenu(hWnd);
SetMenuInfo(hMenu, &mi);
```
```


Question:
I'm trying this:

Type ThreadContextType = typeof(Application).GetNestedType("ThreadContext", System.Reflection.BindingFlags.NonPublic);
MethodInfo FDoIdleMi = ThreadContextType.GetMethod("FDoIdle", BindingFlags.NonPublic |
    BindingFlags.Instance, null, new Type[] { typeof(Int32) }, null);

ThreadContextType is ok but FDoIdleMi is null. I know there is something wrong in the GetMethod call because FDoIdle comes from the UnsafeNativeMethods.IMsoComponent interface.

How to do that? Thanks.

Answer:
You need to fully-qualify the method name, because they're using explicit interface implementation:
```
```
Type type = typeof( Application ).GetNestedType( "ThreadContext",
    BindingFlags.NonPublic );
MethodInfo doIdle = type.GetMethod(
    "System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle",
    BindingFlags.NonPublic | BindingFlags.Instance );
```
```
For the record, reflecting on non-public members is generally bad practice, but you probably already know that.
EDIT
In the spirit of teaching a person to fish, I figured this out by calling
```
GetMethods(...)
```
on the type object, and examining the returned array to see how the methods were named. Sure enough, the names included the complete namespace specification.


Question:
I'm using a ListView in C# to make a grid.  I would like to find out a way to be able to highlight a specific cell, programatically.  I only need to highlight one cell.

I've experimented with Owner Drawn subitems, but using the below code, I get highlighted cells, but no text!  Are there any ideas on how to get this working?  Thanks for your help.

//m_PC.Location is the X,Y coordinates of the highlighted cell.

void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    if ((e.ItemIndex == m_PC.Location.Y) && (e.Item.SubItems.IndexOf(e.SubItem) == m_PC.Location.X))
        e.SubItem.BackColor = Color.Blue;
    else
        e.SubItem.BackColor = Color.White;
    e.DrawBackground();
    e.DrawText();
}

Answer:
You can do this without owner-drawing the list:
```
```
// create a new list item with a subitem that has white text on a blue background
ListViewItem lvi = new ListViewItem( "item text" );
lvi.UseItemStyleForSubItems = false;
lvi.SubItems.Add( new ListViewItem.ListViewSubItem( lvi,
    "subitem", Color.White, Color.Blue, lvi.Font ) );
```
```
The Color arguments to the ListViewSubItem constructor are controlling the foreground and background color of the subitem. The critical thing to do here is set
```
UseItemStyleForSubItems
```
to False on the list item, otherwise your color changes will be ignored.
I think your owner-draw solution would have worked as well, but you have to remember to change the text (foreground) color when you change the background to blue, otherwise the text will be hard to see.


Question:
We need to implement a large-scale key-value store (let's say up to 500GB) and BerkeleyDB seemed like it might be a decent option, but we would really like it to be network accessible. This led me to look at memcachedb. I haven't found much on the web where people talk about actual experiences with memcachedb, so my questions are, if you've used memcachedb:

would you recommend using it for a large k-v store?

if not, why not?

Thanks in advance!

Francis

Answer:
I have used memcached a little bit in one of my projects. I think it's a very efficient and scalable caching platform. By changing small configurations, you're able to replicate the cached objects in more than one server. Facebook uses memacached for their in-memory storage and it's a large scale entity on the web. This gives a thumb up for memcahced.
The only problem I faced in implementation is that doesn't automatically accept objects to store. You will need to serialize the objects before storing which may be a little bit confusing at the beginning.
FYI, there is a nother caching platform produced by Microsoft called: Velocity. You may need to take a look on it:
http://www.microsoft.com/downloads/details.aspx?FamilyId=B24C3708-EEFF-4055-A867-19B5851E7CD2&displaylang=en


Question: I know a fair bit about the Windows Task Manager in XP, but I would like to understand it better in Vista.  What is the difference between "Working Set (Memory)" and "Memory (Private Working Set)".  What is the Paged Pool, what is the NP Pool (Non-Paged?).  How do I use these to determine what is going on with memory usage?  As an aside, when you minimize a program it frequently returns 90% of the memory it is using.  Is there any way to do this without minimizing it?

Answer:
This MSDN blog entry
might be informative on the first part of the question. A brief excerpt:
Working set is the subset of virtual pages that are resident in physical memory only; this will be a partial amount of pages from that process.
As discussed in the article, the part about private versus not-private has to do with memory used by the process that can be shared by other processes. If you can't share the memory (perhaps the memory is used by the image of a DLL had to be relocated in memory), it becomes private. Heap memory is also always going to be private.
The reason you see the memory drop dramatically when minimizing a program is that Windows automatically trims the working set of a process whenever it its main window is minimized. See
this Microsoft KB article
for more, including instructions on how to do this yourself.
The paged pool and non-paged pool memory refers to kernel memory used by the process. Memory from the paged pool can be paged out (removed from physical memory when memory pressure increases). Memory from the non-paged pool will always remain in physical memory, so generally it's preferable for this to stay small. Unless you're writing device drivers, though, as a user-mode application developer you generally won't need to worry about these two items.


Question:
First some background. I recently went for an interview and some of the questions asked to me was about Enterprise Content Management. Obviously, I did not have any experience and did not get the offer.

But, it increased my curiosity and tried Internet to get some info on the topic. Wikipedia made me more confused with even more buzzwords. Most of the stuff on the web is marketing related and relevant to specific products like Sharepoint or Drupal etc.

I need some help in understanding more about the topic or the domain in simpler terms. What is the requirement to use it? What kind of companies use it? What are the problem areas it tries to address? Any popular use cases? Any places where it looks like a good fit but it is not actually?

Lastly, any good book or articles on the topic without being specific to any product?

Answer:
CMS (Content Management System) describe systems that are used to manage content :-) as for example Joomla, Drupal, Sharepoint and etc.
Content management means document, records, processes and other information related to your company business management.
Enterprise Content Management, as far as I know is this "Content management" concept applied to a organization. The mainly focus is to Capture, Manage, Store, Preserve, and Deliver content and documents related to the organization.


Question: I need a regex that matches all strings ending in .cs, but if they end in .g.cs they should not match. I'm using .NET regular expressions.

Answer:
This will match the end if it's .cs but not .g.cs
```
```
(?<!\.g)\.cs$
```
```
For the entire string start to finish, something like this:
```
```
^.*(?<!\.g)\.cs$
```
```


Question: I have a fairly simple addition to the HTTP standard.  An ambitious goal I know, but I'd at least like to submit a proposal and get feedback on the idea.  What is the proper forum/method of doing so?

Answer:
According to W3C's
HTTP page
:
Now that both HTTP extensions and
  HTTP/1.1 are stable specifications,
  W3C has closed the HTTP Activity. The
  Activity has achieved its goals of
  creating a successful standard that
  addresses the weaknesses of earlier
  HTTP versions.
An effort to revise HTTP/1.1 started
  in the
IETF httpbis Working Group
The page from the latter link has a mailing list you can join, as well as the scope of the working group. You may well be able to get feedback about the merit of your idea in the abstract, but certainly don't get your hopes up at effecting change.


Question:
The calculations in my code are well-tested, but because there is so much GUI code, my overall code coverage is lower than I'd like. Are there any guidelines on unit-testing GUI code? Does it even make sense?

For example, there are graphs in my app. I haven't been able to figure out how to automate the testing of the graphs. It takes a human eye, AFAIK, to check if the graph is correct.

(I'm using Java Swing)

Answer:
Designs like MVP and MVC typically try to abstract as much logic out of the actual GUI as possible. One very popular article about this is
"The Humble Dialog Box"
by Michael Feathers. Personally I've had mixed experiences with trying to move logic out of the UI - sometimes it's worked very well, and at other times it's been more trouble than it's worth. It's somewhat outside my area of expertise though.


Question:
In VS2008 I have written a C# service, an installer, and have created a setup package to install it. The service needs to load an xml file to operate. Where is the best place to put this file in the various filesystem folders offered by the VS setup project, and how do I then refer to these paths from my code?

I should point out the the service runs as LocalService, which means that the ApplicationData folder offered by the "User's Application Data Folder" item in the VS setup project is not accessible, even when "Install for all users" is used during installation. I could easily hack around this, but would like to understand best practice.

Answer:
I am not sure which place is better to store the XML file. I don't think it will matter alot. But if you need to get special folder path in the system you can use Environment class to do so. The following line of code get the path of the Program Files:
```
```
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
```
```


Question: In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?

Answer:
The official tutorial
may be of some use to you.
Class
Package
Subclass
(same pkg)
Subclass
(diff pkg)
World
```
public
```
+
+
+
+
+
```
protected
```
+
+
+
+
no modifier
+
+
+
```
private
```
+
+ : accessible
blank : not accessible


Question:
It's been my experience that some security software (like Symantec's Norton AntiVirus) oftentimes prohibit their removal from a Windows system via the "Add or Remove Programs" utility, going so far as to occasionally require a removal program obtained from Symantec's homepage.  (I assume this it to prevent a malicious program from disabling the security software... any other reason?)

How can a program be configured to resist removal via a system's uninstall utility, or via deleting the program's directory?  Is Norton the only software suite that employs this technique, or is this widespread amongst security software?  Are there similar techniques that can be used on Unix / -like systems?

Answer:
Norton is not the only one that does this, however McAfee and Norton are the only ones who make it almost impossible to remove the software.  Not because they care about viruses or security threats, they don't want to give up control of the system.  Many other Antivirus software that works just as well if not better than Norton, like AVG, Avast, and others do allow you to uninstall from the add remove.  If they tell you anything different they are just lying because you have to physically click the add remove programs to run the uninstall process.  There is no programmatic way to do this.
They do this by just hijacking the uninstall with a custom process.  There is not really a standardized uninstall method.  The closest to that is the MSI package that Microsoft provides, however that doesn't have to be used, and even if they do use it they can customize the operations to do whatever they want when uninstalling.
In NTFS you can lock folders and files that are currently executing in memory.  Norton either uses this method or uses the service running in the background to prevent it.
Norton and McAfee are some of the most invasive resource hogs that you can never get out of your system once installed.  They don't do this for security.  They do this because they are in a market that has Free alternatives that are 20 times better than their legacy software.  So they strike deals with the OEM's to install their software by default in the hopes that people will continue to pay yearly subscriptions to them.  On top of that if they make it really hard to remove, some people won't be bothered and just pay up.


Question:
I am working on a winforms html editor with multiple editor windows as each editor window will be written to a database field.

I am creating the editor windows as a control array and was hoping to just have one toolbar above them that would handle the events such as apply bold, italic... based on the window I was currently in. Unfortunately obviously the event handler of an event on the toolbar doesn't know what the control selected before it was.

Is there a way to get this or should I be adding an onenter event to each editor window and storing statically the last editor window used.

Answer:
I'm not familiar with the types of events you mention, and I'm probably missing something, but it's common in WinForms development to have events fire and provide information about the sender as well as the event, conforming to the
EventHandler
delegate?
```
```
[SerializableAttribute]
[ComVisibleAttribute(true)]
public delegate void EventHandler(
    Object sender,
    EventArgs e
)
```
```
This is how
System.Windows.Forms.Control.Click
operates.
Could you follow this example, where
```
sender
```
would be the editor window in each case?


Question:
Some iPhone applications, such as Pandora seem to directly manipulate the hardware volume and respond to physical volume button. How is this done?

AudioSessionServices allows you to get the current hardware output volume with the kAudioSessionProperty_CurrentHardwareOutputVolume property, but it is (allegedly) read-only.

Answer:
They use the MPVolumeView, simple add it and it's makes the rest when the user touch it. Note: Doesn't work in iPhone Simulator. I think the release note also mentioned do not use it direct in Interface Builder.
```
```
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];
[self.view addSubview:volumeView];
[volumeView release];
```
```


Question:
So am I crazy for considering doing a beta/production release on Glassfish V3 Prelude?
Since all of my content is dynamic, I'm not even thinking of bothering to set up apache in front either.  Doing so complicates the setup by requiring something like AJP or mod_jk and will not offer us much in terms of capability.

So there will be three war files on deployment.
3 JNDI data sources with about 90 connections parked, scaling up to 160 to a PGSQL datastore....

The three wars comprise a CMS system and a grails application?

Is my logic fatally flawed that I don't need to put apache in front of this setup?

Answer:
They use the MPVolumeView, simple add it and it's makes the rest when the user touch it. Note: Doesn't work in iPhone Simulator. I think the release note also mentioned do not use it direct in Interface Builder.
```
```
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];
[self.view addSubview:volumeView];
[volumeView release];
```
```


Question:
I'd like to create a script to manipulate Apache2 configuration directly, reading and writing its properties (like adding a new VirtualHost, changing settings of one that already exists).

Are there any libs out there, for Perl, Python or Java that automates that task?

Answer:
This is the ultimate Apache configurator:
http://perl.apache.org/
exposes many if not all Apache internals to programs written in Perl.
For instance:
http://perl.apache.org/docs/2.0/api/Apache2/Directive.html
(Of course that it can do much much more than just configuring it).
On the other hand, it needs to be loaded and runs within Apache, it's not a config file parser/editor.


Question: From what I understand, the parent attribute of a db.Model (typically defined/passed in the constructor call) allows you to define hierarchies in your data models. As a result, this increases the size of the entity group. However, it's not very clear to me why we would want to do that. Is this strictly for ACID compliance? I would like to see scenarios where each is best suited or more appropriate.

Answer:
The only purpose of entity groups (defined by the parent attribute) is to enable transactions among different entities. If you don't need the transactions, don't use the entity group relationships.
I suggest you re-reading the
Keys and Entity Groups
section of the docs, it took me quite a few reads to grasp the idea.
Also watch these talks, among other things they discuss transactions and entity groups:
Building Scalable Web Applications with Google App Engine
Under the Covers of the Google App Engine Datastore


Question:
What is the purpose of the colon before a block in Python?

Example:

if n == 0:
    print "The end"

Answer:
The colon is there to declare the start of an indented block.
Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the
Python koan
“explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so
any
statement that
should
be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)
It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.
This question turns out to be a
Python FAQ
, and I found one of its answers by Guido
here
:
Why are colons required for the if/while/def/class statements?
The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:
```
```
if a == b
    print a
```
```
versus
```
```
if a == b:
    print a
```
```
Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.
Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.


Question: What is a good resource to get started with Windows file system driver development for a newbie?

Answer:
You might try
Windows Hardware Developer Central
, which has links to blogs, newsgroups, books, and other useful resources for driver authors.
I also recommend downloading and installing the
Windows DDK
and exploring some of the included samples. There should be various skeleton drivers that can be used as starting points for your custom work.


Question:
Erlang support to partition its nodes into groups using the global_group module.
Further, Erlang supports adding nodes on the fly to the node-network. Are these two features usable with each other?

As far as I understand, you have to name every node on startup to use the global groups.

Answer:
A node is an executing Erlang runtime
  system which has been given a name,
  using the command line flag -name
  (long names) or -sname (short names).
A hidden node is a node started with
  the command line flag -hidden.
  Connections between hidden nodes and
  other nodes are not transitive, they
  must be set up explicitly. Also,
  hidden nodes does not show up in the
  list of nodes returned by nodes().
  Instead, nodes(hidden) or
  nodes(connected) must be used. This
  means, for example, that the hidden
  node will not be added to the set of
  nodes that global is keeping track of.
So in short , yes, you need to give our node a name to be able other nodes to find it.
It feels that you either are asking without trying out or have a very complex question and maybe an example of what you are trying to accomplish could make it possible to give a better answer.


Question:
How do I load MS Word document (.doc and .docx) to memory (variable) without doing this?:

wordApp.Documents.Open

I don't want to open MS Word, I just want that text inside.

You gave me answer for DOCX, but what about DOC? I want free and high performance solution - not to open 12.000 instances of Word to process all of them. :( Aspose is commercial product, and 900$ is a way too much for what I do.

Answer:
If you are dealing with docx you can do this with out doing any interop with Word
.docx file actually a ZIP contains an XML file , you can read the XML
Please refer the below links
http://conceptdev.blogspot.com/2007/03/open-docx-using-c-to-extract-text-for.html
Office (2007) Open XML File Formats


Question:
I am trying to use some pinvoke code to call a C function.  The function fills a buffer with data.

The structure is set up as a DWORD for the length, followed by a string.  How do I extract the string from the IntPtr?

 IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
 PInvokedFunction(buffer, nRequiredSize);
 string s = Marshal.PtrToStringAuto(buffer + 4); //this is an error.
 Marshal.FreeHGlobal(buffer);

Answer:
The best I could come up with was the following, though the use of the UnmanagedMemoryStream seems a bit of a hack.
```
```
IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize);
 PInvokedFunction(buffer, nRequiredSize);
 UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize);
 memStream.Seek(4, SeekOrigin.Begin);
 IntPtr ptr = new IntPtr(memStream.PositionPointer);
 string s = Marshal.PtrToStringAuto(ptr);
 Marshal.FreeHGlobal(buffer);
```
```


Question:
I'm having some trouble with Visual Studio 2008 on my Windows XP SP2 laptop.

What happens is that when I start a program with a few textboxes and stuff like that, the boxes are see-through. I can litteraly see through them and see what's on the underlaying screen. Like if I only have this Form showing and behind that my wallpaper, I can see my wallpaper through the Textbox, ComboBox, even through the small cracks between various elements.

i've searched the web but haven't encountered info on this yet. Does anybody know what might be causing this and how to solve it? I'm in the process of trying to see how the text in my TextBoxes is parsed, but I can't since I can't even enter anything. I click on the textbox and I'm focused on the desktop...

Answer:
Hmmm... I'm not sure about this, but check the "Transparency" property of your main form. That's all I can think that it might be as of now...
Update: I meant the "
Opacity
" property, sorry.
Update 2: No, never mind, sorry. Right-click the "
TransparencyKey
" property, and press
```
Reset
```
to set it back to default.


Question:
I have a std::multimap where key is a custom class. Something like this:

Class X {
public:
    std::string s;
    int x;
    operator <(const X& other) const { return s < other.s; }
};
std::multimap<X, int> mymap;

Now, I'd like to use upper_bound and lower_bound to iterate over all elements with the same value of "s". Do I need to implement some other operator for X (for example: ==). Or it will work properly just like this?

Also, what should I supply as argument for upper_bound and lower_bound? I assume I should create a dummy object with desired value of "s"?

Answer:
you only need to provide an operator == and <.
upper_bound and lower_bound are just like any other find-type method, so you need the same kind of object to compare with - in your case, a 'dummy' object with the required value of s.
edit
: the comments are correct that you only need operator< for lower/upper_bound, and find. But if you want to call other methods on your container, you will need operator== as well. Eg. if you want to sort() your container, you will need operator==.
The 2 overloads you need for all STL containers are operator< and operator==. I find its best practise to implement them both.
Of course, the question could also be answered more fully by implementing a comparison functor in the map itself, not relying on the objects. This is often a good way to implement different ways of calling find() on the map.


Question:
I still haven't got my head around decorators in Python.

I've already started using a lot of closures to do things like customize functions and classes in my coding.

Eg.

class Node :
    def __init__(self,val,children) :
        self.val = val
        self.children = children

def makeRunner(f) :
    def run(node) :
        f(node)
        for x in node.children :
            run(x)
    return run

tree=Node(1,[Node(2,[]),Node(3,[Node(4,[]),Node(5,[])])])

def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)
printTree(tree)

As far as I can see, decorators are just a different syntax for doing something similar.

Instead of

def pp(n) : print "%s," % n.val
printTree = makeRunner(pp)

I would write :

@makeRunner
def printTree(n) : print "%s," % n.val

Is this all there is to decorators? Or is there a fundamental difference that I've missed?

Answer:
Are your examples real code, or just examples?
If they're real code, I think you overuse decorators, probably because of your background (i.e. you are used to other programming languages)
Stage 1: avoiding decorators
```
```
def run(rootnode, func):
    def _run(node): # recursive internal function
        func(node)
        for x in node.children:
            _run(x) # recurse
    _run(rootnode) # initial run
```
```
This run method obsoletes makeRunner. Your example turns to:
```
```
def pp(n): print "%s," % n.val
run(tree, pp)
```
```
However, this ignores completely generators, so…
Stage 2: using generators
```
```
class Node :
    def __init__(self,val,children) :
        self.val = val
        self.children = children

    def __iter__(self): # recursive
        yield self
        for child in self.children:
            for item in child: # recurse
                yield item

def run(rootnode, func):
    for node in rootnode:
        func(node)
```
```
Your example remains
```
```
def pp(n): print "%s," % n.val
run(tree, pp)
```
```
Note that the special method
```
__iter__
```
allows us to use the
```
for node in rootnode:
```
construct. If you don't like it, just rename the
```
__iter__
```
method to e.g.
```
walker
```
, and change the
```
run
```
loop into:
```
for node in rootnode.walker():
```
Obviously, the
```
run
```
function could be a method of
```
class Node
```
instead.
As you see, I suggest you use directly
```
run(tree, func)
```
instead of binding them to the name
```
printTree
```
, but you can use them in a decorator, or you can make use of the
```
functools.partial
```
function:
```
```
printTree= functools.partial(run, func=pp)
```
```
and from then on, you would just
```
```
printTree(tree)
```
```


Question:
What is the state of native SVG support in the most popular browsers in their latest releases?

Internet explorer

Firefox

Opera

Safari

Chrome

Konqueror

Camino

Answer:
Opera has native
SVG support
Firefox has native
SVG support
Internet Explorer does NOT include
SVG support
natively.
Safari has native
SVG support
for images and Fonts since version 3.1.
Camino contains native
SVG support
as per its own documentation
Chrome uses an old version of Web Kit to support
SVG natively
Konqueror has SVG support via a plugin
KSVG2
From 2007 a
here
is a list of the state of SVG support in many browsers


Question:
What the best way to get up to speed on MathML and its usage in the world?

In particular I mean:

What do you use for rendering/editing it

Is it used in any commercial/open source applications that you can point me to

Is it popular and used a lot?

Are there any viewers that can be used inside a C#, C++, Java, ... application?

... (any other info available about MathML)

Answer:
The
W3C's MathML homepage
is of course a good place to start. They have a list of software using MathML. There are two portions to the MathML specification: the presentation set, which will tell a rendering engine how to typeset the equation (for instance, distinguishing between a stacked vs. beveled fraction), and the content set, which will tell calculation engines how to interpret the equation (is y(x) a function y of x or two variables being multiplied?). Most applications will focus on one subset of MathML or the other depending on the scope of the application.
MathML is being used more and more widely and with good reason - MathML has all of the advantages of XML (for more information, see our white paper
MathML is XML
).
Design Science makes
WebEQ
, which includes components for editing and displaying MathML on your website. We also have an SDK version if you would like to include these components in a desktop application. WebEQ is Java based.
Hope this helps, but if you have more questions, feel free to email support@dessci.com.
Best wishes,
Autumn Cuellar, XML Specialist at Design Science


Question:
MTOM is the W3C Message Transmission Optimization Mechanism, a method of efficiently sending binary data to and from web services.

How does it work in general?

Answer:
If you put
Wireshark
(or enabled
System.Net Logging
) on the non-MTOM enabled service, you should see the SOAP requests with the binary data encoded as BASE64. Sending it as BASE64 increases the size of the binary data but (I assume) makes it more interoperable.
With MTOM, the SOAP messages are sent as MIME messages with the BASE64 encoding being replaced with a placeholder. The binary data is then placed between delimiters (which happens for each piece of binary data), and then placed at the end of the SOAP request. The binary data is then sent unencoded. IIRC, MTOM also determines whether sending it as a MIME message will increase the size of the SOAP call and if doesn't provide a saving, it will send it as a normal SOAP message.
This
provides an example of what the message sent over the wire looks like.


Question: Are there any other ways to avoid LazyInitializationExceptions in a Hibernate web application besides using the OpenSessionInView pattern? Are there any downsides to using OpenSessionInView?

Answer:
When working on our web applications, we usually decide beforehand which objects/fields will be needed in the view pages and make sure that all the objecs are properly initialized  from the model before dispatching to the view.
This can be accomplished in (at least) three ways:
fetching
properties using eager strategy (i.e. with
```
FetchMode.JOIN
```
, if you're using the
Criteria API
)
explicitly initializing properties (i.e. with
```
Hibernate.initialize(property)
```
)
implicitly initializing properties by calling the appropriate property accessor
About the downsides of OpenSessionInView, have you checked out
this
page?


Question:
If you have something like:

val myStuff = Array(Person("joe",40), Person("mary", 35))

How do you create an XML value with that data as nodes? I know how to use { braces } in an XML expression to put a value, but this is a collection of values. Do I need to iterate explicitly or is there something better?

val myXml = <people>{ /* what here?! */ }</people>

The resulting value should be something like:

<people><person><name>joe</name><age>40</age></person>
<person><name>mary</name><age>39</age></person></people>

Answer:
As it's a functional programming language Array.map is probably what you're looking for:
```
```
class Person(name : String, age : Int){
    def toXml() = <person><name>{ name }</name><age>{ age }</age></person>
}

object xml {
    val people = List(
        new Person("Alice", 16),
        new Person("Bob", 64)
    )

    val data = <people>{ people.map(p => p.toXml()) }</people>

    def main(args : Array[String]){
        println(data)
    }
}
```
```
Results in:
```
```
<people><person><name>Alice</name><age>16</age></person><person><name>Bob</name><age>64</age></person></people>
```
```
A formatted result (for a better read):
```
```
<people>
   <person>
      <name>Alice</name>
      <age>16</age>
   </person>
   <person>
      <name>Bob</name>
      <age>64</age>
   </person>
</people>
```
```


Question:
I've got an unmanaged Linux VPS running ubuntu that I'm using for the web server for a personal website.  I'd like to get a barebones email server up and running.  All the installation guides I've found so far are for a full-fledged email server with a webmail interface and everything.  That's a lot more than I need.  There's only two things I need:

My web application needs to be able to send email.  Specifically, it'll be emailing me when an exception occurs.

I want all email sent to [anything]@domain.com forwarded to my personal gmail account.  The server doesn't even need to retain the email or anything.

I want to reserve resources for the actual web app, so I don't want to install anything I won't need for this.

Answer:
Your web application needs a SMTP server.  That server can be a hosted service like Google's or
MailHop
.  If you really want to be an email administrator postfix should be installed
HOWTO is here
.
If not:
```
```
sudo apt-get install postfix
```
```


Question: When using XmlDocument.Load , I am finding that if the document refers to a DTD, a connection is made to the provided URI. Is there any way to prevent this from happening?

Answer:
Use an
```
XMLReader
```
to load the document and set the
```
ValidationType
```
property of the reader settings to
```
None
```
.


Question:
I have an s-expression bound to a variable in Common Lisp:

(defvar x '(+ a 2))

Now I want to create a function that when called, evaluates the expression in the scope in which it was defined.  I've tried this:

(let ((a 4))
  (lambda () (eval x)))

and

(let ((a 4))
  (eval `(lambda () ,x)))

But both of these create a problem: EVAL will evaluate the code at the top level, so I can't capture variables contained in the expression.  Note that I cannot put the LET form in the EVAL.  Is there any solution?

EDIT: So if there is not solution to the EVAL problem, how else can it be done?

EDIT: There was a question about what exactly I am try to do.  I am writing a compiler.  I want to accept an s-expression with variables closed in the lexical environment where the expression is defined.  It may indeed be better to write it as a macro.

Answer:
CLISP implements an extension to evaluate a form in the lexical environment. From the fact that it is an extension, I suspect you can't do that in a standard-compliant way.
```
```
(ext:eval-env x (ext:the-environment))
```
```
See
http://clisp.cons.org/impnotes.html#eval-environ
.


Question:
If I add an after_save callback to an ActiveRecord model, and on that callback I use update_attribute to change the object, the callback is called again, and so a 'stack overflow' occurs (hehe, couldn't resist).

Is it possible to avoid this behavior, maybe disabling the callback during it's execution? Or is there another approach?

Thanks!

Answer:
Check out how
update_attribute
is implemented.  Use the send method instead:
```
```
send(name.to_s + '=', value)
```
```


Question:
For performance reasons, I draw the strings for my UITableViewCell in a custom view that overrides its drawRect method to draw strings directly in the view rectangle using NSString:drawInRect. This is similar to Apple's TableViewSuite Example 5-CustomTableViewCell.

However, when I invoke setEditing on the cell to bring up the delete button, the view ends up with a squeezed appearance after the animation completes. To demonstrate this, invoke setEditing:YES on the CustomTableViewCell example mentioned above and observe the distortion. Is there any way around this or should I just revert back to using UILabels for my text?

Answer:
I had this problem too, and in my case I fixed it by handling the 2 states in my drawRect method, one while editting, the other while not. In other words I accounted for the size of the delete button, and got my UI to repaint the cell differently. I'm not sure if it's the most efficient way to go, but here is the code that I used to force a repaint:
```
```
-(void)_refreshTableAndCells{
    //refresh the table
    [myCustomTableView reloadData];
    //refresh all the visible cells
    for (UITableViewCell *cell in myCustomTableView.visibleCells){
        LocationCellView *locationCell = [cell.contentView.subviews objectAtIndex:0];
        [locationCell setNeedsDisplay];
    }

}
```
```
I'm an Objective-C n00b though, so I'd be more than happy for someone to suggest a better way than this.


Question:
I'm wondering if there's any way to have Firefox 3 (or IE 7 or safari 3.1 or Opera) flag that a redirect has occurred (i.e. any deltas between the hyperlink or URL entered into address bar, and the page you land on), whether you've arrived from a hyperlink or entering URL into address bar.

I've googled some, looked at the linker addon, but the rightclick is an additional step I don't want to have to do.

Edit: If anybody can point me at the mozilla docs that show how to track clicked links and pages landed on in different tabs, i'll take a crack at writing a bookmarklet.  TIA

Answer:
I don't think this will help, since you don't want to do the right click for the linker add-on, but if I needed to do know if I was being redirected, I would use the
LiveHTTPHeaders
extension.  It supports regular expressions, so you can only get headers that include 'Location'.
The reason I don't think it is what you are looking for is that you have to open it before the link, it won't "flag" a redirect and pop a message up or anything.


Question: I'm writing an application that processes PowerPoint presentations and I'm looking into ways of detecting whether or not a PowerPoint presentation has a password if it does then stop processing it.

Answer:
It seems to me that there is
no way to check
if the presentation is password-protected. You have to open the document first to make properties accessible. You have to provide the password when you are opening the document.
There is a
Password Property
you can check.
I've found a
workaround on Expert Exchange
:
The problem is the following:
Visual
  Basic is a single threaded
  application
, this means that you cant
  put a certain procedure on hold and
  proceed with another (in the same
  application). When powerpoint has an
  "on open"-password set, the
  CreateObject procedure inside your
  application is put on hold untill
  powerpoint releases it, this is when
  the user types in a password. There is
  no way around this that I know off,
  but you can make a workaround:
Make 2 applications
, 1 application is
  the application you already have, the
  second one is a "powerpoint unlocker".
  You run the second program just before
  you open the protected powerpoint
  presentation in application 1. You can
  do that with the shell command. The
  "powerpoint unlocker" can be as
  advanced as you want it to be, you can
  for example provide command line
  parameters to specify which
  presentation must be unlocked with
  what password. Then you use the
findwindow api to get the window
  handle of the locked presentation
.
  Once you have that, you
use the
  sendmessage api
to input the password.
  After this the "powerpoint unlocker"
  unloads and the first application can
  resume with its excution.
I hope this helps!
Osmodean


Question:
Does anyone know of any notepad++ plugin that saves a version of whatever I'm working on periodically? Ideally, it would save many versions with the automatic version number and the date in the title, and perhaps store them in a zipped archive to save space.

Does something like this exist already, or shold I attempt to write such a plugin myself?

Thanks,

Cameron

P.S. It should be freeware or (preferably) open-source.

Answer:
You might be better off looking into something closer to "real" version control -
Mercurial
, perhaps. It doesn't require a server, and it's really easy to set up.
To automate it, you could turn on autosave in Notepad++, and set up a windows scheduled task to do an
```
hg commit
```
every few minutes.


Question:
I am implementing a BFS, and what it is going to do is go through an ordered tree to find the shortest solution to a puzzle.

What i will be doing is creating a Snapshot object that holds the current position of each piece in a puzzle. I will add this Snapshot object into the queue and check if it is the solution. However, I am creating these snapshots on the fly. So is there some kind of way that will automatically generate the names of the Snapshot objects when they are put into the queue?

or do i have to keep track of how many declarations i have made and just hard code it by saying...

Snapshot snapshot2;
Snapshot snapshot3;
Snapshot snapshot4;
etc..

Answer:
You could use a queue from the standard template library, then create a function that creates a Snapshot object and puts in into the queue.  Give this function a static variable which gets incremented every time it is called and written into an id field of the snapshot.
http://www.csci.csusb.edu/dick/samples/stl.html
http://www.cppreference.com/wiki/stl/queue/start


Question:
I've read the documentation on WideCharToMultiByte, but I'm stuck on this parameter:

lpMultiByteStr
[out] Pointer to a buffer that receives the converted string.

I'm not quite sure how to properly initialize the variable and feed it into the function

Answer:
You use the lpMultiByteStr [out] parameter by creating a new char array.  You then pass this char array in to get it filled.  You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.
Here are a couple of useful helper functions for you, they show the usage of all parameters.
```
```
#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}
```
```
--
Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it.  The function will use that pointer to fill your variable.
So you can understand this better:
```
```
//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}
```
```


Question: It seems OpenLaszlo can run on AIR. What's less obvious is whether OpenLaszlo apps can use the AIR-specific APIs, like file system access. If so, how exactly is this done?

Answer:
While I don't have any specifics, the article you linked mentions that his application window can be dragged and closed. Those are AIR-only APIs (see the NativeWindow class), so presumably what you're asking about must be possible to some extent.
However, my understanding is that OpenLaszlo tries not to implement things that can be done in Flash but not (say) DHTML, so it may be less obvious how to do things like local file access. Probably you'll want to download the source linked in the article and see how he implemented the window drag/close.


Question:
My PHP/MS Sql Server 2005/win 2003  Application occasionally becomes very unresponsive, the memory/cpu usage does not spike. If i try to open any new connection from sql management studio, then the it just hangs at the open connection dialog box.
how to deterime the total number of active connections ms sql server 2005

Answer:
This shows the number of connections per each DB:
```
```
SELECT
    DB_NAME(dbid) as DBName,
    COUNT(dbid) as NumberOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE
    dbid > 0
GROUP BY
    dbid, loginame
```
```
And this gives the total:
```
```
SELECT
    COUNT(dbid) as TotalConnections
FROM
    sys.sysprocesses
WHERE
    dbid > 0
```
```
If you need more detail, run:
```
```
sp_who2 'Active'
```
```
Note:
The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)


Question:
How hard would it be to use GCC instead of VC++ from within Visual Studio 2008? Obviously, some of the keywords won't match, and some may not get syntax highlighting (unless you made a new language service).

Is this what a 'makefile project' is for, pretty much?

Answer:
There is no GCC plugin for Visual Studio as the one for example for Intel C++, which allows Intel's compiler to be used as a drop-in replacement for Visual C++.
You can use Makefile projects which allows you to use any external tool you like (make, SCons, jam, whatever) to do your build. If you don't like Makefiles, you may want to look at
CMake
which allows you to generate Makefiles or Visual Studio projects from a much simpler description. This also means that you're not bound to Makefiles or Visual Studio projects, but can switch between them as you like.


Question:
Is there a better way to do the following:

$array = array('test1', 'test2', 'test3', 'test4', 'test5');
// do a bunch of other stuff, probably a loop
$array[] = 'test6';
end($array);
echo key($array); // gives me 6

This will give the key of the most recently add array element.

Is there a better way to do this?

Answer:
You could also do:
```
```
$end = end(array_keys($array));
```
```
But I think your way makes it clear what you want to do, so you could whip something up like:
```
```
function array_last_key($array) {
    end($array);
    return key($array);
}
```
```
That's about it.


Question:
Sometimes you're developing and you decide to commit, forgetting you created a few files on your project. Then a few days down the line your buddy gets your build out of Subversion and complains that some files appear to be missing. You realize, ah crap, I forgot to add those files!

How can I get a list of the files that are not under version control from Subversion so I'm sure I've added everything to the repository?

Answer:
Use the
```
svn status
```
command:
```
```
svn status | grep ^?
```
```
Files that are not versioned are indicated with a ? at the start of the line.
If you find that you always have some specific files that should not be added to the repository (for example, generated binaries), you should set up the
```
svn:ignore
```
property on the containing directory so these files won't keep showing up when using
```
svn status
```
.


Question:
I haven't found an answer to this particular question; perhaps there isn't one. But I've been wondering for a while about it.

What exactly causes a binary file to display as "gibberish" when you look at it in a text editor? It's the same thing with encrypted files. Are the binary values of the file trying to be converted into ASCII? Is it possible to convert the view to display raw binary values, i.e. to show the 1s and 0s that make up the file?

Finally, is there a way to determine what program will properly open a data file? Many times, especially with Windows, a file is orphaned or otherwise not associated w/ a particular program. Opening it in a text editor sometimes tells you where it belongs but most of the time doesn't, due to the gibberish. If the extension doesn't provide any information, how can you determine what program it belongs to?

Answer:
The display looks interesting, because a binary file can contain non-printable characters. It is up to the displaying program to replace such characters with something else.
This can be prevented by using a hex editor. Such a program displays each byte from the file as its hexadecimal value. That makes for a nice tabular view of the file, but it is not easy for the average person to decipher this view, because we are not used to look at data that way.
There are a few ways to find out what program a file might belong to. You can look at the beginning of the file and with some knowledge, you might recognize the file type. There are some types that begin with the same characters (RAR, GIF etc.). For other types it might not be as easy.
In Linux you can use the "file" command to help you determine file type. There are probably programs for Windows that will do the same.


Question:
I am parsing an input text file.  If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer?  I was thinking something similar to getNextInt() in Java.

I know there has to be 2 numbers in that input line; however, these values will be separated by one or more white space characters, so I can't just go to a specific position.

Answer:
If the only thing in there is whitespace and integers, just try something like this:
```
```
int i1, i2;
stringstream ss(lineFromGetLine);
ss >> i1 >> i2;
```
```
or easier:
```
```
int i1, i2;
theFileStream >> i1 >> i2;
```
```


Question:
Is it possible to scale a UIView down to 0 (width and height is 0) using CGAffineTransformMakeScale?

view.transform = CGAffineTransformMakeScale(0.0f, 0.0f);

Why would this throw an error of "<Error>: CGAffineTransformInvert: singular matrix." ?

Update:
There is another way of scaling down a UIView to 0

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
view.frame = CGRectMake(view.center.x, view.center.y, 0, 0);

[UIView commitAnimations];

Answer:
I'm not sure it's possible to do this; you'll start running into divide-by-zero issues. If you try to do this, you'll be creating a transform that looks like:
```
```
0  0  0
   0  0  0
   0  0  1
```
```
Which, when applied to ANY other transform, will produce the above transform.
Why not just hide the view (if you want to scale it out of sight) or set the scaling factor to something like 0.001 (if you want to scale it in)?


Question: Looking for code samples to access a memory map file in C#

Answer:
You can take a look at
this CodeProject article
which shows a simple array over MMF implementation using
Winterdom's FileMap library
- basically a wrapper around the Win32 APIs for memory mapped files.
Caveat emptor: 1) I have not used FileMap, so I can't vouch for it; 2) FileMap is under LGPL, if the licensing terms are of any concer of you.
You can also search on
http://pinvoke.net
for the P/Invoke definitions of the corresponding Win32 APIs and roll your own implementation.


Question: Does anyone know of any good tools to view the store name, store location, or values of an X.509 Certificate?

Answer:
i'm supposing that you are using Windows. So here it is
http://msdn.microsoft.com/en-us/library/aa529278.aspx
. It's a good tool, but to do it thru API is not hard and it's a good exercise to learn the API.
Regards,
Victor


Question:
Are any of you aware of a library that helps you build/manipulate SQL queries, that supports JOIN's?

It would give a lot of flexibility i'd think if you have something where you could return an object, that has some query set, and still be able to apply JOIN's to it, subqueries and such.

I've search around, and have only found SQL Builder, which seems very basic, and doesn't support joins. Which would be a major feature that would really make it useful.

Answer:
Maybe you can try an
ORM
, like
Propel
or
Doctrine
, they have a nice programmatic query language, and they return you arrays of objects that represent rows in your database...
For example with Doctrine you can do joins like this:
```
```
$q = Doctrine_Query::create();
$q->from('User u')
->leftJoin('u.Group g')
->innerJoin('u.Phonenumber p WITH u.id > 3')
->leftJoin('u.Email e');

$users = $q->execute();
```
```
And with Propel:
```
```
$c = new Criteria(AuthorPeer::DATABASE_NAME);

$c->addJoin(AuthorPeer::ID, BookPeer::AUTHOR_ID, Criteria::INNER_JOIN);
$c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::INNER_JOIN);
$c->add(PublisherPeer::NAME, 'Some Name');

$authors = AuthorPeer::doSelect($c);
```
```
and you can do a lot more with both...


Question:
Does anybody know any resources on this subject?

I'm developing an embedded application for 2x16 LCD display. Ideally I would like to have a general (display independent) framework, that could be used virtually on any display - one or more segment(s) LED, 1x16, 2x16 LCD, etc.
Also would like to learn about general guidelines for such small user interfaces.

EDIT: I'm interested in high-level functionality, how to organize the user interface - the menus, options and the user input. We don't dicuss the LCD controller issues here.

Answer:
If you're referring to a 2 line by 16 character display, they'll generally be pixel based and will have an integrated controller as they're much more complicated to control.  The 2x16 and 4x16 LCD devices I've used in the past actually have a nibble-wide interface, and the commands are sent to the device in
```
<command>[<address>][<data>]
```
style, with the number of nibbles required for a valid command being dictated by the command itself.  If would be helpful if you link to the target device as there really doesn't seem to be a standard from manufacturer to manufacturer.
With respect to segmented LEDs and LCDs, there is a standard layout for so-called seven segment devices that started back with the pixie tubes.  Here's a diagram that shows this segmentation:
```
```
a
  ---
f| g |b
  ---
e|   |c
  ---
   d
```
```
Another question is whether you want to drive the display directly or will use a controller IC.  It's pretty easy to drive a seven-segment LED as they generally have a common cathode or anode and you simply need to be able to sink or source enough current.  Driving an LCD directly is a little more complicated as the polarity applied to a pixel or segment has to constantly flipped to avoid damage to the device.  It's much easier to find a controller with an integrated clock that performs this function.


Question:
I am writing a small program.  The interface I am writing to control each repository that is made defines a method of Save(IPublicObject).  I am using LINQ for the SQL Version of the repository CRUD.  My question is this.  I would like to have only the one method which accepts the interface type.  I want to think how I can best locate the Save action for the inherited type I then pass in.

In the book I am reading Patterns of Enterprise Application Architecture.  I am leaning on the Inheritance Maping.  So I create a derived object of

public class ConcretePublicObjectOne : IPublicObject{}

I want to then pass this into the Save Function of the respository.  It is at this point where I am trying to think how best to say, ok we need to use "WHAT?" Save Method etc...

Should I use a registry, configuration setting mapping the types?

Answer:
What you wish to do is to have a:
```
```
Repository.Save(publicObject)
```
```
and the repository to call a method from publicObject?
If this is the requirement then you can define the Save method in repository as:
```
```
public class Repository {
    public void Save(IPublicObject publicObject) {
        publicObject.Save();
    }
}
```
```
where IPublicObject is defined as:
```
```
public interface IPublicObject {
    void Save();
}
```
```
But with this approach you will have to define a save method for each entity (like ConcretePublicObjectOne in your example)


Question:
Is there a max length for an array in C++?

Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?

Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?

What I have to do is storing long long int on an array, I'm working in a Linux environment. My question is: what do I have to do if I need to store an array of N long long integers with N > 10 digits?

I need this because I'm writing some cryptographic algorithm (as for example the p-Pollard) for school, and hit this wall of integers and length of arrays representation.

Answer:
There are two limits, both not enforced by C++ but rather by the hardware.
The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's
```
std::size_t
```
can take. This data type is large enough to contain the size in bytes of any object
The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a
```
vector<int>
```
of a given size
n
typically takes multiple times as much memory as an array of type
```
vector<char>
```
(minus a small constant value), since
```
int
```
is usually bigger than
```
char
```
. Therefore, a
```
vector<char>
```
may contain more items than a
```
vector<int>
```
before memory is full. The same counts for raw C-style arrays like
```
int[]
```
and
```
char[]
```
.
Additionally, this upper limit may be influenced by the type of
```
allocator
```
used to construct the
```
vector
```
because an
```
allocator
```
is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory.
Apart from that, C++ doesn't enforce any limits.


Question:
I'm creating a site where the user unfortunately has to provide a regex to be used in a MySQL WHERE clause. And of course I have to validate the user input to prevent SQL injection. The site is made in PHP, and I use the following regex to check my regex:

/^([^\\\\\']|\\\.)*$/

This is double-escaped because of PHP's way of handling regexes.
The way it's supposed to work is to only match safe regexps, without unescaped single quotes. But being mostly self-taught, I'd like to know if this is a safe way of doing it.

Answer:
If it is anly for the purposes of display this reg expression then most programs simply Html Encode the value and store in the DB and then the Decode on the way out.  Again only for Display purposes though, if you need to use the reg exp that is submitted this won't work.
Also know there is a method where the person intent on injecting writes out there SQL, Converts it to varbinary and submits the exec command with the base 64 representation of the query which I have been hit with in the past.


Question:
I want to apply a function to all columns in a matrix with MATLAB. For example, I'd like to be able to call smooth on every column of a matrix, instead of having smooth treat the matrix as a vector (which is the default behaviour if you call smooth(matrix)).

I'm sure there must be a more idiomatic way to do this, but I can't find it, so I've defined a map_column function:

function result = map_column(m, func)
    result = m;
    for col = 1:size(m,2)
        result(:,col) = func(m(:,col));
    end
end

which I can call with:

smoothed = map_column(input, @(c) (smooth(c, 9)));

Is there anything wrong with this code? How could I improve it?

Answer:
If this is a common use-case for your function, it would perhaps be a good idea to make the function iterate through the columns automatically if the input is not a vector.
This doesn't exactly solve your problem but it would simplify the functions' usage. In that case, the output should be a matrix, too.
You can also transform the matrix to one long column by using
```
m(:,:) = m(:)
```
. However, it depends on your function if this would make sense.


Question:
I have a very strange problem, when I try to var_dump (or print_r) a Doctrine Object, my Apache responses with an empty blank page (200 OK header). I can var_dump a normal php var like:

$dummy = array("a" => 1, "b" =>2);

And it works fine. But I can't with any object from any Doctrine class, (like a result from $connection->query(), or an instance of a class from my object model with Doctrine).

Anybody knows why this happens?

Answer:
I've had that sometimes when trying to
```
print_r()
```
a self-referencing object - it gets into a loop and runs out of memory.  Possibly that's what's happening to you.
Try increasing the memory limit (
```
ini_set('memory_limit', '256M');
```
) and see if that fixes it.
Edit:   I don't think there's an actual fix for this - it's PHP's internal
```
var_dump
```
/
```
print_r
```
that don't limit depth on recursion (or don't do it properly, at least).  If you install the
XDebug
extension, this can replace the built-in
```
var_dump
```
with a version that handles recursion much better.


Question:
As I understand it, when asked to reserve a larger block of memory, the realloc() function will do one of three different things:

if free contiguous block exists
    grow current block
else if sufficient memory
    allocate new memory
    copy old memory to new
    free old memory
else
    return null

Growing the current block is a very cheap operation, so this is behaviour I'd like to take advantage of.  However, if I'm reallocating memory because I want to (for example) insert a char at the start of an existing string, I don't want realloc() to copy the memory.  I'll end up copying the entire string with realloc(), then copying it again manually to free up the first array element.

Is it possible to determine what realloc() will do?  If so, is it possible to achieve in a cross-platform way?

Answer:
No
- and if you think about it, it can't work. Between you checking what it's going to do and actually doing it, another process could allocate memory.
In a multi-threaded application this can't work. Between you checking what it's going to do and actually doing it, another thread could allocate memory.
If you're worried about this sort of thing, it might be time to look at the data structures you're using to see if you can fix the problem there. Depending on how these strings are constructed, you can do so quite efficiently with a well designed buffer.


Question:
Highly embedded (limited code and ram size) projects pose unique challenges for code organization.

I have seen quite a few projects with no organization at all. (Mostly by hardware engineers who, in my experience are not typically concerned with non-functional aspects of code.)

However, I have been trying to organize my code accordingly:

hardware specific (drivers, initialization)

application specific (not likely to be reused)

reusable, hardware independent

For each module I try to keep the purpose to one of these three types.

Due to limited size of embedded projects and the emphasis on performance, it is often keep this organization.

For some context, my current project is a limited DSP application on a MSP430 with 8k flash and 256 bytes ram.

Answer:
I've worked with some sensors like the Tmote Sky, I too have seen poor organization, and I have to admit i have contributed to it. Anyway I'd say that some confusion has to be, because loading too much modules or too much part of program will be (imho) resource killing too, so try to be aware of a threshold between organization and usability on the low resources.
Obviously this don't mean let caos begin, but for example try to get a look on the organization of the
tinyOS
source code and applications, it's an idea on what I'm trying to say.


Question:
Is there a key shortcut for this in XCode?

Can I implement an Applescript for this and run it within XCode?

Answer:
You can probably do that using a script (check out the relevent piece of Xcode documentation). Also see the "Insert Text Macro" menu item…
But you might find it to be more efficient to just use the auto-correct feature. I just type "[[F", then hit my auto-correct key (bound to F5 I believe, but I've changed it), type enough of the class name for it to be selected in the autocorrect popup. Hit space, start typing alloc but let auto correct kick in. Close the brace. Start typing init, use autocorrect again.
You generally shouldn't need to create macros/scripts for something this trivial. The autocorrect, placeholders and autofill features should be all you really need.


Question: I have a groovy script with an unknown number of variables in context at runtime, how do I find them all and print the name and value of each?

Answer:
Well, if you're using a simple script (where you don't use the "def" keyword), the variables you define will be stored in the binding and you can get at them like this:
```
```
foo = "abc"
bar = "def"

if (true) {
    baz = "ghi"
    this.binding.variables.each {k,v -> println "$k = $v"}
}
```
```
Prints:
```
```
foo = abc
    baz = ghi
    args = {}
    bar = def
```
```
I'm not aware of an easy way to enumerate through the variables defined with the "def" keyword, but I'll be watching this question with interest to see if someone else knows how.


Question:
What is the best way to format a decimal if I only want decimal displayed if it is not an integer.

Eg:

decimal amount = 1000M
decimal vat = 12.50M

When formatted I want:

Amount: 1000 (not 1000.0000)
Vat: 12.5 (not 12.50)

Answer:
```
```
decimal one = 1000M;
    decimal two = 12.5M;

    Console.WriteLine(one.ToString("0.##"));
    Console.WriteLine(two.ToString("0.##"));
```
```


Question:
I am displaying a scrolled data table in a web page.  This table has several thousands of dynamic rows, so it is loaded from the server (via AJAX).

The user can scroll up and down, so what I need is to detect when the user reaches the end of the scrollbar (that is, the last row at the bottom of the table) in order to request and show more data.

You can find this effect in google reader, when you scroll down to the last post in a given feed, google requests and shows new posts in a transparent way, but I can't figure out how they achieve it.

By the way, right now I am using a YUI Datatable

Answer:
I'm not familiar with the specific element you are using, but in order
 to implement this on a full size window, you can do the following:
```
```
$wnd.onscroll = function() {
    if (($wnd.height - $wnd.scrollTop) < SOME_MARGIN) then doSomething();
};
```
```
Where scrollTop is essentially "how many pixels have been scrolled".
I assume applying this to the table you are working with will do the job.


Question: How would I go about adding enctype="multipart/form-data" to a form that is generated by using <% Html.BeginForm(); %>?

Answer:
As part of htmlAttributes,e.g.
```
```
Html.BeginForm(
    action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
```
```
Or you can pass
```
null
```
for action and controller to get the same default target as for BeginForm() without any parameters:
```
```
Html.BeginForm(
    null, null, FormMethod.Post, new { enctype="multipart/form-data"})
```
```


Question:
I'm having to start building the architecture for a database project but i really don't know the differences between the engines.

Anyone can explain whats the pros and bads of each of these three engines? We'll have to choose one of them and the only thing I actually know about them is this:

Mysql & Postgres:

Are free but not so good as oracle

Mysql as security problems (is this true?)

Oracle:

Best data base engine in the world

Expensive

Can someone clear out other differences between them? This is a medium/large (we're thinking of around some 100 to 200 tables) project with low budget, what would you choose? And with a higher budget?

Answer:
See the comparison tables on wikipedia:
http://en.wikipedia.org/wiki/Comparison_of_object-relational_database_management_systems
&&
http://en.wikipedia.org/wiki/Comparison_of_relational_database_management_systems
Oracle may or may not be the best. It's expensive, but that doesn't mean best.
Have you looked at DB2? Sybase? Teradata? MS SQL?


Question:
Does anyone know of a good dictionary API or ruby library to lookup the definitions of words?

I'm thinking it should work something like:

I call get_definition(word)

It returns the definition for that word (ideally in some way to easily format the definition for display.

Thanks

Answer:
I discovered a webservice for this yesterday.
Go to the
British Council
homepage and double click on any word (that isn't already a hyperlink).
This should open a popup window with a Cambridge Dictionary definition in it. The API is relatively simple (and
it is
a public API, I checked it yesterday):
```
```
http://dictionary.cambridge.org/learnenglish/results.asp?searchword=SEARCH_PHRASE&dict=L
```
```
For reference, here's the code they use to launch this on double-click:
```
```
/* BC double-click pop-up dictionary */
var NS = (navigator.appName == "Netscape" || navigator.product == 'Gecko') ? 1 : 0;
if (NS) document.captureEvents(Event.DBLCLICK);
document.ondblclick = dict;
var dictvar;

function dict() {
    if (NS) {
        t = document.getSelection();
        pass_to_dictionary(t);
    } else {
        t = document.selection.createRange();
        if(document.selection.type == 'Text' && t.text != '') {
            document.selection.empty();
            pass_to_dictionary(t.text);
        }
    }
}

function pass_to_dictionary(text) {
    //alert(text);
    if (text > '') {
        window.open('http://dictionary.cambridge.org/learnenglish/results.asp?searchword='+text+ '&dict=L', 'dict_win', 'width=650,height=400,resizable=yes,scrollbars=yes');
    }
}
```
```


Question:
How can I construct the following string in an Excel formula:

Maurice "The Rocket" Richard

If I'm using single quotes, it's trivial: ="Maurice 'The Rocket' Richard" but what about double quotes?

Answer:
Have you tried escaping with an additional double-quote? By escaping a character, you are telling Excel to treat the " character as literal text.
```
```
= "Maurice ""The Rocket"" Richard"
```
```


Question: Is there an Open Source Free Graph Control for Windows Forms .NET 2.0?

Answer:
I have been using
ZedGraph
for a while. You can generate various types of graphs that look very professional.


Question:
I have a table called logs which has a datetime field.
I want to select the date and count of rows based on a particular date format.

How do I do this using SQLAlchemy?

Answer:
I don't know SQLAlchemy, so I could be off-target.  However, I think that all you need is:
```
```
SELECT date_formatter(datetime_field, "format-specification") AS dt_field, COUNT(*)
    FROM logs
    GROUP BY date_formatter(datetime_field, "format-specification")
    ORDER BY 1;
```
```
OK, maybe you don't need the ORDER BY, and maybe it would be better to re-specify the date expression.  There are likely to be alternatives, such as:
```
```
SELECT dt_field, COUNT(*)
    FROM (SELECT date_formatter(datetime_field, "format-specification") AS dt_field
              FROM logs) AS necessary
    GROUP BY dt_field
    ORDER BY dt_field;
```
```
And so on and so forth.  Basically, you format the datetime field and then proceed to do the grouping etc on the formatted value.


Question: What is the best way to manage the JavaScript files and the functions/objects context in an ASP.NET MVC app?

Answer:
I put all my js files in the Content/Js folder. Then add URL helpers that allow me to change this in the future. My code isn't online, but I stole the idea from
Rob Conery MVC Commerce demo
.
Not sure what you mean by "manage...the functions/objects context in ASp.NET MVC app"
I think you're asking how to segment/partition your scripts.
You should separate your JS files into separate chunks of functionality.


Question: How do I get a status report of all files currently being uploaded via HTTP form based file upload on an Apache Server?

Answer: I don't believe you can do this with Apache itself. The upload looks like nothing more than a POST as far as Apache cares. There are modules and other servers that do special processing to uploads so you may have some luck there. It would probably be easier to keep track of it in your application.


Question:
When I run the following, PowerShell hangs waiting for the dialog to close, even though the dialog is never displayed:

[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )
$d = New-Object Windows.Forms.OpenFileDialog
$d.ShowDialog( )

Calling ShowDialog on a Windows.Forms.Form works fine. I also tried creating a Form and passing it as the parent to $d.ShowDialog, but the result was no different.

Answer:
I was able to duplicate your problem and found a workaround.  I don't know why this happens, but it has happened to others.
If you set the ShowHelp property to $true, you will get the dialog to come up properly.
Example:
```
```
[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )
$d = New-Object Windows.Forms.OpenFileDialog
$d.ShowHelp = $true
$d.ShowDialog( )
```
```
Good Luck!


Question:
I use MS SQL Server 2005 application roles in an application. I execute the sp_setapprole to start the SPs role and to finish  sp_unsetapprole.

"connection pooling doesn't work" with application pooling, and there is no way to react on connection "disconnect event" (execute sp_unsetapprole just before disconnection).

I decide to call sp_setapprole at the start of all my SPs and call sp_unsetapprole at the end of all SPs.

Have you used SQL application roles? What are your XPs? What about performance hits?

Answer:
I have not used app roles before, but from what I know about the perf hit is that after setting the application role there is no way to revert to the prev. security context. Thus the connection cannot be reused in pooling. This alone is a huge perf. hit that forces you to think twice about using app roles.
However, the docs say that starting from SQL Server 2005 there is a way to remember the original security context in a kind of cookie returned from sp_setapprole and after that use sp_unsetapprole to revert back to it. So the pooling should work again. If I were you, I would compare the perf. with a couple of simple statements/sprocs.
Any reason you don't use the standard ASP.NET membership API on the application level instead of app roles?


Question:
File formats I would like to play include .wav, .mp3, .midi.

I have tried using the Wireless Toolkit classes with no success. I have also tried using the AudioClip class that is part of the Samsung SDK; again with

Answer:
Without source code to review, I would suggest using the wireles toolkit (from
http://java.sun.com)first
.
It contains the standard J2ME emulator for windows and example code that will allow you to play a wav file.
assuming that works OK for you, try the same code on your Samsung device (of course, the location of the wav file will probably change so you have a tiny modification to make in the example code).
Assuming that works, compare your code that doesn't with the example code.


Question:
I know that this is a simple question for PHP guys but I don't know the language and just need to do a simple "get" from another web page when my page is hit. i.e. signal the other page that this page has been hit.

EDIT: curl is not available to me.

Answer:
If curl wrappers are on (they are per default), you can use:
```
```
file_get_contents('http://www.example.org');
```
```
Note that this happens synchronous, so before the request has completed, your page won't either. It would be better to log access to a logfile (or database) and export the data occasionally. Alternatively, you could do the request after your page has completed, and output has been sent to the client.


Question:
I'm looking for a straightforward example / tutorial for implementing a JAX-WS (soap1.1 and soap1.2) web service based on wsdl definition using spring, axis2 and tomcat.

hint anyone ?

-- Yonatan

Answer:
There is no such thing as "straightforward" in the world of SOAP. Any example and tutorial is bound to be complex due to the overengineered nature of this beast.
If you can choose your technologies, I'd recommend putting axis aside, and using Tomcat 6 + Java 6 + Metro.
Metro
is Sun's latest, greatest Java web services  (jax-ws) stack. Coupled with JavaEE annotations, it's a
relatively
painless way to get a web service off the ground quickly.
Sorry to not answer the question directly.