q:
I'm using AspectJ to advice all the public methods which do have an argument of a chosen class. I tried the following:

pointcut permissionCheckMethods(Session sess) :
    (execution(public * *(.., Session)) && args(*, sess));

This is working wonderfully for methods with at least 2 arguments:

public void delete(Object item, Session currentSession);

but it does not work with methods like:

public List listAll(Session currentSession);

How may I change my pointcut to advice both methods executions? In other words: I expected the ".." wildcard to represent "zero or more arguments", but it looks like it means instead "one or more"...

[A]
Oh well... I worked that around with this nasty trick. Still waiting for someone to show up with an "official" pointcut definition.
```
```
pointcut permissionCheckMethods(EhealthSession eheSess) :
    (execution(public * *(.., EhealthSession)) && args(*, eheSess))
    && !within(it.___.security.PermissionsCheck);

pointcut permissionCheckMethods2(EhealthSession eheSess) :
    (execution(public * *(EhealthSession)) && args(eheSess))
    && !within(it.___.security.PermissionsCheck)
    && !within(it.___.app.impl.EhealthApplicationImpl);

before(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods(eheSess)
{
    Signature sig = thisJoinPointStaticPart.getSignature();
    check(eheSess, sig);
}

before(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods2(eheSess)
{
    Signature sig = thisJoinPointStaticPart.getSignature();
    check(eheSess, sig);
}
```
```


q:
What is exactly the function of Python's Global Interpreter Lock?
Do other languages that are compiled to bytecode employ a similar mechanism?

[A]
The following is from the
official Python/C API Reference Manual
:
The Python interpreter is not fully
  thread safe. In order to support
  multi-threaded Python programs,
  there's a global lock that must be
  held by the current thread before it
  can safely access Python objects.
  Without the lock, even the simplest
  operations could cause problems in a
  multi-threaded program: for example,
  when two threads simultaneously
  increment the reference count of the
  same object, the reference count could
  end up being incremented only once
  instead of twice.
Therefore, the rule exists that only
  the thread that has acquired the
  global interpreter lock may operate on
  Python objects or call Python/C API
  functions. In order to support
  multi-threaded Python programs, the
  interpreter regularly releases and
  reacquires the lock -- by default,
  every 100 bytecode instructions (this
  can be changed with
  sys.setcheckinterval()). The lock is
  also released and reacquired around
  potentially blocking I/O operations
  like reading or writing a file, so
  that other threads can run while the
  thread that requests the I/O is
  waiting for the I/O operation to
  complete.
I think it sums up the issue pretty well.

s: huggingface

c: devops

d: intermediate


q:
In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class:
http://docs.python.org/library/httplib.html#httplib.HTTPConnection

However, this is only a timeout for the connection to a server.  I am looking to set a timeout value for the request, not the connection.  This doesn't seem to be supported by httplib.

Is there any way to emulate this behavior?

[A]
You can set a global socket timeout
(*)
:
```
```
import socket

timeout = 10
socket.setdefaulttimeout(timeout)
```
```
(*)
EDIT
: As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of multiple socket operations (e.g. DNS requests or other things that might be abstracted away from an HTTP client). The timeout of the overall operation becomes unpredictable because of that.


q: I have some constants that represent the valid options in one of my model's fields. What's the best way to handle these constants in Ruby?

[A]
I put them directly in the model class, like so:
```
```
class MyClass < ActiveRecord::Base
  ACTIVE_STATUS = "active"
  INACTIVE_STATUS = "inactive"
  PENDING_STATUS = "pending"
end
```
```
Then, when using the model from another class, I reference the constants
```
```
@model.status = MyClass::ACTIVE_STATUS
@model.save
```
```


q:
Consider the following code:

<a href="#label2">GoTo Label2</a>
... [content here] ...
<a name="label0"></a>More content
<a name="label1"></a>More content
<a name="label2"></a>More content
<a name="label3"></a>More content
<a name="label4"></a>More content

Is there a way to emulate clicking on the "GoTo Label2" link to scroll to the appropriate region on the page through code?

EDIT: An acceptable alternative would be to scroll to an element with a unique-id, which already exists on my page.  I would be adding the anchor tags if this is a viable solution.

[A]
I suppose this will work:
```
```
window.location="<yourCurrentUri>#label2";
```
```


q:
I have a control that is basically functioning as a client-side timer countdown control.

I want to fire a server-side event when the count down has reached a certain time.

Does anyone have an idea how this could be done?

So, when timer counts down to 0, a server-side event is fired.

[A]
When you render the page create a client-side button that would do the action you want on postback. Then use
ClientScriptManager.GetPostBackEventReference
passing in the control as reference and add a client-side event to it using attributes as the example at the bottom of that link shows.
You can then see the Javascript it renders and use that in your function to trigger the correct server-side event.


q:
I have a dataset that contains 2 datatables they link together using a DataRelation.

it it possible to select from those tables into into one result set?

thanks,
Ofer

[A]
You can create JOIN tables with the VS DataSet editor, whcih combine your results - you can then write Select queries against that and call them from within your app.
To do it, simply create a new TableAdapter, then add BOTH tables into the editor (use the visual one), and select the fields you want to use from both tables, then write the relevant select functions.


q:
Usually, I need to retrieve data from a table in some range; for example, a separate page for each search result. In MySQL I use LIMIT keyword but in DB2 I don't know. Now I use this query for retrieve range of data.

SELECT *
FROM(
   SELECT
      SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO
      , DATA_KEY_VALUE
      , SHOW_PRIORITY
   FROM
      EMPLOYEE
   WHERE
      NAME LIKE 'DEL%'
   ORDER BY
      NAME DESC
   FETCH FIRST 20 ROWS ONLY
) AS TMP
ORDER BY
  TMP.RUNNING_NO ASC
FETCH FIRST 10 ROWS ONLY

but I know it's bad style. So, how to query for highest performance?

[A]
Not sure why you are creating the TMP table.  Isn't RUNNING_NO aready in ascending sequence?  I would think:
```
```
SELECT SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO,
       DATA_KEY_VALUE,
       SHOW_PRIORITY
  FROM EMPLOYEE
 WHERE NAME LIKE 'DEL%'
 ORDER BY NAME DESC
 FETCH FIRST 10 ROWS ONLY
```
```
would give the same results.
Having an INDEX over NAME on the EMPLOYEE table will boost performance of this query.


q: I am interested in using/learning RoR in a project where I have to use a .NET dll. Is Ruby capable of importing a .NET dll?

[A]
If you use IronRuby (Ruby implementation built on .Net) then it should be able to.  If you're already using .Net and want to try out Ruby then you might want to look into IronRuby.
Outside of IronRuby I'm not sure.  I haven't used Ruby myself, so I don't know what kinds of things it's capable of.


q:
I'm coding a small CMS to get a better understanding of how they work and to learn some new things about PHP. I have however come across a problem.

I want to use mod_rewrite (though if someone has a better solution I'm up for trying it) to produce nice clean URLs, so site.com/index.php?page=2 can instead be site.com/tools

By my understanding I need to alter my .htaccess file each time I add a new page and this is where I strike a problem, my PHP keeps telling me that I can't update it because it hasn't the permissions. A quick bit of chmod reveals that even with 777 permissions it can't do it, am I missing something?

My source for mod_rewrite instructions is currently this page here incase it is important/useful.

[A]
One approach is to rewrite everything to a handling script
```
```
RewriteEngine on
RewriteBase /

# only rewrite if the requested file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-s

# pass the rest of the request into index.php to handle
RewriteRule ^(.*)$ /index.php/$1 [L]
```
```
so if you have a request to
http://yourserver/foo/bar/
what you actually get is a request to
http://yourserver/index.php/foo/bar
- and you can leave index.php to decide what to do with /foo/bar (using $_SERVER['PATH_INFO'] -
tom
)
You only need to modify .htaccess the first time. All future requests for inexistent files can then be handled in PHP.
You might also find
the docs for mod_rewrite
useful - but keep it simple or prepare to lose a lot of sleep and hair tracking down obscure errors.


q:
I'm generating and showing a new WinForms window on top of a Main Window. How can I achieve that the original (Main Window) keeps the focus? Setting the focus back after showing the new window does not solve my problem because I need to prevent the Main Window's title bar from flickering. The new window has to stay on top of the Main Window so I have to set topMost=true. However, this makes no difference for the problem I think.

Thank you!

[A]
Setting the focus after you show the new form works fine. My taskbar does not flicker.
```
```
private void button1_Click(object sender, EventArgs e)
{
     Form2 f2 = new Form2();
     f2.TopMost = true;
     f2.Show();
     this.Focus();
}
```
```
Can I ask why you want to set the focus back on the main form because the new form will, by default, draw on top of the main window and you'll have to close or move the new form to view the main window.


q: Basically, I would like to check if I have rights to open the file before I actually try to open it; I do not want to use a try/catch for this check unless I have to. Is there a file access property I can check before hand?

[A]
I have done this countless times in the past, and nearly every time I was wrong to even make the attempt.
File permissions (even file existence) are
volatile
— they can change at any time.  Thanks to Murphy's Law this
especially
includes the brief period between when you check the file and when you try to open it. There are other reasons this can fail, too, such as locking or network availability and path resolution. An errant result is even more likely if you're in an area where you know you need to check first. Yet strangely enough it will never happen in your testing or development environments, which tend to be fairly static. This makes the problem difficult to track down later and makes it easy for this kind of bug to make it into production.
What this means is you must still be ready to handle the exception if file permissions or existence are bad, in spite of your check. Exception handling code is
required
, whether or not you check the file in advance, and good exception handler can provide
all
of the functionality of existence or permissions checks.
But isn't exception handling slow? I'm glad you asked. Yes, yes it is. In fact, unwinding the stack to handle an exception is up there with the slowest stuff you can do inside a single computer. However, it's important to remember that disk I/O is even slower — a
lot
slower — and calling the
```
.Exists()
```
function or checking permissions will always force an additional I/O operation on the file system.
Therefore, we see an initial check before trying to open the file is both redundant and wasteful. There is no additional benefit over exception handling. It will actually hurt, not help, your performance. It adds cost in terms of more code that must be maintained. Finally, it can introduce subtle bugs. There is just no upside at all to doing the initial check.
Instead, the correct thing here is immediately trying to open the file, with no initial check, and putting your effort into a good exception handler if it fails. The same is true whether you're checking permissions, locking, or even just whether or not the file exists.
In summary: the choice is paying the extra cost for file check every time with more code, or paying the smaller-but-still-bad cost for exception handling only some of the time and with less code.


q:
I am pretty new to php, but I am learning! I have a simple form on a client website. I am testing the form and when I click submit, I get the following error:

Form Mail Script

Wrong referrer (referring site). For security reasons the form can only be used, if the referring page is part of this website.

Note for the Admin: Please add the name of your server to the referrer variable in the index.php configuration file: mywebsite.com

Powered by Form Mail Script

I am looking through the forms configuration and support files but I do not understand exactly what it is I need to change.

Can someone please explain to me what the Admin note above means and how to fix it?

[A]
You are obviously using the Form Mail script on your page. It has a security feature that prevents other domains from submitting to the form. This is done to prevent bots from using the script to send out spam.
In the configuration for the form mail script or in the script itself, you will find an array or variable with the referrers listed. This is the sites that you want to allow calling of this form mail. You should add your own domain to this list or assign it to this variable.
Sorry, I haven't used this script, so I can't be more specific.


q:
It seems like there should be a simpler way than:

import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)

Is there?

[A]
Not necessarily simpler, but a different way, if you are more familiar with the re family.
```
```
import re, string
s = "string. With. Punctuation?" # Sample string
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
```
```


q:
Let's say we have defined a CSS class that is being applied to various elements on a page.

colourful
{
    color: #DD00DD;
    background-color: #330033;
}

People have complained about the colour, that they don't like pink/purple. So you want to give them the ability to change the style as they wish, and they can pick their favourite colours. You have a little colour-picker widget that invokes a Javascript function:

function changeColourful(colorRGB, backgroundColorRGB)
{
    // answer goes here
}

What goes in the body of that function?

The intent being that when the user picks a new colour on the colour-picker all the elements with class="colourful" will have their style changed.

[A]
Something like
```
```
function changeColourful(colorRGB, backgroundColorRGB)
 {changeColor (document, colorRGB, backgroundColorRGB)}

function changeColor (node, color, changeToColor)
{
   for(var ii = 0 ; ii < node.childNodes.length; ii++)
   {
     if(node.childNodes[ii].childNodes.length > 0)
     {
        changeColor(node.childNodes[ii], color, changeToColor);
     }

      if(node[ii].style.backgroundColor == color)
      {
        node[ii].style.backgroundColor = changeToColor;
      }

   }

}
```
```


q:
I'm using this XPath to get the value of a field:

//input[@type="hidden"][@name="val"]/@value

I get several results, but I only want the first. Using

//input[@type="hidden"][@name="val"]/@value[1]

Doesn't work. Once I have this, how do I pick up the value in Greasemonkey? I am trying things like:

alert("val " + val.snapshotItem);

But I think that's for the node, rather than the string.

[A]
For the XPath, try:
```
//input[@type="hidden" and @name="val" and position() = 1]/@value
```
For use in a GreaseMonkey script, do something like this:
```
```
var result = document.evaluate(
  "//input[@type='hidden' and @name='var' and position()=1]/@value",
  document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);

var hiddenval = result.snapshotItem(0);

if (hiddenval)
  alert("Found: " + hiddenval.nodeValue);
else
  alert("Not found.");
```
```
Strictly speaking: Using
```
"position()=1"
```
in the XPath filter is not absolutely necessary, because only the first returned result is going to be used anyway (via
```
snapshotItem(0)
```
). But why build a larger result set than you really need.
EDIT: Using an XPath result of the
```
ORDERED_NODE_SNAPSHOT_TYPE
```
type makes sure you get the nodes in
document order
. That means the first node of the result will also be the first node in the document.


q:
Just looking for the relevant documentation.  An example is not necessary, but would be appreciated.

We have a situation where we are having to create 100s of virtual directories manually, and it seems like automating this would be a good way to make the process more efficient for now.

Perhaps next year we can rework the server environment to allow something more sane, such as URL rewriting (unfortunately this does not seem feasible in the current cycle of the web application).  Isn't it great to inherit crap code?

~ William Riley-Land

[A]
NOT TESTED (from an old code base and written by a former contractor of mine)
```
```
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.IO;

namespace Common.DirectoryServices
{
    public class IISManager
    {

        private string _webSiteID;

        public string WebSiteID
        {
            get { return _webSiteID; }
            set { _webSiteID = value; }
        }

        private string _strServerName;
        public string ServerName
        {
            get
            {
                return _strServerName;
            }
            set
            {
                _strServerName = value;
            }
        }

        private string _strVDirName;
        public string VDirName
        {
            get
            {
                return _strVDirName;
            }
            set
            {
                _strVDirName = value;
            }
        }

        private string _strPhysicalPath;
        public string PhysicalPath
        {
            get
            {
                return _strPhysicalPath;
            }
            set
            {
                _strPhysicalPath = value;
            }
        }

        private VDirectoryType _directoryType;
        public VDirectoryType DirectoryType
        {
            get
            {
                return _directoryType;
            }
            set
            {
                _directoryType = value;
            }
        }

        public enum VDirectoryType
        {
            FTP_DIR, WEB_IIS_DIR
        };

        public string CreateVDir()
        {
            System.DirectoryServices.DirectoryEntry oDE;
            System.DirectoryServices.DirectoryEntries oDC;
            System.DirectoryServices.DirectoryEntry oVirDir;
            //try
           // {
                //check whether to create FTP or Web IIS Virtual Directory
                if (this.DirectoryType == VDirectoryType.WEB_IIS_DIR)
                {
                    oDE = new DirectoryEntry("IIS://" +
                          this._strServerName + "/W3SVC/" + _webSiteID + "/Root");
                }
                else
                {
                    oDE = new DirectoryEntry("IIS://" +
                          this._strServerName + "/MSFTPSVC/1/Root");
                }

                //Get Default Web Site
                oDC = oDE.Children;

                //Add row
                oVirDir = oDC.Add(this._strVDirName,
                          oDE.SchemaClassName.ToString());

                //Commit changes for Schema class File
                oVirDir.CommitChanges();

                //Create physical path if it does not exists
                if (!Directory.Exists(this._strPhysicalPath))
                {
                    Directory.CreateDirectory(this._strPhysicalPath);
                }

                //Set virtual directory to physical path
                oVirDir.Properties["Path"].Value = this._strPhysicalPath;

                //Set read access
                oVirDir.Properties["AccessRead"][0] = true;

                //Create Application for IIS Application (as for ASP.NET)
                if (this.DirectoryType == VDirectoryType.WEB_IIS_DIR)
                {
                    oVirDir.Invoke("AppCreate", true);
                    oVirDir.Properties["AppFriendlyName"][0] = this._strVDirName;
                }

                //Save all the changes
                oVirDir.CommitChanges();

                return null;

           // }
            //catch (Exception exc)
            //{
             //   return exc.Message.ToString();
            //}
        }
    }
}
```
```


q:
We have simple web-based data entry internal business app.
Now business wants to be able to attach a document to a row in the database that represents business entity. Document can be Word, Excel, PDF.

How can we do that?

I think creating yet another home grown document management system is not a good idea.
Instead we can try to use an third party document management system and integrate tightly form our app.
Ideally all user interface will stay within application, without going to an external system.
Is sharepoint or documentum capable of doing it?
What other options are there?

The application platform is Java/Websphere. We ave both Windows and Unix infrastructure available.

[A]
I think any document management system can do what you are requesting. At one time we did something similar with Sharepoint. The systems expose an API that allows you to query documents that are stored. Exactly how the integration happens depends on the solution you go for.
You need to consider the platform on which your current system is built when choosing because different solutions support different integration technologies. For instance, if your current system uses .NET then Sharepoint would be easy to integrate.
Many document management systems use a backend database like SQL server and integration could be as easy as querying the backend database from your application.


q: How do I tell if my application (compiled in Visual Studio 2008 as Any CPU) is running as a 32-bit or 64-bit application?

[A]
I found this code from
Martijn Boven
that does the trick:
```
```
public static bool Is64BitMode() {
    return System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8;
}
```
```


q: How do you programmatically obtain a picture of a .Net control?

[A]
There's a method on every control called
DrawToBitmap
.  You don't need to p/invoke to do this.
```
```
Control c = new TextBox();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(c.Width, c.Height);
c.DrawToBitmap(bmp, c.ClientRectangle);
```
```


q: if A is extension use case (not base use case), can A be directly referenced by the actor?

[A]
You can make the case that there are two kinds of use cases:
Abstract -- not directly experience by an actor, but extensions ("subclasses") are.
Concrete -- experienced by an actor.


q:
Can someone post a simple example of starting two (Object Oriented) threads in C++.

I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.

I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.

[A]
It largely depends on the library you decide to use. For instance, if you use the
wxWidgets
library, the creation of a thread would look like this:
```
```
class RThread : public wxThread {

public:
    RThread()
        : wxThread(wxTHREAD_JOINABLE){
    }
private:
    RThread(const RThread &copy);

public:
    void *Entry(void){
        //Do...

        return 0;
    }

};

wxThread *CreateThread() {
    //Create thread
    wxThread *_hThread = new RThread();

    //Start thread
    _hThread->Create();
    _hThread->Run();

    return _hThread;
}
```
```
If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it.
More information is in the
wxThread documentation
.


q:
I'm trying to be responsible with my "DOM" references in this little Flash 8/AS2 project.

What has become increasingly frustrating is obtaining references to other movie clips and objects.  For example, currently my code to access the submit button of a form looks something like this

var b:Button = _level0.instance4.submitBtn;

I was hoping there was an instance-retrieval method for AS2 similar to AS3's MovieClip.getChildByName() or even Javascript's document.getElementById().  Because hard-coding the names of these anonymous instances (like instance4 in the above) just feel really, really dirty.

But, I can't find anything of the sort at this AS2 Reference.

[A]
If the MovieClip was placed on the stage in the Flash IDE, you can give it a proper instance name in the properties panel.
If it was dynamically added, you can also give it a name, and additionally store a reference:
```
```
var my_MC=createEmptyMovieClip("instanceName", depth);
```
```
In either case, you can then adress them with
```
_parentClip.instanceName
```
or
```
my_MC.
```


q: Is there a programming language "below" Assembly?

[A]
Machine code
. Time it was programmers coded in the 1 and 0's of binary. Hex was considered an advance over this. That was before assembly, which uses the code's names and separates the parts of an instruction into its parts.


q:
It there any article/book that defines upper bounded design limits for WS timeouts? Do you timeout at the server or recommend the client specific timeouts too?

Is there a common best practice like "never design WS that can take longer than 60 seconds, use an asynchronous token pattern"

I am interested in knowing what you do or your opinion too.

[A]
Take the amount of data you are transfering via your web service an see how long the process takes.
Add 60 secs to that number and test.
If you can get it to timeout on a good connection then add 30 more seconds.
rinse and repeat.


q: Is there a limit to the length of a GET request?

[A]
Not in the
RFC
, no, but there are practical limits.
The HTTP protocol does not place any a priori limit on the length of
a URI. Servers MUST be able to handle the URI of any resource they
serve, and SHOULD be able to handle URIs of unbounded length if they
provide GET-based forms that could generate such URIs. A server
SHOULD return 414 (Request-URI Too Long) status if a URI is longer
than the server can handle (see section 10.4.15).
Note: Servers should be cautious about depending on URI lengths
above 255 bytes, because some older client or proxy implementations
may not properly support these lengths.


q:
Am I safe in casting a C++ bool to a Windows API BOOL via this construct

bool mybool = true;
BOOL apiboolean = mybool ? TRUE : FALSE;

I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears.

Thanks to Dima for (gently) pointing out my carelessness in the way I'd originally phrased the question.

[A]
Do you mean
```
```
bool b;
...
BOOL apiboolean = b ? TRUE : FALSE;
```
```
If so, then yes, this will work.


q:
A pattern that's started to show up a lot in one of the web apps I'm working are links that used to just be a regular a-tag link now need a popup box asking "are you sure?" before the link will go.  (If the user hits cancel, nothing happens.)

We've got a solution that works, but somehow we're a web app shop without a Javascript expert, so I'm left with this crawling feeling like there's a better way to get the job done.

So, JS experts, what's the most standards-compliant, cross-browser way to get this done?

(For the record, this is already a site that requires JS, so no need to have a "non-JS" version.  But, it does need to work in any and all reasonably modern browsers.)

(Also, for bonus points it would be nice if people with JS turned off didn't have the links  work, rather than bypassing the confirm box.)

[A]
Here's how we've been doing it:
```
```
Go to new page`

function goThere()
{
   if( confirm("Are you sure?") )
    {
       window.location.href="newPage.aspx";
    }
}
```
```
(EDIT: Code reformatted to avoid horizontal scroll)


q:
I got a quick question about running a directX application (C++) in a managed environment. I'm attempting to write a MDI tool (in C#) where the background of the parent window would be an embedded render window of directX (C++).

I've read ways that involved writing the C++ into a native dll, however it would be prefered to be able to have the C++ projects included within the solution (I dont even know if that's possible though). Eitherway, if you know of some helpful steps, hints, or if this is a bad idea in general, please let me know. Thanks!

[A]
First of all writing the C++ part in a different dll file doesn't mean that it couldn't be at the same solution as the C# project.
In order to use native DX to render on a managed window you need to pass the HWND window id (use form.WindowId.ToInt32) to the C++ D3Ddevice c'tor. after that each time you'll render using that device it would render on the .NET window.
To do this you probably need two saparate projects - a C++ dll & .NET project. use COM wrapper or p-invoke to pass the HWND to the C++ dll.


q:
I have a MS Access form with a Datasheet subform.

Using code, I change the ColumnHidden property of various of its columns.
But, when I close the form, I'm asked whether to save the table layout of the Datasheet's table.

How can I stop the form from asking the user to same the table layout continually?

Do I have no choice but to change the Datasheet to a regular subform?

[A]
If you are always hiding the same columns - create a query that only has the columns you want displayed and use that as the source of your subform.
If you still need some hidden fields (child keys, etc.) you will have to create a regular form. It's not too bad:
just base it on your table,
drag your columns onto the form (formatting, and placement doesn't matter)
set it to datasheet view
edit labels (these become column headings)
change the tab order (this controls the order the columns are displayed)
view the datasheet and hide the columns you want
save the form
add this form as a subform to the main form


q: In VIM in command line mode a "%" denotes the current file, "cword" denotes the current word under the cursor. I want to create a shortcut where I need the current line number. What is the symbol which denotes this?

[A]
. (dot) stands for the current line.
To clarify:
This is meant for stuff like
```
:1,.s/foo/bar/g
```
which will transform every
```
foo
```
to
```
bar
```
from the beginning of the file up to the current line.
I don't know know of a way to get the current line number expanded for a shell command, which is what you are trying to do by doing
```
:!echo .
```
You can find out about the expansions that are done (like
```
%
```
and
```
#
```
for example) in
```
:he cmdline-special
```
.


q:
I've got a WAR file that I need to add two files to. Currently, I'm doing this:

File war = new File(DIRECTORY, "server.war");
JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war)));

//Add file 1
File file = new File(DIRECTORY, "file1.jar");
InputStream is = new BufferedInputStream(new FileInputStream(file));
ZipEntry e = new ZipEntry("file1.jar");
zos.putNextEntry(e);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf, 0, buf.length)) != -1) {
    zos.write(buf, 0, len);
}
is.close();
zos.closeEntry();

//repeat for file 2

zos.close();

The result is that the previous contents get clobbered: the WAR has only the 2 files I just added in it. Is there some sort of append mode that I'm not using or what?

[A]
Yeah, there's an extra boolean argument to the
FileOutputStream constructor
which lets you force it to append to the file rather than overwrite it. Change your code to
```
```
JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war, True)));
```
```
and it should work the way you want.


q:
We are in a Windows environment and looking to automate this process for non-company machines.  If a vendor comes on site, we'd like to be able to have him/her hit a website that can perform a quick scan of the workstation to determine if they have the proper MS KB patches and if their virus scanner dats are up to date.

I can scan for the KB updates relatively easy, what I'm having a hard time finding is a way to check the virus dat status and since there are so many different engines out there, it seemed to make sense to use the (built into XP at least) proprietary MS security center stuff.

Eventually we'd like to have our routers redirect non-company machines to a website that will force validation, but until that point it will be a manual process.

Any thoughts?

[A]
In Windows Vista there are some new APIs to interface with the Security Center component status:
http://msdn2.microsoft.com/en-us/library/bb963845(VS.85).aspx
Through WMI, here's a VBS code snippet I checked out on
http://social.msdn.microsoft.com/forums/en-US/windowssecurity/thread/bd97d9e6-75c1-4f58-9573-9009df5de19b/
to dump Antivirus product information:
```
```
Set oWMI = GetObject
("winmgmts:{impersonationLevel=impersonate}!\\.\root\SecurityCenter")
    Set colItems = oWMI.ExecQuery("Select * from AntiVirusProduct")

    For Each objAntiVirusProduct In colItems
    msg = msg & "companyName: " & objAntiVirusProduct.companyName & vbCrLf
    msg = msg & "displayName: " & objAntiVirusProduct.displayName & vbCrLf
    msg = msg & "instanceGuid: " & objAntiVirusProduct.instanceGuid & vbCrLf
    msg = msg & "onAccessScanningEnabled: "
 & objAntiVirusProduct.onAccessScanningEnabled & vbCrLf
    msg = msg & "productUptoDate: " & objAntiVirusProduct.productUptoDate & vbCrLf
    msg = msg & "versionNumber: " & objAntiVirusProduct.versionNumber & vbCrLf
    msg = msg & vbCrLf

    Next

    WScript.Echo msg
```
```


q:
How would I format the standard RSS pubDate string as something closer to ASP.NET's DateTime?

So, from this:

Wed, 29 Oct 2008 14:14:48 +0000

to this:

10/29/2008 2:14 PM

[A]
Something close to this should work:
```
```
string orig = "Wed, 29 Oct 2008 14:14:48 +0000";
string newstring = String.Format("{0:MM/dd/yyyy hh:mm tt}", DateTime.Parse(orig.Remove(orig.IndexOf(" +"))));
```
```
Taken from
http://blog.stevex.net/index.php/string-formatting-in-csharp/


q: I'm using linq to pull back an object (i.e. customer) that might have a collection of other objects(customer.orders).  I would be nice if I can pass this list of customers to the ultragrid and a hierarchical view of customers and thier orders displayed on databind.  When I try this, I just get customers.  Anyone know how to get this to work with non dataset objects?

[A]
Figured it out.  IList collection works and will create bands for properties of your domain object if it is an
```
IList<T>
```
.  Just make sure that
```
DisplayLayout.ViewStyle                 = ViewStyle.MultiBand
```
.


q: Are there any drawbacks to using the STL or templates. Are there any situations for which they are inappropriate.

[A]
First, you should use probably use them if they help you solve your problem.  Templates are a very important part of C++ and have been part of the standard for years.  STL is very powerful and fast at run time and should be supported on all decent compilers, but of course there are issues.
If you have a really old compiler, STL might not be completely supported.
The thread-safety of the STL implementation might be work for your application
Templates can lead to slower compile-times and possibly larger executable, especially with older compilers.
Compilers often produce incomprehensible error messages on code using templates.
just to name a few, but the drawbacks of not using them are likely to be much greater.


q:
I really like the Flex framework, however I routinely deal with SWF files that are ~ 500KB.

I don't know at what point a file considered to be "too big" to be served on the internet, but I would assume that a 500KB download just to use a web application would certainly annoy some users.

Are there any tips or techniques on reducing the size of compiled SWFS?

As a side note, the 500KB SWF file really isn't that big of application...

[A]
This answer is a little more general than you're probably looking for (it applies to all web apps, whether Flash/Flex-based or HTML/CSS/JS based or whatever), but...
It depends a lot on the use case for your application. Is it an application that will be loaded all day and pull in updates as necessary (like Gmail) or is it something that will be launched, used, then closed?
If the former, besides reducing resource size, you are probably alright here. It makes more sense to get the downloading all out of the way at once, rather than to expect the user to tolerate delays at every turn.
If the latter, you should lazy-load as much as possible. In other words, for example, instead of embedding all of the application's graphics into the SWF, load them with
```
URLRequest
```
s or whatever method necessary when they are needed. A quicker launch will "feel" faster and more than make up for the increased HTTP requests over a short time.


q:
I am coding in ColdFusion, but trying to stay in cfscript, so I have a function that allows me to pass in a query to run it with

<cfquery blah >
  #query#
</cfquery>

Somehow though, when I construct my queries with sql = "SELECT * FROM a WHERE b='#c#'"  and pass it in, ColdFusion has replaced the single quotes with 2 single quotes.  so it becomes  WHERE b=''c'' in the final query.

I have tried creating the strings a lot of different ways, but I cannot get it to leave just one quote.  Even doing a string replace has no effect.

Any idea why this is happening?  It is ruining my hopes of living in cfscript for the duration of this project

[A]
ColdFusion, by design, escapes single quotes when interpolating variables within
```
<cfquery>
```
tags.
To do what you want, you need to use the
```
PreserveSingleQuotes()
```
function.
```
```
<cfquery ...>#PreserveSingleQuotes(query)#</cfquery>
```
```
This doesn't address, however, the danger of SQL injection to which you are exposing yourself.
Using
```
<cfqueryparam>
```
also allows your database to cache the query, which in most cases will improve performance.
It might be helpful to read
an old Ben Forta column
and
a recent post by Brad Wood
for more information about the benefits of using
```
<cfqueryparam>
```
.


q:
I'm running an application (web service) in tomcat with TLS enabled (with certificates both for the client and the server).

I want that my application will be able to send audit message (logging) when TLS handshake fails. For example I want to log when:

the client certificate is expired,

the client certificate is unknown (not in the server trust store)

any other  handshake failure

Is there any event that I can catch and handle in order to do that?

My application is web service based and is running in tomcat. Tomcat is handling all network and the TLS layers, and the application does not aware of that.

As I don't open any socket myself, where should I catch this Exception?

[A]
Since I spent the past week debugging Tomcat's SSL configuration, I am pretty sure catching
```
javax.net.ssl.SSLHandshakeException
```
in your code and logging it should take care of all three of those errors.
When you instantiate a new webservice connection in your application, that is when the exception will occur.


q:
I'm consuming an axis 1.4 web service that returns soap responses that I want to unmarshal into my domain objects using jaxb annotations.  My initial tests worked very well until some of the returned messages had multiRef elements. Objects that were marshalled using multiRef were showing up as null in my client side annotated model objects.

My question is does JAXB support unmarshalling soap responses with multiRef elements?  If so, how? and if not, does anybody know of a better way to unmarshal axis 1.4 soap responses into my domain model in java?

[A]
In case of web services JAXB doesn't come alone, but as data binding part of ws client framework. So I assume your question is how to use JAXB as data binding within axis 1.4. In general I think there is no easy way to achieve that, have a look at the following thread in axis-user mailing list:
Specify JAXB generated complex types to Axis web service
.
If you can upgrade to consume web service with axis2 then it should be much easier since axis2 comes with pluggable data binding architecture including integrated jaxb implementation.


q:
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?

This is how far I got by now:

Script receives image via HTML Form Post and is processed by the following code

...
incomming_image = self.request.get("img")
image = db.Blob(incomming_image)
...

I found mimetypes.guess_type, but it does not work for me.

[A]
If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data.  The format for this is:
```
```
Start Marker  | JFIF Marker | Header Length | Identifier
0xff, 0xd8    | 0xff, 0xe0  |    2-bytes    | "JFIF\0"
```
```
so a quick recogniser would be:
```
```
def is_jpg(filename):
    data = open(filename,'rb').read(11)
    if data[:4] != '\xff\xd8\xff\xe0': return False
    if data[6:] != 'JFIF\0': return False
    return True
```
```
However this won't catch any bad data in the body.  If you want a more robust check, you could try loading it with
PIL
.  eg:
```
```
from PIL import Image
def is_jpg(filename):
    try:
        i=Image.open(filename)
        return i.format =='JPEG'
    except IOError:
        return False
```
```


q:
I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best?

1)

void example()
{
    lock (mutex)
    {
    //...
    }
    return myData;
}

2)

void example()
{
    lock (mutex)
    {
    //...
    return myData;
    }

}

Which one should I use?

[A]
It doesn't make any difference; they're both translated to the same thing by the compiler.
To clarify, either is effectively translated to something with the following semantics:
```
```
T myData;
Monitor.Enter(mutex)
try
{
    myData= // something
}
finally
{
    Monitor.Exit(mutex);
}

return myData;
```
```


q: Is there any way in JavaScript to create a "weak reference" to another object? Here is the wiki page describing what a weak reference is. Here is another article that describes them in Java. Can anyone think of a way to implement this behavior in JavaScript?

[A]
http://www.jibbering.com/faq/faq_notes/closures.html
ECMAScript uses automatic garbage collection. The specification does not define the details, leaving that to the implementers to sort out, and some implementations are known to give a very low priority to their garbage collection operations. But the general idea is that if an object becomes un-referable (by having no remaining references to it left accessible to executing code) it becomes available for garbage collection and will at some future point be destroyed and any resources it is consuming freed and returned to the system for re-use.
This would normally be the case upon exiting an execution context. The scope chain structure, the Activation/Variable object and any objects created within the execution context, including function objects, would no longer be accessible and so would become available for garbage collection.
Meaning there are no weak ones only ones that no longer become available.


q:
I'm trying to figure out a way to detect files that are not opened for editing but have nevertheless been modified locally. p4 fstat returns a value headModTime for any given file, but this is the change time in the depot, which should not be equal to the filesystem's stat last modified time.

I'm hoping that there exists a more lightweight operation than backing up the original file, forcing a sync of the file, and then running a diff. Ideas?

[A]
From:
http://answers.perforce.com/articles/KB/3481/?q=disconnected&l=en_US&fs=Search&pn=1
See step 2 specifically:
2 . Next, open for "edit" any files that have changed:
```
```
p4 diff -se //myclient/... | p4 -x - edit
```
```
p4 diff -se returns the names of depot files whose corresponding client file differs in any way from the clients #have revision.


q:
I'm trying to submit a form with javascript. Firefox works fine but IE complains that "Object doesn't support this property or method" on the submit line of this function:

function submitPGV(formName, action)
{
    var gvString = "";

    pgVisibilities.each(function(pair) {
        gvString += pair.key + ":" + pair.value + ",";
    });

    $('pgv_input').value = gvString;

    var form = $(formName);
    form.action = action;
    form.submit();
}

Called here:

<a href="javascript:submitPGV('ProductGroupVisibility','config/productgroupvis/save')">

Here's the form:

<form id="ProductGroupVisibility" action="save" method="post">
    <input type="hidden" name="ows_gv..PGV" id="pgv_input" value=""/>
</form>

Any ideas?

[A]
Are you sure you have your JavaScript library loaded? (jQuery or Prototype)
It worked for me in IE7 with Prototype.
Try:
```
```
alert($('ProductGroupVisibility').id)
```
```
See if you get an error.


q:
I have a C# class the returns a List, using System.Collections.Generic Lists not F# List

I want to iterate though the list to find a object or not find it.  Here is how I would do it in C#.  How would I accomplish the similar thing in F#

foreach (AperioCaseObj caseObj in CaseList)
{
     if (caseObj.CaseId == "")
     {
     }
     else
     {
     }
}

[A]
See this example for iterating an integer generic list:
```
```
#light
open System.Collections.Generic

let genList = new List<int>()

genList.Add(1)
genList.Add(2)
genList.Add(3)

for x in genList do
  printf "%d" x
```
```


q:
Is there any performance reason to declare method parameters final in Java?

As in:

public void foo(int bar) { ... }

Versus:

public void foo(final int bar) { ... }

Assuming that bar is only read and never modified in foo().

[A]
Compilers that operate after class loading, such as JIT compilers, can take advantage of final methods. Consequently, methods declared final could have some performance benefit.
http://www.javaperformancetuning.com/tips/final.shtml
Oh and another good resource
http://mindprod.com/jgloss/final.html


q:
I need to see if a string value matches with an object value, but why won't this work?

public int countPacks(String flavour) {
    int counter = 0;
    for(int index = 0; index < packets.size(); index++) {
        if (packets.equals(flavour)) {
           counter ++;
        }
        else {
           System.out.println("You have not entered a correct flavour");
        }
    }
    return counter;
}

[A]
You probably mean something like
```
```
if (packets.get(index).equals(flavour)) {
   ...
```
```


q:
Where is the best place to add a method to the integer class in Rails?
I'd like to add a to_meters and to_miles methods.

[A]
Normally (and logically), integers can't be converted to miles or to meters. It sounds like you may want to create a new class like "Feet" or "inches" that is initialized with an integer, then contains methods like size_in_miles or size_in_meters. For convenience those methods could return decimal or float types, but you might also want to write a miles class or a meters class.
As an alternate method, you might want to create a static method in your new class that would have a signature like this:
```
Float feetToMiles(integer I)
```
that you would call
```
miles = Feet.feetToMiles(5280);
```
and get
```
miles = 1.0
```


q: I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.

[A]
If you're using a version of Java prior to 8... you can use
Joda Time
and
```
PeriodFormatter
```
. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using
```
Duration
```
for the most part - you can then call
```
toPeriod
```
(specifying whatever
```
PeriodType
```
you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a
```
Period
```
which you can format.
If you're using Java 8 or later: I'd normally suggest using
```
java.time.Duration
```
to represent the duration. You can then call
```
getSeconds()
```
or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a
single
negative sign in the output string. So something like:
```
```
public static String formatDuration(Duration duration) {
    long seconds = duration.getSeconds();
    long absSeconds = Math.abs(seconds);
    String positive = String.format(
        "%d:%02d:%02d",
        absSeconds / 3600,
        (absSeconds % 3600) / 60,
        absSeconds % 60);
    return seconds < 0 ? "-" + positive : positive;
}
```
```
Formatting this way is
reasonably
simple, if annoyingly manual. For
parsing
it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.


q:
I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending.
Ideas how this can be done?


q:
I'm writing a Rails plugin that includes some partials.  I'd like to test the partials, but I'm having a hard time setting up a test that will render them.  There's no associated controller, so I'm just faking one:

require 'action_controller'
require 'active_support'
require 'action_pack'
require 'action_view'

class MyTest < Test::Unit::TestCase
  def setup
    @renderer = ActionController::Base.new
    @renderer.append_view_path File.expand_path(File.join(File.dirname(__FILE__), '..', 'views'))
  end

  def test_renders_link
    result = @renderer.render(:partial => '/something')
    assert ...
  end
end

But that :render call always blows up.  I've tried using an ActionView::Base instead of an ActionController::Base, but that gets even less far.

Has anyone had any success?

[A]
checkout ActionView::TestCase -
http://api.rubyonrails.org/classes/ActionView/TestCase.html
You can also use these to test helpers, which I've found extremely helpful.
RSpec also has a way to test views:
http://rspec.info/documentation/rails/writing/views.html
Hope that helps!


q: I am about 2 minor revisions behind.

[A]
I'm one of those guys who always upgrade stuff. But have a look at the official
changelog
and see if the many bugfixes and new features are interesting enough to you.
I noticed 1.7.0 is out, and I'm definetly going to upgrade. But I need to test my applications after upgrading, since changes
could
break existing code.


q:
How can I create an instance of the following annotation (with all fields set to their default value).

    @Retention( RetentionPolicy.RUNTIME )
    public @interface Settings {
            String a() default "AAA";
            String b() default "BBB";
            String c() default "CCC";
    }

I tried new Settings(), but that does not seem to work...

[A]
If used with a method:
```
```
@Settings
public void myMethod() {
}
```
```
Now your annotation is initialized with default values.


q:
I am trying to convert a date with individual parts such as 12, 1, 2007 into a datetime in SQL Server 2005. I have tried the following:

CAST(DATEPART(year, DATE)+'-'+ DATEPART(month, DATE) +'-'+ DATEPART(day, DATE) AS DATETIME)

but this results in the wrong date. What is the correct way to turn the three date values into a proper datetime format.

[A]
Try CONVERT instead of CAST.
CONVERT allows a third parameter indicating the date format.
List of formats is here:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Update after another answer has been selected as the "correct" answer:
I don't really understand why an answer is selected that clearly depends on the NLS settings on your server, without indicating this restriction.


q:
We have a Windows Form application which hosts an IE browser control. Our users run the application and open links to documents stored in MOSS. We are trying to set the application up to pass in credentials of a service account so that we can avoid giving all users access to the MOSS site. We have used code found here which seems to work fine if the user is not currently signed on to our domain. However the application will not seem to pass in the service account authentication for any user which is already authenticated to the domain. In this case it just seems to use the authenticated users credentials.

How can we make this work?

[A]
Would impersonation not help here? You can run that bit of code (the form) under the guise of the service account user you're talking about and the browser control should then run within the same context.
the following links might help;
http://msdn.microsoft.com/en-us/library/b80a7e92.aspx
http://www.buro9.com/blog/2006/10/06/impersonating-a-user-in-c/


q: I'm trying to save the output of an vector image drawin in Java2D to an SWF file. There are great libraries for saving java2D output as things like SVG (BATIK) and PDF(itext) but I can't find one for SWF.  Any ideas?

[A]
Flash generally uses SVG as its native format.  You could export to SVG and then write a trivial Flash program to embed and display the image.  But why use Flash at all?  Most browsers are capable of displaying SVG nowadays.
Edit
: I don't know why I was downvoted for a clearly correct answer.  I can understand not being upvoted for not having the best answer (I fully acknowledge that this soltuion isn't ideal), but I really don't think it deserves a downvote.  You can consult the section in the middle of
this page
about embedding SVG in Flex programs.  For those of you who aren't familiar, Flex is an adobe toolkit/library that generates SWF programs that run in the normal Flash player.  Many (all?) of the normal Flash libraries are available to it.  It uses ActionScript.  For you doubters, here's a snippet showing exactly how you do it, copied from a Flex program I wrote.  It should go inside an MXML file.
```
```
<mx:Script><![CDATA[

[Embed(source="../images/down.svg")]
[Bindable]
protected var drillDownImage:Class;

]]></mx:Script>

<mx:HBox width="50%" horizontalAlign="right">
    <mx:Image id="drillDownButton" source="{drillDownImage}" height="20" width="20" click="drillDown();" />
</mx:HBox>
```
```
Now all you need to do is wrap that in an appropriate MXML file, maybe import some controls packages for the HBox and Image tags, and you're good to go.  The example in the link I provided should be sufficient for you to figure it out.


q:
I'm trying to understand what this method means as I'm reading this and have wondered what uses this may have. I don't quite understand the example given.

Can anyone give another explanation of it. Examples would help.

Thanks

[A]
The simplest example is a LinkButton. Drop one in a page and look at the HTML it generates. You'll see something like.
```
```
href="javascript:__doPostBack('ctl00$LinkButton1','')"
```
```
GetPostBackEventReference allows you to get that piece of JavaScript, so that you can trigger that postback from elsewhere. However you run that bit of JavaScript, a postback will happen and the OnClick event will fire on the server just as if you'd clicked the LinkButton. The example on MSDN wires up a similar bit of JavaScript to the links to trigger server-side events on the GridView.
The more practical uses are when you want to handle postbacks in a custom control. Your control implements
IPostBackEventHandler
to handle the postbacks on the server, and you use GetPostBackEventReference to get the JavaScript that will trigger those postbacks.


q: I need to read an Excel 2007 XLSX file in a Java application. Does anyone know of a good API to accomplish this task?

[A]
I had to do this in .NET and I couldn't find any API's out there.   My solution was to unzip the .xlsx, and dive right into manipulating the XML.   It's not so bad once you create your helper classes and such.
There are some "gotchas" like the nodes all have to be sorted according to the way excel expects them, that I didn't find in the official docs.  Excel has its own date timestamping, so you'll need to make a conversion formula.


q: Could someone please tell me which objects types can be tested using Regular Expressions in C#?

[A]
If I understand you correctly and you are asking which object types can be tested against regular expressions then the answer is: strings and only strings.
Thus your test would be:
```
```
if(obj is string){...}
```
```


q:
I always try to avoid to return string literals, because I fear they aren't defined outside of the function. But I'm not sure if this is the case. Let's take, for example, this function:

const char *
return_a_string(void)
{
    return "blah";
}

Is this correct code? It does work for me, but maybe it only works for my compiler (gcc). So the question is, do (string) literals have a scope or are they present/defined all the time.

[A]
This code is fine across all platforms.  The string gets compiled into the binary as a static string literal.  If you are on windows for example you can even open your .exe with notepad and search for the string itself.
Since it is a static string literal scope does not matter.
String pooling:
One thing to look out for is that in some cases, identical string literals can be "pooled" to save space in the executable file.  In this case each string literal that was the same could have the same memory address.  You should never assume that it will or will not be the case though.
In most compilers you can set whether or not to use static string pooling for stirng literals.
Maximum size of string literals:
Several compilers have a maximum size for the string literal.  For example with VC++ this is approximately 2,048 bytes.
Modifying a string literal gives undefined behavior:
Modifying a string literal should never be done.  It has an undefined behavior.
```
```
char * sz = "this is a test";
sz[0] = 'T'; //<--- undefined results
```
```
Wide string literals:
All of the above applies equally to wide string literals.
Example: L"this is a wide string literal";
The C++ standard states:
(section lex.string)
1 A  string  literal  is  a  sequence
  of  characters  (as  defined   in
lex.ccon
) surrounded by double quotes, optionally beginning with the
  letter L, as in "..." or L"...".  A string literal that does not begin
  with  L  is  an  ordinary string literal, also referred to as a narrow
  string literal.  An ordinary string literal has type "array of n
  const
  char"  and  static storage duration (
basic.stc
), where n is the
  size
  of the string as defined below, and  is  initialized  with  the  given
  characters.   A string literal that begins with L, such as L"asdf",
  is
  a wide string literal.  A wide string literal has  type  "array  of
  n
  const wchar_t" and has static storage duration, where n is the size
  of
  the string as defined below, and is initialized with the given charac-
  ters.
2 Whether  all  string  literals  are  distinct  (that is, are stored in
    nonoverlapping objects)  is  implementation-defined.   The  effect
  of
   attempting to modify a string literal is undefined.


q:
I have a site where I use CustomErrors in the web.config to specify a custom error page, and that's working just fine.  The custom 404 page is also specified in the IIS configuration (because if it's not, I don't get my custom 404 page).

But I have some logic that kicks in if a user gets a 404 that looks at their requested URL and make a navigation suggestion, if appropriate.  This logic relies on the aspxerrorpath value.  On my development PC, the aspxerrorpath is correctly appended to the URL, like so:
http://localhost:3092/FileNotFound.aspx?aspxerrorpath=/badpage.aspx, but on my test site, there's no aspxerrorpath appended to the URL, so all of my custom logic is bypassed and my suggestions don't work.  I'm not sure if this is an IIS config issue or something else.  The web server is Windows Server 2008 with IIS 7.

Any thoughts?

Many Thanks.

[A]
The aspxerrorpath parameter is passed if the error was caught by .NET (and the error page specified in web.config is used). This happens if you're using the development web server, or if IIS is configured not to check that the file exists.
If IIS checks that the file exists, then the custom error configured in IIS is used, and the requested URL is included in the querystring as something like
```
http://example.com/FileNotFound.aspx?404;http://example.com/badpage.aspx
```


q:
I recently added JQuery's date-picker control to a project. In Internet Exploder, I get the following error message:

Internet Explorer cannot open the
  Internet site

http://localhost/

Operation aborted

What is causing this problem?

[A]
Found this possibly related blog post:
http://blogs.msdn.com/ie/archive/2008/04/23/what-happened-to-operation-aborted.aspx
Or this:
http://weblogs.asp.net/infinitiesloop/archive/2006/11/02/Dealing-with-IE-_2600_quot_3B00_Operation-Aborted_2600_quot_3B002E00_-Or_2C00_-how-to-Crash-IE.aspx
Seems to be pretty common


q: In C++ when can a virtual function use static binding? If it is being accessed through a pointer, accessed directly, or never?

[A] Static binding can only be done when the object's type is totally unambiguous at compile time. I can only think of four places where an abstract object's type is unambiguous: in the constructor, in the destructor, when declared locally and within the same scope as a dynamic allocation. I don't know the standard that well so I couldn't say what it says about those four possibilities (I'd say the first two are statically bound, the third possible statically bound and the last not; although it probably says it's undefined or implementation dependent). Other than those points, the object being accessed through a base class pointer could be pointing to a derived class and the current translation unit has no way of knowing, so static binding is not possible. The function could be called with a pointer to the base class in one instance and a pointer to a derived class in another!


q:
Bascially I want to know the best way to hide/show an ASP.NET control from a Javascript function.  I figured I would just access the control in Javascript using:

var theControl = document.getElementById("txtEditBox");

Then just set the control's Visible property to true/false.  It doesn't seem to be working, I can't seem to figure out how to set "Visible" to true/false.  How can I do that?  Also, is that the best way to hide/show a ASP.NET control from a Javascript function?

Thanks,
Jeff

[A]
The "Visible" property of an ASP.NET control determines whether or not it will be rendered on the client (i.e. sent to the client). If it is false when the page is rendered, it will never arrive at the client.
So, you cannot, technically, set that property of the control.
That said, if the control
is
rendered on the client because the Visible property is true when the page is rendered, you can then hide it using javascript like this:
```
```
var theControl = document.getElementById("txtEditBox");
theControl.style.display = "none";

// to show it again:
theControl.style.display = "";
```
```
That assumes that the control's
```
id
```
attribute really is "txtEditBox" on the client and that it is already visible.
Also, is that the best way to hide/show a ASP.NET control from a Javascript function?
There is not necessarily a "best" way, although one better approach is to use CSS class definitions:
```
```
.invisible { display: none; }
```
```
When you want to hide something, dynamically apply that class to the element; when you want to show it again, remove it. Note, I believe this will only work for elements whose
```
display
```
value starts off as
```
block
```
.


q:
I have a computer at home which I can't access from work.  I'd like to be able to view results from work that my home computer produces.  The best idea I've come up with is an automated script running on my home computer that emails myself the results (from a text file or stderr/out) when complete.

I'm decent with bash (I have a linux machine) and java, so an answer using either or both of those would be ideal, but if there's something easier that's fine too.

I typically use gmail, but also have yahoo mail.

My question is this: what would be the basic steps in solving this problem?  I can do the nitty gritty stuff, but can't really get the big picture of how something like this would work.

Please help.

jbu

[A]
Traditionaly, with unix systems like Linux, you'd have an MTA, a mail transfer agent, on the computer that deals with sending e-mail.
This could be a full blown e-mail server like exim, or something simple like ssmtp that just sends messages on to a relaying SMTP server such as would be provided by your ISP.
This isn't neccessarily the case anymore, since mail clients like Thunderbird include their own MTA, much like mail clients on Windows do.
However, it is likely that your distro will install some MTA or other by default, if for no other reason than the fact that other things on your system, like cron, want to be able to send e-mail. Generally there will be a command line tool called sendmail (sendmail being the original MTA [citation needed], other MTAs maintain compatability with its interface and it has sort of become the standard) that can be used from a shell script to send an e-mail.


q:
We need to handle this event in the base form, regardless of which controls currently have focus. We have a couple of global key commands that need to work regardless of control focus.

This works by handling the PreviewKeyDown event in the form normally.  When we add a user control to the form, the event no longer fires.

Am I missing something trivial here?  Or do we need to handle the event in the user control first?

Thanks for your help!

Thanks Factor.  When I get more time :) I'll get it working 'properley'!

[A]
This is probably not the best way of doing it, but the first way that comes to mind.
In your forms constructor, after you call InitializeComponent(); do something like this:
```
```
foreach (Control control in this.Controls)
            {
                control.PreviewKeyDown += new PreviewKeyDownEventHandler(HandlePreviewKeyDown);
            }
```
```
I THINK that should do the trick. In your HandlePreviewKeyDown method you can then do your work and it should trigger regardless of which control has focus.


q:
I want to display the current host and database names in a view.

Where can I get these names?

Are there some predefined environment or global variables?

[A]
You can create a rails configuration object and obtain the necessary information from it:
```
```
config   = Rails::Configuration.new
host     = config.database_configuration[RAILS_ENV]["host"]
database = config.database_configuration[RAILS_ENV]["database"]
```
```
See the
documentation
for Rails::Configuration for details.


q:
I would like to write an application that will copy MP3 files to a SanDisk Sansa M240.  The SanDisk doesn't have a drive letter and uses MTP for file transfer.
I stumbled through the sample of connecting to the device at : http://blogs.msdn.com/dimeby8/archive/2006/09/27/774259.aspx

but once connected, I can't figure out how to actually copy files / create folders on the device.

I am very surprised that there aren't any .Net wrappers for this COM library.

[A]
It looks like dimeby8 posted some code that handles data transfers.  Check other posts in his blog, especially:
Sending MTP commands through WPD part 1
Sending MTP commands through WPD part 2
Sending MTP commands through WPD part 3


q:
It seems if I do something like

$file = fopen($filepath, "w");
$CR = curl_init();
curl_setopt($CR, CURLOPT_URL, $source_path);
curl_setopt($CR, CURLOPT_POST, 1);
curl_setopt($CR, CURLOPT_FAILONERROR, true);
curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($CR, CURLOPT_FILE, $file);
$result = curl_exec( $CR );
$error = curl_error( $CR );
print filesize($filepath);

I get a different result than if I just run

print filesize($filepath);

a second time.  My guess is that curl is still downloading when do a filesize().

[A]
Note that functions like filesize() cache their result, try adding a call to clearstatcache() above 'print filesize(...);'. Here is an example:
```
```
$file = '/tmp/test12345';
file_put_contents($file, 'hello');
echo filesize($file), "\n";
file_put_contents($file, 'hello world, this is a test');
echo filesize($file), "\n";
clearstatcache();
echo filesize($file), "\n";
```
```
See www.php.net/clearstatcache


q:
I have some code that looks like:

template<unsigned int A, unsigned int B>
int foo() {
  int v = 1;
  const int x = A - B;
  if (x > 0) {
    v = v << x;
  }
  bar(v);
}

gcc will complain about x being negative for certain instantiations of A, B; however,  I do perform a check to make sure it is non-negative.  What's the best way around this?  I know I can cast x to be unsigned int but that will cause warnings about x being larger than the width of v (since it is casting a negative number to be positive).  I know there is a work-around that involves creating a new templatized shift function, but I'd like to avoid that if possible.

[A]
Would this work?
```
```
const short unsigned int x = A - B;
```
```
It's cutting off a lot more bits than need to be cut off, but if your values of A - B are small enough...


q:
I am using getch() and my app crashes instantly. Including when doing:

int main()
{
    getch();
}

I can't find the link but supposedly the problem is that it needs to turn off buffering or something strange along those lines, and I still want cout to work along with cross platform code.

I was told to use std::cin.get(), but I'd like the app to quit when a key is pressed, not when the user typed in a letter or number then press enter to quit.

Is there any function for this? The code must work under Mac (my os) and Windows.

Linking/compiling is not an issue; I include <curses.h> and link with -lcurses in XCode, while Windows uses <conio.h>.

[A]
You have not exhibited a
```
```
#include <stdio.h>
```
```
or
```
```
#include <curses.h>
```
```
or similar line. Are you sure that you are linking against a library that
includes
```
getch()
```
?


q:
After considering the answers to my previous question (One SVN Repository or many?), I've decided to take the 4 or so repositories I have and consolidate them into one. This of course leads to the question, what's the best way to do this?

Is there a way to combine two or more repositories maintaining the version history for both?

Edit: I should also point out that I'm using Assembla.com, which does not provide access to the svnadmin command, AFAIK

Another edit: Does this even matter? If svnadmin works on URLs, then it's no problem then.

[A]
Yes, using
svnadmin dump
and
svnadmin load
.
Let's assume that you have to repositories, one with HEAD revision 100 and the other with HEAD revision 150.
You dump the first repository and load it in the new one: you end up with the full story of the first repository, from revision 0 to revision 150.
Then you dump the second repository and load it in the new one: it gets loaded with its full history, the only things that change are the actual revision numbers. The history of the second repository will be represented in the new repository from revision 151 to revision 250.
The full history of both repositories is preserver, only the revision numbers change for the repository that is imported for second.
The same of course applies for more than two repositories.
EDIT: I posted while you were editing, so I didn't see your note...


q:
The Dragon Book includes an exercise on converting integers to roman numerals using a syntax-directed translation scheme.

How can this be completed?

[A]
I would consider parsing from right-to-left.
First, I would map the units column:
```
```
0 -> ''
1 -> 'I'
2 -> 'II'
3 -> 'III'
4 -> 'IV'
...
9 -> 'IX'
```
```
Then, if there was a second column (e.g. second from the right = tens column), I would use that to map to
```
```
0 -> ''
1 -> 'X'
2 -> 'XX'
...
9 -> 'XC'
```
```
That would need to be prepended to the initial output.
Repeat for next columns (hundreds, thousands) until you run out of letters.
Double-check the number isn't '0' or negative.


q:
I have a Grid in WPF. The Grid has a transparent background (necessary) and each of the cells potentially has a different colored solid background, or maybe no background. When I put arbitrary content in these cells, when two adjacent cells both have colored backgrounds (same or different color, it doesn't matter) there is often (and unpredictably) a thin transparent line separating them, allowing you to see through the grid at that line.

Does anyone know how this could possibly be fixed?

Edit: Meant to mention it in my question, but I've tried enabling SnapsToDevicePixels anywhere and everywhere I can, to no avail.

[A]
My answer: Do a simple comparsion of the time taken to perform a simple Get/Edit/Update sequence.  I think you will find that LINQ to SQL is twice as quick.  I did a quick comparsion project when i was investigating the differences.
The results where:
Entity Framework 8,700 milliseconds
LINQ to SQL 3,100 milliseconds
Data-sets 2,000 milliseconds
So for me it was a simple question.  Use DataSets or use Linq-Sql - Entity Framework didn't even factor into it!
link text


q:
When beginning a new web project, i'm always a bit worried about removing pieces of the web.config.  It seems there are more entries than ever with Net 3.5 SP1.

Which bits of the .config do you delete for the following scenarios:

WCF Web Service, no Javascript support

Simple MVC Website

EDIT
Can someone document a basic list of things left in and taken out of the web.config for a simple website?

[A]
I usually just delete items from the web.config until things break -- a process of trial and error.
It's astonishing how much of web.config you can remove without affecting anything. It's gotten quite crufty in .NET 3.5.


q: What is the best option for a windows application that uses SQL server authentication? Should I create a single SQL account and manage the users inside the application (using a users table). Or should I create a SQL server account for each user. What is your experience? Thank you!

[A]
What about having SQL accounts based on the level of permissions needed for the task. For example you could have a read only account just used for reporting if your system has a lot of reporting. You would also need an account what has write access for people to change their passwords and other user admin tasks.
If you have situations where certain users are only going to have access to certain data I would have separate accounts for that data. The problem with using 1 account is you are saying that there is no SQL injection anywhere in your application. That is something everyone would strive for but sometimes perfect security is not possible, hence the multi-pronged approach.


q:
For example, if I have a unicode string, I can encode it as an ASCII string like so:

>>> u'\u003cfoo/\u003e'.encode('ascii')
'<foo/>'

However, I have e.g. this ASCII string:

'\u003foo\u003e'

... that I want to turn into the same ASCII string as in my first example above:

'<foo/>'

[A]
It's a little dangerous depending on where the string is coming from, but how about:
```
```
>>> s = '\u003cfoo\u003e'
>>> eval('u"'+s.replace('"', r'\"')+'"').encode('ascii')
'<foo>'
```
```


q:
I would like to read/write encrypted XML files using LINQ to XML. Does anyone know how to use encryption algorithms built into the .NET Framework to encrypt the Stream used by the XDocument object?

I did try it, but you can't set the CryptoStream to Read/Write access. It only support Read or Write, which causes LINQ to XML to throw an exception.

Update: It would be nice to read/write the document "on the fly", but I am only required to read the encrypted xml file, manipulate it, then write it back out encrypted again.

[A]
The easiest approach is probably an XDocument.Load(), Linq around, then XDocument.Save(). From a quick test app (go easy on non-disposed resources):
```
```
XDocument writeContacts = new XDocument(
   new XElement("contacts",
      new XElement("contact",
         new XElement("name", "Patrick Hines"),
         new XElement("phone", "206-555-0144",
             new XAttribute("type", "home")),
         new XElement("phone", "425-555-0145",
             new XAttribute("type", "work")),
         new XElement("address",
            new XElement("street1", "123 Main St"),
            new XElement("city", "Mercer Island"),
            new XElement("state", "WA"),
            new XElement("postal", "68042")
         )
      )
   )
);

Rijndael RijndaelAlg = Rijndael.Create();

FileStream writeStream = File.Open("data.xml", FileMode.Create);
CryptoStream cStream = new CryptoStream(writeStream,
    RijndaelAlg.CreateEncryptor(RijndaelAlg.Key, RijndaelAlg.IV),
    CryptoStreamMode.Write);

StreamWriter writer = new StreamWriter(cStream);

writeContacts.Save(writer);

writer.Flush();
writer.Close();

FileStream readStream = File.OpenRead("data.xml");

cStream = new CryptoStream(readStream,
  RijndaelAlg.CreateDecryptor(RijndaelAlg.Key, RijndaelAlg.IV),
  CryptoStreamMode.Read);

XmlTextReader reader = new XmlTextReader(cStream);

XDocument readContacts = XDocument.Load(reader);

//manipulate with Linq and Save() when needed
```
```
Swap your favorite ICryptoTransform into the CryptoStream.


q:
I'm looking for a wrapper that distills zlib to:

OpenZipFile()

GetItemInfo(n)

UnzipItem(n)  // Bonus points for unzipping recursively if item n is a directory.

I see a lot of wrappers around the zlib library on, say, codeproject.com but they are all platform-specific in order to provide the added platform-specific functionality of unzipping to file/memory buffer/pipe.

[A]
In the zlib source archive, there is a contribution named "minizip".
"minizip" is a set of files you can use to play with .zip files. Basic services you need are already there :
unzOpen
unzLocateFile
unzOpenCurrentFile
unzGetCurrentFileInfo
unzCloseCurrentFile
unzClose
Of course, this is not object oriented (and I'm sure that was not the goal of the creator of minizip), but writing a simple object oriented wrapper should be easy.


q:
On IBM DB2 v.9 windows, when someone connect to database by Server\Administrator user
DB2 database will automatically accept and grant all the permissions to this user?
But, in some case environment Administrator of server does not need to see every data in the database. So how to prevent Administrator use connect to database?

[A]
By default, DB2 databases are created with
```
CONNECT
```
authority granted to public.  If you want to restrict some users from connecting, you need to do
```
```
GRANT CONNECT ON DATABASE TO <user1>, <user2>, ...
```
```
Then revoke the CONNECT authority from PUBLIC
```
```
REVOKE CONNECT ON DATABASE FROM PUBLIC
```
```


q:
I'm having some trouble figuring out how to use more than one left outer join using LINQ to SQL.  I understand how to use one left outer join.  I'm using VB.NET.  Below is my SQL syntax.

T-SQL

SELECT
    o.OrderNumber,
    v.VendorName,
    s.StatusName
FROM
    Orders o
LEFT OUTER JOIN Vendors v ON
    v.Id = o.VendorId
LEFT OUTER JOIN Status s ON
    s.Id = o.StatusId
WHERE
    o.OrderNumber >= 100000 AND
    o.OrderNumber <= 200000

[A]
I think you should be able to follow the method used in
this
post.  It looks really ugly, but I would think you could do it twice and get the result you want.
I wonder if this is actually a case where you'd be better off using
```
DataContext.ExecuteCommand(...)
```
instead of converting to linq.


q:
I have two tables that I would like to join but I am getting an error from MySQL

Table: books
bookTagNum ShelfTagNum
book1      1
book2      2
book3      2

Table: shelf
shelfNum   shelfTagNum
1          shelf1
2          shelf2

I want my results to be:

bookTagNum ShelfTagNum shelfNum
book1      shelf1           1
book2      shelf2           2
book3      shelf2           2

but instead I am also getting an extra result:

book1      shelf2           2

I think my query is doing a cross product instead of a join:

SELECT `books`.`bookTagNum` , `books`.`shelfNum` , `shelf`.`shelfTagNum` , `books`.`title`
FROM books, shelf
where `books`.`shelfNum`=`books`.`shelfNum`
ORDER BY `shelf`.`shelfTagNum` ASC
LIMIT 0 , 30

What am I doing wrong?

[A]
I think you want
```
```
where `books`.`shelfTagNum`=`shelf`.`shelfNum`
```
```
In order to match rows from the
```
books
```
and
```
shelf
```
tables, you need to have terms from each in your
```
where
```
clause - otherwise, you're just performing a no-operation check on the rows of
```
books
```
, since every row's
```
shelfNum
```
will be equal to its
```
shelfNum
```
.
As @fixme.myopenid.com suggests, you could also go the explicit
```
JOIN
```
route, but it's not necessary.


q: I would like to implement a telnet server in C. How would I proceed with this? Which RFCs should I look at? This is important to me, and I would appreciate any help.

[A]
For very basic telnet (just telnet to a port and echo bytes), there's not much to do.  Read from a socket, process it (in an echo server, do nothing), spit back a result.  You could implement a simple MUD-style server without knowing anything in any RFCs.
But if you're really concerned about RFCs, RFC 854 might be a starting point.
http://www.faqs.org/rfcs/rfc854.html


q:
I'd like to know what are the most useful JQuery plugins. I'm particularly interested in  those which are likely to be useful in general UI development, such as Tablesorter, rather than those which serve uncommon needs.

If you could provide a very brief description of the plugin's purpose, that would be really helpful.

Thanks,
Don

[A]
I'll list one I'm working on...
My jLINQ plugin
is a jQuery version of .NET LINQ. It's made for working with in-memory collections (not talking directly to the server) and let's you use syntax similar to the following.
```
```
var results = $.from(data)
    .ignoreCase()
    .startsWith("firstName","m")
    .or("n")
    .isNot("administrator")
    .orderBy("lastName")
    .select();
```
```
It supports a bunch of other commands that you find in LINQ for ordering and grouping along with most of the selection commands like contains, between, greaterThan, etc...
Here is a demo
-
It's stable, but still in progress
Maybe not must have, but might be useful as it progresses...


q:
Using jquery how do I focus the first element (edit field, text area, dropdown field, etc)
in the form when the page load?

Something like:

document.forms[0].elements[0].focus();

but using jquery.

Another requirement, don't focus the first element when the form has class="filter".

[A]
```
```
$('form:not(.filter) :input:visible:enabled:first').focus()
```
```
This will select the first visible input element (
```
<input />
```
,
```
<select>
```
,
```
<textarea>
```
) that doesn't have the class
```
filter
```
in it.


q:
I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.

Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?

Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.

Update 2 : If you're interested in this question, check out this too.

[A]
I think both FL Studio and Reason can be configured as the default MIDI playback device.  To send MIDI messages to either from VB.NET, you'll need to PInvoke the midiOutOpen, midiOutShortMsg and midiOutClose API calls.  Here's a link to code samples:
http://www.answers.com/topic/midioutopen
They're for VB6, but they should be easy to translate to VB.NET.
I know FL Studio can be "driven" from a plugin authored for FL (or a VSTx plugin), but I think these are always written in C or C++.
Edit:  I just learned that Windows Vista dropped the MIDI Mapper (which would have made setting up FL or Reason as the default MIDI device simple).  Amazing.  Here is a link I found with an alternative solution:
http://akkordwechsel.de/15-windows-vista-und-der-midi-mapper/
I just tried it out (it's just a *.CPL file that you double-click to run) and it appears to work (although the GM Synth is the only option available on my laptop, so I'm not sure if it will pick up FL or Reason as choices).


q:
Does anyone know how to generate SQL scripts from a query?

For example,

Script some tables.

Do custom action 1.

Script the views.

Do custom action 2.

Etc.

[A]
It sounds like you want to write a cursor to execute custom SQL.  This is common and easy to do.  What you need to do is specify a few things to help us more completely answer your question:
What type of SQL server are you using? (MSSQL, Oracle, MySQL)
What language are you writing in? (Java, C++, PL/SQL, TSQL)
You can either write code (Java / C++) to generate SQL from a query, or possibly use a cursor to iterate over recordsets (PL/SQL / TSQL).  You can use the results to give you information that can then be executed as SQL via an exec (of some kind depending on the language).


q:
I am trying to use native windows API with Qt using mingw toolset. There are link problems with some functions. What happens? Is this a bug with mingw name mangling?

#ifdef Q_WS_WIN
    HWND hwnd = QWidget::winId();
    HDC hdcEMF  = CreateEnhMetaFile(NULL, NULL, NULL, NULL ) ;
    Rectangle(hdcEMF,100,100,200,200);
    HENHMETAFILE hemf = CloseEnhMetaFile(hdcEMF);
    OpenClipboard(hwnd);
    EmptyClipboard();
    SetClipboardData(CF_ENHMETAFILE,hemf);
    CloseClipboard();
#else

The errors:

undefined reference to `CreateEnhMetaFileW@16'

undefined reference to `Rectangle@20'

undefined reference to `CloseEnhMetaFile@4'

[A]
The functions
```
CreateEnhMetaFileW()
```
and
```
CloseEnhMetaFile()
```
are defined in the static library Gdi32.lib, so you have to make sure to link against that.  Try adding
```
-lgdi32
```
to the end of your command line you're using to compile.  If that doesn't work, you might have to specify the full path to Gdi32.lib by adding
```
-L/path/to/folder/containing/the/library -lgdi32
```
instead.


q: Is it possible to inspect the return value of a function in gdb assuming the return value is not assigned to a variable?

[A]
Yes, just examine the
```
EAX
```
register by typing
```
print $eax
```
.  For most functions, the return value is stored in that register, even if it's not used.
The exceptions to this are functions returning types larger than 32 bits, specifically 64-bit integers (
```
long long
```
),
```
double
```
s, and
```
structs
```
or
```
classes
```
.
The other exception is if you're not running on an Intel architecture. In that case, you'll have to figure out which register is used, if any.


q:
This question is regarding the performance issue in Mac OS X

Canvas3D object is embedded in a JPanel; then the panel is integrated with the rest of the Swing-built application. Within that Canvas I am rendering a simple cube by applying
certain transformations. At the initial launch It works fine. But when i try to resize the window or perform some operations on vertical or horizontal split bar buttons.Swing components take certain time to appear on the screen. A flashy white coloured thing appears first then swing components will appear? ( Totally saying flickering kind of stuff will happen). Is there any to solve this issue?

Kindly help me in this regard.

J3DSwinger


q:
We're building an C# .NET app which will be running on computers sitting inside trucks.  We need to talk to Digital IO ports on the truck computers which do not exist on our developer machines, so I need to write a dummy library which will be included in our dev builds, but will be replaced with our actual Digital IO library when we do releases.  And I want this library substitution to be automated by the build process.

Coming from a Java background, I can do this easily in maven using build profiles.  Is there a similar way I can do it using MSbuild??  If not, whats the best way to handle this in C# microsoft land.

[A]
I recently developed something similar where I assumed an interface for communicating with some embedded computers that operated servos.  To write the software that controlled these computers I
used Moq to mock
the interfaces I wrote, and then later
plugged in real classes via StructureMap
that implemented those interfaces.
I also used Moq to write the unit tests for the software controlling the machine using the same interfaces.


q:
I just recently installed the MVC beta.
However, I assumed because the versioning numbers have changed and because it now uses the GAC instead of the bin folder that it wouldn't break existing applications.

However, it has.

What steps do I need to follow to ensure my existing preview 3 applications use a bin copy of the .dlls and are not broken by the installation of the beta?

[A]
ASP.NET MVC beta is also bin-deployable, Move the following DLL's from GAC to the bin folder of your app
```
```
* System.Web.Mvc
* System.Web.Routing
* System.Web.Abstractions
```
```
Check this article for more information


q:
I need to do a date comparison in Mysql without taking into account the time component i.e. i need to convert '2008-11-05 14:30:00' to '2008-11-05'

Currently i am doing this:

SELECT from_days(to_days(my_date))

Is there a proper way of doing this?

[A]
Yes, use the
date
function:
```
```
SELECT date(my_date)
```
```


q:
I have a swing application deployed in HTTP Server. Users use the browser to point an URL and install the client using java webstart. Now I need to enable https access to my application deployed on HTTP server. I am using JDK 1.5 as default jdk supported in the jnlp file. For time being I use a self signed certificate to the sign the jars (by default created using Sun's jarsigner, keytool, etc, utils).

Solution/steps would be much appreciated.

Thanks in advance

Ramesh

[A]
What is the feature of https that you are hoping to leverage?
The signing/server authentication is done by code signing, though you are undermining this using a self-signed certificate.
Does your application code contain secrets that must be hidden from eavesdroppers?
As you say you "need to enable" there must be an underlying reason.
I believe that before you "need https" you need a proper code signing certificate. You might want to rephrase your question so that your underlying problem can be solved instead of the very specific question.


q:
What is the difference in the accessibility of the following variables in Java?

public class Joe {
    public int a;
    protected int b;
    private int b;
    int c;
}

I'm most interested in what the last one is doing.

[A]
```
public
```
: read/writable for anyone
```
protected
```
: read/writable for
instances of subclasses
and from within the enclosing package
```
private
```
: read/writable for
any
instance of the class
and inner or outer (enclosing) instance
```
int c
```
:
package-private, read/writable for
all classes inside same package
See the
JLS
for more details
EDIT: Added the comment for protected stating that access is granted from inside same package, you guys are totally right. Also added comment for
```
private
```
. I remember now... ;-)


q:
So I've been trying to learn the boost::asio stuff to communicate to a serial device using RS232.  The documementation is sparse and the examples are non-existent.  Can't figure out exactly how to communicate with the device.  The device can't send data so all I need to do is write, but other projects require actual back and forth communication so help with that would be appreciated.  What code I have so far follows.

#include <boost/asio/serial_port.hpp>
using namespace::boost::asio;

int main()
{
    io_service io;
    serial_port port( io, "COM3" );
    port.set_option( serial_port_base::baud_rate( 19200 ) );

    unsigned char commands[4] = { 1, 128, 240, 0 };

    // write the commands to the device

    return 0;
}

In short: need help with the io part of the serial_port.

[A]
In addition to the baud rate, you may also need to set other options like: character_size, flow_control, parity and stop_bits. To write your data to the serial port you can do the following:
```
```
boost::asio::write(port, boost::asio::buffer(commands, 4));
```
```
The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here:
Buffers
.


q:
I'm impressed with the simplicity of Microsoft's Virtual Earth Street Address search service.

My requirement is to type rough address info with no comma separators into a simple text box, press a find button, wait a few seconds and then observe a result picklist.

I mocked up something here using the virtual earth SDK.

Does Google Maps have a similar API?

Which street address search service is better?


q:
I need to copy a set of rows from one tab to another tab of the same Excel document by just clicking a button.

Also, can I also get information on how can I copy a set of rows that are hidden and paste it in the same tab without copying the "hidden" format?

[A]
If 'Copystart' is your original rows, and 'Copyend' is where you want to paste them, then using named ranges:
```
```
Sub Copybutton_Click()

Range("Copyend").value = Range("Copystart").value
Range("Copyend").visible = True

End Sub
```
```
If you have multiple named ranges with the same name, then add [Sheetname]. in front of the range, where Sheetname is the name of the sheet that the named range is in that you want to reference.


q:
Slightly related to my other question: What is the difference between the following:

private class Joe
protected class Joe
public class Joe
class Joe

Once again, the difference between the last 2 is what I'm most interested in.

[A]
A public class is accessible to a class in any package.
A class with default access (
```
class Joe
```
) is only visible to other classes in the same package.
The private and protected modifiers can only be applied to inner classes.
A private class is only visible to its enclosing class, and other inner classes in the same enclosing class.
A protected class is visible to other classes in the same package, and to classes that extend the enclosing class.


q:
(Note: This is for MySQL's SQL, not SQL Server.)

I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.

[A]
Check the
Pattern Matching
and
Regular Expressions
sections of the MySQL Reference Manual.


q:
Hey, in the Programming Pearls book, there is a source code for setting, clearing and testing a bit of the given index in an array of ints that is actually a set representation.

The code is the following:

#include<stdio.h>
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000

int a[1+ N/BITSPERWORD];

void set(int i)
{
    a[i>>SHIFT] |= (1<<(i & MASK));
}

void clr(int i)
{
    a[i>>SHIFT] &= ~(1<<(i & MASK));
}

int test(int i)
{
    a[i>>SHIFT] & (1<<(i & MASK));
}

Could somebody explain me the reason of the SHIFT and the MASK defines? And what are their purposes in the code?

I've already read the previous related question.

[A]
From
Here
(General answer to get this thread started)
A bit mask is a value (which may be stored in a variable) that enables you to isolate a specific set of bits within an integer type.
Normally the masked will have the bits you are interested in set to 1 and all the other bits set to 0. The mask then allows you to isolate the value of the bits, clear all the bits or set all the bits or set a new value to the bits.
Masks (particularly multi-bit ones) often have an associated shift value which is the amount the bits need shifting left so that the least significant masked bit is shifted to the least significant bit in the type.
For example using a 16 bit short data type suppose you wanted to be able to mask bits 3, 4 and 5 (LSB is number 0). You mask and shift would look something like
```
```
#define MASK 0x0038
#define SHIFT 3
```
```
Masks are often assigned in hexadecimal because it is easier to work with bits in the data type in that base as opposed to decimal. Historically octal has also been used for bit masks.
If I have a variable, var, that contains data that the mask is relevant to then I can isolate the bits like this
```
```
var & MASK
```
```
I can isolate all the other bits like this
```
```
var & ~MASK
```
```
I can clear the bits like this
```
```
var &= ~MASK;
```
```
I can clear all the other bits like this
```
```
var &= MASK;
```
```
I can set all the bits like this
```
```
var |= MASK;
```
```
I can set all the other bits like this
```
```
var |= ~MASK;
```
```
I can extract the decimal value of the bits like this
```
```
(var & MASK) >> SHIFT
```
```
I can assign a new value to the bits like this
```
```
var &= ~MASK;
var |= (newValue << SHIFT) & MASK;
```
```


q: I am writing a Rails app that processes data into a graph (using Scruffy).  I am wondering how can I render the graph to a blog/string and then send the blog/string directly to the  the browser to be displayed (without saving it to a file)? Or do I need to render it, save it to a file, then display the saved image file in the browser?

[A]
I think you will be able to use
send_data
for this purpose:
```
```
send_data data_string, :filename => 'icon.jpg', :type => 'image/jpeg', :disposition => 'inline'
```
```
If you put this in a controller action - say show on a picture controller, then all you need do is include the following in your view (assuming RESTful routes):
```
```
<%= image_tag picture_path(@picture) %>
```
```