q:
I have some directories that are bundled with my installer and I need to access them from within a custom action.  I have done some research and seen that the SourceDir can be used to obtain the currently executing dir location.  However I cannot find any examples of how to obtain this property?  Or another way to obtain the current directory?

Can anyone advise or point me to anything other than the unhelpful Microsoft site?

[A]
I'm assuming you're using vbscript for the custom action. If so, properties can be accessed via the Session object. See below:
```
```
strSourceDir = Session.Property("SourceDir")
```
```
Be aware that the SourceDir property is only available at
specific times during the installation
.


q:
I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the regular expression validator. I want to be able to do something like this:

$("Textbox").rules("add", { regularExpression: "^[a-zA-Z'.\s]{1,40}$" })

How do I add a custom rule to achieve this?

[A]
You can use the addMethod()
e.g
```
```
$.validator.addMethod('postalCode', function (value) {
    return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value);
}, 'Please enter a valid US or Canadian postal code.');
```
```
good article here
https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/

s: huggingface

c: devops

d: intermediate


q:
Possible Duplicate:

  What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?

I need to wite a query that will retrieve the records from Table A , provided that the key in Table A does not exist in Table B.

Any help will be appreciated.

Thanks

[A]
```
```
SELECT *
FROM A
WHERE ID NOT IN
     (SELECT ID FROM B)
```
```


q:
I need to suppress autoplay for the mass storage devices.
This needs to be achieved programatically through a service/deamon running in the background.

I know it can be done by an application which opens a window and handles the "queryCancelAutoPlay" message sent by windows.

Can this be done without GUI.I have the guid/pid/vid for the device whose autoplay needs to be disabled.

[A]
There is a registry entry that controls AutoRun:
```
```
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
```
```
This can be set to disable AutoRun on specific device types, from
technet
:
```
```
NoDriveTypeAutoRun

Value   Meaning
0x1     Disables Autoplay on drives of unknown type.
0x4     Disables Autoplay on removable drives.
0x8     Disables Autoplay on fixed drives.
0x10    Disables Autoplay on network drives.
0x20    Disables Autoplay on CD-ROM drives.
0x40    Disables Autoplay on RAM drives.
0x80    Disables Autoplay on drives of unknown type.
0xFF    Disables Autoplay on all types of drives.
```
```


q:
I need to highlight, case insensitively, given keywords in a JavaScript string.

For example:

highlight("foobar Foo bar FOO", "foo") should return "<b>foo</b>bar <b>Foo</b> bar <b>FOO</b>"

I need the code to work for any keyword, and therefore using a hardcoded regular expression like /foo/i is not a sufficient solution.

What is the easiest way to do this?

(This an instance of a more general problem detailed in the title, but I feel that it's best to tackle with a concrete, useful example.)

[A]
You
can
use regular expressions if you prepare the search string. In PHP e.g. there is a function preg_quote, which replaces all regex-chars in a string with their escaped versions.
Here is such a function for javascript (
source
):
```
```
function preg_quote (str, delimiter) {
  //  discuss at: https://locutus.io/php/preg_quote/
  // original by: booeyOH
  // improved by: Ates Goral (https://magnetiq.com)
  // improved by: Kevin van Zonneveld (https://kvz.io)
  // improved by: Brett Zamir (https://brett-zamir.me)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  //   example 1: preg_quote("$40")
  //   returns 1: '\\$40'
  //   example 2: preg_quote("*RRRING* Hello?")
  //   returns 2: '\\*RRRING\\* Hello\\?'
  //   example 3: preg_quote("\\.+*?[^]$(){}=!<>|:")
  //   returns 3: '\\\\\\.\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:'

  return (str + '')
    .replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&')
}
```
```
So you could do the following:
```
```
function highlight(str, search) {
    return str.replace(new RegExp("(" + preg_quote(search) + ")", 'gi'), "<b>$1</b>");
}
```
```


q:
I'm trying to make a class that will execute any one of a number of stored procedures with any amount of variables

Im using php and mysqli

My class enumerates an array and constructs a string based on the number of elements if any

giving something like this CALL spTestLogin(?,?) for example

I now need to bind the input from my array using somethin like this:

$stmt->bind_param($this->paramTypes,$this->paramValues);//paramValues is my array

Then if that works I can work on getting my results

Any ideas

[A]
You have to do something like this:
```
```
$params=array_merge(
    array($this->paramTypes),
    $this->paramValues
);
call_user_func_array(array($stmt, 'bind_param'), $params);
```
```
given that
```
$this->paramTypes
```
is a string in the format required by
```
mysqli_stmt::bind_param
```
- if not, you have to create this
```
string
```
parameter first.
I don't know if
```
out
```
or
```
inout
```
parameters do work in this case.


q:
Possible Duplicate:

  What Ruby IDE do you prefer?

I'm making a simple script using ruby on a Windows 2003 Server.
My questions are:

How can I connect to a database through ODBC?  I will be connecting to both Sybase on Solaris and MSSQL Server.

How can I send emails through an Exchange Server 2003?

Update

What's the best simple IDE for Ruby scripting?  I currently use SciTE (which comes with Ruby)

[A]
There is an ODBC package for the
Ruby DBI module
available, or you can try to use the
ODBC binding for Ruby
, which also includes a Win32 binary.
Here an example that uses RDI (stolen from
here
):
```
```
require 'DBI'

# make an ODBC connection
conn = DBI.connect('DBI:ODBC:datasource','your_username','your_password')

# returns a list of the table names from your database
conn.tables

# returns an array with the resultset from your query
rs = conn.select_all('SELECT * FROM TheTable')
```
```
(ODBC datasources can be defined using the ODBC Administrator available via Control Panel/Administrative Tools.)
For e-mailing I would suggest you simply use the
standard mailing capabilities
of Ruby and connect to your Exchange Server through SMTP.
I cannot recommend you a Ruby IDE, though, as I do my text-editing with VIM. :-) Other people might be able to give you a hint on that.


q:
I'm currently working on an asp.net-mvc content management system. It would be incredibly useful to be able to deploy nested applications e.g. /shop to have a separate app inside. Or even another instance of the cms.

I've found some information around talking about limiting the inheritance of the web.config but I've no idea how this maps to an MVC application. I'm hoping as its essentially the same stack it will just run. Nothing is ever that easy though.

If anyone has any experience doing this I would be really grateful. The idea of one big application to rule them all is not at all nice.

Si.

[A]
To be honest you biggest hurdle is going to be creating the routes and making sure they don't interfere with routes already in the system.  After you get that working the rest is easy as pie.
The first thing you will need is an HttpModule that will be inserted in to the web.config under the .  This module will be used to register and custom ViewEngines or Routes that you want to register.  You do this in the same way that you do in the Global.asax but instead of putting them in the Application_Start you put them in the static constructor of the HttpModule.  This is so they are only loaded once like Application_Start.
By do the above you will have created a module that is easily transportable and doesn't require the implimentor to modify their Global.asax code to get your stuff to work.
The second thing you probably want to do is create a custom configuration in the web.config to set stuff like the root path of your application.  This will be prepended on to the route when you are setting it up in the HttpModule.  Also you can use this to store customization information that is not appropriate for the database.
Last but not necessary is that you may want to create a custom ViewEngine that knowns and understands your folder structure.  This is only necessary if you want to store the views in a different path than the default views, in order to minimize conflicts.


q:
Does anyone know of an open source web service/wcf service that can stream media content to clients? In particular I am looking for something that could access my music collection and stream it to a client (could be a client browser, win mobile app or even iphone application).

I guess it would have to be WCF based as I'm not sure that webservices do streaming really well. Also Windows Media Streaming Services is not the best way to go as the service should operate from a vista/xp machine (preferably).

If not, does anyone know the best way to start going about creating something like this - I'm not sure I know where to start with this one, although I can see many many uses for such a service!

[A]
Remove the comment on top of the page
The "Put IE into quirks mode" thing
You are using a lot of 'hacks'. By that I mean the CSS selectors that begin with * html
I'm not saying that is the cause of the problem, but it is not good practice and is error prone.
1) try using conditional comments for the browser that has the gap problem instead of using those hacks
2) try editing your question by providing information about the version of IE you're testing against (my guess is IE 6 or even lower).


q:
I'm trying to write a vba macro for a group tha

has one workbook where they daily create new worksheets, and also have

Sheet 1, Sheet 2 and Sheet 3 at the end of their long list of sheets.

I need to create a external cell reference in a new column in a different workbook where this information is being summarized.

So I need to know how to get the last non-empty sheet so I can grab this data and place it appropriately in the summary.

[A]
This function works through the sheets from right to left until it finds a non-blank sheet, and returns its name
```
```
Function GetLastNonEmptySheetName() As String
Dim i As Long
For i = Worksheets.Count To 1 Step -1
  If Sheets(i).UsedRange.Cells.Count > 1 Then
    GetLastNonEmptySheetName = Sheets(i).Name
    Exit Function
  End If
Next i
End Function
```
```


q:
In some existing code there is a test to see if the user is running IE, by checking if the object Browser.Engine.trident is defined and returns true.

But how can I determine if the user is running IE6 (or earlier) or IE7 (or later)?

The test is needed inside a JavaScript function so a conditional comment doesn't seem suitable.

[A]
If you are already using jQuery in a pre-1.9 version AND you don't need to detect IE 11, you can do this:
```
```
if (jQuery.browser.msie == true) {
if (jQuery.browser.version == 7.0)
  // .. do something for 7.0
else
  // .. do something for < 7.0
}
```
```


q: I have an access database, with a query made. I need to automate it so that each night this query can run and export to a tab delimited csv file. It is not possible to export a query to a csv file from within access. My question is, are there any tools that can select certain tables, or perform an sql query on an mdb file, and export to a csv file?

[A]
VBScript works quite well with the Jet engine. However, I do not see why you say " It is not possible to export a query to a csv file from within access."
```
```
Sub TransferCSV()

    DoCmd.TransferText acExportDelim, , "PutNameOfQueryHere", "C:\PutPathAnd\FilenameHere.csv", True

 End Sub
```
```
Is the usual way in VBA.
EDIT:
It is possible to run a VBScript file (.vbs) from the command line. Here is some sample VBScript to output a tab delimited file.
```
```
db = "C:\Docs\LTD.mdb"
TextExportFile = "C:\Docs\Exp.txt"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open _
   "Provider = Microsoft.Jet.OLEDB.4.0; " & _
   "Data Source =" & db

strSQL = "SELECT * FROM tblMembers"

rs.Open strSQL, cn, 3, 3

Set fs = CreateObject("Scripting.FileSystemObject")

Set f = fs.CreateTextFile(TextExportFile, True)

a = rs.GetString

f.WriteLine a

f.Close
```
```


q:
I seem to be in the minority, but to be honest I am not comfortable with linq and don't see any benefits in my personal development (not to say there are no benefits, just a personal opinion based on my situation).

I build web applications (.net, .net mvc) and I love having part of my data layer in stored procedures.  One thing I love about sprocs is that I can generate the entire db to script, then scan my queries, readable queries I might add, at a high level.

For those of you who don't like linq, what is your reason?  Is it just lack of knowledge/learning curve or is there a business case for not using it?

[A]
There was a helpful discussion
here
recently about whether to use LINQ or stored procedures, which includes the advantages and disadvantages of each approach.
And some people have concerns about the future of LINQ to SQL.
Is LINQ to SQL DOA?
Has Microsoft really killed LINQ to SQL?


q:
My Sharepoint 2007 web part executes code to start a K2 workflow process. The workflow server resides on another server.

When my code executes, I get the following error:
"24408 K2:NT AUTHORITY\ANONYMOUS LOGON from 172.172.172.172:1721 does not have rights to Start Process MyProject\MyProcessName"

I'm sure this is a general IIS delegation problem (not K2 specific), but I'm not sure how to go about solving it. Why does Sharepoint try to connect to the other server as AnonymousLogon when it should be impersonating the current domain user?

Notes:
- My Sharepoint AppPool identity is a domain user (not Network Service).
- ASP.NET impersonation is enabled.

[A]
What you are trying to do is called delegation and not impersonation. Impersonation is only on the local server. There are many thing that have to be right for delegation to work.
A place to start would be
Kerberos authentication and troubleshooting delegation issues
David Wang blog
is a very useful resource on thous issues.


q: Could anyboby help me with the alternative solution in C# regarding AddressOf operator in VB6? AddressOf returns a long value. What way can I get the output in C#?

[A]
C# has special syntax for assigning functions to delegates/events.  Just use
```
<delegate> += <function>;
```
If you're actually trying to get the address for some other use, you're out of luck.  One of the things about managed code is that these addresses aren't necessarily fixed.  While it would be unlikely that most functions would ever change there are circumstances where it's possible.


q:
Within my InfoPath form (which has to be loaded within a SharePoint Portal by the browser)I have a repeating table containing multiple fields. Now I would like to make the first textfield autoincrement starting by 1. How exactly can I do this?

I have already heard of a way by using the "count" function but this produces errors or in best case a static number which unfortunately does not count.
The function I have added for the field is "count(.) + 1"

Any suggestions?

[A]
Let's say your repeating group is called "item" and your autoincrement field is called "index". The default value of the index field should be
```
```
count(/my:myFields/my:item)
```
```
This should count correctly for you.


q: I am looking to protect the code of my Firefox extension because it has server calls in it that no would be a security risk if someone could make them outside of the extension. Any suggestions on how to encrypt it?

[A]
If it's going to be executed on the client side, with no reliable secret, then basically you've definitely got a security vulnerability.
It's hard to suggest ways round this without knowing a bit more about your extension. An obvious suggestion would be to request a username/password, authenticate (over HTTPS) with the server and receive a time-limited token, and then present that token with the "dodgy" request. That won't stop anyone with the right username and password though...


q: Are "out" parameters a bad thing in .NET? Any good articles/discussions on this topic?

[A]
For most circumstances I would recommend against using Out parameters. They basically add side-effects to your code and could be a nightmare when it comes to debugging.
There's an article on MSDN regarding Out parameters available here:
http://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx


q:
I am not that hot at regular expressions and it has made my little mind melt some what.

I am trying to find all the tables names in a query.  So say I have the query:

SELECT one, two, three FROM table1, table2 WHERE X=Y

I would like to pull out "table1, table2" or "table1" and "table2"

But what if there is no where statement.  It could be the end of the file, or there could be a group by or an order by etc.  I know "most" of the time this will not be an issue but I don't like the idea of coding for "most" situations and knowing I have left a hole that could cause things to go wrong later.

Is this a doable Regex expression?  Am I being a Regex pleb?

(P.S. this will be done in C# but presume that doesn't matter much).

[A]
It's definitely not easy.
Consider subqueries.
```
```
select
  *
from
  A
  join (
    select
       top 5 *
    from
      B)
    on B.ID = A.ID
where
  A.ID in (
    select
      ID
    from
      C
    where C.DOB = A.DOB)
```
```
There are three tables used in this query.


q:
I have a compiled AppleScript application which I have moved to my windows server. I'd like to then insert a text file into the application (which looks like a zip file on windows):

myapplescript.app/Contents/Resources/MyNewDir/MyTxtFile.txt

So, I've precompiled the AppleScript to try to read from this text file and get the contents as a string. This is what I do:

set theFolder to POSIX path of (the path to me)
set theFile to theFolder & "Contents/Resources/MyNewDir/MyTxtFile.txt"
open for access theFile
set fileContents to (read theFile)
close access theFile

but this is the error I get:

Can't make
  "/Users/mike/Desktop/myapplescript.app/Contents/Resources/MyNewDir/MyTxtFile.txt"
  into type file

[A]
Ok, I figured it out, I changed the second line to this:
```
```
set theFile to (POSIX file (theFolder & "Contents/Resources/MyNewDir/MyTxtFile.txt"))
```
```


q:
How do I replace text from one file with text from another file using vbscript?

The text being replaced is somewhere in the middle of the file.

[A]
filea.txt:
hello cruel world
fileb.txt:
cruel
filec.txt:
happy
will make sResult = "hello happy world" after the following has executed.
```
```
Dim oFSO
Dim sFileAContents
Dim sFileBContents
Dim sFileCContents
Dim sResult
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFileAContents = oFSO.OpenTextFile("c:\filea.txt").ReadAll()
sFileBContents = oFSO.OpenTextFile("c:\fileb.txt").ReadAll()
sFileCContents = oFSO.OpenTextFile("c:\filec.txt").ReadAll()
sResult = Replace(sFileAContents, sFileBContents, "")
```
```


q: Has anyone written a version of .Net's generic Queue that implements INotifyCollectionChanged, or is there one hidden deep in the .Net framework somewhere already?

[A]
A quick search didn't show any results.  But the interface is simple and it would be almost trivial to extend the Queue class and add support for the interface.  Just override all methods thusly:
```
```
// this isn't the best code ever; refactor as desired
protected void OnCollectionChanged( NotifyCollectionChangedEventArgs ccea){
  var temp = CollectionChanged;
  if(temp != null) temp(this, ccea);
}

// and later in the class

public override SomeMethodThatAltersTheQueue(object something){
  // record state of collection prior to change
  base.SomeMethodThatAltersTheQueue(something)
  // create NotifyCollectionChangedEventArgs with prior state and new state
  OnCollectionChanged(ccea);
}
```
```


q:
The default generated hashCode and equals implementations are ugly at best.

Is it possible to make eclipse generate ones from HashCodeBuilder and EqualsBuilder, and perhaps even a toString with ToStringBuilder?

[A]
Take a look at
Commons4E
It hasn't been updated in a while, but then I don't guess it needs to change much?
Update: Just checked against 3.4.1 and it works fine.


q: Is there any difference between a volatile Object reference and AtomicReference in case I would just use get() and set()-methods from AtomicReference?

[A]
Short answer is: No.
From the
```
java.util.concurrent.atomic
```
package documentation. To quote:
The memory effects for accesses and updates of atomics generally follow the rules for volatiles:
```
get
```
has the memory effects of reading a
```
volatile
```
variable.
```
set
```
has the memory effects of writing (assigning) a
```
volatile
```
variable.
By the way, that documentation is very good and everything is explained.
```
AtomicReference::lazySet
```
is a newer (Java 6+) operation introduced that has semantics unachievable through
```
volatile
```
variables. See
this post
for more information.


q:
What would be the easiest way to move the mouse around (and possibly click) using Python on OS X?

This is just for rapid prototyping, it doesn't have to be elegant.

[A]
I dug through the source code of Synergy to find the call that generates mouse events:
```
```
#include <ApplicationServices/ApplicationServices.h>

int to(int x, int y)
{
    CGPoint newloc;
    CGEventRef eventRef;
    newloc.x = x;
    newloc.y = y;

    eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,
                                        kCGMouseButtonCenter);
    //Apparently, a bug in xcode requires this next line
    CGEventSetType(eventRef, kCGEventMouseMoved);
    CGEventPost(kCGSessionEventTap, eventRef);
    CFRelease(eventRef);

    return 0;
}
```
```
Now to write Python bindings!


q:
My code:

        string input1;

        input1 = Console.ReadLine();

        Console.WriteLine("byte output");

        byte[] bInput1 = Encoding.Unicode.GetBytes(input1);

        for (int x = 0; x < bInput1.Length; x++)
            Console.WriteLine("{0} = {1}", x, bInput1[x]);

outputs:

104
0
101
0
108
0
108
0
111
0

for the input "hello"

Is there a reference to the character map where I can make sense of this?

[A]
You should read "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" at
http://www.joelonsoftware.com/articles/Unicode.html
You can find a list of all Unicode characters at
http://www.unicode.org
but don't expect to be able to read the files there without learning a lot about text encoding issues.


q:
Is it possible to share a single 'god' instance among everyone that links to this code, to be placed in a shared object?

god* _god = NULL;
extern "C"
{

int set_log_level(int level)
{
    if(_god == NULL) return -1;
    _stb->log_level(level);
    return 0;
}

int god_init(){
    if(_god == NULL){
        _god = new god(); //Magic happens here
    }
}

}

Provided that I perform a lock synchronization at the beginning of every function, and considering that God itself can new/malloc other things, but those things will never be returned themselves to the caller (God mallocs only for internal use), what is the simplest way of doing this, if possible.

How can that be extended to an arbitrary number of programs linked to this shared library?

[A]
This isn't the correct approach at all. By doing what you suggest, the variable, yes, is global to the library, and thus the program, but the data is private to the actual running process. You won't be able to share the values across running programs. @grieve is referring to a global accessed by multiple threads, but threads share the same parent process instance.
Across actual processes, you need to break out to an OS specific shared memory facility.
Take a look at
Shared Memory
for details. It's a doable issue, but it's not particularly trivial to pull off. You'll also need a interprocess synchronization system like Semaphores as well to coordinate usage.


q:
I am having some trouble grasping some concepts behind the MVC framework. I am doing a very simple application which categorizes products.

The Creation screen will simply use a dropdown list showing the list of categories, the name of the product and submit.

On a normal .Net app, I would databind a server dropdownlist in the Page_Load, but in a MVC app, what is the best way to retrieve my categories from the database and add them to the dropdown list?

(Sorry, my question is extremely noobish but unfortunately resources are spare on MVC, and examples are often broken due to early changes)

[A]
Your models retrieve data, your presenter organizes data for the view, and the view controls binding your model to UI elements.  For example, here's a model for a LogEvent:
```
```
public class LogEvent{
  public string Title {get;set;}
  public string Date {get;set;}
  public string Message {get;set;}

  // this is for example only; you would most likely bind directly against the host.GetAllLogs() result
  public static IEnumerable<LogEvent> RetrieveAllLogs(ILogProvider host){
    return from x in host.GetAllLogs() select new LogEvent(x.LogTitle, x.Date, x.Message);
  }
```
```
Here's the controller that handles a user request to view all logs:
```
```
[DependencyPropertyLolJk]
protected ILogProvider MyLogProvider {get;set;} // set by DI

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Logs()
{
    return View("Logs", LogEvent.GetAllLogs(MyLogProvider).OrderByDescending(x => x.Date));
}
```
```
And here is the view and how it binds to the model:
```
```

                Date

                Title

                Message

    <% foreach(var log in ViewData.Model) %>

<%= log.Date %>
<%= log.Title %>
<%= log.Message %>

    <% }; %>

```
```
So you see, you have to write your html using inline code.  This works well for simple UIs, but can be complex and a drudgery when it comes to more complex things, such as pagers and gridviews.
When your UI gets complex, the easiest thing to do is to create extensions to the HtmlHelper class.  Here are two examples that show how this can cut down the complexity of your UI:  HtmlHelper
GridView
and
Pager
controls.  I've created similar helper methods, and its pretty remarkable how you can mix html and inline code within lambdas.  Now if the designer was only able to format this kind of mixed code/markup decently...


q: I have an installer that deploys web services to IIS.  After this has finshed a custom action fires that updates the database with the scripts required by the webservices.  The scripts are currently deploying to IIS aswell because they are part of the .net project.  How can I configure the installation process so the scripts arn't part of the project and get un-packed from the MSI so my custom action can access them?

[A]
Using WIX, sorry no clue as to what you are using.  I would create a
```
```
<Binary Id="webServiceScript.sql" src="[DirectoryToFile]\webServiceDataScript.sql" />
```
```
After setup a CA to run the script
```
```
<CustomAction Id="CallCmd" Value="[Path_to_Exe_Folder][Your_EXE_TO_RUN_SCRIPT_HERE]" />

<CustomAction Id="RunCmd" ExeCommand="webServiceScript.sql" BinaryKey="webServiceScript.sql" Return="Ignore" />
```
```
Then just Setup the Installation Sequence
```
```
<InstallExecuteSequence>
  <Custom Action="CallCmd" Before="InstallFinalize" />
  <Custom Action="RunCmd" After="CallCmd" />
</InstallExecuteSequence>
```
```


q:
I have a ClickOnce environment like this:

\\Fileserver\ClickOnceApps\App1.application

C:\Documents and Settings\user\Start Menu\Programs\publisher\app1.appref-ms

My understanding is the .apppref-ms file is a glorified link to the app.application file. Does it do anything else?

[A]
If you open the appref-ms file in a text editor you'll see it contains the Url for the application, culture, processor architecture and key used to sign the application, so yes, it's just a link.
The difference between those "Application Reference" files and shortcuts (.lnk) is that the application reference points to the original application Url and not the location of the exe on disk, when you run the appref-ms file the system knows how to find the copy of the program on the local disk and run it from there without accessing the Url (this is not accurate and depends on settings in the ClickOnce manifest, but its a close approximation).


q:
I have to add either an embed tag for Firefox or an object tag for Internet Explorer with JavaScript to address the appropriate ActiveX / Plugin depending on the browser. The plugin could be missing and needs to get downloaded in this case. The dynamically added embed tag for Firefox works as expected. The dynamically added object tag for Internet Explorer seems to do nothing at all. The object tag needs the following attributes to function properly.

id ="SomeId"
classid = "CLSID:{GUID}"
codebase = "http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1"

Even a general working idea or method would be nice.

Thanks!

[A]
I needed to do this same thing and simply place all of the HTML needed for the OBJECT tag in a string in JavaScript and simply replace the innerHTML of a div tag with the OBJECT HTML and it works in IE just fine.
```
```
// something akin to this:
document.getElementById(myDivId).innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc";
```
```
That should work, it does just fine for me - I use it to embed Windows Media Player in a page.
UPDATE: You would run the above code after the page loads via an event handler that either runs on the page's load event or maybe in response to a user's click. The only thing you need to do is have an empty DIV tag or some other type of tag that would allow us to inject the HTML code via that element's
```
innerHTML
```
property.
UPDATE: Apparently you need more help than I thought you needed? Maybe this will help:
Have your BODY tag look like this:
```
<body onload="loadAppropriatePlugin()">
```
Have somewhere in your page, where you want this thing to load, an empty DIV tag with an
```
id
```
attribute of something like "Foo" or whatever.
Have code like this in a
```
<script>
```
tag in your
```
<head>
```
section:
```
```
function getIEVersion() { // or something like this
   var ua = window.navigator.userAgent;
   var msie = ua.indexOf("MSIE ");
   return ((msie > 0) ? parseInt(ua.substring(msie+5, ua.indexOf(".", msie))) : 0);
}

function loadAppropriatePlugin() {
    if(getIEVersion() != 0) { // this means we are in IE
        document.getElementById("Foo").innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc";
    } else {
        // if you want to maybe do the same for FF and load that stuff...
    }
}
```
```
Does that help?


q:
How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

[A]
Try this.  Pass it your array and it will return with empty elements removed.  *Updated to address the bug pointed out by Jason
```
```
function removeEmptyElem(ary) {
    for (var i = ary.length - 1; i >= 0; i--) {
        if (ary[i] == undefined)  {
            ary.splice(i, 1);
        }
    }
    return ary;
}
```
```


q:
I am attempting to insert a copy of a row from one table into another table with the same schema, with the addition of one column (a timestamp) to provide a "history" of the first table in MS Sql Server 2005.

So, my query, without the additional column would be:

"SELECT INTO [WebsiteHistory] FROM [Website]"

I want to populate the timestamp column as well, but am not sure how to best do this. I'd like to do something like:

"SELECT Website.*, '" + DateTime.Now.ToShortDateString() + "' INTO [WebsiteHistory] FROM [Website]"

But that shouldn't work, especially if the timestamp column is not the last one. Is there any way to do this?

[A]
Be warned. This works, but it is neither
nice
nor recommendable:
```
```
INSERT
  WebsiteHistory
SELECT
  *,
  GETDATE()
FROM
  Website
WHERE
  Id = @WebsiteId
```
```
This assumes
```
WebsiteHistory
```
has the same structure as
```
Website
```
(you said it has), plus there is one additional
```
DATETIME
```
field.
Better is this, because it is much more fail-safe (at the expense of being more verbose):
```
```
INSERT
  WebsiteHistory
  (
  Id,
  Field1,
  Field2,
  Field3,
  Field4,
  ModifiedDate
  )
SELECT
  Id,
  Field1,
  Field2,
  Field3,
  Field4,
  GETDATE()
FROM
  Website
WHERE
  Id = @WebsiteId
```
```


q:
So for the second day in a row, someone has wiped out an entire table of data as opposed to the one row they were trying to delete because they didn't have the qualified where clause.

I've been all up and down the mgmt studio options, but can't find a confirm option.  I know other tools for other databases have it.

[A]
Try using a
```
BEGIN TRANSACTION
```
before you run your
```
DELETE
```
statement.
Then you can choose to
```
COMMIT
```
or
```
ROLLBACK
```
same.


q:
Our windows deliverable has different sets of config files and binary assets for different customers.  Right now the configuring is done by hand before packaging and its error prone.  What do you think of using branches for each customer, and having the package build/script automerge the customer's branch with trunk?

I'm less concerned with scalability than I am of getting this automated ASAP.

The entire packag contents is in SVN, but SVN branching and merging is so delicate that I don't trust it to work consistently when its automated.  If you guys like the idea I might try to use git-svn for this, because it will hopefully make merging less delicate.  We don't necessarily have to merge the assets, because they are organized so the installer can just skip inappropriate directory trees, but configuration is not so simple.

[A]
I suppose it depends on how many things have to change. For config files, I like to keep a single file under source control and use a build script to set the environment-specific (or in your case client-specific) items.
http://automaticchainsaw.blogspot.com/2008/02/automate-config-changes-for-different.html
For binaries, it probably has more to do with how many of them you have and where they come from.  If they are part of a code compile, then the compilation process ideally would create what you need.  If they are other resources, such as graphics, perhaps you have a customer-specific set of folders under one directory.  The build script would pull in the correct client folder based on a parameter passed to the script.  This is basically the branch and merge idea you mentioned in your question.
Regarding your later comment about multi-line config changes - assuming it is xml, you might look at the XmlMassUpdate class in the MSBuild Community Tasks.  I've not used it myself, but it looks like it might be what you need.


q:
I am using WinCVS as client and CVSNT as my source control server. Some of the files I wanted to add to my CVS repo, were added as Unicode files. Now, I want to recommit the same as ANSI (aka ASCII) files. However, despite deleting the old files from the repo, every time I add the file with the same  name, it automatically assigns Unicode encoding to the file.

Is there a way out? Or in other words, can I change the encoding of a file, once it is added to CVS?

[A]
Firstly, I'd recommend using
TortoiseCVS
as it has better
```
CVSNT
```
support.  Whie
```
CVS
```
and
```
CVSNT
```
are very similar,
```
CVSNT
```
is
not
```
CVS
```
.
TortoiseCVS
```
Add
```
dialog will show the file types as it guesses they are and you can override the filetype there.
For the existing situation, assuming that you don't want to keep the history of the Unicode files, you may try the following.
OK, first the warning:
THOU SHALT NOT EDIT THE CVS REPOSITORY BY HAND (unless thou art truly desperate)
Now for the instructions to break said rule, at your own risk.
Make a backup of your CVSNT repository directory (simple ZIP file will do)
On the client, ensure that the Unicode files are actually deleted locally and in the repository.
In the CVSNT repository directory:
Find the module directory where you originally added the files
Find the
```
Attic
```
directory
Delete the files and any
```
,v
```
extensions of them.
On the client:
Verify that the files have ANSI encoding (plain ol' text files)
```
cvs add
```
the files again


q:
If I have the following code,

Foo *f = new Foo();
vector<Foo*> vect;
vect.push_back(f);
// do stuff
vect.erase(f);

Did I create a memory leak?
I guess so, but the word erase gives the feeling that it is deleting it.

Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What do you think?

[A]
Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won't free the memory the pointer points to.
It's not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the container. A better, yet simple, way to do the above, is to use boost::shared_ptr:
```
```
{
    boost::shared_ptr<foo> f(new foo);

    std::vector< boost::shared_ptr<foo> > v;
    v.push_back(f);
    v.erase(v.begin());
} /* if the last copy of foo goes out of scope, the memory is automatically freed */
```
```
The next C++ standard (called C++1x and C++0x commonly) will include
```
std::shared_ptr
```
. There, you will also be able to use
```
std::unique_ptr<T>
```
which is faster, as it doesn't allow copying. Using
```
std::unique_ptr
```
with containers in c++0x is similar to the
```
ptr_container
```
library in boost.


q:
As the title suggests, I am having trouble maintaining my code on postback. I have a bunch of jQuery code in the Head section and this works fine until a postback occurs after which it ceases to function!

How can I fix this? Does the head not get read on postback, and is there a way in which I can force this to happen?

JavaScript is:

        <script type="text/javascript">
        $(document).ready(function()
        {
            $('.tablesorter tbody tr').tablesorter();

        $('.tablesearch tbody tr').quicksearch({
            position: 'before',
            attached: 'table.tablesearch',
            stripeRowClass: ['odd', 'even'],
            labelText: 'Search:',
            delay: 100
        });
       });
        </script>

[A]
If you just have that code hard coded into your page's head then a post back won't affect it. I would check the following by debugging (FireBug in FireFox is a good debugger):
Verify the script is still in the head on postback.
verify that the css classes are in fact attached to some element in the page.
verify that the jquery code is executing after the browser is done loading on post back.
EDIT: Are you using UpdatePanels for your post back? In other words is this an asynchronous postback or a normal full page refresh?
EDIT EDIT:  AHhhhh... Ok. So if you're using UpdatePanels then the document's ready state is already in the ready so that portion of jquery code won't be fired again. I would extract the jquery delegate out to a separate function that you can also call after the async postback.


q:
I am implementing long running processes that require to a process bar - or progress percentage - to be displayed. The overall logic of the long running process is complex (various paged data retrieval), and as a result, I end up hardcoding lots of percentages in various places within the code.

What are considered as the best design patterns when it comes to update a completion percentage?

[A]
If you know in advance the 'length' of the task you're going to perform, and have a way of knowing how far along you are, you should let the bar determine the percentage. For example, if you have to process a known number of files, give this number to the progress bar on construction. Then, during the process either the bar can poll the process, or the process can tell the bar how far along it is (in number of files). The bar can compute the percentage from these two values. This is how the
standard progress bar in Java
works.


q:
I have a SSRS 2005 report that has a number of images in it.  The way that I have the images included is I have an image object with the URL set in the value property.  The actual images are hosted by an IIS virtual directory on the same server.   I'm doing it this way because I need to dynamically change the image source using an expression depending on the data within the report.

The problem is that the images work great when previewing the report in Visual Studio but do not display when the report is deployed. When I look at the HTML rendered by SSRS the SRC attribute of the image tag is an empty string.

[A]
I have had this problem before.
You should check to see if you have any warnings being thrown when you deploy the reports. A rsWarningFetchingExternalImages warning means that reporting services is having problems anonymously accessing the images.  This could be because anonymous access is not properly configured in IIS or, as in my case, you could possibly have a problem with the MIME type for the image you're hosting. I was trying to host PNG files and it worked when I changed the images to GIFs.


q:
create table person
(
    name varchar(15),
    attr1 varchar(15),
    attr2 varchar(1),
    attr3 char(1),
    attr4 int
)

How I can use basic ORM in Perl by taking a simple table like the one above and mapping it to Perl objects?  Next I'd like to perform basic operations like select results using some criteria system Perl like syntax. eg.:

@myResults = findAll(attr1 == 3 && attr2 =~ /abc/);

[A]
Rule #1, don't write your own.
There are quite a number of ORMs on CPAN, including ...
DBIx::Class
- probably #1 in popularity at the moment
Rose::DB::Object
Fey::ORM
- my own contribution, most notable for being
Moose
-based, which means you get all the power of Moose in your ORM-based classes.


q:
I need to convert several Java classes to C#, but I have faced few problems.

In Java I have following class hierarchy:

public abstract class AbstractObject {
    public String getId() {
        return id;
    }
}

public class ConcreteObject extends AbstractObject {
    public void setId(String id) {
        this.id= id;
    }
}

There are implementation of AbstractObject which do not need to have setId() defined, so I cannot move it up in the hierarchy.

How to convert this to C# using properties? Is that possible?

[A]
When you supply only the
```
get
```
portion of a property in .Net, you are explicitly telling the compiler that this property is read-only.  It's a bigger deal than just not providing a
```
set
```
.  This is evident in the vb version of the property syntax, where you must also explicitly declare the property is ReadOnly.
What you might be able to do is provide both a getter and a setter, but throw a
```
NotImplementedException
```
in the abstract setter, decorate it with the appropriate attributes and document so that no one uses it unless the setter has been property overridden.  Otherwise, you're probably better off keeping these as methods anyway, to avoid a disconnect between Java and .Net versions of the code.


q:
A Wicket application serializes and caches all pages to support stateful components, as well as for supporting the back button, among other possible reasons. I have an application which uses setResponsePage to navigate from screen to screen. Over a pretty short amount of time the session gets rather large because all of the prior pages are stored in the session. For the most part, I only need the session to contain the current page, for obvious reasons, and perhaps the last 2 or 3 pages to allow easy navigation using the browser's back button.

Can I force a page to expire after I have navigated away from it and I know that I don't want to use to back button to that version of the page? More generally what is the recommended way to deal with session growth in Wicket?

[A]
http://apache-wicket.1842946.n4.nabble.com/Wicket-Session-grows-too-big-real-fast-td1875816.html
If you use loads of domain objects on your page, which are eventually tightly coupled to other domain objects, be sure to avoid serialization for these!
Have a look at
LoadableDetachableModel for wrapping domaing objects
DataView and IDataProvider for displaying list of domain objects
Thou shalt not stuff domain objects into instance variables of components.
Thou shalt not make domain object references final in order to use them in anonymous subclasses.
Thou shalt not pass a mere List of domain objects to a ListView.
Perhaps, when subclassing WbeRequestCycle in your Application class, you might gain control of a page's lifetime in the pagemap... haven't tried it, though


q: I currently have Apache HTTP Server, but I'm guessing I'll need Tomcat (and then have to configure it in a way that makes it not open to the public), a Java JDK (which I already have, but should probably update), and an IDE (I have Eclipse). But what else should I have or know before starting?

[A]
I would go for maven.
It will give you a quick start in configuring your project (by using archetypes) and it will manage your dependencies.
Install it and run the archetype command to create your project.
```
```
mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-webapp -DarchetypeArtifactId=maven-archetype-webapp
```
```
After that just use the maven eclipse plugin to configure your eclipse environment for that project (
http://maven.apache.org/plugins/maven-eclipse-plugin/
).


q:
Most of my PHP apps have an ob_start at the beginning, runs through all the code, and then outputs the content, sometimes with some modifications, after everything is done.

ob_start()
//Business Logic, etc
header->output();
echo apply_post_filter(ob_get_clean());
footer->output();

This ensures that PHP errors get displayed within the content part of the website, and that errors don't interfere with header and session_* calls.

My only problem is that with some large pages PHP runs out of memory. How do I stop this from happening?

Some ideas:

Write all of the buffered content to a temporary file and output that.

When the buffers reaches a certain size, output it. Although this might interfere with the post filter.

Raise the memory limit (thanx @troelskn).

Whats the drawbacks on each of these approaches? Especially raising the memory limit?

[A]
Can't you raise the memory limit? Sounds like the best solution to me.
Edit: Obviously, raising the memory limit just because a script tops out should raise some red flags, but it sounds to me like this is a legitimate case - eg. the script is actually producing rather large chunks of output. As such, you have to store the output
somewhere
, and memory seems to be the best pick, for both performance and convenience reasons.
I should note also that the memory limit setting is just that - a limit. Scripts that don't consume much memory, won't consume more just because you raise the limit. The main reason for its existence, is to prevent misbehaving/buggy scripts from taking down the entire server. This is something that is important if you have a lot of amateurs hacking away on a shared host (Something PHP has been used a lot for). So if this is your own server, or at least you generally know what you're doing, there isn't really any benefit from having a low memory-limit.


q:
I have the very same delphi version, bpls, components, everything. And yet in three machines the resulting executables are different in size.
What else can influence in the size of the exe?

In my machine I get this size (Vista 6.0.6001):

4.547.584 bytes

In my colleague's machine, he gets (XP 5.1.2600 SP3):

4.530.688 bytes

In a third colleage, he gets: (XP 5.1.2600 SP2)

4.527.104 bytes

Does the OS version influence in the compiled exe size?

[A]
With Delphi/BCB these are a few factors that can influence size:
Your Build Configuration
: Release Mode does not link in the debug section into the EXE (by default) so is smaller. also you may get a boost from code optimization.
Linking with Dynamic RTL
: If enabled you EXE will be smaller but you will require the external libraries to be available.
Building with Runtime Packages
: If enabled, you dynamically link to the runtime packages you use instead of linking them directly into your EXE. This can result in the largest size differences.
Their are other factors but the above tends to be the main ones I come across.


q:
As I use the web, I regularly get runtime errors (usually javascript) being reported via popups. This can make for a really unsatisfying user experience on many otherwise excellent websites and also makes me wonder what functionality I am not getting access to.

Why is this such a common issue? Is this down to a lack of testing or is it browser compatibility issues? What can be done to minimise this kind of issue?

Incidently I don't have the 'Display a notification about every script error' checked.

[A] It's easy to make mistakes in JavaScript. Until recently with Aptana, there weren't many good tools for coding JavaScript. Not have the benefit of syntax checking or compilation, small typing error can make it into pages. Beyond that, there are time where code that works fine in one browser will cause an error in another. For example, I saw a jQuery plugin that didn't work in IE, but it was fine in every other browser. It turned out to be a variable declared without the 'var' keyword. Firefox and Safari were OK with that, IE wasn't, so it's possible that whoever wrote the code didn't even know it was a problem.


q:
I'm trying to do Ruby password input with the Highline gem and since I have the user input the password twice, I'd like to eliminate the duplication on the blocks I'm passing in. For example, a simple version of what I'm doing right now is:

new_pass = ask("Enter your new password: ") { |prompt| prompt.echo = false }
verify_pass = ask("Enter again to verify: ") { |prompt| prompt.echo = false }

And what I'd like to change it to is something like this:

foo = Proc.new { |prompt| prompt.echo = false }
new_pass = ask("Enter your new password: ") foo
verify_pass = ask("Enter again to verify: ") foo

Which unfortunately doesn't work. What's the correct way to do this?

[A]
I don't think the language supports a construct like this. The only way I can see to generalize this in any way is:
```
```
def foo(prompt)
  prompt.echo = false
end
new_pass = ask("Enter your new password: ") { |prompt| foo(prompt) }
verify_pass = ask("Enter again to verify: ") { |prompt| foo(prompt) }
```
```
It doesn't really shorten the code, though it does remove some duplication--if you wanted to do more than set
```
prompt.echo
```
to
```
false
```
, you'd only have to add code in one place.


q:
Using an ORM approach in applications can often lead to the scenario where you have a collection of objects you've retrieved and would like to display them in a tabular view using a DataGridView.

In my (limited) experience, binding collections of objects using a custom BindingList to a DataGridView results in poor performance and unsatisfactory sorting.  I'm looking for a generic solution to this problem such that it's straightforward to populate a DataGridView and also extract the underlying objects later.

I will describe a good solution I've found, but I'm looking for alternatives.


q:
I want to make custom control which has couple of <input type='checkbox' /> controls which I render in Render method.
Is it possible to retain ViewState (e.g. checked or not) on these Controls?

There is a way of doing this by using ASP.NET server CheckBox control,
adding them in OnLoad event with this.Controls.Add(),
and giving them same Ids everytime,
but I don't wat to do this :)

[A]
You can just access the ViewState directly:
```
```
bool checked = (bool)(ViewState["ThisControlCheckState"] ?? false);
if (checked) {
    write("<input ... >");
}
else {
    write("<input ... >");
}
```
```
To save the value form the user, you could do something like this in the PostBack:
```
```
ViewState["ThisControlCheckState"] = request.Params["checkboxName"].ToString() == "1";
```
```


q:
What are the actual performance differences between Int64 and Int32 on 32 and 64 bit MS Windows?

It would also be great to see some actual timings of Int64 vs Int32 on each of the two operating system variants.  XP or Vista would also be interesting.

See also this question about memcpy performance.

[A]
As far as hardware, Int64 will be more efficient on an x64 and IA64 than x86 because the 64-Bit processors have 64-Bit registers to perform the operations on them.
Int32 will be equally as efficient on all x86, x64, and IA64.
On an x64 and on an IA64 both Int32 and Int64 are equally as efficient.
On an x86 Int32 will be more efficient than an Int64.
As far as the OS itself, I don't think you will see any extra performance issues than the performance results mentioned above.


q:
Why does UDP have a length field in the header and TCP does not?

I am guessing that the length of the segment in TCP is inferred from the IP header but one should be able to do the same for a UDP datagram

[A]
There is a 96 bit pseudo header conceptually prefixed to the TCP header that contains the information already.
The checksum field description from
this source
gives the answer:
Checksum: 16 bits
The checksum field is the 16 bit one's complement of the one's
  complement sum of all 16 bit words in the header and text.  If a
  segment contains an odd number of header and text octets to be
  checksummed, the last octet is padded on the right with zeros to
  form a 16 bit word for checksum purposes.  The pad is not
  transmitted as part of the segment.  While computing the
  checksum,
  the checksum field itself is replaced with zeros.
The checksum also covers a 96 bit pseudo header conceptually
  prefixed to the TCP header.  This pseudo header contains the Source
  Address, the Destination Address, the Protocol, and TCP length.
  This gives the TCP protection against misrouted segments.  This
  information is carried in the Internet Protocol and is transferred
  across the TCP/Network interface in the arguments or results of
  calls by the TCP on the IP.
```
```
+--------+--------+--------+--------+
      |           Source Address          |
      +--------+--------+--------+--------+
      |         Destination Address       |
      +--------+--------+--------+--------+
      |  zero  |  PTCL  |    TCP Length   |
      +--------+--------+--------+--------+
```
```
The information is not needed at the TCP level since TCP is a stream based protocol.


q:
How do I get a human-readable file size in bytes abbreviation using .NET?

Example:
Take input 7,326,629 and display 6.98 MB

[A]
```
```
int size = new FileInfo( filePath ).Length / 1024;
string humanKBSize = string.Format( "{0} KB", size );
string humanMBSize = string.Format( "{0} MB", size / 1024 );
string humanGBSize = string.Format( "{0} GB", size / 1024 / 1024 );
```
```


q:
Currently our dev team set up all the websites they're working on in IIS on their local machine. We're thinking of switching to using the built in ASP.NET development server instead.

Is this a good idea? What are the pros / cons of using the ASP.NET dev Server? Are there any gotchas we should be aware of?

Thanks.

NB: Running on Win XP / IIS 5 / VS2005

Edit:

Didn't realise it was called Cassini.. More answers for Cassini v IIS here.

[A]
There is nothing that the ASP.NET Dev WebService can do that IIS can't (You can set breakpoints etc, just attach the VS debugger to the ASP.NET runtime).
However, the ASP.NET Dev WebService does not represent a true production environment, and as such you can get caught by gotchas that you wouldn't expect when you deploy to production.
Because of that, I mandate that all development is done using IIS on a local machine. It doesn't take much work to configure a site in IIS.


q:
I am trying to set the innerxml of a xmldoc but get the exception: Reference to undeclared entity

XmlDocument xmldoc = new XmlDocument();
string text = "Hello, I am text &alpha; &nbsp; &ndash; &mdash;"
xmldoc.InnerXml = "<p>" + text + "</p>";

This throws the exception:

Reference to undeclared entity 'alpha'. Line 2, position 2..

How would I go about solving this problem?

[A]
Try replacing &Alpha with
```
```
Α
```
```


q:
I want to set up an ASP.NET custom control such that it has a custom name, specifically, with a hyphen within it, so it might look like this in markup:

<rp:do-something runat="server" id="doSomething1" />

I don't mind if this syntax requires setting up a tag mapping in web.config or something to that effect, but the tagMapping element doesn't quite match up for what I'd like to do.


q:
I used code like this to find the remote user name:

banner_label.Text = "Welcome, <B>" + User.Identity.Name + "</B>!"

I'd also like to find the remote host name.
My production environment will be a corporate intranet with active directory.

[A]
maybe this would work for you
```
```
Request.UserHostName
```
```
edit:
i think what you're trying to do will not working over the internet, what you're trying to get is the name of the computer, which will not be transmitted with the request to the server.


q:
I just don't get it. Tried on VC++ 2008 and G++ 4.3.2

#include <map>

class A : public std::multimap<int, bool>
{
public:
    size_type erase(int k, bool v)
    {
        return erase(k); // <- this fails; had to change to __super::erase(k)
    }
};

int main()
{
    A a;
    a.erase(0, false);
    a.erase(0); // <- fails. can't find base class' function?!

    return 0;
}

[A]
When you declare a function in a class with the same name but different signature from a superclass, then the name resolution rules state that the compiler should
stop looking
for the function you are trying to call once it finds the first match. After finding the function by name,
then
it applies the overload resolution rules.
So what is happening is the compiler finds your implementation of
```
erase(int, bool)
```
when you call
```
erase(0)
```
, and then decides that the arguments don't match.


q: Do you have any ideas how to call DoEvents from a C# DLL

[A] Don't. It's sketchy enough when you are the app controlling the event loop; pumping messages from a DLL just adds to the risk that you'll end up hitting code a naive programmer didn't make safe for re-entrancy.


q: From my experiments, it does not appear to do so. If this is indeed true, what is the best method for removing line breaks? I'm currently experimenting with the parameters that TRIM accepts of the character to remove, starting with trimming \n and \r.

[A]
```
```
select trim(both '\n' from FIELDNAME) from TABLE;
```
```


q:
I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so.

-edit-

I'll have several classes that inherit from SomeTag. I don't want to write the same specialization for each of them.

class SomeTag {};
class InheritSomeTag : public SomeTag {};

template <class T, class Tag=T>
struct MyClass
{
};

template <class T>
struct MyClass<T, SomeTag>
{
    typedef int isSpecialized;
};

int main()
{
    MyClass<SomeTag>::isSpecialized test1; //ok
    MyClass<InheritSomeTag>::isSpecialized test2; //how do i make this specialized w/o changing main()
    return 0;
}

[A]
In your case, the only way that I see would be to explicitly specialize
```
MyClass
```
for
```
InheritSomeTag
```
. However, the
SeqAn paper
proposes a mechanism called “template sublassing” that does what you want – albeit with a different inheritance syntax, so the code isn't compatible with your current
```
main
```
function.
```
```
// Base class
template <typename TSpec = void>
class SomeTag { };

// Type tag, NOT part of the inheritance chain
template <typename TSpec = void>
struct InheritSomeTag { };

// Derived class, uses type tag
template <typename TSpec>
class SomeTag<InheritSomeTag<TSpec> > : public SomeTag<void> { };

template <class T, class Tag=T>
struct MyClass { };

template <class T, typename TSpec>
struct MyClass<T, SomeTag<TSpec> >
{
    typedef int isSpecialized;
};

int main()
{
    MyClass<SomeTag<> >::isSpecialized test1; //ok
    MyClass<SomeTag<InheritSomeTag<> > >::isSpecialized test2; //ok
}
```
```
This certainly looks strange and is very cumbersome but it allows a true inheritance mechanism with polymorphic functions that is executed at compile time. If you want to see this in action, have a look at some
SeqAn examples
.
That being said, I believe that SeqAn is a special case and not many applications would profit from this extremely difficult syntax (deciphering SeqAn-related compiler errors is a real pain in the *ss!)


q:
I have a client which is shipping via UPS, and therefore cannot deliver to Post Office boxes. I would like to be able to validate customer address fields in order to prevent them from entering addresses which include a PO box. It would be best if this were implemented as a regex so that I could use a client-side regex validation control (ASP.NET).

I realize there's probably no way to get a 100% detection rate, I'm just looking for something that will work most of the time.

[A]
This should get you started.  Test to see if the Address field matches this regex.
```
```
"^P\.?\s?O\.?\sB[Oo][Xx]."
```
```
Translation to English:  That's a P at the beginning of the line, followed by an optional period and space, followed by an O, followed by an optional period, followed by a space, followed by "Box", followed by anything else.


q:
Can someone explain how exactly prepared connection pooling using dbcp can be used? (with some example code if possible). I've figured out how to turn it on - passing a KeyedObjectPoolFactory to the PoolableConnectionFactory.
But how should the specific prepared statements be defined after that?
Right now I'm only using a PoolingDataSource to get connections from the pool. How do I use the prepared statements from the pool?

[A]
Well talking about getting connection from the pool vs getting "not-pooled" connection, do you have any change in your code :)? I bet you do not. Same way with prepared statements. Your code should not change. So, there is no useful code example to this.
You should read docs for your JDBC Datasource implementation and see what developers have to say about pooling. There is no other source of reliable info on this.
From
here
:
This component has also the ability to pool PreparedStatements. When enabled a statement pool will be created for each Connection and PreparedStatements created by one of the following methods will be pooled:
```
```
* public PreparedStatement prepareStatement(String sql)
* public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
```
```
So, you just keep using prepareStatement() call and your dbcp will in theory take care of pooling (i.e. if you are trying to create "select * from users u where u.name like :id", it will try to find this statement in the pool first)


q:
I have a pretty much default installation on mysql on Windows 2003. I am rebuilding some indexes and the process only seems to use 3-20% of the CPU.

Is there a way to allow it to use more and speed up the process?

[A] This applies to every application/process, not only mysql. If your database is using 3-20% CPU and the final performance is still unacceptable it means that you don't lack processor power, since it is most of the time idle. What is most probable is your bottleneck is at your HDD or HDD-controller level. Have you tested the I/O bandwitch and access time of your HD?


q: How do I build a VST plugin on Mac without using Xcode? (I'm using Code::Blocks).


q:
I want to set the background of an NSBox to be a gradient. In Interface Builder it is possible to set the background color of an NSBox to selectedMenuColor which is a gradient.

NSBox only has a setFillColor method so how is Interface Builder filling it with a gradient?

How do I programmatically fill an NSBox without subclassing it? It would be trivial to subclass NSBox but the workings of Interface Builder suggest there may be better solution.

[A]
Probably the closest you could come would be to use an NSColor created with
```
colorWithPatternImage:
```
, then create the gradient you want as an image and load that in. Ugly, but should work. I think subclassing is your best bet.


q: How do I test if two dates are within a certain tolerance in NUnit?

[A]
Convert your tolerance to Ticks and then use an And constraint. Something like;
```
```
long ticks = mydate.Ticks;
long tolerance = 1000;
Assert.That( ticks, Is.LessThan( ticks + tolerance ) & Is.GreaterThan( ticks - tolerance ) );
```
```
I would create an extension method or your own Assert to do this though.


q:
I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a type_info class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. typeid(std::vector<int>).name() returns St6vectorIiSaIiEE.

Is there a way to produce something useful from this? Like std::vector<int> for the above example. If it only works for non-template classes, that's fine too.

The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.

[A]
It's implementation defined, so it's not something that's going to be portable.  In MSVC++, name() is the undecorated name, and you have to look at raw_name() to get the decorated one.
Just a stab in the dark here, but under gcc, you might want to look at
demangle.h


q: I would like to parse HTML document and replace action attribute of all the forms and add some hidden fields with XSL. Can someone show some examples of XSL that can do this?

[A]
You can start from
this tutorial
But be aware that generally
```
XSLT
```
requires well-formed
```
XML
```
as input and
```
HTML
```
isn't always well-formed


q:
I realize you can't get the target entity in the Attribute itself, but what about in an associated Permission object when using a CodeAccessSecurityAttribute?  The Permission object gets called at runtime so it seems there should be a way but I'm at a loss.

public sealed class MySecurityAttribute : CodeAccessSecurityAttribute
{
    public override IPermission CreatePermission()
    {
        MySecurityPermission permission = new MySecurityPermission();

        //set its properties
        permission.Name = this.Name;
        permission.Unrestricted = this.Unrestricted;
        return permission;
    }

}

public class MySecurityPermission : IPermission, IUnrestrictedPermission
{

    public MySecurityPermission(PermissionState state)
    {
           // what method was the attribute decorating that
           // created this MySecurityPermission?
    }

    public void Demand()
    {
           // Or here?
    }
}

[A]
Well, I guess you could use reflection to scan through all the loaded assemblies, looking for any class/member that has
```
this
```
as an attribute.  It'd be quite slow, though, so it's not something you'd want to do often, or in a large project.


q:
For what I can read, it is used to dispatch a new thread in a swing app to perform some "background" work, but what's the benefit from using this rather than a "normal" thread?

Is not the same using a new Thread and when it finish invoke some GUI method using SwingUtilities.invokeLater?...

What am I missing here?

http://en.wikipedia.org/wiki/SwingWorker

http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html

[A]
SwingWorker is an implementation of a common pattern (in .Net i read there is
GuiWorker
BackgroundWorker for this), where you have to do some work in a GUI program, but keep the GUI responsive. The problem is that often GUI libraries are not multi thread safe, so the common way to implement such workers is to use the message loop of the library to transfer messages into the event loop of the application.
These classes allow you to easily update your GUI. Usually, they have a
```
update(int status)
```
method that is called by the thread, dispatched by the class, and handled by the GUI, while the thread continues its work.
Using normal threads, you would need to code your own events or some other messaging mechanism for this task, which can be a pain if you need this functionality often. Using invokeLater in Java for example, you would intermix the code for updating the gui into the code for doing the work. The SwingWorker allows you to keep things separate.


q:
In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:

import subprocess
subprocess.Popen('explorer "C:\path\of\folder"')

but I have no solution for files.

[A]
From
Geoff Chappell's
The Windows Explorer Command Line
```
```
import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
```
```


q:
There are Hibernate tools for mapping files to ddl generation; ddl to mapping files and so on, but I can't find any command line tools for simple DDL generation from JPA annotated classes.

Does anyone know an easy way to do this? (Not using Ant or Maven workarounds)

[A]
I'm not sure, whether this is considered a workaround, because you already referred to it in your question. You can use
Hibernate Tools
to generate DDL from JPA annotated classes. You just need hibernate tools and its dependencies on the classpath and should be fine with something like the following:
```
```
<target name="schemaexport" description="Export schema to DDL file"
    depends="compile-jpa"> <!-- compile model classes before running hibernatetool -->

  <!-- task definition; project.class.path contains all necessary libs -->
  <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"
      classpathref="project.class.path" />

  <hibernatetool destdir="export/db"> <!-- check that directory exists -->
    <jpaconfiguration persistenceunit="myPersistenceUnitName" />
    <classpath>
      <!--
          compiled model classes and other configuration files don't forget
          to put the parent directory of META-INF/persistence.xml here
      -->
    </classpath>
    <hbm2ddl outputfilename="schemaexport.sql" format="true"
        export="false" drop="true" />
  </hibernatetool>
</target>
```
```
On the other hand, if you are using Eclipse with Webtools and have configured the project settings correctly, you can just right click and select
Generate DDL
from the context menu. More information about that on the
Eclipse Dali website
.


q:
I'm using ASP.NET Membership and noticed there isn't a method in the Roles class to modify a role (its name for instance), only to create and delete them.

Is it possible or it's not supported?

EDIT: @CheGueVerra: Yes, nice workaround.

Do you know (for extra credit :) ) why it's not possible?

[A] Renaming a Role in the ASP.NET Membership model programatically would be a Bad Thing™, because the Role names are used in the configuration file to define permissions. If there were a programmatic way to change the Role name (which persisted the change to the database), you would immediately break any Role-based security configurations in web.config for any web apps using the database, and there'd be no way to guarantee that a single web app could alter the configuration of every web app using that Membership DB.


q:
I need a distinct sound to play when a error occurs.  The error is the result of a problem with one of perhaps two hundred barcodes that are being inputted in rapid fire.  The event queue seems to handle keyboard input (which the barcode scanner emulates) first, and playing of my sound second.  So if the barcodes are scanned quickly, the error sound stays in the queue, being bumped by the next scan.

Can I manipulate the priority of the queue?

[A]
Javascript is not multi-threaded, so option 2 won't work. And I suspect that the event queue you speak of is the OS's event queue, which isn't likely to accessible from a browser, if at all.
Beyond that, I'm having a little trouble understanding your problem. What is firing the error sound? Is it a
```
keyup
```
, etc event or is it a server side validation that returns an error code or something else?


q:
Given a word, I've to replace some specific alphabets with some specific letters such as 1 for a, 5 for b etc. I'm using regex for this. I understand that StringBuilder is the best way to deal with this problem as I'm doing a lot of string manipulations. Here is what I'm doing:

String word = "foobooandfoo";
String converted = "";
converted = word.replaceAll("[ao]", "1");
converted = converted.replaceAll("[df]", "2");
converted = converted.replaceAll("[n]", "3");

My problem is how to rewrite this program using StringBuilder. I tried everything but I can't succeed. Or using String is just fine for this?

[A]
I don't know if StringBuilder is the tool for you here. I'd consider looking at
Matcher
which is part of the java regex package and might be faster than your example above
in case you really need the performance
.


q:
Does anyone know of a way to store values as NVARCHAR in a manually created query in ColdFusion using the querynew() function?  I have multiple parts of a largish program relying on using a query as an input point to construct an excel worksheet (using Ben's POI) so it's somewhat important I can continue to use it as a query to avoid a relatively large rewrite.

The problem came up when a user tried storing something that is outside of the VARCHAR range, some Japanese characters and such.

Edit: If this is not possible, and you are 100% sure, I'd like to know that too :)

[A]
The only thing I've been able to come up with so far is this:
```
```
<cfset x = QueryNew("foobar")/>
<cfset queryAddRow(x) />
<cfset querySetCell(x, "foobar", chr(163)) />
<cfdump var="#x#">
```
```
When dumped, this query does contain the British Pound symbol.
I haven't tried this with Ben's POI utility, but hopefully it helps you some.


q:
Do you generate your data dictionary? If so, how?

I use extended procedures in SQL Server 2005 to hold onto table and field information. I have some queries that create a dictionary out of them, but it's ... meh.  Do you have a particular query or tool you use? Do you generate it off of your database diagrams?

Googling for "data dictionary sql server" comes up with many queries, but they're all about equally as attractive. Which is to say, good starting off points, but not production ready.

[A]
I generate it from
```
INFORMATION_SCHEMA
```
views plus other tables of metadata which are application specific.
I also use wildcard searches of
```
INFORMATION_SCHEMA.ROUTINES
```
in order to track usage patterns within code and identify unused columns and tables.
This article just showed up in one of my news feeds:
http://www.mssqltips.com/tip.asp?tip=1619


q:
I have an object that starts a thread, opens a file, and waits for input from other classes.  As it receives input, it writes it to disk. Basically, it's a thread safe data logging class...

Here's the weird part. When I open a form in the designer (Visual Studio 2008) that uses the object the file gets created. It's obviously running under the design time vhost process...

The odd thing is I've not been able to reproduce the issue in another project. I'm not sure what the rules are for code that gets executed in the designer and code that does not. For example, creating a file in a Windows Forms constructor doesn't actually create the file at design time...

What is the explanation? Is there a reference?

[A]
There are some things you shouldn't do with the designer. I don't have any hard evidence, but I found that the Windows Forms designer hates it when you take away the default constructor from it. Just go ahead and create new overloads, but leave the empty constructor in place.
Also try to avoid doing
```
Form_Load
```
events in base classes you inherit from.


q:
I'm doing some maintenance on a private svn server. Authentication is handled through Apache basic HTTP+mod_authz_svn. I need to have it so every user has read/write access, except for a single read-only user. The read-only user still needs to be authenticated, though. I setup my authz config file like this:

[/]
* = rw
read-only = r

But this doesn't work. The user "read-only" can still commit changes. I can make things read-only for everyone, but the * bit seems to override what I'm trying to set for "read-only."

FWIW, relevant piece of the Apache conf is:

 <Location /repos>
   DAV svn
   SVNPath ...
   SVNIndexXSLT "/svnindex.xsl"

   AuthzSVNAccessFile ...

   AuthType Basic
   AuthName ...
   AuthUserFile ...
   Require valid-user
 </Location>

[A]
In this case, the read-only user has still write access as it also matches the * group.
A safe way to achieve what you want is to create a group of all users except read-only, e.g.
```
```
[groups]
all-but-ro = harry, sally, ...

[/]
@all-but-ro = rw
read-only = r
```
```
(alternatively, you might just generate many =rw lines out of the passwd file)
It might be that svn matches from top to bottom - this is not documented, and I didn't test. So try
```
```
[/]
read-only = r
* = rw
```
```


q:
In building an ASP.NET 3.5 WAP, I'm always frustrated by the feeling that no matter how I "isolate" or "encapsulate" bits of logic or UI I'm still going to bring down the whole site any time I need to update a single line of code. I may be misunderstanding how ASP.NET handles changes in the "bin" directory, but given the number of "why is my AppDomain unloading?" messages in the various groups this still seems like something to avoid.

Does anyone have any guidance and/or frameworks to truly modularize an ASP.NET 3.5 WAP so that logic and pages can be added/updated "in flight"? I Googled System.AddIn a bit, but it seems to be focused on WPF applications.

Thanks for your help!

James White

[A]
This is really hard to achieve since .NET doesn't support unloading a type that has been loaded into the app domain.
One way to do it is playing around with app-domains, or having WCF do it for you.
Another would be implementing ayende's
hod code swapping
.
A third way would be putting logic in the dynamically compiled part (the ASPX). However the app will restart after a configurable amount of changes.


q:
Help!

I have a PHP (PHP 5.2.5) script on HOST1 trying to connect to an MySql database HOST2. Both hosts are in Shared Host environments controlled through CPanel.

HOST2 is set to allow remote database connections from HOST1.

The PHP connect I'm using is:-
    $h2 = IPADDRESS;
    $dbu = DBUSER;
    $dbp = DBPASS;

$DBlink = mysql_connect($h2, $dbu, $dbp);

This always fails with:-

Access denied for user '<dbusername>'@'***SOMESTRING***' (using password: YES)

nb: SOMESTRING looks like it could be something to do with the shared host environment.

Any ideas???

BTW: I can make remote connections to HOST2 from my laptop using OpenOffice via ODBC, and SQLyog. The SQLyog and ODBC settings are exactly the same as the PHP script is trying to use.

[A]
Just some ideas:
HOST1 does not have remote access to HOST2 (shared host is disallowing)
MySQL account does not have access from HOST1 (IP address specified on account creation, or wildcard)
Edit:
In response to your comment, I meant that HOST1 cannot get to the MySQL port on HOST2. Web services will work, of course, because port 80 is open to the public. As another user pointed out though, you are getting a response, so you are reaching it. I would try specifying the DB, and double checking the account creation command you ran.
For the second piece, I meant this:
http://dev.mysql.com/doc/refman/5.0/en/adding-users.html
You can specify what host the username can connect from. If it isn't set to HOST2's IP or the wildcard, HOST2 can't log in with those credentials.


q:
I am instantiating a local COM server using CoCreateInstance.  Sometimes the application providing the server takes a long time to start.  When this happens, Windows pops a dialog box like this:

Server Busy

The action cannot be completed because the other program is busy. Choose 'Switch To' to activate the busy program and correct the problem.

[Switch To...] [Retry] [Cancel]

I have found mention of a Visual Basic property on the Application object, OleRequestPendingTimeout, that can be used to control the time before this dialog comes up.  I can't find any good documentation on this or an equivalent that is useful from C++.  Can anyone point me in the right direction?

[A]
Have a look at
```
IMessageFilter
```
and
```
CoRegisterMessageFilter
```
.


q:
I want my php script to create an output file in a folder based on the date.  The way I'm doing this is that its supposed to get the foldername/filename from a text file outputted by another program which I am unable to edit.

So the file its grabbing the data from looks like this:

data/newfolder/10302008/log_for_Today.txt | 24234234

Only with multiple lines, I just need the script to go through it line by line, grab the folder/filename and create an empty file with that name in that location.

The directories are all 777.  Now I know how to create a new empty exe file in a folder but can't seem to figure out how to create the folder first then the exe inside of it, any ideas?

[A]
Can't you just do this by creating the dir with mkdir (
http://nl.php.net/manual/en/function.mkdir.php
) then chmod it 777 (
http://nl.php.net/manual/en/function.chmod.php
) the change directory with chdir (
http://nl.php.net/manual/en/function.chdir.php
) and then create the file (touch)?


q:
What's the Hi/Lo algorithm?

I've found this in the NHibernate documentation (it's one method to generate unique keys, section 5.1.4.2), but I haven't found a good explanation of how it works.

I know that Nhibernate handles it, and I don't need to know the inside, but I'm just curious.

[A]
The basic idea is that you have two numbers to make up a primary key- a "high" number and a "low" number. A client can basically increment the "high" sequence, knowing that it can then safely generate keys from the entire range of the previous "high" value with the variety of "low" values.
For instance, supposing you have a "high" sequence with a current value of 35, and the "low" number is in the range 0-1023. Then the client can increment the sequence to 36 (for other clients to be able to generate keys while it's using 35) and know that keys 35/0, 35/1, 35/2, 35/3... 35/1023 are all available.
It can be very useful (particularly with ORMs) to be able to set the primary keys on the client side, instead of inserting values without primary keys and then fetching them back onto the client. Aside from anything else, it means you can easily make parent/child relationships and have the keys all in place before you do
any
inserts, which makes batching them simpler.


q:
I've used a Continuous Integration server in the past with great success, and hadn't had the need to ever perform a code freeze on the source control system.

However, lately it seems that everywhere I look, most shops are using the concept of code freezes when preparing for a release, or even a new test version of their product. This idea runs even in my current project.

When you check-in early and often, and use unit tests, integration tests, acceptance tests, etc., are code freezes still needed?

[A]
I think that code freezes are important because each new feature is a potential new source of bugs. Sure regression tests are great and help address this issue. But code freezes allow the developers to focus on fixing
currently outstanding bugs
and get the current feature set into a release worthy state.
At best, if I really wanted to develop new code during a code freeze, I would fork the frozen tree, do my work there, then after the freeze, merge the forked tree back in.


q: I know about using a -vsdoc.js file for IntelliSense, and the one for jQuery is easy to find. What other JavaScript, Ajax, and DHTML libraries have them and where can  I find those files? Also, is there a document which outlines the specifications for -vsdoc.js files?

[A]
An excellent blog posting from Betrand LeRoy on IntelliSense format for JavaScript:
The format for JavaScript doc comments
.
In a nutshell:
Summary - used to describe a function/method or event. Syntax:
```
```
<summary locid="descriptionID">Description</summary>
```
```
Parameter - describe a parameter to a function/method. Syntax:
```
```
<param name="parameterName"
    mayBeNull="true|false" optional="true|false"
    type="ParameterType" parameterArray="true|false"
    integer="true|false" domElement="true|false"
    elementType="ArrayElementType" elementInteger="true|false"
    elementDomElement="true|false"
    elementMayBeNull="true|false">Description</param>
```
```
The param tag is used to describe the parameters of a method or constructor. The param tags should be in the same order as the method or constructor's parameters and have the same names.
Function return type - syntax:
```
```
<returns
    type="ValueType" integer="true|false" domElement="true|false"
    mayBeNull="true|false" elementType="ArrayElementType"
    elementInteger="true|false" elementDomElement="true|false"
    elementMayBeNull="true|false">Description</returns>
```
```
Value type - describes a property (shouldnt use 'summary' for a prop) - syntax:
```
```
<value
    type="ValueType" integer="true|false" domElement="true|false"
    mayBeNull="true|false" elementType="ArrayElementType"
    elementInteger="true|false" elementDomElement="true|false"
    elementMayBeNull="true|false"
    locid="descriptionID">Description</value>
```
```
Field - used to describe a field in a JavaScript class - syntax:
```
```
<field name="fieldName" type="FieldType"
    integer="true|false" domElement="true|false" mayBeNull="true|false"
    elementType="ArrayElementType" elementInteger="true|false"
    elementDomElement="true|false" elementMayBeNull="true|false"
    locid="descriptionID">Description</field>
```
```
How to include IntelliSense for an external JavaScript file, the following syntax as the first line(s) in a JavaScript file:
```
```
<reference path="path/to/the/script/reference.js"
    assembly="Assembly.Name" name="ScriptResourceName.js"/>
```
```


q: Assuming one has an abstract base class foo with __get() defined, and a child class bar which inherits from foo with a private variable $var, will the parent __get() be called when trying to access the private $var from outside the class?

[A]
Yes.
```
```
<?php
    abstract class foo
    {
        public function __get($var)
        {
            echo "Parent (Foo) __get() called for $var\n";
        }
    }

   class bar extends foo
   {
        private $var;
        public function __construct()
        {
            $this->var = "25\n";
        }

        public function getVar()
        {
            return $this->var;
        }
    }

    $obj = new bar();
    echo $obj->var;
    echo $obj->getVar();
?>
```
```
output:
$ php test.php
Parent (Foo) __get() called for var
25


q:
I just found out that by converting PNG32 to PNG8 via Photoshop will fix the PNG transparency bug in IE<=6.

So I had this thought that instead of serving PNG32 to all browser, why not serve PNG8 if the client is using IE<=6.

I'm not really an expert when it comes to htaccess/httpd directives so I'm here for help.

The title is the psuedocode itself.

[A]
Put this in your .htaccess
```
```
RewriteEngine on
RewriteRule ^/(.*)\.png$ /$18.png [L,QSA]
```
```
Should work.


q:
How do I write the CC logo in HTML, is there something like &copy; (which gives ©)?

(CC stands for Creative Commons).

[A]
As far as I know, there is no character for this, so you'll have to use a graphic.
There are some nice ones
here
. By the way, on this page, there's also a logo font you could use in HTML, but this won't show correctly for other users that don't have the font installed.


q:
in my flex application, I created a Tilelist. In this Tilelist, I am using an ItemRenderer to create a box consisting of an image and an VSlider in each tile.

The tile need to be dragable when you click on the image, but not dragable when you slide the slider. How can I achieve this ? I have been scratching my head searching on Google for one day and I have really no idea.

I look forward to your help.
Thank you.

[A]
I found a solution to my problem, however it may not be the best one.
Using this :
```
```
public var overImage:Boolean = false;

        public function checkAllow(evt:DragEvent):void {

            if(overImage == false)
            {
                evt.preventDefault()
            }
        }

        public function isOverImage():void {
            overImage = true;
        }

        public function isOutImage():void {
            overImage = false;
        }
```
```
I call those functions like this :
On my image component
```
```
mouseOver="outerDocument.isOverImage()" mouseOut="outerDocument.isOutImage()"
```
```
And for my tilelist I did this
```
```
Tiles.addEventListener(DragEvent.DRAG_START, checkAllow);
```
```
Hope it helps some people.


q: I am trying to find out how much memory my application is consuming from within the program itself. The memory usage I am looking for is the number reported in the "Mem Usage" column on the Processes tab of Windows Task Manager.

[A]
A good starting point would be
GetProcessMemoryInfo
, which reports various memory info about the specified process. You can pass
```
GetCurrentProcess()
```
as the process handle in order to get information about the calling process.
Probably the
```
WorkingSetSize
```
member of
```
PROCESS_MEMORY_COUNTERS
```
is the closest match to the Mem Usage coulmn in task manager, but it's not going to be exactly the same. I would experiment with the different values to find the one that's closest to your needs.


q: I want to select a bunch of spans in a div whose CSS contains a particular background color. How do I achieve this?

[A]
Use the attribute selector [attribute=value] to look for a certain attribute value.
```
```
#id_of_the_div span[background-color=rgb(255,255,255)]
```
```


q: I'm trying to pull data from an ODBC app to SQL2005(dev ed) DB on an hourly basis.  When I run SSIS the option to import all tables and views is grayed out and forces your to write a query. How would I go about setting up a SSIS integration service to update ALL 250 some tables on an hourly basis.

[A]
perhaps you could rephrase your question a little, I am not 100% sure what you are asking here. Are you trying to get data into SQL Server from an application via SSIS with the Data Transform task using an ODBC connection to the Application?
Anyhoo, the simple answer to the MS Access part of your question is "hell no" MS Access is never, ever the answer to anything ;-)
I would be inclined to find out why the tables and views are greyed out and fix that issue. (not enough info in this question to determine why they are greyed out)


q:
I just want ask the steps when trying to create a simple SQL select statement in UNIX inside/within IF..THEN..FI statement.

I know how to use the 'select' and 'if..then' statements in SQL*Plus, but I'm having a difficulties having a UNIX script to point to variables: If 'ABC' to 'Select...'

Example:

if [ "$?" = 'ABC' ]
then
    SELECT employid, name, age FROM tablename;
else
    exit 1
fi

if [ "$?" = 'XYZ' ]
then
    SELECT employid, name, age FROM tablename;
else
    exit 1
fi

How do I put it in a UNIX script more correctly syntax wise and right to the point?

Thanks.

[A]
This sounds like you're trying to embed SQLPlus in a shell script.  From memory the incantation should look something like:
```
```
if [ $? -eq ABC ]; then
SQLPLUS /S USER/PASS@Instance <<EOF
SET echo off;
SET pagesize 0;
SET heading off;
SPOOL foo.out
select foo from bar
EOF
fi
```
```
Everything between the SQLPLUS and EOF is passed to SQLPlus, so we have some statements to control the formatting (you may want different ones) and the actual query.  The SPOOL command in the SQLPlus script sends the output to a file.  For more detailed docs on using SQLPlus, You can download them from
Oracle's web site.


q: I know they're using a jQuery plugin, but I can't seem to find which one they used. In particular, what I'm looking for is autocomplete with exactly the same functionality as SO's autocomplete, where it will perform an AJAX command with each new word typed in and allow you to select one from a dropdown.

[A]
Note that the tag editor
has been completely re-written now
, and no longer resembles the original, simple text box w/ suggestion drop-down that adorned the site for nearly three years.
If you're interested in the new form, see this Meta question:
https://meta.stackexchange.com/questions/102510/can-i-use-the-tag-textbox-script
Autocomplete
is the plugin used originally, albeit with various tweaks and customizations made to it over the years.


q:
I run a series of time consuming operations on a background worker thread.  At various stages I update a (windows form) progress bar by invoking a delegate.  However, one of the more time operations occurs on a single line of code.

Is it possible to :

a) Update the UI while that single line of code is being executed, or at least display an animated icon that shows the user that work is being done.

b) Let the user cancel the background worker thread while that single line of code is being executed

[A]
Unfortunately, probably not.  The background worker thread needs to call ReportProgress to update the UI thread, and it needs to watch the CancellationPending to know whether it should stop or not.  So, if your worker thread is running along-running operation in a single line, there's no way to make this work.
Perhaps, I've misunderstood, so here's code that simulates what I'm getting at:
```
```
public void DoWork() {
    System.Threading.Thread.Sleep(10000);

    // won't execute until the sleep is over
    bgWorker.ReportProgress(100);
}
```
```


q:
Recently I had to move one of my web applications to a new hosting provider. The mail and web service is still held on the old hosting site however, when I try to send an email from the new server,I get an error;

"The server rejected one or more recipient addresses. The server response was:

450 <email_address>: Recipient address rejected: Greylisted for 5 minutes

I asked my old hosting provider what I need to do to fix this and they replied with

The mail server operates on POP before
  SMTP. If a valid POP login is not
  received before sending mail through
  the server, then the mail is
  greylisted and held for 5 minutes
  before a retry.

To prevent this, simply do a Receive
  before sending mail

Does anyone have any idea how I do a POP before SMTP in C#?

[A]
i'm not sure how C# would handle the specifics (sockets?), but basically you just want to make a connection to your new POP server. here's a sample POP transaction:
```
```
$ telnet new-pop-server.com 110
Connected to new-pop-server.com.
Escape character is '^]'.
+OK
USER <username>
+OK
PASS <password>
+OK               // you're authenticated at this point
LIST
+OK
.                 // no new messages!
QUIT
+OK
```
```
once you're authorized you should be able to send your mail programatically. (USER, PASS, LIST, QUIT) are all commands you would send (
pop3 RFC
).


q:
want to pass boost::bind to a method expecting a plain function pointer (same signature).

typedef void TriggerProc_type(Variable*,void*);
void InitVariable(TriggerProc_type *proc);
boost::function<void (Variable*, void*)> triggerProc ...
InitVariable(triggerProc);

error C2664: 'InitVariable' : cannot convert parameter 1 from
'boost::function<Signature>' to 'void (__cdecl *)(type *,void *)'

I can avoid storing a boost::function and just pass the bound functor directly, but then I get similar error:

error C2664: 'blah(void (__cdecl *)(type *,void *))' : cannot convert parameter
1 from 'boost::_bi::bind_t<R,F,L>' to 'void (__cdecl *)(type *,void *)'

[A]
I think you want to use the target() member function of boost::function (isn't that a mouthful...)
```
```
#include <boost/function.hpp>
#include <iostream>

int f(int x)
{
  return x + x;
}

typedef int (*pointer_to_func)(int);

int
main()
{
  boost::function<int(int x)> g(f);

  if(*g.target<pointer_to_func>() == f) {
    std::cout << "g contains f" << std::endl;
  } else {
    std::cout << "g does not contain f" << std::endl;
  }

  return 0;
}
```
```


q:
In Visual Studio, How do I show all classes inherited from a base class?

For example, in ASP.NET MVC there are several 'ActionResult' types -- and they all inherit from / implement the base class ActionResult.

It looks like unless you just 'know' that View and Json are valid ActionResult types, there is no way you can easily find this information out.

Please prove me wrong.

Is there something in the object browser that makes this easy to find out?

I'm even up for suggestions of tools outside of Visual Studio to discover this information about various classes.  For example: is there something in Resharper that will help me out?

[A]
Sure,
Resharper
can do this. And much more.
Just right click on type name in any place and choose "Go To Inheritor" in context menu.
"Go To Inheritor" can be also applied to method for navigating to overrides and an interface method's implementations. For an interface you could call "Find Usages Advanced" again, just right click) where to find all extendings and implementations. For a type - derived types.
And my favorite feature - click with holding Control on any type/method for navigating to its declaration.
I think it's a must-have tool for .net developers.
In Resharper 9.2, on any type in source code, rt-click "Find Usage Advanced", select Find="Derived" and Scope="Solutions and Libraries".
For example, to find all inheritors (both in the library and your code) of some base class in an included DLL from any vendor, declare a variable in your code with that base class. Then right-click on that base class name you just typed.


q: I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?

[A]
With:
```
```
decorator(original_function)()
```
```
Without:
```
```
original_function()
```
```
A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some
documentation
might help clarify things.