Question:
What I want to do is the following:

read in multiple line input from stdin into variable A

make various operations on A

pipe A without losing delimiter symbols (\n,\r,\t,etc) to another command

The current problem is that, I can't read it in with read command, because it stops reading at newline.

I can read stdin with cat, like this:

my_var=`cat /dev/stdin`

, but then I don't know how to print it. So that the newline, tab, and other delimiters are still there.

My sample script looks like this:

#!/usr/local/bin/bash

A=`cat /dev/stdin`

if [ ${#A} -eq 0 ]; then
        exit 0
else
        cat ${A} | /usr/local/sbin/nextcommand
fi

Answer:
This is working for me:
```
```
myvar=`cat`

echo "$myvar"
```
```
The quotes around
```
$myvar
```
are important.


Question:
I have G729 encoded audio files. I need to programmatically convert them to WAV PCM (16bit 8kHz mono) in the flow of a tool that is doing other thing too. I have an executable that will do that for me. But spawning that external process every time I convert is too heavy on resources. Especially if I need many of them being done in parallel.
Looking for a .NET library or code that will let me call this inside my process.

Answer:
According to Wikipedia, G.729 includes several patents and is licensed by
Sipra
, so you probably won't have much luck finding an appropriate lobrary.  Unless you're decoding a large number of very small files, the cost of spawning a new process shouldn't be that big compared to the cost of doing the decoding, so I'd say use the executable you have.
As far as resources go, yes, spawning processes requires a lot more resources compared to using threads.  This shouldn't really matter, though, so long as you only spawn as many processes as you have cores in your machine.  Spawning more processes just wastes resources and doesn't gain you any extra parallelism.


Question:
I need a way to build C++ code from UML diagrams and vice versa.

Should be simple too hopefully. I don't mind paying too much.

Answer:
You could try
Sparx Enterprise Architect
but the code quality would be average, not excellent.
I am not aware of any great automatic code generators for C++
Prices start from $135


Question: I tried "x = y ** e", but that didn't work.

Answer:
use the
```
pow
```
function (it takes
```
float
```
s/
```
double
```
s though).
```
man pow
```
:
```
```
#include <math.h>

   double pow(double x, double y);
   float powf(float x, float y);
   long double powl(long double x, long double y);
```
```
EDIT
: For the special case of positive integer powers of
```
2
```
, you can use bit shifting:
```
(1 << x)
```
will equal
```
2
```
to the power
```
x
```
. There are some potential gotchas with this, but generally, it would be correct.


Question:
I have a class library with some extension methods written in C# and an old website written in VB.

I want to call my extension methods from the VB code but they don't appear in intelisense and I get compile errors when I visit the site.

I have got all the required Imports because other classes contained in the same namespaces are appearing fine in Intelisense.

Any suggestions

EDIT: More info to help with some comments.

my implementation looks like this

//C# code compiled as DLL
namespace x.y {
    public static class z {
        public static string q (this string s){
             return s + " " + s;
        }

    }
}

and my usage like this

Imports x.y

'...'
Dim r as string = "greg"
Dim s as string = r.q() ' does not show in intelisense
                        ' and throws error : Compiler Error Message: BC30203: Identifier expected.

Answer:
Extension methods are just syntactic sugar for static methods. So
```
```
public static string MyExtMethod(this string s)
```
```
can be called in both VB.NET and C# with
```
```
MyExtMethod("myArgument")
```
```


Question:
I've been trying to SSL working on my IW program for the last little while and I keep running up against the 'Could not load SSL Library'. I've followed every piece of advice I could find on the subject, but still no joy. I've tried the suggested DLLs in both the local directory and in system32.

Does anyone have a definitive answer about what OpenSSL DLLs I should be using? And what build of them? Or any other ideas at all?

Indy: updated to the most recent snapshot yesterday
IntraWeb: stock D2007 installed

This is running on a Vista machine, if that makes any difference.

TIA,

Trevor

Answer:
You need the OpenSSL dlls (0.9.8i worked for me, but I'm not using Vista), which you can download
here
(as I think you're suggesting, the Indy dlls don't work with IW9, which is the version bundled with D2007).
After installation, copy ssleay32.dll and libeay32.dll from system32 to your application directory.
If it still doesn't work:
is your servercontroller's ssl port set to 443?
does your cert pw match your servercontroller's ssl cert pw?
is servercontroller.sslversion set to sslv23?
have you tried compiling/running the AtoZed demo application for SSL (standalonessl)?
Hope this helps.
EDIT: once you get this working, you'll want to change sslversion to sslv3, and get users to turn off v2.


Question:
The general problem:

We have urls coming to our IIS web servers formatted like:

http://www.server.com/page.aspx

We are also seeing that urls like this are coming in:

http://www.server.com//page.aspx

We would like to get rid of that extra path character because when the user agent is Internet Explorer, this is resolving as 2 different pages, and thus, downloading the content twice when it should be resolved from a cache.

I am not sure if this is a problem to be solved with something like a url-rewriting module, or if there is a configuration setting.

Answer:
Perhaps you need to enable it?
```
```
DBMS_AQADM.ENABLE_PROPAGATION_SCHEDULE(queue_name => 'Test_Q');
```
```


Question: Is there a built-in/custom script available?

Answer:
Although its maybe not really programing related you could try
Orca
.


Question:
Umm, I guess my questions in the title:

How do I turn on Option Strict / Infer in a VB.NET aspx page without a code behind file?

<%@ Page Language="VB" %>
<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub
</script>

Answer:
```
```
<%@ Page Language="VB" Strict="true" %>
```
```


Question:
In my ideal world, what I'm looking for would exist as something along the lines of this:

public string UserDefinedField
{
    get { return _userDefinedField; }
    internal set { _userDefinedField = value; }
    set { _userDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); }
}

Where one statement is executed regardless of the access modifier, and another statement is executed if it's called from an external assembly or class.

I'm sure I could code something by using reflection and checking up the current call stack to see if the caller is in the same assembly, but I'm looking to see if there's a more elegant approach than that.

Answer:
```
```
public string UserDefinedField
{
    get { return _userDefinedField; }
    set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); }
}

// Call this from internal methods and use the public property for other cases
internal string SetField(string userValue)
{
    _userDefinedField = userValue;
}
```
```
You
could
get the caller information by
examining the calling stack
but that is extremely slow (compared to the above) and I wouldn't recommend it.


Question:
When I try to login to this site using my yahoo openid, it takes me to the yahoo site, I click "continue" meaning that i want to send my authentication details to stackoverflow.com and stackoverflow.com gives me the following error underneath the login text field:

Unable to log in with your OpenID provider:

failed to authenticate, returning Failed. Please ensure your identifier is correct and try again.

Answer:
```
```
public string UserDefinedField
{
    get { return _userDefinedField; }
    set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); }
}

// Call this from internal methods and use the public property for other cases
internal string SetField(string userValue)
{
    _userDefinedField = userValue;
}
```
```
You
could
get the caller information by
examining the calling stack
but that is extremely slow (compared to the above) and I wouldn't recommend it.


Question: I have a few batch files I need to run frequently in developing a certain project. I'd like to create a Visual Studio toolbar called "MyProject" and have commands underneath to execute these batch files. What is the easiest way to accomplish this?

Answer:
In the
Tools...
menu, select
External Tools...
and add references to the batch files. Then right-click on a toolbar, select
Customize...
, go to the
Toolbars
tab, click on
New...
, name your new toolbar, click on
OK
, go to the
Commands
tab, select the
Tools
category and drag-drop the appropriate
External Command
Command onto your custom tool bar.
If you need to run batch files that always run right before or after a build, you're probably better off making use of
build events
.


Question: I've been reading that Adobe has made crossdomain.xml stricter in flash 9-10 and I'm wondering of someone can paste me a copy of one that they know works. Having some trouble finding a recent sample on Adobe's site.

Answer:
This is what I've been using for development:
```
```
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
```
```
This is a very liberal approach, but is fine for my application.
As others have pointed out below, beware the risks of this.


Question: How do I go about positioning a JDialog at the center of the screen?

Answer:
In Java 1.4+ you can do:
```
```
final JDialog d = new JDialog();
d.setSize(200,200);
d.setLocationRelativeTo(null);
d.setVisible(true);
```
```
Or perhaps (pre 1.4):
```
```
final JDialog d = new JDialog();
d.setSize(200, 200);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
final int x = (screenSize.width - d.getWidth()) / 2;
final int y = (screenSize.height - d.getHeight()) / 2;
d.setLocation(x, y);
d.setVisible(true);
```
```


Question:
I'm trying to pass one method to another in elisp, and then
have that method execute it.  Here is an example:

(defun t1 ()
  "t1")

(defun t2 ()
  "t1")

(defun call-t (t)
  ; how do I execute "t"?
  (t))

; How do I pass in method reference?
(call-t 't1)

Answer:
First, I'm not sure that naming your function
```
t
```
is helping as 't' is used as the
truth value
in lisp.
That said, the following code works for me:
```
```
(defun test-func-1 ()  "test-func-1"
   (interactive "*")
   (insert-string "testing callers"))

(defun func-caller (callee)
  "Execute callee"
  (funcall callee))

(func-caller 'test-func-1)
```
```
Please note the use of 'funcall', which triggers the actual function call.


Question:
window.scrollMaxY can be set via that property in IE and older versions of Firefox, but when trying in FF3 it says "Cannot set this property as it only has a getter".

What is my alternative?

EDIT:

The reason why I'm asking is that I'm fixing some very horrible JS written by someone else, it has a function to keep a div centered on the page while scrolling, and has this line:

// Fixes Firefox incrementing page height while scrolling
window.scrollMaxY = scrollMaxY

Obviously this doesn't work, but the main issue is that when the page is scrolled, it grows in length.

Answer:
First, I'm not sure that naming your function
```
t
```
is helping as 't' is used as the
truth value
in lisp.
That said, the following code works for me:
```
```
(defun test-func-1 ()  "test-func-1"
   (interactive "*")
   (insert-string "testing callers"))

(defun func-caller (callee)
  "Execute callee"
  (funcall callee))

(func-caller 'test-func-1)
```
```
Please note the use of 'funcall', which triggers the actual function call.


Question:
I'm storing an ArrayList of Ids in a processing script that I want to spit out as a comma delimited list for output to the debug log. Is there a way I can get this easily without looping through things?

EDIT: Thanks to Joel for pointing out the List(Of T) that is available in .net 2.0 and above. That makes things TONS easier if you have it available.

Answer:
Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:
...in VB.NET:
```
```
String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String()))
```
```
...in C#
```
```
string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String")))
```
```
The only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.
EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!
```
```
String.Join(",", TargetList.ToArray())
```
```


Question:
There are many tools out there for writing and managing requirements, but are there any good ones for reviewing them?

I'm not talking about managing reviews, but automation tools that look for common requirement blunders (such as using negative requirements, or ones that are worded in a way that makes testing difficult).

More of a screening tool that someone writing requirements can use to screen their document before distributing to a group of reviewers so that the review process need not be slowed down by everyone commenting on the same easily recognizable issues.

I'm curious if anyone's used anything like this in the past.

Answer:
I'm working on a console application that takes a xml configuration file like this:
```
```
<?xml version="1.0" encoding="utf-8"?>
<ReqCheck>
  <Categories name="Reconsider wording">
    <Keyword>may</Keyword>
    <Keyword>should</Keyword>
  </Categories>
  <Categories name="Potential logic problem" format="{0}: consider both then and else conditions.">
    <Keyword>not</Keyword>
  </Categories>
</ReqCheck>
```
```
The application takes a MS-Word document and adds 'balloon-style' comments to the document.


Question:
Is it possible to create, for instance, a box model hack while using in-line CSS?

For example:

<div id="blah" style="padding: 5px; margin: 5px; width: 30px; /*IE5-6 Equivalent here*/">

Thanks!

Answer:
The most appropriate answer is
don't
. (Edit: to be clear, I mean don't do it inline, I don't mean don't use CSS hacks.)
Edit: This doesn't work, IE ignores the conditional comment. Leaving the answer here to not be a bastard.
The next most appropriate answer is conditional comments:
```
```
<div id="blah" style="padding: 5px; margin: 5px; width: 30px; <!--[if lte IE 6]> ... <![endif]-->">
```
```


Question:
I have a generic class in C# with 2 constructors:

public Houses(params T[] InitialiseElements)
{}
public Houses(int Num, T DefaultValue)
{}

Constructing an object using int as the generic type and passing in two ints as arguments causes the 'incorrect' constructor to be called (from my point of view).

E.g. Houses<int> houses = new Houses<int>(1,2) - calls the 2nd construtor. Passing in any other number of ints into the constructor will call the 1st constructor.

Is there any way around this other than removing the params keyword and forcing users to pass an array of T when using the first constructor?

Answer:
Perhaps instead of Params you could pass in IEnumerable
```
```
public Houses(IEnumerable<T> InitialiseElements){}
```
```


Question: I have a neural network written in Erlang, and I just bought a GeForce GTX 260 card with a 240 core GPU on it. Is it trivial to use CUDA as glue to run this on the graphics card?

Answer:
No, using CUDA is not a trivial matter.
The CUDA programming model basically uses C (with some additions) but in order to get the most of the GPGPU's capabilities you would have to ensure that your algorithms follow the CUDA guidelines. (see
NVidia CUDA Programming Guide
)
For example in order to get the best memory performance (somewhere around 70Gbps) you need to access memory in streaming mode with coalescing, also branches are very costly on the GPUs so you should avoid conditionals as much as possible. Check out the guide and samples provided with the SDK, they'll provide an excellent starting point


Question:
Is it possible to create Eclipse plugins that auto-discover eachother?

I am developing a set of plugins that need to operate in two primary situations:

individually

in concert with each other.

When run individually, the plugins should "just work" but when in concert, they will be sharing some of the same model content, and one of the plugins should present the user with a list of other plugins to share content with. eg:

Foo Plugin detected the following
  plugins it can share ontologies with:

[ ] Bar plugin

[ ] Baz plugin

[ ] Don't share

Does Eclipse offer any internal publication / detection methods that would facilitate this sort of auto-detection of other plugins?

Answer:
The answer should be through
Declarative Service
, which combines the advantages of both eclipse xml extensions and osgi POJO services. Something that is implicitly dynamic like osgi services, but loaded “on demand” like eclipse extensions.
Introduced in 2006 for eclipse3.3, you will find those concepts illustrated in
this presentation
.
Declarative Services gives the option to define reference to other services. It is also possible to specify the cardinality of the reference. The cardinality is specified using two numbers, the first one, 0 or 1, indicates the optionality, the second one, 1 or n, indicates the multiplicity.
In practice, those
DS (Declarative Services)
are not easy to use, as you have to access the BundleContext, meaning keeping track of the BundleActivator,
which is not always easy
...
If what you need is to define some sort of Service Oriented Component Model,
this presentation
should provide you with the different alternatives existing today, as well as detailing those "Declarative Services"
To publish what rcreswick has found in relation with DS:
Getting Started with OSGi:
Introducing Declarative Services
Getting Started with OSGi:
Declarative Services and Dependencies


Question:
I am trying to create a new instance of Excel using VBA using:

Set XlApp = New Excel.Application

The problem is that this new instance of Excel doesn't load all the addins that load when I open Excel normally...Is there anything in the Excel Application object for loading in all the user-specified addins?

I'm not trying to load a specific add-in, but rather make the new Excel application behave as though the user opened it themself, so I'm really looking for a list of all the user-selected add-ins that usually load when opening Excel.

Answer:
Using
```
CreateObject("Excel.Application")
```
would have the same result as using
```
New Excel.Application
```
, unfortunately.
You will have to load the Addins that you need individually by file path & name using the
```
Application.Addins.Add(string fileName)
```
method.


Question:
I develop a number of desktop Java applications using Swing, and while Swing is quite powerful (once you get the hang of it), there are still a lot of cases where I wish some advanced component was available right out of the box.

For example, I'd really like to see easy-to-use components (without writing them myself, which I could do given enough time) like:

Multi-line label

Windows File Explorer-like Icons or Thumbnails view

Drop-down button (like Firefox's old Back button)

5-star rating widget

Combo box with automatic history (like the text field on Google)

An Outlook-style accordion-style bar

and so on

I know of a couple of sources of free Swing components, like SwingLabs, home of JXTable, JXDatePicker, and a few others.

Where do you go for Swing components beyond those included with Java itself?

Answer:
The following are worth a look:
swingX
Glazed lists
Substance look'n'feel
Flamingo components
Ken Orr's Mac Widgets
Jide's open source components


Question:
Is it currently possible to translate C# code into an Abstract Syntax Tree?

Edit: some clarification; I don't necessarily expect the compiler to generate the AST for me - a parser would be fine, although I'd like to use something "official." Lambda expressions are unfortunately not going to be sufficient given they don't allow me to use statement bodies, which is what I'm looking for.

Answer:
Check out .NET
CodeDom
support.  There is an old article on code project for a
C# CodeDOM parser
, but it won't support the new language features.
There is also supposed to be support in #develop for generating a CodeDom tree from C# source code according to this
posting
.


Question: I'm having trouble dynamically adding controls inside an update panel with partial postbacks. I've read many articles on dynamic controls and I understand how to add and maintain them with postbacks but most of that information doesn't apply and won't work for partial postbacks. I can't find any useful information about adding and maintaining them with UpdatePanels. I'd like to do this without creating a web service if it's possible. Does anyone have any ideas or references to some helpful information?

Answer:
This is, I think, one of the common pitfalls for asp.net programmers but isn't actually that hard to get it right when you know what is going on (always remember your viewstate!).
the following piece of code explains how things can be done. It's a simple page where a user can click on a menu which will trigger an action that will add a user control to the page inside the updatepanel.
(This code is borrowed
from here
, and has lots more of information concerning this topic)
```
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Sample Menu</title>

    <form id="form1" runat="server">
        <asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
            <Items>
                <asp:MenuItem Text="File">
                    <asp:MenuItem Text="Load Control1"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control2"></asp:MenuItem>
                    <asp:MenuItem Text="Load Control3"></asp:MenuItem>
                </asp:MenuItem>
            </Items>
        </asp:Menu>

        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Menu1" />
            </Triggers>
        </asp:UpdatePanel>
    </form>

```
```
and
```
```
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PlainSampleMenuPage : System.Web.UI.Page
{
    private const string BASE_PATH = "~/DynamicControlLoading/";

    private string LastLoadedControl
    {
        get
        {
            return ViewState["LastLoaded"] as string;
        }
        set
        {
            ViewState["LastLoaded"] = value;
        }
    }

    private void LoadUserControl()
    {
        string controlPath = LastLoadedControl;

        if (!string.IsNullOrEmpty(controlPath))
        {
            PlaceHolder1.Controls.Clear();
            UserControl uc = (UserControl)LoadControl(controlPath);
            PlaceHolder1.Controls.Add(uc);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        LoadUserControl();
    }

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        MenuItem menu = e.Item;

        string controlPath = string.Empty;

        switch (menu.Text)
        {
            case "Load Control2":
                controlPath = BASE_PATH + "SampleControl2.ascx";
                break;
            case "Load Control3":
                controlPath = BASE_PATH + "SampleControl3.ascx";
                break;
            default:
                controlPath = BASE_PATH + "SampleControl1.ascx";
                break;
        }

        LastLoadedControl = controlPath;
        LoadUserControl();
    }
}
```
```
for the code behind.
That's basically it. You can clearly see that the viewstate is being kept with
LastLoadedControl
while the controls themselves are dynamically added to the page (inside the updatePanel (actually inside the placeHolder inside the updatePanel) when the user clicks on a menu item, which will send an asynchronous postback to the server.
More information can also be found here:
http://aspnet.4guysfromrolla.com/articles/081402-1.aspx
http://aspnet.4guysfromrolla.com/articles/082102-1.aspx
and of course on
the website that holds the example code
I used here.


Question:
I know how to write trace statements that I can view in a webforms environment, but how do I do this in a windows forms app?

I am inside of a static method, and I want to display the sql query that it is generating.

I don't have access to messagebox.show, what are my options?

Answer:
You could use a global logging object:
```
```
enum LogLevel
{
    Info,
    Warning,
    Error
}

delegate void OnLog (string msg, LogLevel level);

interface ILogger
{
    void Log(string msg, LogLevel level);
    event OnLog;
}
```
```
Then extend ILogger with a class that you acquire using a public static method in the Program class.
And in your main form, attach yourself to the OnLog event and use it to print messages on the for itself. Then all you have to do is call the Log method in your static method with the SQL query.
:)


Question:
Is there a maximum length when using window.returnValue (variant) in a modal?

I am calling a modal window using showModalDialog() and returning a comma delimited string.  After selecting a group of users, I am putting them into a stringbuilder to display in a literal.

Dim strReturn As New StringBuilder
strReturn.Append("<script type=""text/javascript"">window.returnValue='")
Dim strUsers As New StringBuilder
For Each dtRow As DataRow In GetSelectedUserTable.Rows
    If strUsers.ToString.Length > 0 Then
        strUsers.Append(",")
    End If
    strUsers.Append(dtRow("UserID"))
Next
strReturn.Append(strUsers.ToString)
strReturn.Append("';window.close();</script>")
litReturnJavascript.Text = strReturn.ToString

So would there be a limit on how many characters can be added to the window.returnValue?

Answer:
First, in what browser are you having problems?
```
window.returnValue
```
isn't even supported in Firefox, maybe not even other browsers.
Second, have you looked the value of
```
strUsers
```
after building it to make sure there are no single or double quotes in that string?
I would guess that the maximum size/length of that property would be determined more by your system's memory than anything else.
EDIT: Maybe you should look at using
```
window.open()
```
to open a new window and
```
window.opener
```
to set the value on the parent form instead - it is supported by more browsers. Just a suggestion...


Question:
I'm working on trying to generate a report from a couple of database tables. The simplified version looks like this

Campaign
----------
CampaignID

Source
-----------------------
Source_ID | Campaign_ID

Content
---------------------------------------------------------
Content_ID | Campaign_ID | Content_Row_ID | Content_Value

The report needs to read like this:

CampaignID - SourceID - ContentRowID(Value(A)) - ContentRowID(Value(B))

Where ContentRowID(Value(A)) means "Find a row the has a given CampaignID, and a ContentRowId of "A" and then get the ContentValue for that row"

Essentially, I have to "pivot" (I think that's the correct term) the rows into columns...

It's an Oracle 10g database...

Any suggestions?

Answer:
This is my first stab at it. Refinement coming once I know more about the contents of the Content table.
First, you need a temporary table:
```
```
CREATE TABLE pivot (count integer);
INSERT INTO pivot VALUES (1);
INSERT INTO pivot VALUES (2);
```
```
Now we're ready to query.
```
```
SELECT campaignid, sourceid, a.contentvalue, b.contentvalue
FROM content a, content b, pivot, source
WHERE source.campaignid = content.campaignid
AND pivot = 1 AND a.contentrowid = 'A'
AND pivot = 2 AND b.contentrowid = 'B'
```
```


Question: How can I bring a console application window to front in C# (especially when running the Visual Studio debugger)?

Answer:
It's hacky, it's horrible, but it works for me (thanks,
pinvoke.net
!):
```
```
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

public class Test
{

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
    static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);

    public static void Main()
    {
        string originalTitle = Console.Title;
        string uniqueTitle = Guid.NewGuid().ToString();
        Console.Title = uniqueTitle;
        Thread.Sleep(50);
        IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);

        if (handle == IntPtr.Zero)
        {
            Console.WriteLine("Oops, cant find main window.");
            return;
        }
        Console.Title = originalTitle;

        while (true)
        {
            Thread.Sleep(3000);
            Console.WriteLine(SetForegroundWindow(handle));
        }
    }
}
```
```


Question:
I get the following warning when using java.net.URLEncoder.encode:

warning: [deprecation] encode(java.lang.String)
         in java.net.URLEncoder has been deprecated

What should I be using instead?

Answer:
Use the other
```
encode
```
method in
URLEncoder
:
```
```
URLEncoder.encode(String, String)
```
```
The first parameter is the text to encode; the second is the name of the character encoding to use (e.g.,
```
UTF-8
```
). For example:
```
```
System.out.println(
  URLEncoder.encode(
    "urlParameterString",
    java.nio.charset.StandardCharsets.UTF_8.toString()
  )
);
```
```


Question:
What are the main reasons personal projects (software apps etc) never get to the level of competing with your salary?

To me one big problem is "on-the-fly" feature expansion, with this problem, the end only gets further and further away!

Answer:
For me, it's simple: I work 8 hours a day already. I spend a few more hours a day keeping current. I have
a girlfriend,
some local family and a decent circle of friends. I have (gasp) non-computer-related interests and hobbies. In other words, I have a life.
So ...
Time.
Time is not on my side. Would that it was ... My blog might be a bit more current if there were just two more hours in every day. :)
(Originally posted by
John Rudy
.)


Question: Is it possible to pass a App setting "string" in the web.config to a Common C# class?

Answer:
In any class you can use
```
ConfigurationManager.AppSettings["KeyToSetting"]
```
to access any value in the  element of web.config (or app.config)


Question: How would I go about implementing dynamic/docking splitter panes in a vb.net app similar to visual studio?

Answer:
Not easily is the short answer.
A high level idea would be to define some regions using divs or a table and using your js framework of choice make these elements resizeable.   that gets you the splitter aspect.
The docking will have to use absoluting positioned elements that you can drag and drop and if you are currently over a docking element, reposition the element to be docked to inside the docking element and change it's position back to normal.  When you want to drag it out you will change it's positioning back to absolute
Also, this is not easy to do and will take a long time and still probably not work correctly.  Sorry to sound pessimistic though.


Question:
I'm writing a sample console service host and I want to plug into WCF stack to be able to print a message to console when new message arrives, even if it won't get processed by the service at the moment (because service is working on previous calls).
This is based on my assumption that messages arriving get queued by the WCF, is that correct?

Additionally, I'm using netTcpBinding if this is important.

Answer:
You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right?
Just use
```
PyString_FromString
```
:
```
```
char *cstring;
PyObject *pystring = PyString_FromString(cstring);
```
```
That's all.  Now you have a Python
```
str()
```
object.  See docs here:
https://docs.python.org/2/c-api/string.html
I'm a little bit confused about how to specify "str" or "unicode."  They are quite different if you have non-ASCII characters.  If you want to decode a C string
and
you know exactly what character set it's in, then yes,
```
PyString_DecodeString
```
is a good place to start.


Question:
How many can relate do this?

Server Error in / Application

Object reference not set to an object

Description: Object reference not set to an object.

Exception Details: System.NullReferenceException: Object reference not set to an object.

Source Error:

Line 56:    posts.Add(post);

On a more serious note, what are the first things you look for when you see the
yellow screen of death? Half the time the debug trace isn't actually telling you what the problem is (understandable I guess).

I must admit, I still use Response.Write more than I should.  I just get lazy going through the debugger.  What techniques do you use to debug the problem?

Answer:
If I'm unable to identify/resolve the issue using the error message that the page presents to me, I will typically try to use the Windows Event Viewer to help me identify what is causing the issue.
For example, SharePoint errors are sometimes far less than descriptive.  So, I'll combine what I'm seeing on the Y.S.O.D. with error messages from the Event Viewer to help me narrow down the cause.
I will do my best to ask a co-worker or other associate that I think might have some experience that might help.  If I'm still unable to identify the cause, I will resort to Google armed with all the information.


Question: I am using an ASP page where I have to read a CSV file and insert it into DB table "Employee". I am creating an object of TestReader. How can I write a loop to execute up to the number of rows/records of the CSV file which is being read?

Answer:
Do not try to parse the file yourself, you'll just give yourself a headache.  There's quite a bit more to it than splitting on newline and commas.
You can use OLEDB to open up the file in a recordset and read it just as you would a db table.  Something like this:
```
```
Dim strConn, conn, rs

strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
Server.MapPath("path to folder") & ";Extended Properties='text;HDR=Yes;FMT-Delimited';"

Set conn = Server.CreateObject("ADODB.Connection")
conn.Open strConn

Set rs = Server.CreateObject("ADODB.recordset")
rs.open "SELECT * FROM myfile.csv", conn

while not rs.eof
    ...
    rs.movenext
wend
```
```
My vbscript is rusty, so verify the syntax.
edit:
harpo's comment brings up a good point about field definitions.  Defining a schema.ini file allows you to define the number and datatypes of the expected fields.  See:  You can handle this by defining a schema.ini file. see:
http://msdn.microsoft.com/en-us/library/ms709353.aspx


Question: I'm trying to use jcarousel to build a container with multiple rows, I've tried a few things but have had no luck. Can anyone make any suggestions on how to create it?

Answer:
We have had to make a similar modifiaction.  We do this by extending the default options, to include a rows value, and the width of each item (we call them modules) then divide the width by the number of rows.
Code added to jCarousel function...
Add to default options:
```
```
moduleWidth: null,
rows:null,
```
```
Then set when creating jCarousel:
```
```
$('.columns2.rows2 .mycarousel').jcarousel( {
        scroll: 1,
        moduleWidth: 290,
        rows:2,
        itemLoadCallback: tonyTest,
        animation: 'slow'
    });
```
```
The find and edit the lines in:
```
```
$.jcarousel = function(e, o) {

if (li.size() > 0) {
...
moduleCount = li.size();
wh = this.options.moduleWidth * Math.ceil( moduleCount / this.options.rows );
wh = wh + this.options.moduleWidth;

this.list.css(this.wh, wh + 'px');

// Only set if not explicitly passed as option
if (!o || o.size === undefined)
   this.options.size = Math.ceil( li.size() / this.options.rows );
```
```
Hope this helps,
Tony Dillon


Question:
I'm doing something like the following:

SELECT * FROM table WHERE user='$user';
$myrow = fetchRow() // previously I inserted a pass to the db using base64_encode ex: WRM2gt3R=

$somepass = base64_encode($_POST['password']);

if($myrow[1] != $somepass) echo 'error';
else echo 'welcome';

Im always getting error, I even echo $somepass and $myrow[1] they are the same, but still error. What Am I doing wrong? Thanks

Answer:
Try using
```
var_dump
```
instead of echo - maybe one of them has a space or newline at the start/end.
Edit:
You must be storing it as CHAR(40):
```
A fixed-length string that is always right-padded with spaces to the specified length when stored
```
Use VARCHAR or
```
trim()
```


Question:
We're looking at upgrading from Visual Studio 2005 to Visual Studio 2008. I discovered the following disturbing comment:

http://msdn.microsoft.com/en-us/library/6sehtctf.aspx

"Beginning with Visual C++ 2008, Visual C++ does not support targeting Windows 95, Windows 98, Windows ME, or Windows NT."

Does this mean that if we rebuild our products with visual C++ 2008, they will stop working on Windows 98 machines? It sounds like it, but I have trouble believing they'd make that big a change.

Thanks for your help.

Answer:
according to the following link, windows 98 is not supported by .NET 3.5 so I would imagine that is what they mean. You can still do .NET 2.0 and lower development, but if you use the 3.5 libraries, Windows 98 is not supported.
.NET 3.5 information


Question:
For example:

from datetime import <c-x><c-o>{list of modules inside datetime package}

Answer:
the following steps should work.
make a blank solution, nothing in it.
Move the solution to where you want the web project to live.
Open the solution.
Create the web project in the desired area.
I often do this sort of moving around so that projects will sit nicely in svn.  Don't forget to svn:ignore the *.suo files.


Question: I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?

Answer:
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:
```
```
template <template<class> class H, class S>
void f(const H<S> &value) {
}
```
```
Here,
```
H
```
is a template, but I wanted this function to deal with all specializations of
```
H
```
.
NOTE
: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).
I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that
```
std::vector
```
doesn't
have a
```
typedef value_type
```
.
So how would you write a function which can create variables of the right type for the vectors elements? This would work.
```
```
template <template<class, class> class V, class T, class A>
void f(V<T, A> &v) {
    // This can be "typename V<T, A>::value_type",
    // but we are pretending we don't have it

    T temp = v.back();
    v.pop_back();
    // Do some work on temp

    std::cout << temp << std::endl;
}
```
```
NOTE
:
```
std::vector
```
has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly.
which you can use like this:
```
```
f<std::vector, int>(v); // v is of type std::vector<int> using any allocator
```
```
or better yet, we can just use:
```
```
f(v); // everything is deduced, f can deal with a vector of any type!
```
```
UPDATE
: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing
```
auto
```
. Now the same function can be written as:
```
```
template <class Cont>
void f(Cont &v) {

    auto temp = v.back();
    v.pop_back();
    // Do some work on temp

    std::cout << temp << std::endl;
}
```
```
which is how I'd prefer to write this type of code.


Question:
I need to get a list of all documents in a site collection, which I believe I can do with either the alldocs table or the  alluserdata table (MOSS 2007 SP1) but do not see how I can get the author information for the document.  I do not need the contents of the document (e.g. AllDocStreams content)

Something like this:

SELECT     tp_DirName, tp_LeafName, tp_Version, tp_Modified, tp_Created
FROM         AllUserData
WHERE     (tp_ContentType = 'Document')
AND (tp_LeafName NOT LIKE '%.css')
AND (tp_LeafName NOT LIKE '%.jpg')
AND (tp_LeafName NOT LIKE '%.png')
AND (tp_LeafName NOT LIKE '%.wmf')
AND (tp_LeafName NOT LIKE '%.gif')
AND (tp_DirName NOT LIKE '%Template%')
AND (tp_IsCurrentVersion = 1)
AND (tp_LeafName NOT LIKE '%.xsl')
ORDER BY tp_SiteId, tp_ListId, tp_DirName, tp_LeafName, tp_IsCurrentVersion DESC

Is there a better way to go about this?

Answer:
MOSS provides many
webservices
out of the box which make life a little easier.  They are always worth exploring.
For this particular instance, I think the article,
Getting a list of files from a MOSS document library using a SharePoint web service
, will be of assistance.  If this isn't your exact scenario, it will get you on the right track.
If the Document service doesn't help you, the Search service will I'm sure.  Check the documentation for usage.


Question:
I'm writing an intranet application for a client and I want to give them the ability to configure through an admin interface, which users and user groups can access certain areas. What I'd like to know is the best way of storing the reference to the user or group that is assigned to an area of the intranet.

Should I be using the domain\username and domain\groupname strings or should i perhaps be using the fully qualified ad name ie ou=computer room;cn=blah etc?

I will be storing the reference in SQL.

Answer:
MOSS provides many
webservices
out of the box which make life a little easier.  They are always worth exploring.
For this particular instance, I think the article,
Getting a list of files from a MOSS document library using a SharePoint web service
, will be of assistance.  If this isn't your exact scenario, it will get you on the right track.
If the Document service doesn't help you, the Search service will I'm sure.  Check the documentation for usage.


Question:
I want to check for duplicated words right next to each other, but even if there is punctuation in between.

For example:

Vivamus Vivamus diam, diam, Vivamus Vivamus diam, diam Vivamus

There should be four distinct hits here.

I can't figure out why this isn't working. Why? What should the correct code be?

(\w*(?:[ ,\.])*?)\1

PS: This is not necessarily for the Perl engine.

Answer:
The
```
(?:
```
is a non-capturing parenthesis, meaning it won't store the matches.  You will need to use capturing parentheses.
```
```
(\w+)\W+\1
```
```


Question:
How can one programmatically sort a union query when pulling data from two tables? For example,

SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY table2.field1

Throws an exception

Note: this is being attempted on MS Access Jet database engine

Answer:
The second table cannot include the table name in the
```
ORDER BY
```
clause.
So...
```
```
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY field1
```
```
Does not throw an exception


Question: I've been doing "plain old java objects" programming for 10 years now, with Swing and JDBC, and I consider myself pretty good at it.  But I start a new job in two weeks where they use JBoss, and I'd like to get a heads up and start learning all this stuff before I start.  What are good resources?  On-line tutorials, books, e-books, anything you can suggest, especially ones that don't try to teach you the basics of plain Java first.

Answer:
A couple of answers come to mind:
if "plain old java" is what you're used to, you'll probably need a grounding of plain old j2EE more than JBOSS specific stuff. I'd start with
the sun tutorials
, but being familiar with the general structure of servlets, the servlet api, is base.
as application servers go, JBoss is (my biased opinion only) insanely large and complicated. Think "launching the space shuttle" and you won't be far off. A million services. It is specifically noted for having an unusual class loader structure (although this may have changed since I used it last, about 1 -2 years ago), among other things. It also has an extensive list of nice services, like a JMX base (management configuration beans) although documentation is likely to be spotty, as support is a paid service.
Best suggestion- familiarize yourself with the J2EE libraries. Next would be to get a basic site running in JBOSS. More specific stuff that you might want to do is likely to be very specific to their installation (e.g. there's a JMS implementation available in there but they may not be using it) as I've seen people use it for nothing but a servlet container.


Question:
So I know that autocommit commits every sql statement, but do updates to the database go directly to the disk or do they remain on cache until flushed?

I realize it's dependent on the database implementation.

Does auto-commit mean
a) every statement is a complete transaction AND it goes straight to disk or
b) every statement is a complete transaction and it may go to cache where it will be flushed later or it may go straight to disk

Clarification would be great.

Answer:
Auto-commit simply means that each statement is in its own transaction which commits immediately.  This is in contrast to the "normal" mode, where you must explicitly
```
BEGIN
```
a transaction and then
```
COMMIT
```
once you are done (usually after several statements).
The phrase "auto-commit" has nothing to do with disk access or caching.  As an implementation detail, most databases will write to disk on commit so as to avoid data loss, but this isn't mandatory in the spec.


Question:
Many C++ books contain example code like this...

std::cout << "Test line" << std::endl;

...so I've always done that too. But I've seen a lot of code from working developers like this instead:

std::cout << "Test line\n";

Is there a technical reason to prefer one over the other, or is it just a matter of coding style?

Answer:
There might be performance issues,
```
std::endl
```
forces a flush of the output stream.


Question:
I'm trying to compile a program called ngrep, and when I ran configure, things seemed to go well, but when I run make, I get:

ngrep.c: In function ‘process’:
ngrep.c:544: error: ‘struct udphdr’ has no member named ‘source’
ngrep.c:545: error: ‘struct udphdr’ has no member named ‘dest’
make: *** [ngrep.o] Error 1

What does that mean, and how do I fix it? There are no earlier warnings or errors that suggest the root of the problem.

Answer:
Well, there is a struct called udphdr (probably short for udp header). And some part of the program assumes the struct has the members source and dest which it hasn't.
Look at file ngrep.c line 544 and 545 to find the offending lines.
Possible causes:
type name type error.
struct is not completely defined.
using the wrong struct.
Edit: probably related problem:
http://ubuntuforums.org/showthread.php?t=371871


Question:
I recently ran into a problem that I thought boost::lambda or boost::phoenix could help be solve, but I was not able to get the syntax right and so I did it another way. What I wanted to do was remove all the elements in "strings" that were less than a certain length and not in another container.

This is my first try:

std::vector<std::string> strings = getstrings();
std::set<std::string> others = getothers();
strings.erase(std::remove_if(strings.begin(), strings.end(), (_1.length() < 24 &&  others.find(_1) == others.end())), strings.end());

How I ended up doing it was this:

struct Discard
{
    bool operator()(std::set<std::string> &cont, const std::string &s)
    {
        return cont.find(s) == cont.end() && s.length() < 24;
    }
};

lines.erase(std::remove_if( lines.begin(), lines.end(), boost::bind<bool>(Discard(), old_samples, _1)), lines.end());

Answer:
You need boost::labmda::bind to lambda-ify function calls, for example the length < 24 part becomes:
```
```
bind(&string::length, _1) < 24
```
```
EDIT
See "Head Geek"'s post for why set::find is tricky.  He got it to resolve the correct set::find overload (so I copied that part), but he missed an essential boost::ref() -- which is why the comparison with end() always failed (the container was copied).
```
```
int main()
{
  vector<string> strings = getstrings();
  set<string> others = getothers();
  set<string>::const_iterator (set<string>::*findFn)(const std::string&) const = &set<string>::find;
  strings.erase(
    remove_if(strings.begin(), strings.end(),
        bind(&string::length, _1) < 24 &&
        bind(findFn, boost::ref(others), _1) == others.end()
      ), strings.end());
  copy(strings.begin(), strings.end(), ostream_iterator<string>(cout, ", "));
  return 0;
}
```
```


Question:
What new features in java 7 is going to be implemented?
And what are they doing now?

Answer:
In addition to what John Skeet said, here's an
overview of the Java 7 project
. It includes a list and description of the features.
Note: JDK 7 was released on July 28, 2011, so you should now go to the official
java SE site
.


Question:
I really like Entity Framework, but there are some key pieces that are a challenge to me. Can anyone tell me how to filter an EntityDataSource on an Association column? EF hides the FK values and instead has an Association property. Given an Entity, Person, with a PersonType association, I would have expected something like this to work if I want to filter my Person Entity by Type:

GridDataSource.EntityTypeFilter = "it.PersonType.PersonTypeID = 1";

or

GridDataSource.Where = "it.PersonType.PersonTypeID = '1'";

or even

GridDataSource.WhereParameters.Add(new Parameter("it.PersonType.PersonTypeID", DbType.Object, "1"));

but none of those work. Anybody know how to do this?

Answer:
Have you tried applying the filter in memory using LINQ? (or Perhaps against the database?)
```
```
var personType = new PersonType { Id = 1 };
var query = PersonDataSource.Where(p => p.PersonType.Equals(personType));
// use this query as the DataSource for your GridView
```
```
I must admit I haven't done anything like this, but I have used this trick to update/create an entity without loading the associated entities first.


Question:
If I have a method such as:

public void MyMethod(int arg1, string arg2)

How would I go about getting the actual names of the arguments?
I can't seem to find anything in the MethodInfo which will actually give me the name of the parameter.

I would like to write a method which looks like this:

public static string GetParamName(MethodInfo method, int index)

So if I called this method with:

string name = GetParamName(MyMethod, 0)

it would return "arg1". Is this possible?

Answer:
```
```
public static string GetParamName(System.Reflection.MethodInfo method, int index)
{
    string retVal = string.Empty;

    if (method != null && method.GetParameters().Length > index)
        retVal = method.GetParameters()[index].Name;

    return retVal;
}
```
```
The above sample should do what you need.


Question:
I just read the Wikipedia article on mock objects, but I'm still not entirely clear on their purpose. It appears they are objects that are created by a test framework when the actual object would be too complex or unpredictable (you know 100% sure what the values of the mock object are because you fully control them).

However, I was under the impression that all testing is done with objects of known values, so I must be missing something. For example, in a course project, we were tasked with a calendar application. Our test suite consisted of event objects that we knew exactly what they were so we could test the interactions between multiple event objects, various subsystems, and the user interface. I'm guessing these are mock objects, but I don't know why you wouldn't do this because without the objects of known values, you can't test a system.

Answer:
Think of the classic case of having client and server software. To test the client, you need the server; to test the server, you need the client. This makes unit testing pretty much impossible - without using mocks. If you mock the server, you can test the client in isolation and vice versa.
The point of the mock is not to duplicate the behaviour of the things its mocking though. It is more to act as a simple state machine whose state changes can be analysed by the test framework. So a client mock might generate test data, send it to the server and then analyse the response. You expect a certain response to a specific request, and so you can test if you get it.


Question:
Say you have a standard template with included (parsed) header, body, footer templates.

In the body template a variable like $subject is defined and you want that also displayed in the header template.

In some other template languages like HTML::Mason(perl based) you would evaluate the body template first to pick up the $subject variable but store it's output temporarily in a variable so your final output could end up in the correct order (header, body, footer)

In velocity it would look something like

set ($body=#parse("body.vm"))

parse("header.vm")

${body}

parse("footer.vm")

This however doesn't seem to work,  any thoughts on how to do this?

Answer:
You can do this using
VelocityLayoutServlet
which is part of
VelocityTools
.
This allows you to define a layout for your application -- let's call it
```
application.vm
```
-- in which you can parse in headers, footers etc and declare where the main body content is placed using the
```
screen_content
```
declaration, e.g:
```
```
<html>
  <head>
    <title>$subject</title>
  </head>
  <body>
  #parse("header.vm")
  $screen_content
  #parse("footer.vm")
  </body>
</html>
```
```
```
VelocityLayoutServlet
```
will evalulate the templates (and, hence, variables) before rendering which allows you to set a
```
$subject
```
variable in your body template, e.g:
```
```
#set($subject = "My Subject")
<div id="content">
</div>
```
```
More detailed information can be found
in the Velocity documentation
.


Question:
Running VISTA 32bit.

I am trying to install c# Visual Express 2008 - but it requires .NET 3.5. One of the prerequisites during the install is .NET 3.5 ... it attempts to install it but fails, with no real error message.

So I downloaded .NET 3.5 standalone from MS website and tried that.Again it fails with the error

[10/17/08,23:17:07] WapUI: [2] DepCheck indicates Microsoft .NET Framework 3.0SP1 (CBS) is not installed.
  [10/17/08,23:50:55] Microsoft .NET Framework 3.0SP1 (CBS): [2] Error: Installation failed for component Microsoft .NET Framework 3.0SP1 (CBS). MSI returned error code 34

I currently have c# Express edition 2005 installed. But everything I read says that I can have these two applications installed together. I believe that 2005 runs Framework 2.0. 2005 express edition works fine. - its just the 2008 edition im having problems installed the .NET 3.5 with ....

any ideas ? thanks

Answer: Have you ever installed any of the pre-release versions of 3.0 or 3.5?  I had a lot of trouble installing 3.5 until I realized that I had installed a CTP of WPF.  Go through all of your Microsoft and .NET installs in Add/Remove programs and make sure that you don't have any pre-release versions.


Question:
I was getting bad data from an application I was writting using C++ in Visual Studio 2k3 so I decided to debug it. Then I found it was throwing an exception but one I can't track down.

Then I placed some try/catch blocks and low and behold, when I don't debug there is no exception. That is, I have code that looks like this:

std::vector<MyClass*> ListOfStuff;
.
.
.
try
{
.
.
.
   const MyClass * localPointer = ListOfStuff[i]; //This is where the exception occurs
.
.
}
 catch (...)
{
   int x = 0;  //place break here
}

So if I step through the code line by line I'll get an exception and shot to the catch. But if I just let it run with a breakpoint inside the catch nothing happens. Using an iterator has the same behavior. And I can successfully check the size of the vector so I know I'm within the bounds.

Can anyone tell me what's going on? If it matters I'm using some standard windows libraries and openGL.

Answer:
Is the exception an ASSERT? These may get compiled out at compile time or otherwise throw an assertion.
For example, you could have
```
```
#ifdef DEBUG
#define ASSERT(cond) if (cond) throw CDebugAssertionObj;
#else
#define ASSERT(cond)
#endif
```
```


Question:
Anyone know of a good free winforms html editor for .NET. Ideally I would like html and preview modes along with the possibility of exporting to a pdf, word doc or similar.

Although the export I could probably create myself from the html output.

Another nice feature would be a paste from word that removes all the extra tags you usually end up with but again it's a nice to have not a required.

Answer:
You can use the
WebBrowser
control in design mode with a second
```
WebBrowser
```
control set in view mode.
In order to put the
```
WebBrowser
```
control in design mode, you can use the following code.
This code is a super stripped down version of a WYSIWYG editor for one of our software products.
Simply create a new Form, drop a
```
WebBrowser
```
control on it, and put this in the Form.Load:
```
```
Me.WebBrowser1.Navigate("")
Application.DoEvents()
Me.WebBrowser1.Document.OpenNew(False).Write("
Edit this text
")

'turns off document body editing
For Each el As HtmlElement In Me.WebBrowser1.Document.All
    el.SetAttribute("unselectable", "on")
    el.SetAttribute("contenteditable", "false")
Next

'turns on editable div editing
With Me.WebBrowser1.Document.Body.All("editable")
    .SetAttribute("width", Me.Width & "px")
    .SetAttribute("height", "100%")
    .SetAttribute("contenteditable", "true")
End With

'turns on edit mode
Me.WebBrowser1.ActiveXInstance.Document.DesignMode = "On"
'stops right click->Browse View
Me.WebBrowser1.IsWebBrowserContextMenuEnabled = False
```
```


Question: I'm working on a table of links within a site using iframes. I'm wondering if there's any way to code a link to go to two simultaneous destinations within two different target frames? I've been reading all afternoon and can't find anything close to what I want to do. Basically I want one link to present a photo in one iframe and some data in another iframe. Any ideas?

Answer:
Short answer: No.
Longer answer: With what you describe, using strictly X/HTML, this isn't possible. You could add in javascript to change the iframe src, however. Something like:
```
```
function click_link(id) {
    document.getElementById('iframe1').src = "page.ext?id=" + id;
    document.getElementById('iframe2').src = "other_page.ext?id=" + id;
}
```
```
But of course, you probably shouldn't be using iframes anyways...


Question:
I am trying to make my window manager conform to the ICCCM specifications. I fully understand the reason for the _NET_SUPPORTING_WM_CHECK atom - this ensures that no invalid information stays whenever the window manager isn't running anymore.

What I don't understand is why are no other atoms like _NET_NUMBER_OF_DESKTOPS expected on the supporting window besides _NET_WM_NAME and _NET_SUPPORTING_WM_CHECK itself.

Window managers are supposed to set and overwrite the data but this can be misleading in the case the new window manager isn't compliant.

Answer:
Well the atoms that you are talking about are not the ICCCM.
They belong to the newer set of
EWMH
So basically it goes like this.
First we had the ICCCM.
They are
old
mature
supported by most window managers (in full or in part)
easy to implement
Unix standard
Then we had EWMH that are
newer (GNOME and KDE)
not many window managers support them
more complex (e.g. virtual desktops)
A freedesktop standard.
Freedesktop wanted to make the EWMH as broad as possible (apart from GNOME and KDE)
and that is why most of the atoms are SHOULD and not MUST. They are giving a chance to small window manager to claim compliance.


Question:
I have several user drawn controls on a form, unfortunately when the form is shown the user drawn controls are showing the previous forms background rather than the current forms background.

The OnPaint event is very simple, and the OnBackgroundPaint event is empty...

Like this:

    protected override void OnPaint(PaintEventArgs pe)
    {
        pe.Graphics.DrawImageUnscaled(_bmpImage, 0, 0);
    }

    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        //Leave empty...
    }

How do I get the current background to be the transparency that is shown, rather than the background of the previous form?

Answer:
Ruby performs shell expansion when %x is used with a single argument (like you are doing).
Here's my guess as to what is going on:
Ruby scans the command to determine if there are any special characters that would result in the need to perform shell expansion, if so it calls the shell to do that.  In the second example the single quotes are enough to make Ruby want to call the shell to do the expansion, hence the fork. In the first example Ruby can determine that shell expansion is not needed as the command contains no special characters (after variable expansion), hence no fork.  The difference between the two versions probably has to do with an internal change in how ruby tries to determine is shell expansion is needed.  I get a fork for the second example on ruby 1.8.5 on a 32-bit machine.
[EDIT]
Okay, I took a look at the source code for ruby 1.8.4 and 1.8.6 and both versions use the same criteria to determine whether or not to call a shell to perform shell expansion, if any of the following characters exist in the command line the shell will be invoked when one argument to %x is provided:
```
```
*?{}[]<>()~&|\\$;'`"\n
```
```
Ruby is actually calling the shell in both cases (in example that contains the quotes), the reason you are seeing different outputs from
```
pstree
```
is due to differences in the the
```
sh
```
command on the different machines, one calls
```
fork
```
, the other doesn't.  To see this for yourself, run this command on both machines:
```
```
/bin/sh -c "pstree $$"
```
```
This is the command that Ruby is using to execute
```
pstree
```
in the example with quotes on both machines.  You should see
```
bash---pstree
```
on the 32-bit machine and
```
bash---sh---pstree
```
on the other one.
So now I'm curious, what led you to discover this difference and is it causing a problem?


Question:
When including a header file in C++, what's the difference between...

including the .h part versus not including .h part when wrapping it in <> signs?

#include <iostream> vs. #include <iostream.h>

wrapping the header name in double quotes versus wrapping it in < > signs?

#include <iostream.h> vs. #include "iostream.h"

Answer:
Here is a decent link
article.
To summarize, the reason given:
The version of the iostream library that the Standards Committee
  produced was quite a bit different from the CFront implementation.
  {snip}
To ease transition, the C++ Standards Committee declared that code
  including the standard C++ headers would use include directives that
  lack an extension. This allowed compiler vendors to ship the old style
  C++ library headers with the .h extension and the new style headers
  without.
An advantage of not using the .h version:
There are several reasons why new code should be written using the
  extensionless version of the header files instead of the .h forms. The
  first is the unpredictability of such code when compiled on modern
  compilers. As previously mentioned, the result of using the .h headers
  is implementation specific. And as time goes by, the chance that a
  given compiler will have the old style library available decreases.


Question:
Recent conversations with colleagues have produced varying points of view on this matter. What say you, SO members?

I know, even the concept of scalability can be taken in so many different ways and contexts, but that was part of the discussion when this came up. Everyone seemed to have a different take on what scalability really means. I'm curious to see the varying takes here as well. In fact, I posted a question just for that concept.

Answer:
It greatly depends on which LINQ provider you are using and how you are using it. LINQ probably is not know for amazing execution speed but is rather provides developers with substantially better productivity.
According to
this
link even with some of the CTPs Linq to SQL was already better than using direct SQL in some cases.
If you are concerned with Speed and are using LINQ to objects alot
here
is a codeplex project (I think) for a provider that can give you 1000x performance improvements.


Question:
I have the following snippet of code, changeTextArea is a TextArea object.

changeTextArea.addKeyboardListener(new KeyboardListenerAdapter()
  public void onKeyPress( Widget sender, char keyCode, int modifier){
    //do something
    //I WISH TO STOP THE EVENT THAT MAPS TO THIS KEYPRESS FROM BUBBLING ANY FURTHER
  }
}

How would I stop the Event that is causing this method to be called from bubbling up from changeTextArea into the Panels/Widgets/Composites/Whatever that contain changeTextArea. Put succinctly, how do I stop it from bubbling any further. Any help would be appreciated (especially code samples).

Answer:
As far as I know you can't do it via a keyboard listener, but it is possible by adding an event preview using the DOM class:
```
```
DOM.addEventPreview(EventPreview preview)
```
```
Then when you get the event:
```
```
onEventPreview(Event event)
```
```
You should return false, to say you want to cancel the event. The Event object also supports this method:
```
```
public final void cancelBubble(boolean cancel)
```
```
Cancels bubbling for the given event. This will stop the event from being propagated to parent elements.
You can find more details here:
http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html?overview-summary.html


Question: When using Fiddler to monitor HTTP Requests & Responses in Internet Explorer it ignores all traffic directed to http://localhost.

Answer:
To get Fiddler to capture traffic when you are debugging on local host, after you hit F5 to begin degugging change the address so that localhost has a "." after it.
For instance, you start debugging and the you have the following URL in the Address bar:
http://localhost:49573/Default.aspx
Change it to:
http://localhost.:49573/Default.aspx
Hit enter and Fidder will start picking up your traffic.


Question:
In C# is there any real difference (other than syntax) under the hood between:

myButton.Click += new EventHandler(myMemberMethod);

and

myButton.Click += myMemberMethod;

?

Answer:
The second method is a shortcut to the first one, it was introduced in C# 2.0
See also
this thread
.


Question:
Does anyone know the bare minimum files required for Ext JS 2.2? I know the ExtJS site has a feature to "build" a small version of ExtJS (ext.js) as a replacement for ext-all.js but that's for minimizing the size of ExtJS on the client. I'm interested in minimizing what's on the server. Currently the SDK comes with the following subdirectories:

ext-2.2/

adapter
air
build
docs
examples
resources
source

I think its pretty safe to remove examples, docs, and air. However, are there other things we can remove to make this smaller or is there a resource (besides the large javascript source code corpus) that documents the minimum required files?

Answer:
This link explains the include order
What is the proper include order for my JavaScript files?
This is the minimum include set
```
```
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css">
<script type="text/javascript" src="../extjs/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../extjs/ext-all.js"></script>
```
```
The ext-all.css depends on files in ../extjs/resources/css so you should include that entire directory structure also.
So you'd need the following files at a minimum
extjs/resources/**/*
extjs/adapter/ext/ext-base.js
extjs/ext-all.js
If you're not using Ext JS for any of the UI components then you don't need any of the stylesheets and supporting images, but in that case you'd have to question why you're using Ext JS since that's it's strong point.


Question: Using any tools which you would expect to find on a nix system (in fact, if you want, msdos is also fine too), what is the easiest/fastest way to calculate the mean of a set of numbers, assuming you have them one per line in a stream or file?

Answer:
Perl.
```
```
@a = <STDIN>;

for($i = 0; $i < #@a; $i++)
{
   $sum += $a[i];
}

print $a[i]/#@a;
```
```
Caveat Emptor: My syntax may be a little whiffly.


Question:
I would like to embed Flash Player directly inside a C++ or Java application.

I found an article that describes how to do this for C#:
http://www.adobe.com/devnet/flash/articles/stock_history03.html

Unfortunately, I have no experience with C#, COM or ActiveX. I need someone to translate this code to C++, allowing me to embed the Flash Player into a Win32 Window. Ultimately I'd like to use this information to embed Flash into a Java application.

I am looking for three main functionalities:

Ability to play a Flash movie

Ability to receive events (such as mouse clicks)

Ability to send events

Edit: I prefer an open-source solution if possible.

Answer:
I don't know how to embed flash in C++, but Christopher Deckers (of
SWTSwing
fame) has developed an interesting hack which allows it to be embedded in Java.  You can find more information in
the Javalobby announcement thread
.
Here is an updated link:
https://github.com/Chrriis/DJ-Native-Swing


Question: How can I set the location (as it's picked up in CoreLocation services) in the iPhone Simulator?

Answer:
In my delegate callback, I check to see if I'm running in a simulator (
```
#if TARGET_ IPHONE_SIMULATOR
```
) and if so, I supply my own, pre-looked-up, Lat/Long. To my knowledge, there's no other way.


Question:
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);

If 'table' has no rows. whats the easiest way to check for this.?

Answer:
You could use
mysql_num_rows($results)
to check if 0 rows were returned, or use this faster alternative:
```
```
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
```
```


Question:
I want to check if a given date is more than a month earlier than today's date using LINQ.

What is the syntax for this?

Thanks in advance.

Answer:
I assume that you're talking about in the where clause.  It's basically the same way you would compare two DateTime objects elsewhere.
```
```
using (DataContext context = new DataContext()) {
   var query = from t in context.table
               where t.CreateDate.Date < DateTime.Today.AddMonths(-1)
               select t;
}
```
```


Question: I would like to show a set of consecutive numbers in a UIPickerView component but have it wrap around like the seconds component of the Clock->Timer application. The only behavior I can enable looks like the hours component of the Timer application, where you can scroll in only one direction.

Answer:
I found my answer here:
http://forums.macrumors.com/showthread.php?p=6120638&highlight=UIPickerView#post6120638
When it asks for the title of a row, give it:
Code:
```
```
return [rows objectAtIndex:(row % [rows count])];
```
```
When it says the user didSelectRow:inComponent:, use something like this:
Code:
```
```
//we want the selection to always be in the SECOND set (so that it looks like it has stuff before and after)
if (row < [rows count] || row >= (2 * [rows count]) ) {
    row = row % [rows count];
    row += [rows count];
    [pickerView selectRow:row inComponent:component animated:NO];
}
```
```
It appears that the UIPickerView does not support wrapping around natively, but you can fool it by inserting more sets of data to be displayed and when the picker stops, centering the component to the middle of the data set.


Question:
I am completely new to programming - my interest lies in PHP & MySql for building a dynamic web application for Military Band Administration purposes. i.e. General info and social networking for members + added functionality for the management team to communicate effectively.

OK so the question - as I learn more about PHP there are terms used that I do not understand that must come from a common basis of familiarity between all languages i.e. "stack overflow" appears to be an obvious one - "using too many recursive functions may smash the stack" is another.

So is there a book (a primer perhaps) about programming in general which allows someone like me to have a better understanding of what all this means?

Bear in mind I am 57 years old (young) and am really just starting out.

Steve

Answer:
To get a good understanding of the inner workings of computer hardware and software in a very readable (not too technical) manner, I can recommend
Code,The Hidden Language of Computer Hardware and Software
by Charles Petzold.
The later chapters in particular talk about some of these more general programming concepts that are present in most programming languages.  The earlier chapters focus on more the history of the computer and software, so not as relevant to your question.
However it's not a large book so the reading it all should be interesting/useful anyway.
There are better books if you are looking for an introduction to PHP/MySQL programming specifically, however if you want more general knowledge about how software and hardware works, Code is great.


Question:
The following Perl statements behave identically on Unixish machines.  Do they behave differently on Windows?  If yes, is it because of the magic \n?

  split m/\015\012/ms, $http_msg;
  split m/\015\012/s, $http_msg;

I got a failure on one of my CPAN modules from a Win32 smoke tester.  It looks like it's an \r\n vs \n issue.  One change I made recently was to add //m to my regexes.

Answer:
For these regexes:
```
```
m/\015\012/ms
m/\015\012/s
```
```
Both /m and /s are meaningless.
/s: makes
```
.
```
match
```
\n
```
too.
Your regex doesn't contain
```
.
```
/m: makes
```
^
```
and
```
$
```
match next to embedded
```
\n
```
in the string.
Your regex contains no
```
^
```
nor
```
$
```
, or their synonyms.
What is possible is indeed if your input handle (socket?) works in text mode, the
```
\r
```
(
```
\015
```
) characters will have been deleted on Windows.
So, what to do? I suggest making the
```
\015
```
characters optional, and split against
```
```
/\015?\012/
```
```
No need for /m, /s or even the leading
```
m//
```
. Those are just cargo cult.


Question:
A long time ago when I was a young lat I used to do a lot of assembler and optimization programming. Today I mainly find myself building web apps (it's alright too...). However, whenever I create fields for database tables I find myself using values like 16, 32 & 128 for text fields and I try to combine boolean values into SET data fields.

Is giving a text field a length of 9 going to make my database slower in the long run and do I actually help it by specifying a field length that is more easy memory aligned?

Answer:
Database optimization is quite unlike machine code optimization. With databases, most of the time you want to reduce disk I/O, and wastefully trying to align fields will only make less records fit in a disk block/page. Also, if any alignment is beneficial, the database engine will do it for you automatically.
What will matter most is indexes and how well you use them. Trying tricks to pack more information in less space can easily end up making it harder to have good indexes. (Do not overdo it, however; not only do indexes slow down INSERTs and UPDATEs to indexed columns, they also mean more work for the planner, which has to consider all the possibilities.)
Most databases have an EXPLAIN command; try using it on your selects (in particular, the ones with more than one table) to get a feel for how the database engine will do its work.


Question:
On the Python side, I can create new numpy record arrays as follows:

numpy.zeros((3,), dtype=[('a', 'i4'), ('b', 'U5')])

How do I do the same from a C program?  I suppose I have to call PyArray_SimpleNewFromDescr(nd, dims, descr), but how do I construct a PyArray_Descr that is appropriate for passing as the third argument to PyArray_SimpleNewFromDescr?

Answer:
See the
Guide to NumPy
, section 13.3.10.  There's lots of different ways to make a descriptor, although it's not nearly as easy as writing
```
[('a', 'i4'), ('b', 'U5')]
```
.


Question:
Is there a good way to add a .swf programatically to a panel on an asp.net page - ie: I know i could just insert the html tags:

ie:

<object type="application/x-shockwave-flash" data="yourflash.swf" width="" height="">
<param name="movie" value="yourflash.swf">
</object>

But is there an existing .net or free FLASH component already that you just set the properties on, or do i need to create a custom web control myself (not preferred) so i dont have to continously do this?

Thank you.

Answer:
Just a guess here, but it looks like you are inheriting either the Static Edge or Client Edge style from you theme.  I create most of my dialogs from the resource editor and set these properties there.
In your case, you can replace your CreateWindow with a
CreateWindowEx
to set these extended styles, which are probably being defaulted in CreateWindow.  Specifically check out
```
WS_EX_STATICEDGE, WS_EX_WINDOWEDGE and WS_EX_CLIENTEDGE
```
Edit: I'm assuming that this is not happening because you button is the default control in the dialog, which would also give a black edge.


Question: I'm looking for something that will let me parse Atom and RSS in Ruby and Rails. I've looked at the standard RSS library, but is there one library that will auto-detect whatever type of feed it is and parse it for me?

Answer:
Googleage reveals some things.  Were they not acceptable?
Simple RSS
Ruby-Feedparser
```
```
require 'simple-rss'
require 'open-uri'
rss = SimpleRSS.parse open('http://slashdot.org/index.rdf')
rss.channel.title # => "Slashdot"
```
```


Question: I'm trying to solve this flickering problem on the iphone (open gl es game).  I have a few images that don't have pow-of-2 dimensions.  I'm going to replace them with images with appropriate dimensions... but why do the dimensions need to be powers of two?

Answer:
Typically, graphics hardware works natively with textures in power-of-2 dimensions.  I'm not sure of the implementation/construction details that cause this to be the case, but it's generally how it is everywhere.
EDIT:  With a little research, it turns out my knowledge is a little out of date -- a lot of modern graphics cards can handle arbitrary texture sizes now.  I would imagine that with the space limitations of a phone's graphics processor though, they'd probably need to omit anything that would require extra silicon like that.


Question: Now that the G1 with Google's Android OS is now available (soon), will the android platform ever support .Net?

Answer:
Yes, it will be possible and it won't be that difficult. All what's needed at this point to start with is some kind of converter that will turn MSIL into
Dalvik bytecode
. Since both formats are open-sourced and well documented, there won't be any problem with it.
So, writing Android applications in C# or VB.NET will be possible, question is how much of .NET framework standard libraries will be supported. But that's another issue.
Oscar Reyes wrote:
I'm pretty sure if google hand ANY
  interest in .net, they would've design
  something while Android was in the
  first stages, not now when they are in
  production stages. I don't mean it is
  not possible, what I'm saying is
  they're not interested. Maybe in mmm
  hhhh 10 yrs.
Actually what they've already designed is
very compatible
with Java and .NET
They can't do everything at once, but if you look into Android SDK, there is a tool called
dx
. This tool converts Java bytecode into Dalvik bytecode, so in other words, you can run programs written in Java on Android with no effort today. Now the same tool is needed for .NET.
Considering how similar .NET and Java are, it's really a matter of time.
ddimitrov wrote:
The .Net->Java->Dalvik translation can
  be done even now
  (
http://dev.mainsoft.com/
), but I
  think you underestimate the lack of
  .Net libraries. Of course somebody can
  port Mono, but it's definitely a
  non-trivial effort.
No need to port Mono. Android already has VM and some basic API. All what's needed is CIL->Dalvik converter and tiny .NET wrapper for Android API (and maybe some basic implementation of some standard .NET classes). That's it.
Update:
.NET already works on Android - you will need product called Monodroid (
http://monodroid.net
) as stated above.


Question:
I have a webservice, which takes java.lang.object objects as parameters (because at runtime only know hte type of object)...after doing process, reply response setting java.lang.Object to it.

I am able to send the reuest objects to webservice from calling program, but getting NotSerializable exception while building the response from webservice.

I came to know that 'if we implement, java.io.serializable, the mebmers also should be serializable objects'... here Object isnot a serializable object..it doesn't impllement Serializable....

If anyone could guide mw with right solution..I wouold be thankful.

Thanks
Bhaskar

Answer:
If the members of the class don't implement Serializable then you can't use native Java serialisation for it.  That's basically what your error message is telling you.
If you cannot cause the underlying objects to implement Serializable, then you are probably going to have to find a different method of serialisation for passing in and out of your web service.  Popular varieties from Java are XML, JSON, AMF, although you can always roll your own.
If you have Java objects on either end of your request then make sure you factor your code so that your serialisation and de-serialisation code is in a library that can be used at both ends.  That will greatly ease the burden of testing in your implementation.
I would recommend keeping all the serialisation code out of the domain objects themselves.  Think about using a factory pattern for creation of your objects.
HTH


Question:
It's just so much HRESULT E_FAIL, if you know what I'm talking about.

And if you use Visual Studio, you know what I'm talking about.

Similar thread, but not a duplicate: Is the design view for aspx pages in Visual Studio useful?

Any insight, including input from Microsoft MVPs (oh, I know you're out there) would be super cool.

Answer:
Try this:
Put your MasterPages in a seperate folder (if they aren't already.  Call it
```
masterpages
```
.  Then add this to your
```
web.config
```
:
```
```
<location path="MasterPage">
<system.web>
  <authorization>
    <allow users="?" />
  </authorization>
</system.web>
```
```
This will allow anonymous access to that folder and allow access to the masterpage.  Also, are these nested masterpages?


Question:
I have two windows services running on the same machine. Both the services uses

private HttpListener listener;

I specify the baseURL as "http://IPAddress:8080/" & "http://IPAddress:8081/" respectively for each of the services. Then I do the needful and call

listener.Start();

The first service starts successfully at 8080 port. But when I now start the 2nd service,
I get HTTPListenerException "The process cannot access the file because it is being used by another process" for listener object.

Could anybody please tell me:
1) If it is possible to start two HTTP listeners on the same IIS at two different ports.
2) If yes, how can we achecive this?
3) Is there any other way of doing this?

For your information:
I am using C#.NET 2.0 and IIS 6.0 server.

Thanks & Regards,

Hari

Answer:
Doesn't HttpListener work independently from IIS? Can you stop the IIS service and see what happens?
Or maybe port 8081 is
used by another program
or process. I suggest to try to set the port to another number. You could open a command line and execute the "
netstat
" command to see
if the port is used
before starting your services.
(source:
googlepages.com
)


Question:
Is there a clever way of adding XML serialization instructions without modifying the serialized class?

I don’t like the default serialization and I can’t modify the class. I was considering inheriting the class, and using Shadows (VB.NET) to re-implement the properties (with the serialization instructions), but it results in a lot of duplicate code and just looks terrible.

The ideal solution I'm looking for is basically a method to keep all the serialization instructions in a separate file.

Answer:
Use reflection to get the values of all the properties from the class then write them as attributes on to an XmlNode
```
```
PropertyInfo[] properties = control.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
  object o = property.GetValue(control, null);
  // write value of o.ToString() out as an attribute on a XmlNode
  // where attribute name is property.Name
}
```
```


Question:
Essentially what I want is a BlockingQueue of size=1. I have a "listener" thread that simply waits, blocking until an object is put into the queue, and then retrieves it--and a "producer" thread that actually puts the object into the queue.

I can implement this with some synchronized blocks and a BlockingQueue implementation, but that seems like overkill. Is there a better, simpler way to do what I want?

Example interface:

public interface Wait<T> {
  /**
   * If "put" has never been called on this object, then this method will
   * block and wait until it has. Once "put" has been called with some T, this
   * method will return that T immediately.
   */
  public T get() throws InterruptedException;

  /**
   * @param object The object to return to callers of get(). If called more
   * than once, will throw an {@link IllegalStateException}.
   */
  public void put(T object);
}

Answer:
Use reflection to get the values of all the properties from the class then write them as attributes on to an XmlNode
```
```
PropertyInfo[] properties = control.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
  object o = property.GetValue(control, null);
  // write value of o.ToString() out as an attribute on a XmlNode
  // where attribute name is property.Name
}
```
```


Question:
I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.)

This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.

Answer:
Have you looked at libpng?
http://www.libpng.org/pub/png/libpng.html
I'm not sure whether the memory footprint will be acceptable, but you should probably be aware that PNG files are a lot more involved than just an array of colors. Performance is likely to be a concern on a DS.
If you go with libpng, you'll also need zlib, and if you're using DevKitPro, you'll probably run into some missing functions (from playing with the code for 5 minutes, it looks like it relies on pow() which doesn't seem to be in libnds.) I have no idea what the official Nintendo SDK offers in the way of a standard library - you might be in better shape if that's what you're using.


Question: Apparently, they're "confusing". Is that seriously the reason? Can you think of any others?

Answer:
Have you seen how many developers don't really understand ref/out?
I use them where they're really necessary, but not otherwise. They're usually only useful if you want to effectively return two or more values - in which case it's worth at least
thinking
about whether there's a way of making the method only do one thing instead. Sometimes using ref/out
is
the most appropriate approach - the various TryParse methods etc.


Question:
I can think of plenty of good reasons to using it; however, what are the downsides to it?

(Apart from buying another server)

What are some advantages to using a daily build instead of it?

Answer:
I don't think there are any downsides to it. But for the sake of the argument, here is
Eric Minick's article on UrbanCode
("It's about tests not builds.")
He criticises the tools that are based on
Martin Fowler's work
saying that they don't let enough time for tests.
"To be truly successful in CI, Fowler asserts that the build should be self-testing and that these tests include both unit and end-to-end testing. At the same time, the build should be very fast - ideally less than ten minutes - because it should run on every commit. If there are a significant number of end-to-end tests, executing them at build time while keeping the whole process under ten minutes is unrealistic.
Add in the demand for a build on every commit, and the requirements start to feel improbable. The options are either slower feedback or the removal of some tests."


Question:
I'm using the contentEditable attribute on a DIV element in Firefox 3.03.  Setting it to true allows me to edit the text content of the DIV, as expected.

Then, when I set contentEditable to "false", the div is no longer editable, also as expected.

However the flashing caret (text input cursor) remains visible even though the text is no longer editable.  The caret is now also visible when I click on most other text in the same page, even in normal text paragraphs.

Has anyone seen this before?  Is there any way to force the caret hidden?

(When I either resize the browser or click within another application, and come back, the caret magically disappears.)

Answer:
I've dealt with this and my workaround is clearing the selection when I disable contentEditable:
```
```
if ($.browser.mozilla) { // replace with browser detection of your choice
  window.getSelection().removeAllRanges();
}
```
```
I am actually removing the "contenteditable" attribute for browsers other than IE, rather than setting it to false:
```
```
if ($.browser.msie) {
  element.contentEditable = false;
}
else {
  $(element).removeAttr( 'contenteditable' );
}
```
```
The browsers manage the contentEditable attribute inconsistently and my testing revealed that this worked better overall. I don't remember if this contributed to fixing the caret problem, but I'm throwing it in here just in case.


Question:
I'm trying to find some references in regards to x86 Assembly languages. Tutorials/Examples to help my understanding.
-Thanks

Answer:
Programming from the Ground Up
(free book, highly recommended)
x86 Assembly
(wikibooks.org)
Essential Resources for x86 Programmers


Question: What is a StackOverflowError, what causes it, and how should I deal with them?

Answer:
Like you say, you need to show some code. :-)
A stack overflow error usually happens when your function calls nest too deeply. See the
Stack Overflow Code Golf
thread for some examples of how this happens (though in the case of that question, the answers intentionally cause stack overflow).


Question:
I am writing an .NET wrapper API for the Netflix API.

At this point I can choose to represent URLs as either strings or URI objects. Seems to me there is a good case for both.

So if you were using an API, which would you prefer?

Answer:
The below quote is from:
Framework Design Guildelines
I
highly
recommend this book to anyone developing frameworks on .Net
Do use
System.Uri to represent URI / URL data.
(For Parameters,
  properties, and return values)
System.Uri is a much safer and richer
  way of representing URIs. Extensive
  manipulation of URI-related data using
  plain strings has been shown to cause
  many security and correctness
  problems.
Consider
providing string-based overloads for most commonly used
  members with System.Uri parameters.
In cases where the usage pattern of
  taking a string from a user will be
  common enough, you should consider
  adding a convenience overload
  accepting a string. The string-based
  overload should be implemented in
  terms of the Uri-based overload.
Do Not
automatically overload all Uri-based members with a version that
  accepts a string.
Generally, Uri-based APIs are
  preferred. String-based overloads are
  meant to be helpers for the most
  common scenarios. Therefore, you
  should not automatically provide
  string-based overloads for all
  variants of the Uri-based members. Be
  selective and provide such helpers
  just for the most commonly used
  variants.
EDIT (per comments):
The book specifically states:
"Extensive manipulation of URI-related data using plain strings has been shown to cause many security and correctness problems."
I am not sure what additional justification you want for using System.Uri / UriBuilder. Additionally, why wouldn't you want to take advantage of the framework to read/manipulate a URI?
When designing an API that will be used by others it is important to make them approachable,
as well as reliable
. For this reason the book does mention, you should provide "nice" overloads for common functionality. However, to ensure correctness, you should always implement the underlying code with URIs.
Can you please clarify your wants, or reasons to use only strings?


Question: For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?

Answer:
```
```
>>> import time
>>> timestamp = "2008-09-26T01:51:42.000Z"
>>> ts = time.strptime(timestamp[:19], "%Y-%m-%dT%H:%M:%S")
>>> time.strftime("%m/%d/%Y", ts)
'09/26/2008'
```
```
See the documentation of the Python
```
time
```
module for more information.


Question:
There are some fairly powerful tools like SIMBL or Airfoil/Instant Hijack which use code injection.

As far as I understand this, these tools inject their own code in other programs. This idea sounds dangerous to me as this seems to have the potential to make perfectly stable software fragile and "buggy". Also this seems to pose security risks.

Should these tools be avoided for stability or security reasons?

Answer:
I believe it does not just refer to that
kind of code injection
for hacking or cracking a system.
It is also a technique often used in java world, with tools like
AOP
or
IPojo
.
When they make sense, they complement the current code, allowing them:
to function within a given framework (OSGI Declarative Services for IPojo)
to add functionalities (logging services for AOP)
As long as the initial code can run without that code injection, the stability is less an issue.
Stability and security - in the case of those two benevolent usages of code injection - of the injected code should be evaluated in a separate test code.


Question:
I have two projects in CPP. One defines a function which I'd like to invoke from the other.
I added a reference to the first project.
I still get the message of "identifier not found".
Assuming that the CPP file in the first project doesn't have a header, how do I make the second project know about its functions?

Answer:
If the first project doesn't have a header and you don't want to add one, then use the
```
extern
```
keyword to declare a prototype for the function you want to call in the second project source:
```
```
extern function_in_first_project(int args_go_here);
```
```
Make 100% sure that the function declaration (including argument list and calling convention) matches that of the actual function or you'll run into further problems.
This may not be the only thing you have to do to make your project link, depending on how you've got your projects set up.


Question:
Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules and changing dll versions globaly...)?

Specifically I would like python to use my version of the sqlite3.dll, rather than the version that came with python (which is older and doesn't appear to have the fts3 module).

Answer:
If your version of sqlite is in sys.path
before
the systems version it will use that. So you can either put it in the current directory or change the
```
PYTHONPATH
```
environment variable to do that.