q:
I followed the commonly-linked tip for reducing an application to the system tray : http://www.developer.com/net/csharp/article.php/3336751 Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load event, but it does nothing.

Edit : I could, as a poster suggested, modify the shortcut properties, but I'd rather use code : I don't have complete control over every computer the soft is installed on.

I don't want to remove it completely from everywhere except the systray, I just want it to start minimized.

Any ideas ?

Thanks

[A]
If you are using a
```
NotifyIcon
```
, try changing ShowInTaskbar to false.
To remove it from the Alt+Tab screen, try changing your window border style; I believe some of the tool-window styles don't appear...
something like:
```
```
using System;
using System.Windows.Forms;
class MyForm : Form
{
    NotifyIcon sysTray;

    MyForm()
    {
        sysTray = new NotifyIcon();
        sysTray.Icon = System.Drawing.SystemIcons.Asterisk;
        sysTray.Visible = true;
        sysTray.Text = "Hi there";
        sysTray.MouseClick += delegate { MessageBox.Show("Boo!"); };

        ShowInTaskbar = false;
        FormBorderStyle = FormBorderStyle.SizableToolWindow;
        Opacity = 0;
        WindowState = FormWindowState.Minimized;
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new MyForm());
    }
}
```
```
If it still appears in the Alt+Tab, you can change the window styles through p/invoke (a bit hackier):
```
```
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    IntPtr handle = this.Handle;
    int currentStyle = GetWindowLong(handle, GWL_EXSTYLE);
    SetWindowLong(handle, GWL_EXSTYLE, currentStyle | WS_EX_TOOLWINDOW);
}
private const int GWL_EXSTYLE = -20, WS_EX_TOOLWINDOW = 0x00000080;
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr window, int index, int value);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr window, int index);
```
```


q:
We need to set up a secure certificate on an Apache reverse proxy.
We've been advised that we need to use a virtual host directive.

I've looked these up in the O'Reilly book bit can't find any examples that pick up https specifically.

Does anyone have any examples of config snippets to do this?

[A]
Not sure if this is what you're after, but I used something like the following in the past:
```
```
<IfModule mod_ssl.c>
    SSLProxyEngine On
    ProxyPreserveHost On
    RewriteRule ^/whatever(.*)$       https://otherhost/whatever$1  [P]
</IfModule>
```
```
I needed to proxy secure content from another host, and that's what we ended up using. Works fine, and has for some time now. Does that sort of cover what you're looking for?

s: huggingface

c: devops

d: intermediate


q:
Can I utilise the new functionality provided by the new JavaFX APIs directly from Java to the same extent as I would be able to using JavaFX Script?

Are all the underlying JavaFX APIs purely Java or JavaFX Script or a mix?

[A]
The JavaFX APIs are a mix of JavaFX and Java. The SDK comes with an archive src.zip which contains a part of the APIs (only the most basic classes are included, but things like javafx.scene are missing).
Calling JavaFX code from Java is not officially supported in JavaFX 1.x AFAIK. There's a
blog entry in the JavaFX blog
that shows you how to do anyway it using unsupported APIs, but it's complicated and won't work this way in future versions.
There are two supported ways to use JavaFX from Java. Either you use the Scripting API to invoke JavaFX code, as shown in
this article
. Or, which is the most elegant solution IMHO, write the API-accessing code using JavaFX, define Java interfaces to interact with your JavaFX code from plain Java, and then implement those interfaces in JavaFX.


q:
I have a python list, say l

l = [1,5,8]

I want to write a sql query to get the data for all the elements of the list, say

select name from students where id = |IN THE LIST l|

How do I accomplish this?

[A]
string.join
the list values separated by commas, and use the
format operator
to form a query string.
```
```
myquery = "select name from studens where id in (%s)" % ",".join(map(str,mylist))
```
```
(Thanks,
blair-conrad
)


q:
I have just converted a project from Visual Studio 2003 to 2005 and although most of it 'converted' fine, I have a series of STL errors from the following line:

void SomeFn( std::vector<CSomeObject*>::iterator it,
std::vector<CSomeObject*>::iterator itBegin = NULL,
std::vector<CSomeObject*>::iterator itEnd = NULL );

The Visual Studio error is as follows:

c:\<path>\Headerfile.h(20) : error C2440: 'default argument' : cannot convert from 'int' to 'std::_Vector_iterator<_Ty,_Alloc>'
        with
        [
            _Ty=CObject *,
            _Alloc=std::allocator<CObject *>
        ]
        No constructor could take the source type, or constructor overload resolution was ambiguous

I can't see anything wrong with that code and it worked perfectly in VS 2003. Any ideas?

[A]
In 2003,
```
std::vector<T>::iterator
```
is just
```
T *
```
. In 2005, at least in debug mode, it is a class, and hence you can't use
```
NULL
```
for its value (
```
NULL
```
resolves to
```
0
```
).
You can use a default-constructed iterator instead:
```
```
std::vector<CSomeObject*>::iterator itBegin = std::vector<CSomeObject*>::iterator()
```
```


q:
In my Java program, I create an OtpNode and a "named" OtpMBox. Whenever a message is received via this mbox, some time-consuming operation needs to be performed after which a reply message is sent back. Since this operation is time-consuming, subsequent messages sent to the mbox won't be processed immediately.

So I want to use Java threads - one per message received. My question is should I also create a new OtpMBox for each message received or can the original OtpMBox be shared among all the threads?

[A]
I'm not really familiar with this stuff, but I suppose you may do some calculates )
You have overhead of running OtpMBox for each java-thread and overhead of controlling system (written in java) that would ask different threads to do some work and take results from them. I believe java isn't good tool for it )
You better do java-thread 'supervisor' that will start some (may be number of CPUs) amount 'worker' java-threads with OtpMBox and send OtpMBox's pids to erlang system.
--sorry my english


q:
What are best practices with regards to C and C++ coding standards?  Should developers be allowed to willy-nilly mix them together.  Are there any complications when linking C and C++ object files.

Should things like socket libraries that traditionally is written in C remain in C and kept in seperate source files? That is keeping c code in .c files and c++ code in .cpp files.
When mixing c and C++ after being parsed with g++ will there be any performance penalties, since typesafe checks are not done in C? but are in C++.  Would would be the best way to link C and C++ source code files.

[A]
The biggest issue is calling a C function from C++ code or vice versa. In that case, you want to make sure you mark the function as having "C" linkage using
```
extern "C"
```
. You can do this in the header file directly using:
```
```
#if defined( __cplusplus )
extern "C" {
#endif

extern int myfunc( const char *param, int another_one );

#if defined( __cplusplus )
}
#endif
```
```
You need the
```
#if
```
s because C code that includes it won't understand
```
extern "C"
```
.
If you don't want to (or can't) change the header file, you can do it in the C++ code:
```
```
extern "C" {
#include "myfuncheader.h"
}
```
```
You can mark a C++ function as having C linkage the same way, and then you can call it from C code. You can't do this for overloaded functions or C++ classes.
Other than that, there should be no problem mixing C and C++. We have a number of decades-old C functions that are still being used by our C++ code.


q:
Is there a way to find the size of a file object that is currently open?

Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size.  As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.

[A]
If you have the file descriptor, you can use
```
fstat
```
to find out the size, if any. A more generic solution is to seek to the end of the file, and read its location there.


q:
I need to create a BAT file to run an application through telnet, but as far as I know there is no way to do this on DOS. Telnet does not allow any command to be sent to the remote machine at the very instant of the connection, and each subsequent command in the BAT file would only be executed after telnet stops. This hypothetical piece of code illustrates what I want to do:

telnet 100.99.98.1 "C:\Application\app.exe -a -b -c"

And that would run the app.exe on the machine 100.99.98.1 with three parameters. Despite my efforts, nothing worked. Is there a way to do that?

Tks,

Pedrin Batista

[A]
Using telnet in the way you want to is imho not possible.
You could you secure shell (ssh), but a ssh server has to run on the remote machine (100.99.98.1 in you case).
EDIT:
See
http://sshwindows.sourceforge.net/
for a ssh client and server (based on cygwin) for Windows.


q:
I am using the Zend Framework.

I have a controller named 'UserController' that has a public function displayAction().

I would like to know how I can get that action method to use a different viewer than the default display.phtml.

Any help is appreciated.

[A]
You can use
```
```
$this->render('actionName');
```
```
or, alternatively, you can call a view script directly by calling
```
```
$this->renderScript('path/to/viewscript.phtml');
```
```
For more information, you can take a look at
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html
, specifically the parts about the
```
render()
```
and
```
renderScript()
```
methods.


q:
I'm automating a web application (the Mantis bug tracker) and I'm getting an interesting response header from it, called Refresh:

HTTP/1.x 200 OK
...
Refresh: 0;url=my_view_page.php

It seems to be acting the same way that meta refresh does, and the meta refresh technique implies that it is an equivalent of a header in HTTP.

Problem is, I can't find any mention of the Refresh header in the HTTP standard or any other definitive documentation on how it should be parsed and what the browser should do when it encounters it.

What's going on here?

[A]
from the W3C HTML 4.01 specification, quote:
META and HTTP headers
The http-equiv attribute can be used in place of the name attribute and has a special significance when documents are retrieved via the Hypertext Transfer Protocol (HTTP). HTTP servers may use the property name specified by the http-equiv attribute to create an [RFC822]-style header in the HTTP response. Please see the HTTP specification ([RFC2616]) for details on valid HTTP headers.
What this means is that when you use the
```
<meta http-equiv="refresh" url="..."/>
```
tag, you are actually instructing the browser to act as if there were a
```
Refresh
```
header being sent.
a good overview of the history of it can be found at
http://www.securiteam.com/securityreviews/6Z00320HFQ.html


q:
I'm converting my applications to Delphi 2009 and faced an intriguing issue with some calls that need to convert a string (wide) to AnsiString.

Here's an example to demonstrate the issue I'm having:

var
  s: PAnsiChar;

...

s := PAnsiChar(Application.ExeName);

With Delphi 2007 and previous versions, s := PChar(Application.ExeName) would return the application exe path.

with Delphi 2009, s := PAnsiChar(Application.ExeName) returns only 'E'.

My guess is that's because I'm converting a unicode string to an ansi string but how can I convert it so that a PAnsiChar gets the full string?

[A]
I have no Delphi 2009 here, so I can't check it. But maybe you have to try:
```
```
s := PAnsiChar(AnsiString(Application.ExeName));
```
```
As gabr already pointed, this is not a very good practice, and you will only use it if you are 100% sure. The string only contains characters that have a direct mapping to the ANSI range.
That's why you should get a warning because you are converting Unicode to ANSI.


q:
I am reading a .csv file and returning its lines in string array. One of the members is manufacturer, for which I have Toyota, Ford, etc.

I want to sort an array (Can be another collection) of the rows, by the value in manufacturer and alphabetical order.

So I'd have:

28437 Ford Fiesta
328   Honda Civic
34949 Toyota Yaris

and so forth...

What would be the best way to do this using C# and no database? I say no database because I could insert the csv into a table in a sql server database, and then query it and return the data. But this data is going into a html table built on the fly, which would make the database approach a little long winded.

[A]
What version of .NET are you using? If you're using 3.5 - or can use C# 3.0 and
LINQBridge
- then I'd definitely go with LINQ. First transform each line into some appropriate object, and then use OrderBy:
```
```
var cars = lines.Select(line => Car.ParseLine(line))
                .OrderBy(car => car.Manufacturer);
```
```


q:
In a SQL Server database, I record people's date of birth. Is there an straight-forward method of working out the person's age on a given date using SQL only?

Using DATEDIFF(YEAR, DateOfBirth, GETDATE()) does not work as this only looks at the year part of the date. For example DATEDIFF(YEAR, '31 December 2007', '01 January 2008') returns 1.

[A]
Check out this article:
How to calculate age of a person using SQL codes
Here is the code from the article:
```
```
DECLARE @BirthDate DATETIME
DECLARE @CurrentDate DATETIME

SELECT @CurrentDate = '20070210', @BirthDate = '19790519'

SELECT DATEDIFF(YY, @BirthDate, @CurrentDate) - CASE WHEN( (MONTH(@BirthDate)*100 + DAY(@BirthDate)) > (MONTH(@CurrentDate)*100 + DAY(@CurrentDate)) ) THEN 1 ELSE 0 END
```
```


q:
As far as Google searches tell me, the maximum allowed number of cookies depends very much on the browser, however I cannot find any recent data as to how much cookies are allowed on modern browsers.

I need to store a somewhat large number of user preferences in cookies (for not-yet-registered users), so what would be the best way of doing that? (Also, those cookies would be accessed both via javascript client-side and php server-side)

[A]
The best way would be to not store them in a cookie at all.
Store them in a database, and store the DB key in the cookie.  If it's just a few preferences then security isn't much of an issue.
Don't forget that cookies will be sent with every request - if you have 2kb of cookie data and load 10 images on a page, that's an extra 22kb of data.


q:
I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package.

My question is: Is there a way to access this object in the default-package from a Java-class in a named package?

[A]
You can’t use
classes in the default package from a named package.
(
Technically
you can, as shown in Sharique Abdullah's
answer
through reflection API,
but
classes from the unnamed namespace are
not in scope
in an
import declaration
)
Prior to J2SE 1.4 you could import classes from the default package using a syntax like this:
```
```
import Unfinished;
```
```
That's
no longer allowed
. So to access a default package class from within a packaged class requires moving the default package class into a package of its own.
If you have access to the source generated by groovy, some post-processing is needed to move the file into a dedicated package and add this "package" directive at its beginning.
Update 2014:
bug 6975015
, for JDK7 and JDK8, describe an even
stricter
prohibition against import from unnamed package.
The
```
TypeName
```
must be the canonical name of a class type, interface type, enum type, or annotation type.
The type must be either a member of a
named package
, or a member of a type whose outermost lexically enclosing type is a member of a
named package
,
or a compile-time error occurs
.
Andreas
points out
in the comments
:
"why is [the default package] there in the first place? design error?"
No, it's deliberate.
JLS 7.4.2. Unnamed Packages
says: "Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development".


q: Does anyone know if there is an implementation of javax.jms.QueueConnectionFactory for WebSphere MQ and where to get it? I Googled it and searched IBM website but couldn't find anything. I don't want to retrieve the connection or factory from Websphere MQ via JNDI, I need my own connection factory.

[A]
I think you need three jars
```
```
com.ibm.mq.jar
com.ibm.mqbind.jar
com.ibm.mqjms.jar
```
```
You instantiate a
MQQueueConnectionFactory
and i hope you can take it from there.
And here's more info:
IBMs HOWTO
Oh, and MQ can do "real" JMS instead of MQ - only the JMS implementation seemed to have problems closing the Channel properly - at least in our environment.


q: How can I call a C++ function from C# .NET?

[A]
compile the C++ function into a dll and
use P/Invoke
or
compile the C++ function into a C++/CLI assembly, wrap in a managed C++ class, and then treat like any other assembly (add a reference, use a using statement and call the class)


q:
I am trying to establish a basic .NET Remoting communication between 2x 64bit windows machines. If Machine1 is acting as client and Machine2 as server, then everything works fine. The other way around the following exception occurs:

System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 172.16.7.44:6666

The server code:

TcpChannel channel = new TcpChannel(6666);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(
  typeof(MyRemotableObject),"HelloWorld",WellKnownObjectMode.Singleton);

The client code:

TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
// Create an instance of the remote object
remoteObject = (MyRemotableObject)Activator.GetObject(
  typeof(MyRemotableObject), "tcp://172.16.7.44:6666/HelloWorld");

Any idea whats wrong with my code?

[A]
Windows Firewall? (Question author says this is not it.)
To track down connection issues the standard approach applies (apply in any order):
ping the machine
double check if some process really is listening in port 6666 (
```
netstat -an
```
)
telnet the machine on port 6666
try to use a different service on the machine.
check if some configuration upsets the server process listening on 6666 and causes it to refuse you. (don't know if that is possible with .NET remoting)
watch communication with the machine using a packet sniffer (Packetyzer, for example) to find out what's going on at the TCP/IP level.
maybe active network infrastructure components between server and client (layer-3 switches, firewalls, NAT-routers, whatever) are interfering


q:
I have an XML input file and I'm trying to output the result of a call like:

<xsl:value-of select="Some/Value"/>

into an attribute.

<Output Attribute="Value should be put here"/>

My problem is, since I'm outputting XML, the XSL processor won't allow me to write:

<Output Attribute="<xsl:value-of select="Some/Value"/>">

How do you accomplish this?

[A]
You can use an xsl:attribute element:
```
```
<Output>
  <xsl:attribute name="Attribute">
    <xsl:value-of select="Some/Value"/>
  </xsl:attribute>
</Output>
```
```


q:
I'm trying to add a new node to an jQuery SimpleTree, but all I seem to be able to get is "sTC.addNode is not a function"...

var simpleTreeCollection = $('.simpleTree').simpleTree({
    animate:true,
    drag:false,
    autoclose: false,
    afterClick:function(node){},
    afterDblClick:function(node){},
    beforeMove:function (destination, source, pos){},
    afterMove:function(destination, source, pos){},
    afterAjax:function() {},
    afterContextMenu:function(node){}
});

simpleTreeCollection.addNode('test', 'test');

Any suggestions what I might be doing wrong? Is there even the possibility to add a node?

[A]
hmm tricky one this and I have to say I dont like the plugin as it uses numerics as id's and w3c states "The attribute's value must begin with a letter in the range A-Z or a-z and may be followed by letters......."
However to get you working u need to select one of the nodes first in order to add to it like this
```
```
//Select first child node in tree
    $('#2').click();
    //Add new node to selected node
    simpleTreeCollection.get(0).addNode(1,'A New Node')
```
```


q:
what's the best/proper way of interacting between several windows in C# app?
Recently, I've run into a problem where one of program windows has to call method modifying main window. My solution was to create factory-like class, that would arrange all underlying model-data and organize the communication between various windows (through delegates). However, as passing one or two delegates was not a problem, I started thinking what if my other windows would need 10 delegates to interact properly with main window? Are delegates good solution? How to pass them in good way - through constructor, properties? Or maybe the need of using that many delegates is some serious design flaw itself?

[A]
If it's only needing to interact with the main window, why not give a reference to the main window in the constructor of the others?
```
```
public class MainForm : Form
{
}

public class OtherForm : Form
{
    protected MainForm MainForm { get; set; }

    public OtherForm(MainForm mainForm) : base()
    {
        this.MainForm = mainForm;
    }
}
```
```
EDIT:
Simple and effective.
If your forms need to interact with all the other forms of the application, then a
service locator
type pattern might be better suited.


q: I need to get an appointment into someone's Outlook calendar based on requests from their employees. The application runs in SharePoint (WSS 3.0). My first impressions are to use iCal or send meeting requests, but I haven't done either before & I'm looking for a very quick & easy way to get it done. Any ideas?

[A]
Sorry, there's no easy answer that I know of or can find.  I'm sure you can do via code but not easily within the SharePoint point-and-click interface.
From
this thread
it seems writing an event handler on a Calendar list would be the most effective way.
So from a 10,000 ft perspective, you'd build a system or workflow in Sharepoint that results in creating calendar entries in a SharePoint calendar.  Then have an event listener whose job it is to create iCal emails when new items are created in that SP calendar.
Brian Wilson (not the Beach Boy) has a few blog posts on
getting started with event handlers in SP


q:
I would like to create a private customized social networking for my company employees and partners so that they can collaborate, exchange messages, share experiences (events, book references, etc) and be grouped into communities. Does anybody know good Java framework for start developing this?

I would be looking for something that would contain basic components such as Profile, Friend List, Community, Events, Messages, etc. Each of this component could be extended to implement domain specific features. It would be nice if it also supports OpenSocial.

[A]
Shindig is in incubation at Apache :
http://incubator.apache.org/projects/shindig.html
YouTube Link About Shindig :
http://www.youtube.com/watch?v=ZcWszaReqXI
A List of Open Source Social Networking >Applications< Written in Java:
http://www.manageability.org/blog/stuff/java-open-source-social-network


q:
This may be a painfully simply question for which I will be mocked but I am having difficulty in using filepaths in master pages. I believe this is because if a page in a sub-directory to using the master page then the filepath is incorrect.

To fix this I need to get the filepath from the root but I can't seem to get it working.

I tried:

<script type="text/javascript" src="~/jQueryScripts/jquery.js"></script>

and

<script type="text/javascript" src="../jQueryScripts/jquery.js"></script>

No luck on either!

Any ideas on how I can tell it to get the filepath from the root?

[A]
I'm just assuming by filepath, you actually mean url (or uri, I forget which one is partial).
Without the ~, the first example should work.
```
<script type="text/javascript" src="/jQueryScripts/jquery.js"></script>
```
would cause the browser to request
http://www.example.com/jQueryScripts/jquery.js
(where www.example.com is your domain).


q:
If for example you follow the link:

data:application/octet-stream;base64,SGVsbG8=

The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself.  Is there any way of suggesting a default name in the markup?  If not, is there a JavaScript solution?

[A]
According to
RFC 2397
, no, there isn't.
Nor does there appear to be any
attribute
of the
```
<a>
```
element that you can use either.
However HTML5 has subsequently introduced the
```
download
```
attribute on the
```
<a>
```
element, although at the time of writing support is not universal (no MSIE support, for example)


q: for a server based j2ee application, I need to retrieve the number of pages from word documents.. any ideas what works?

[A]
If the documents are modern Word 2007 format you can use direct XML-based manipulation, through
OOXML
. This is by far the better long term solution, though I realize it may not be realistic for an entire organization to change overnight.
If they are older Word formats, you're probably stuck with server-side Word/Excel/Powerpoint/Outlook programmable object models, although
you're not supposed to do that on the server
..


q:
I have a JComponent that's painting various shapes on itself.  I'm detecting whenever the mouse enters one of these shapes and changing the tooltip accordingly.

The problems I'm having are:

The tooltip doesn't follow the mouse as the user tracks the mouse across the shape. It
stays where it was first set and then only jumps whenever another shape changes the tooltip.

It takes about a second for the tooltip to appear, but I'd like it to appear immediately.

Can someone suggest a way of getting these behaviours without writing a custom tooltip mechanism?

[A]
Take a look at the
ToolTipManager
.
You can register your component with that manager and then adjust a number of settings. Its pretty straight forward to use.
That at least can solve your initialdelay problem.
For your first problem you can overide the createTooltip command from your component to get a hold of the JTooltip instance. and then its easy make the position change whenever you move your mouse(aka follow your mouse) as its a subclass of the JComponent class.


q: Does the C++ STL set data structure have a set difference operator?

[A]
Yes, there is a
set_difference
function in the algorithms header.
Edits:
FYI, the set data structure is able to efficiently use that algorithm, as stated in its
documentation
.  The algorithm also works not just on sets but on any pair of iterators over sorted collections.
As others have mentioned, this is an external algorithm, not a method.  Presumably that's fine for your application.


q: What is the best way to convert a fixed length string array to a fixed lengh integer array in C++ ?

[A]
This will copy an array of characters into an array of ints:
```
```
#include <algorithm>
char foo[9] = "asdfasdf";
int bar[9];
std::copy(foo, foo+9, bar);
```
```
std::copy
This assigns the values of a null terminated character array {'a', 's', 'd', 'f', 'a', 's', 'd', 'f', '\0'} to an integer array, yielding {97, 115, 100, 102, 97, 115, 100, 102, 0}.  Note that this includes the null termination of the original string.
This will parse an array of strings, and put their integer values into an array of ints:
```
```
#include <algorithm>
#include <sstream>
#include <string>

template <class T>
T parse(const std::string& str)
{
    T temp;
    std::istringstream iss(str);
    iss >> temp;
    if(iss.bad() || iss.fail())
    {
        // handle conversion failure
    }
    return temp;
}

...

std::string foo[3];
int bar[3];
foo[0] = "67";
foo[1] = "11";
foo[2] = "42";

std::transform(foo, foo+3, bar, parse<int>);
```
```
std::transform
This will transform each of the strings in the array foo into ints, and place them in the array of ints, bar.


q:
I am currently modifying some jsf application. I have two beans.

connectionBean

UIBean

When I set my connection parameters in connectionBean the first time, the UIBean is able to read my connectionBean information and display the correct UI Tree.

However when I try to set the connection parameters in the same session. My UIBean will still use the previous connectionBean information.

It only will use after I invalidate the whole httpSession.

Is there anyway I can make one session bean update another session bean?

[A]
Sounds to me like it's some kind of problem with UIBean referencing an out-of-date version of ConnectionBean. This is one problem with JSF - if you re-create a bean, JSF will not update the references in all your other beans.
You could try getting a 'fresh' copy of the ConnectionBean each time. The following method will retrieve a backing bean by name:
```
```
protected Object getBackingBean( String name )
{
    FacesContext context = FacesContext.getCurrentInstance();

    return context
            .getApplication().createValueBinding( String.format( "#{%s}", name ) ).getValue( context );
}
```
```
Without knowing the specifics of your code and how you're using the beans it's difficult to be more specific!


q:
If I'm writing unit tests in Python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error?

I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.

For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:

class TestBar(unittest.TestCase):
    def runTest(self):
        for t1, t2 in testdata:
            f = Foo(t1)
            self.assertEqual(f.bar(t2), 2)

If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.

[A]
You can use simple print statements, or any other way of writing to standard output.  You can also invoke the Python debugger anywhere in your tests.
If you use
nose
to run your tests (which I recommend), it will collect the standard output for each test and only show it to you if the test failed, so you don't have to live with the cluttered output when the tests pass.
nose
also has switches to automatically show variables mentioned in asserts, or to invoke the debugger on failed tests.  For example,
```
-s
```
(
```
--nocapture
```
) prevents the capture of standard output.


q: How do you get the current directory where your app is running?

[A]
You could try this:
```
```
using System.IO;
using System.Reflection;

namespace Utilities
{
    static public class DirectoryHelper
    {
        static public string GetCurrentDirectory ()
        {
            return Path.GetDirectoryName (Assembly.GetExecutingAssembly ().GetName ().CodeBase);
        }
    }
}
```
```


q: I am working on an application where I have an images folder relative to my application root. I want to be able to specify this relative path in the Properties -> Settings designer eg. "\Images\". The issue I am running into is in cases where the Environment.CurrentDirectory gets changed via an OpenFileDialog the relative path doesn't resolve to the right location. Is there a way to specifiy in the Settings file a path that will imply to always start from the application directory as opposed to the current directory? I know I can always dynamically concatenate the application path to the front of the relative path, but I would like my Settings property to be able to resolve itself.

[A]
As far as I know, there is no built-in functionality that will allow this type of path resolution. Your best option is to dynamically determine the applications executing directory and concatenate to it your images path. You don't want to use
```
Environment.CurrentDirectory
```
specifically for the reasons you mention - the current directory may not always be correct for this situation.
The safest code I've found to find the executing assembly location is this:
```
```
public string ExecutingAssemblyPath()
{
   Assembly actualAssembly = Assembly.GetEntryAssembly();
   if (this.actualAssembly == null)
   {
      actualAssembly = Assembly.GetCallingAssembly();
   }
   return actualAssembly.Location;
}
```
```


q:
I'm currently refactoring code to replace Convert.To's to TryParse.

I've come across the following bit of code which is creating and assigning a property to an object.

List<Person> list = new List<Person>();

foreach (DataRow row in dt.Rows)
{
     var p = new Person{ RecordID = Convert.ToInt32(row["ContactID"]) };

     list.Add(p);
}

What I've come up with as a replacement is:

var p = new Person { RecordID = Int32.TryParse(row["ContactID"].ToString(), out RecordID) ? RecordID : RecordID };

Any thoughts, opinions, alternatives to what I've done?

[A]
Write an extension method.
```
```
public static Int32? ParseInt32(this string str) {
    Int32 k;
    if(Int32.TryParse(str, out k))
        return k;
    return null;
}
```
```


q:
I've just been tasked with building a web application using ASP (.net) and am looking for some advice on where to start.   In a nutshell the application needs to be able to.

Handle user verification / authentication

Handle sessions

Do SOAP messaging

The application is intended to act as a front end for system functions that are accessible via web service calls.

I intend to do a lot of work on the client side using JavaScript and am thinking of using ASP solely as the framework for the 3 items I listed above.

Appreciate any suggestions you may have.

[A]
WCF for Soap -- I would also suggest picking this up:
alt ASP.NET 3.5 http://ecx.images-amazon.com/images/I/518N8vYWf1L._SL500_AA240_.jpg
This book is in tutorial form -- and Jesse Liberty is a great teacher (as are his co-authors).


q:
My class contains a Dictionary<T, S> dict, and I want to expose a ReadOnlyCollection<T> of the keys. How can I do this without copying the Dictionary<T, S>.KeyCollection dict.Keys to an array and then exposing the array as a ReadOnlyCollection?

I want the  ReadOnlyCollection to be a proper wrapper, ie. to reflect changes in the underlying Dictionary, and as I understand it copying the collection to an array will not do this (as well as seeming inefficient - I don't actually want a new collection, just to expose the underlying collection of keys...). Any ideas would be much appreciated!

Edit: I'm using C# 2.0, so don't have extension methods such as .ToList (easily) available.

[A]
If you really want to use ReadOnlyCollection<T>, the issue is that the constructor of ReadOnlyCollection<T> takes an IList<T>, while the KeyCollection of the Dictionary is only a ICollection<T>.
So if you want to wrap the KeyCollection in a ReadOnlyCollection, you'll have to create an adapter (or wrapper) type, implementing IList<T>, wrapping the KeyCollection. So it would look like:
```
```
var dictionary = ...;
var readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys)
);
```
```
Not very elegant though, especially as the KeyCollection is already a readonly collection, and that you could simply pass it around as an ICollection<T> :)


q:
How do I build an escape sequence string in hexadecimal notation.

Example:

string s = "\x1A"; // this will create the hex-value 1A or dec-value 26

I want to be able to build strings with hex-values between 00 to FF like this (in this example 1B)

string s = "\x" + "1B"; // Unrecognized escape sequence

Maybe there's another way of making hexadecimal strings...

[A]
You don't store hexadecimal values in strings.
You can, but it would just be that, a string, and would have to be cast to an integer or a byte to actually read its value.
You can assign a hexadecimal value as a literal to an int or a byte though:
```
```
Byte value = 0x0FF;
int value = 0x1B;
```
```
So, its easily possible to pass an hexadecimal literal into your string:
```
```
string foo = String.Format("{0} hex test", 0x0BB);
```
```
Which would create this string "126 hex test".
But I don't think that's what you wanted?


q:
What is the best way to do cross-platform handling of hidden files?
(preferably in Python, but other solutions still appreciated)

Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?

[A]
"Is there a standard way to deal with this?"  Yes.  Use a standard (i.e., POSIX-compliant) OS.
Since Windows is non-standard -- well -- there's no applicable standard.  Wouldn't it be great if there was?  I feel your pain.
Anything you try to do that's cross-platform like that will have Win32 oddities.
Your solution is -- for the present state of affairs -- excellent.  At some point in the future, Microsoft may elect to write a POSIX-compliant OS.  Until then, you're coping well with the situation.


q:
I am using a Flex dataGrid, and need to sort some of my columns numerically.

Looking at the sortCompareFunction, it seems like i need to create a different function for each column that i want to sort, because my sort function has to know what field it is sorting on.

Is there any way that I can pass the field to be sorted on into the function? so that I only need one numeric sorting function.

[A]
I did it using this function:
```
function fieldNumericSorter(field:String):Function {
    return function (obj1:Object, obj2:Object):int {
        return sign( int(obj1[field]) - int(obj2[field]) );
    }
}
```
and for each column that needed sorting set
```
colToBeSorted.sortCompareFunction = fieldNumericSorter("fieldname");
```


q:
public class Item
{
        private int  _rowID;
        private Guid _itemGUID;

        public Item() { }

        public int Rid
        {
            get
            {
                return _rowID;
            }
            set {  }

        }

        public Guid IetmGuid
        {
            get
            {
                return _itemGuid;
            }
            set
            {
                _itemGuid= value;
            }

        }

}

The above is my custom object.

I have a list:

List<V> myList = someMethod;

where V is of type Item, my object.

I want to iterate and get the properties as such

foreach(V element in mylist)
{
   Guid test = element.IetmGuid;
}

When I debug and look at the 'element' object I can see all the properties in the 'Quickwatch' but I cannot do element.IetmGuid.

[A]
```
```
foreach( object element in myList ) {
    Item itm = element as Item;
    if ( null == itm ) { continue; }
    Guid test = itm.ItemGuid;
}
```
```


q:
So let's say you wanted to make a copy of a Web Form page within a .Net Project.

Is there an easier way than:

Copy Source Page

Page Source Page within project to get new page

Exclude Source Page

Rename code behind class for new page

Add Source Page Back

Sometimes I miss something obvious is there a better way to do this?  I know the next question would be "Why are you copying code within a project instead for reusing it?"  Let's just say that's a secret;).

[A]
I do this:
Select the original ASPX file in solution explorer
Ctrl+C followed by Ctrl+V (quick copy paste)
Rename new ASPX file (let's say NewFile.aspx)
Rename code-behind class name to NewFile
Rename
```
Inherits
```
attribute of
```
Page
```
directive within HTML to end with 'NewFile'
(Optional) If you moved the page into a different folder, you'll need to update the Namespace references in the HTML's
```
Page
```
directive as well as in the code-behind.


q:
As part of our build process I need to set the version information for all of our compiled binaries. Some of the binaries already have version information (added at compile time) and some do not.

I want to be able to apply the following information:

Company Name

Copyright Notice

Product Name

Product Description

File Version

Product Version

All of these attributes are specified by the build script and must be applied after compilation. These are standard binaries (not assemblies) compiled with C++ Builder 2007.

How can I do this?

[A]
There is this tool
ChangeVersion
[1]
List of features (from the website):
command line interface
support for .EXE, .DLL and .RES files
update FileVersion and ProductVersion based on a version mask
add/change/remove version key strings
adjust file flags (debug, special, private etc)
update project files ( .bdsproj | .bpr | .bpk | .dproj )
add/change main application icon
use ini file with configuration
Windows Vista support (needs elevation)
easy to integrate into a continuous build environment
Full Disclosure: I know the guy who wrote this tool, I used to work with him.  But this also means that I know he makes quality software ;)
[1]
the link is dead. There seems to be mirrored version at
download.cnet.com
.


q: If I have an xmlreader instance how can I use it to read its current node and end up with a xmlElement instance?

[A]
Not tested, but how about via an
```
XmlDocument
```
:
```
```
XmlDocument doc = new XmlDocument();
    doc.Load(reader);
    XmlElement el = doc.DocumentElement;
```
```
Alternatively (from the cmoment), something like:
```
```
doc.LoadXml(reader.ReadOuterXml());
```
```
But actually I'm not a fan of that... it forces an additional xml-parse step (one of the more CPU-expensive operations) for no good reason. If the original is being glitchy, then perhaps consider a sub-reader:
```
```
using (XmlReader subReader = reader.ReadSubtree())
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(subReader);
        XmlElement el = doc.DocumentElement;
    }
```
```


q:
We're using Infragistics grid (most probably, we'll have 8.2 version at the end) and we want to configure row/cells appearances "on-demand" in order to be able to provide sort of "dynamic appearance".

For example, I want some cell to be red or green, depending on its value. We might want to tweak other characteristics as well (font, size, image, etc).

A perfect place to do it would be some event, that happen before a cell gets repainted... But it seems there is no such event in Infragistics...

Or am I wrong? Any help?

Clarification: I'm talking about WinForms Infragistics UltraGrid

[A]
There is an event.  I don't remember exactly what it's called, but it's got to be something like 'DataRowBound' or 'ItemDataBinding', etc..
Also,
this article
might help.
Not that this has anything to do with your question, but I'd stay away from heavy use of Infragistics controls - they're very heavy and will slow down the page rendering process considerably.  Just my $0.02.


q: How can I generate valid XML in C#?

[A]
It depends on the scenario.
```
XmlSerializer
```
is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5,
```
XDocument
```
, etc. are also very friendly. If the size is very large, then
```
XmlWriter
```
is your friend.
For an
```
XDocument
```
example:
```
```
Console.WriteLine(
    new XElement("Foo",
        new XAttribute("Bar", "some & value"),
        new XElement("Nested", "data")));
```
```
Or the same with
```
XmlDocument
```
:
```
```
XmlDocument doc = new XmlDocument();
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));
el.SetAttribute("Bar", "some & value");
el.AppendChild(doc.CreateElement("Nested")).InnerText = "data";
Console.WriteLine(doc.OuterXml);
```
```
If you are writing a
large
stream of data, then any of the DOM approaches (such as
```
XmlDocument
```
/
```
XDocument
```
, etc.) will quickly take a lot of memory. So if you are writing a 100 MB XML file from
CSV
, you might consider
```
XmlWriter
```
; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here):
```
```
XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data");
writer.WriteEndElement();
```
```
Finally, via
```
XmlSerializer
```
:
```
```
[Serializable]
public class Foo
{
    [XmlAttribute]
    public string Bar { get; set; }
    public string Nested { get; set; }
}
...
Foo foo = new Foo
{
    Bar = "some & value",
    Nested = "data"
};
new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);
```
```
This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with
```
XmlSerializer
```
is that it doesn't like to serialize immutable types : everything must have a public getter
and
setter (unless you do it all yourself by implementing
```
IXmlSerializable
```
, in which case you haven't gained much by using
```
XmlSerializer
```
).


q:
I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like

    <c:forEach items="${m.items}" var="i" varStatus="itemsRow">
      <form:input path="items[${itemsRow.index}]"/>
    </c:forEach>
    <form:errors path="items" />

would work fine for a List-type property, but for a Set throws an error when, upon submit, it tries to bind input field content to object attributes.

Is there something in Spring that works out of the box with Sets?

[A]
I think it has to be an ordered collection.  For example,there's
a chart
in the Spring reference that talks about how to reference properties.  It says:
account[2]    Indicates the third element
  of the indexed property account.
  Indexed properties can be of type
  array, list or other
naturally ordered
collection (emphasis theirs)
Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray().  Then your items attribute would reference the array.  Of course, you can't depend on the ordering.


q:
I'm using nusoap to connect to a soap webservice. The xml that the class sends to the service is constructed from an array, ie:

$params = array("param1" => "value1", "param2" => "value1");
$client->call('HelloWorld', $params, 'namespace', 'SOAPAction');

This works fine. A multidimensional array also constructs a nice nested xml message.

I encounter a problem when i need two tags with the same name:

<items>
   <item>value 1</item>
   <item>value 2</item>
</item>

$params = array("items" => array("item" => "value 1", "item" => "value 2"));

The second item in the array overwrites the first which results in:

<items>
   <item>value 2</item>
</item>

How can achieve this?

[A]
The problem is with the inner array()
```
```
$test_array = array("item" => "value 1", "item" => "value 2");
```
```
creates an array with a single key ("item").
Try this and see if it works:
```
```
$params = array("items" => array("item" => array("value 1", "value 2")));
```
```
No guarantees, though... I haven't used nusoap in a
long
time and don't have PHP installed here to test it.


q:
I'm using system catalog views such as SYS.ALL_ OBJECTS, SYS.FOREIGN_KEYS etc. to get information about my database structure in MS SQL 2005.

Are there equivalent functions/views for MySQL (v. 5) servers?

[A]
Hmm, I haven't studied everything it contains, but there's a good deal of information in the
information_schema
.  There's also the
show
command.
Still, I don't see a single command to show all the foreign keys in there.


q:
I would like to add a backcolor for specific line depending of a Property of the object binded.

The solution I have (and it works) is to use the Event DataBindingComplete but I do not think it's the best solution.

Here is the event:

    private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {

        for (int i = 0; i < this.myGrid.Rows.Count; i++)
        {
            if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special)
            {
                this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
            }
        }
    }

Any other option that would be better?

[A]
I don't really work with WinForms that much, but in ASP you would use the 'ItemDataBound' method.  Is there something similar in windows forms for a DataGrid?
If so, in that method, the event arguments would contain the item that was databound, along with the DataGrid row.  So the general code would look something like this (syntax is probably off):
```
```
if(((MyObject)e.Item.DataItem).Special)
   e.Item.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
```
```


q:
Is it possible to have two virtual directories under the same website in IIS but have the virtual directories be using different versions of the .net framework?

For example, under the default website, can I have one virtual directory targeting the 2.0 framework and a second virtual directory targeting the 1.1 framework?

This is for IIS 6, thanks!

[A] You are not saying which version of IIS you are using, but for 6.0 and up, just assign them to different application pools, and set the pools to use the right version of .Net.


q:
We're developing a product that relies on the Microsoft Sync Framework to keep the data on a client app and on the server in sync.  What we have noticed is when syncing about 16 tables and ~2200 records it will take about 4 minutes, which is not acceptable.

Using the SQL Server Profiler we found it is using sp_executesql to execute the queries.  when run without sp_executesql a specific query runs in <1s, but with it takes over 10s.

So the question is: What are we doing wrong and is there anything we can do to speed it up.

[A]
sp_executesql is using dynamic sql. each row is being processed singularly.
4 minutes seems rather long, you should look at the design of your 16 tables and check the performance on them. Try using the execution plan to view where the bottleneck may be occurring.
check out this link that covers the basics:
SQL Execution Plan basics
Try scrolling down to the bottom of the article, where there are screen shots of the actual graphical interface in SQL Management Studio. There are some boring parts of the article, but you can atleast see the graphical execution plan and its benefits.


q:
Html.TextBox("ParentPassword", "", new { @class = "required" })

what the gosh darned heck is the @ for the @class.

[A]
```
class
```
is a reserved keyword, so you can't use this as a variable name.
The @ operator allows you to get around this rule.  The reason why its being done here is that the anonymous object is used to populate attributes on a HTML element.  A valid attribute name is "class", which lets you set the CSS class on the element.


q:
I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do

Obj *obj = libname_newDevice();

Now, should I use delete or should I do obj->deleteMe();? I ask because I am not exactly doing new so I shouldn't be doing the delete?

I have obj->create(theType); which returns a class with the Obj interface.
My real question is do I need a libname_deleteDevice(); or is obj->deleteMe() fine since I have a deleteMe in the interface?

[A]
Since you are abstracting the creation inside
```
libname_newDevice()
```
(which I have to say isn't a good approach), you should destroy using something like
```
libname_destroyDevice (obj)
```
.
And as the comment from Martin suggests, it's best to put them in the constructor and destructor of a custom class, that you just need to create on stack, and the compiler will take care of the rest.


q:
I'm creating an interface wrapper for a class.  The member within the class is a reference(to avoid copying the large structure).  If I create a private constructor, what is the best way to initialize that reference to appease the compiler?

struct InterfaceWrapper {
    InterfaceWrapper( SomeHugeStructure& src ):m_internal(src){};
    int someElement(void) const { return m_internal.someElement; };
private:
    InterfaceWrapper(){}  // initialize m_internal
    SomeHugeStructure& m_internal;
};

[A]
If you really need to construct the class without having an element, a reference is not the way to go.
If your only reason to use a reference is to avoid copying, I'd suggest using a pointer.
You can simply take the address of the passed reference in you regular constructor, and initialize it to NULL in the private constructor. When the object's lifetime ends the pointer will be a dangling pointer, but the same is true for references...
Alternatively, have the public constructor take a smart pointer and use such a smart pointer as member too, if you're concerned about lifetimes.
And of course, cope with the pointer possibly being NULL in the remainder of the class' code. (but you had to cope with the member possible being a stub in the reference case too, so that's not really an issue)


q:
I've got a timer running in my Delphi MDI application and I'd like to use it to pop up a message if something changes in the background. But I don't want that message to pop up when the the application has a modal dialog in the foreground because the user couldn't do anything about it.

So what I'd like to know is how can I check for the existence of a modal dialog in my application?

[A]
You could try with this code:
```
```
var
  ActForm: TCustomForm;
begin
  ActForm := Screen.ActiveForm;
  if (ActForm = nil) or not (fsModal in ActForm.FormState) then begin

  end;
end;
```
```
I tested with Delphi 4, works for me.
[EDIT]: But you should really think about whether popping up a form and stealing focus is a good idea. It depends on your application, but if a user is currently entering something into an edit field, or doing something with the mouse, then this might break their workflow.


q:
Into some view data i have put the result of an anonymous type:

            var projectData = from p in db.Projects
                          orderby p.title
                          select new
                          {
                              Title = p.title,
                              DevURL = p.devURL ?? "N/A",
                              QAURL = p.qaURL ?? "N/A",
                              LiveURL = p.liveURL ?? "N/A",
                              Users = p.GetUsers().MakeUserList()
                          };

        ViewData["ProjectSummary"] = projectData;

How do I iterate through this view data in the MVC view on the front end to say, make a table of results?

[A]
The problem is not that it's an anonymous type.  The problem is that it's merely a lazy-evaluated IQueryable<> object, and it hasn't been evaluated yet.
I can't answer for ASP.NET MVC, but in the very similar Monorail, you would have to convert it from an iterator into an actual collection:
```
```
var projectData = (from p in db.Projects
                      orderby p.title
                      select new
                      {
                          Title = p.title,
                          DevURL = p.devURL ?? "N/A",
                          QAURL = p.qaURL ?? "N/A",
                          LiveURL = p.liveURL ?? "N/A",
                          Users = p.GetUsers().MakeUserList()
                      }).ToList();
```
```


q:
I have an .xsd, .vb, .xsc, and .xss file for a dataset in Visual Studio 2008 that I copied over from another Visual Studio project, however I need to make changes to the dataset. Thus I got into the XSD file, created new columns, deleted ones that aren't needed, etc., etc.  However I realized when I attempted to use the new dataset I did not have the Visual Basic code behind the scenes. This code is typically found in dataset.designer.vb. When I copied the old one over of course it was no longer valid since columns changed.

How I can force Visual Studio 2008 to use a .xsd file and to have it create/update its designer code?

[A]
Unfortunately, this is in the gray area of things things that I can do when I need to, but I haven't needed to do enough to impart the knowledge to others.
All I know is that
```
*.designer.vb
```
means that this code was generated by Visual Studio, and if it generated it once it can do it again. Additionally, the very few times (maybe twice, both in Visual Studio 2005) that I have done this, it seemed like it was as simple as adding the  *.xsd file to Solution Explorer. If that alone doesn't do it, try showing all files or right/double clicking on the *.xsd.


q:
I'm trying to insert a comment character into a string something similar to this:

-CreateVideoTracker VT1 "vt name"

becomes

-CreateVideoTracker VT1 # "vt name"

The VT1 word can actually be anything, so I'm using the regex

$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g;

which gives me the result:

-CreateVideoTracker w #T1 "vt name"

Is there any way to do this with a single regex, or do I need to split up the string and insert the comment manually?

[A]
```
```
$line =~ s/^(\-CreateVideoTracker)\s+(\w+)/$1 $2 #/;
```
```
The bracketed expressions (known as "capture buffers") in the first half of the regexp are referenced as
```
$1
```
,
```
$2
```
. etc in the second half.


q:
What is the preferred way to insert strings that can contain both single and double quotes (",') into MySql using DBI?  For example, $val1 and $val2 can contain quotes:

my $dbh = DBI->connect( ... );
my $sql = "insert into tbl_name(col_one,col_two) values($val1, $val2)";
my $sth = $dbh->prepare($sql);
$sth->execute();

[A]
Use a bound query using
```
```
$sth = $dbh->prepare("insert into tbl_name(col_one,col_two) values(?,?)");
$sth->execute($val1, $val2);
```
```
If you use bound variables, everything is escaped for you.
Update: Changed my example to correspond with the example edited into the question.
Update: I don't know why Adam deleted his answer, but if for some reason you can't use bound variables (aka "placeholders"), you can also use
```
$dbh->quote($var)
```
on the variable.  For example:
```
```
$sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
    $dbh->quote(q("Don't"));
```
```


q:
I'm creating a control and need to pass it the current logon user as a parameter (declaratively)

I tried this but didn't work (I got "<%= User.Identity.Name %>" as value):

<cc1:MyControl id="myid" runat="server" User="<%= User.Identity.Name %>" />

Is there a way to do it?

[A]
Try using:
```
```
User="<%= User.Identity.Name %>"
```
```
%= is for output
%# is for databinding.


q: Is there any way in a Win32 environment to "tune" the timeout on a socket connect() call?  Specifically, I would like to increase the timeout length.  The sockets in use are non-blocking.  Thanks!

[A]
Yes, this is possible.
If you're in non-blocking mode after
```
connect()
```
, you normally use
```
select()
```
to wait till I/O is ready. This function has a parameter for specifying the timeout value and will return 0 in case of a timeout.


q: I have an implementation of default handler. When it gets to a   in the character data it stops parsing. Is there any reason that it is doing this? Are there additional properties that I need to set in order for it to deal with &nbsp?

[A]
```

```
is not a valid xml entity. You might try replacing it with
```

```
instead, it does the same thing (non-breaking space).


q:
I'm automating some source control software functionality using a dot bat script but given that our svn repos are hosted in a *NIX box, I'm facing the eternal case problem between these two worlds.

Is there any cmd.exe function to convert the value of the Windows system variable %USERNAME% to lower case?

Thanks much in advance!

[A]
a quick google found
this
...
```
```
@echo off
goto :end_remarks
*************************************************************************************
*
*
*    authored:Sam Wofford
*    Returns lowercase of a string
*    12:13 PM 11/13/02
**************************************************************************************
:end_remarks
setlocal
set errorlevel=-1
if {%1}=={} echo NO ARG GIVEN&call :Help &goto :endit
if {%1}=={/?} call :Help &goto :endit
call :set_LCASE_array a b c d e f g h i j k l m n o p q r s t u v w x y z

:start
set input=%1
set input=%input:"=%
set totparams=0
call :COUNT_PARAMS %input%
call :MAKE_LOWERCASE %input%
set errorlevel=
echo %convertedstring%
endlocal
goto :eof
:endit
echo %errorlevel%
endlocal
goto :eof

:MAKE_LOWERCASE
:nextstring
if {%1}=={} goto :eof
set string=%1
set /a params+=1
set STRINGCONVERTED=
set pos=0
:NEXT_CHAR
set onechar=%%string^:^~%pos%,1%%
for /f "tokens=1,2 delims==" %%a in ('set onechar') do for /f %%c in ('echo %%b') do call :checkit %%c
if not defined STRINGCONVERTED goto :NEXT_CHAR
shift /1
if %params% LSS %totparams% set convertedstring=%convertedstring% &:add one space,but not at end
goto :nextstring
goto :eof

:Help
echo USAGE:%~n0 string OR %~n0 "with spaces"
echo function returns the lowercase of the string or -1 (error)
echo strings with embedded spaces needs to be in quotes Ex. "lower case"
echo in a batch NTscript "for /f %%%%A in ('lcase STRING') do set var=%%%%A"
set errorlevel=
goto :eof

:checkit
set LCFOUND=
if /i {%1}=={echo} set STRINGCONVERTED=Y&goto :eof
set char=%1
for /f "tokens=2 delims=_=" %%A in ('set LCASE_') do call :findit %%A %char%
:skipit
if defined LCFOUND (set convertedstring=%convertedstring%%ucletter%) else (set convertedstring=%convertedstring%%char%)
set /a pos+=1
goto :eof

:set_LCASE_array
:setit
if {%1}=={} goto :eof
set LCASE_%1_=%1
SHIFT /1
goto :setit

:findit
if defined LCFOUND goto :eof
set ucletter=%1
set lcchar=%2
if /i {%ucletter%}=={%lcchar%} set LCFOUND=yes
goto :eof

:COUNT_PARAMS
:COUNTPARAMS
if {%1}=={} goto :eof
set /a totparams+=1
shift /1
goto :COUNTPARAMS
```
```
add that as a file (lowercase.cmd) to your path and you should be able to call it as "Lowercase.cmd %Username%", you could pipe it into another command if needed.


q:
Some databases support commands such as:

SELECT TOP 10 START AT 10 * FROM <TABLE>

Essentially I need to pull the first 10 records, then the next 10, then the next 10 etc.  Maybe there is another way to do this but in the past I've done it like the above for databases that support 'START AT'.

[A]
```
```
SELECT Top 10 *
FROM Table
WHERE <primary key> Not IN (
    SELECT Top 10 <primaryKey>
    FROM Table
    ORDER BY <primary Key> ASC)
ORDER BY <primary Key> ASC
```
```


q:
I have a Lotus Domino server with a truly astounding number of Domino databases on it, arranged in various folders.

Is there some means of exporting a list of all these databases, with their titles and creators' names, in a spreadsheet format of some kind? I have the Domino Admin and Domino Designer software, and I have or can get whatever access rights I'd need.

[A]
You'd think there'd be a way in the Domino Admin, but there's no way to export the list.  So, your best bet I think is to use the Domain Catalog database.  To build it, go into the server configuration doc > Server Tasks > and turn on the Domain Catalog.  Then the catalog.nsf database will be built and will contain all the databases in your domain.  You can customize the views to include the information you need.
Then finally, you can go into a view, select all the documents and click Edit > Copy Selected As Table.  Then paste that into a spreadsheet.


q:
For Each line As String In System.IO.File.ReadAllLines("file.txt")
'Do Something'
Next

and

Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt")
    Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
            While Not s.EndOfStream
                    Dim line As String = s.ReadLine

                    'put you line processing code here

            End While
    End Using
End Using

are both showing as mostly red, I'm running a clean install of MS VS2005 and these codes were both recomended to me, am I missing something else I need to install or declare?

[A]
FROM Msdn you should do the following to read all lines
```
```
Dim Lines As String()
Lines = System.IO.File.ReadAllLines("file.txt")
```
```
For the second example something like this might work
```
```
Dim sr as New StreamReader("somefile.txt")
Dim line as String = sr.ReadLine()
Do While Not line is Nothing
    line = sr.ReadLine()
    'do something else
Loop
```
```
I just created the following VB.Net Console app and it works fine:
```
```
Imports System.IO

Module Module1

Sub Main()
    Dim sr As New StreamReader("somefile.txt")
    Dim line As String = sr.ReadLine()
    Do While Not line Is Nothing
        line = sr.ReadLine()
        'do something else
    Loop

End Sub

End Module
```
```


q:
If you have a sequence of block elements and you wanted to place margin in between them.

Which do you prefer, margin-top or margin-bottom or both? Why?

[A]
I always use
```
margin-bottom
```
, which means there is no unnecessary space before the first element.


q: I'm looking for a library to read a SWF file and let me parse through its actionscript and header information. Is there anything out there that will work?

[A]
I do not know of any libraries (including .NET) that let you read and parse (or reverse engineer) the contents of SWF's files. The ActionScript you are referring to is compiled down to byte code during compilation so you will not find the actual ActionScript source code in the SWF file.
For more information in the SWF file format I suggest you have a look at the
official specifications
.


q:
My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.

I could store them in XML, but XML is way to complex, and it would require traversing nodes, and child nodes and so on, all I want is some class that takes a file and generates key value pairs. I want as little error handling as possible, and I want it done with as little code as possible.

I could code a class like that myself, but I'd rather learn how it's don'e in the framework than inventing the wheel twice. Are there some built in magic class in .NET (3.5) that are able to do so?

MagicClass kv = new MagicClass("Settings.ini"); // It doesn't neccesarily have to be an INI file, it can be any simple key/value pair format.
string Value1 = kv.get("Key1");
...

[A]
I don't know of any builtin class to parse ini file. I've used
nini
when needed to do so. It's licensed under the MIT/X11 license, so doesn't have any issue to be included in a closed source program.
It's very to use. So if you have a Settings.ini file formatted this way:
```
```
[Configuration]
Name = Jb Evain
Phone = +330101010101
```
```
Using it would be as simple as:
```
```
var source = new IniConfigSource ("Settings.ini");
var config = source.Configs ["Configuration"];

string name = config.Get ("Name");
string phone = config.Get ("Phone");
```
```


q:
I am trying to setup a failover location for MOSS. The current farm is built on 32 bit Windows 2003. The servers ar the failover location are all 64 bit Windows 2008.

Is there any way to make these two environments talk and stay in sync? I have considered a "stretched" farm configuration, but that won't work unles the bit width of both locations are the same.

The current database server for MOSS is replicated to our failover location using clustering and is visible at both locations.

[A]
You can mix 32 bits and 64 bits in the same farm, it's fully supported.
However, it's highly recommenced to keep each tiers in the same bit width (for example all WFE 64 bits, application server 32 bits, SQL servers 64 bits).
From msdn @
http://technet.microsoft.com/en-us/library/cc261700.aspx
You can deploy an Office SharePoint Server 2007 farm on a mix of 32-bit and 64-bit servers, provided that you maintain architecture homogeneity at each topology layer. For example, you should not mix 32-bit and 64-bit Web front-end (WFE) servers, but you may use 64-bit database servers in a farm with 32-bit WFE servers and application servers.


q:
I have a number of web apps running on several IIS6/Server 2003 boxes. They run well and are happy. They are all asp.net web apps and use .NET 3.5.

What, if any, would be valid reasons for contemplating moving the web apps to IIS7/Server 2008?

[A]
Eventually, Microsoft will discontinue Server 2003 support. Admittedly, that won't be for several years, so it doesn't impact you today.
Improved support for ASP.NET MVC. This is probably the big one for most of us. You can get ASP.NET MVC working on IIS6, but there are
some hoops to jump through
.
I'd give you more, but I myself am not yet on Server 2008 yet, and have nothing else to give. Presumably Vista (which I do use, both at work and at home) has the "same" IIS7 as 2008 does -- the UIs certainly look very similar -- but I wouldn't consider my experience there to be useful to your question.


q:
We have a few SGI Onyx 350 and Orgin 350 systems running IRIX 6.5.x that we would like to install Subversion on.  One of them will likely be used as a simple repository server running svnserve.  The others will only need client installs.

The Subversion webpage has links to unofficial binaries for many *NIX systems, including HP-UX, Solaris, AIX, the BSDs and Linux distros.  Unfortunately, there aren't any for IRIX.  A Google search also comes up empty.

So, is there someplace on the web that publishes IRIX binaries for Subversion?

If not, does anyone have experience compiling SVN from source on such systems?  How hard is it to track down all of the dependencies?  Are there any caveats we should be aware of?

[A]
The guy that maintains
This website
sells secondhand SGI gear.  He sells them with CD's of contributed software.  Maybe he can do something for you.
Also,
The SGI forum on nekochan.net
has postings of contributed software.  You may be able to ask for something there.
Subversion is fairly pernickety about its dependencies (as you have probably already worked out).
This link
gives some of the dependencies for installing on Redhat 7.3, which dates back to the early 2000's (I don't know what minor release of Irix you're using).  You may find it to be a reasonable guide to the dependencies.


q:
Let's say we have these tables;

table user:

- id

- username

- email

table user2group:

- userid

- groupid

table group:

- id

- groupname

How do I make one query that returns all users, and the groups they belong to (as an array in the resultset or something..)

[A]
```
```
select u.id, u.username, u.email, g.groupid, g.groupname
from user u
join user2group ug on u.userid=ug.userid
join group g on g.groupid=ug.groupid
order by u.userid
```
```
As you are looping through the result set, each time you see a new userid make a new user object (or whatever) and add the groups to it.


q: It is possible to get stacktrace using System.Diagnostics.StackTrace, but thread has to be suspended. Suspend and Resume function are obsolete, so I expect that better way exists.

[A]
I think that if you want to do this without the cooperation of the target thread (such as by having it call a method that blocks it on a Semaphore or something while your thread does the stacktrace) you'll need to use the deprecated APIs.
A possible alternative is the use the
COM-based ICorDebug
interface that the .NET debuggers use. The MDbg codebase might give you a start:
```
http://blogs.msdn.com/jmstall/archive/2005/11/07/views_on_cordbg_and_mdbg.aspx
```
```
http://geekswithblogs.net/johnsPerfBlog/archive/2008/10/13/mdbg-a-managed-wrapper-around-icordebug.aspx
```


q:
During undergrad i opted to take a network programming course using the POSIX sockets for linux.  As a reference we used the book Internetworking using TCP/IP (comer and stevens). 2008 its a pretty dated and still applicatable texts which takes one through several server designs.

One design that is not really featured in the book is the case there a client connects to the backend application server sends multiple requests to the server over a single TCP connection.  Since multiple requests comes via the slave socket to the server and responses send via the same slave socket.  The slave socket is becomes congested as response and requests are received via the same socket, would it be a better option to allow for a second TCP connection between the to end-points to allow full duplex communication speed?  What other architectures can be used to improve server performance?

[A]
Since a socket is simply a number attached to a packet (call it a routing number or address), I can't imagine the socket itself getting congested.
Your code handling the socket could, but that should be pretty easily fixed by distributing packets as they arrive.
You could also code incoming and outgoing packet processing to happen on different threads, or even queue packets for distribution to many threads.
But I really don't see the original supposition as being completely accurate.  I could be wrong...


q:
Suppose I have a python object x and a string s, how do I set the attribute s on x? So:

>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'

What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().

[A]
```
```
setattr(x, attr, 'magic')
```
```
For help on it:
```
```
>>> help(setattr)
Help on built-in function setattr in module __builtin__:

setattr(...)
    setattr(object, name, value)

    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ``x.y = v''.
```
```
However, you should note that you can't do that to a "pure" instance of
```
object
```
. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.


q:
Is there a way to make OpenGL transform a general vector I give it with the current modelview matrix and get the result back?

The obvious way is to query the modelview matrix and do the multiplication myself but
I am almost sure there should be a way to make OpenGL do this for me.

[A]
You are right, you have to get the modelview matrix and transform the vector yourself.
For a confirm, see
this link
at paragraph 9.120.


q:
Given a week-day (1-7), how can I calculate what that week-day's last date was?

Example: Today is Wednesday, 2008/11/12, and I want to know what last Friday's date was.

[A]
If
```
today
```
is the current day of the week, then you can use something like:
```
```
days_since_friday = (((today - 1) + 7) - (6 - 1)) % 7
```
```
This assumes that Friday is represented by day number 6 of the week (that is, 1 represents Sunday). Then subtract
```
days_since_friday
```
from the current date, and you'll get the date of the end of last week.
The above expression is slightly more complicated than it needs to be. If your day-of-week started at 0 for Sunday, it simplifies to:
```
```
days_since_friday = ((today + 7) - 5) % 7
```
```
or
```
```
days_since_friday = (today + 2) % 7
```
```


q:
For some reason sql server 2008 is not allowing me to add columns to an existing table.

The table is empty btw.

Is there a setting that prevents modifying tables in sql 2008?


q:
Trying to create several layers of folders at once C:\pie\applepie\recipies\
without using several different commands, is there an easy way similar to Directory.CreateDirectory()

[A]
Here's some code I used in one of my projects.  It requires a reference be added to the project for the file system object.
First, click Project -> References, scroll down to "Microsoft Scripting Runtime" and select it.  Then you can use this function:
```
```
Public Sub MakePath(ByVal Folder As String)

    Dim arTemp() As String
    Dim i As Long
    Dim FSO As Scripting.FileSystemObject
    Dim cFolder As String

    Set FSO = New Scripting.FileSystemObject

    arTemp = Split(Folder, "\")
    For i = LBound(arTemp) To UBound(arTemp)
        cFolder = cFolder & arTemp(i) & "\"
        If Not FSO.FolderExists(cFolder) Then
            Call FSO.CreateFolder(cFolder)
        End If
    Next

End Sub
```
```


q:
Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc?
Eventhough I am an emacs guy, I find it much easier to create GUI with VS.

[A]
Eclipse
has python support.
There's also
IDLE
or
Wingware
, though I'm not sure of their GUI support.
I'm sure a good
google search
would turn up more.
But in the end, I doubt it.  Python is dependent on third-party widget sets like Qt, Tk, Gtk, wxWidgets, etc for GUI support.  Each of those will have their own system for laying things out.


q:
I'm trying to duplicate the effect used in the Firefox search box where, if the search field does not have focus ( the user has not clicked inside of it ), it just says Google in gray text. Then, when the user clicks in the box, the text is removed and they can fill in their search term.

I want to use this to provide example field data for a web form.

JQuery syntax would be preferable to plain javascript, but plain JS would be fine too.

Thanks SO Hive Mind!

[A]
```
$(selector).text('Google');
  $(selector).click(function(){
    $(this).text('');
  });
```
There's probably a more elegant way to do it, but this assumes your box has no text in it at page load.  If it does you can remove the first line.
I haven't tested this, but it should work.


q: I had experience with struts, and briefly experimented with tiles.  I know that within a layout each tile is a separate jsp page.  Suppose I hit a  button on each of four tiles, and each tile was (indirectly) calling a different web service.  Would the tiles refresh asynchronously as results came in at different times?

[A]
I think it would depend on the code in the background.  You say that the tiles were indirectly calling web services.  I would think it would refresh asynchronously unless you specified in your code for it not to do so.  Say you push button 1 and then button 2.  Action 1 comes back and your code says that the screen needs to be updated and the page will refresh.  Once action 2 gets back, your code would again update the screen.  I believe this is how it works, but having never tried it, I can't be sure.
Why not just throw together a two tiled test page with buttons and try it out.  That should give you a definitive answer.


q:
I'm mostly a .Net person at the moment, but I've been playing with Java some lately-- exploring what's out there.

Now I'm looking for the Java equivalent for WPF.  I know I could find an OpenGL library or two out there, but that's not really as rich or simple as the WPF system.

[A]
I think a combination of JavaFX, Swing, Java2D, and Java's browser-based JRE comprise the solutions that WPF provides:
JavaFX applications (actually, any Java app) can run in the browser or on a desktop
JavaFX provides high-end video support
JavaFX provides for scripted animations and visual special effects
Swing provides UI capabilities, and can be used in both Java and JavaFX
Java2D, which provides the underpinnings for all drawing tasks (including Swing), takes advantage of hardware acceleration and DirectX support
The JRE on the desktop or the browser enable Java applications to be deployed to multiple environments (including other screens, like set-top boxes or phones)


q: Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?

[A]
Yes, it is possible:
```
```
public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}
```
```
To chain to a particular superclass constructor instead of one in the same class, use
```
super
```
instead of
```
this
```
. Note that
you can only chain to one constructor
, and
it has to be the first statement in your constructor body
.
See also
this related question
, which is about C# but where the same principles apply.


q:
I have a database table (sql server 2008) that I want to view data for, what is the quickest way of displaying this data?

(if it could have paging that would be perfect).

Would it be a gridview or ?

query: select * from testData

[A]
if you're using .NET 3.5 you could use ASP.NET Dynamic Data:
http://www.asp.net/dynamicdata/
Hope this helps!


q: Can Spirit (part of Boost C++ library) be used to parse out binary data coming from a stream?  For example, can it be used to parse data coming from a socket into structures, bytes, and individual bit flags?  Thanks!

[A]
Boost Spirit allows for a parser to be defined using
Extended Backus–Naur Form (EBNF)
syntax with
template meta-programming
. It is very flexible and uses abstract classes in all phases of the parsing process that can be customized. In order to process a binary data stream, you would need to implement custom scanner classes since the default types are tailored for text input. You can read further in
The Scanner and Parsing
section of the
Spirit User's Guide
.
In my humble opinion, binary data streams are best handled with hand rolled serialization code. Spirit is geared more towards well formed grammars like mark-up or scripting languages. For example,
The Complete Syntax of Lua
is provided in EBNF. So, it might make sense to use Spirit to build a custom parser. On the other hand, a proprietary serial data link with synchronization bytes and CRC bracketing messages would require a lot more work just to define the EBNF if a
context-free grammar
even exists for it.
Addendum
The latest version of Boost Spirit includes functionality for dealing with binary data.


q:
We are looking to improve our marketing email list by preventing fake emails from entering in the first place.  We want to confirm that an email address exists (and that there is actually a mailbox for that email address).

Does anyone know of any services or components to validate an email address?

[A]
the following regular expression is an example of how you could validate an email address is in the correct general format:
```
```
(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})
```
```
For security reasons, very few email servers provide a function to remotely validate whether or not a mailbox exists, so it is very unlikely a service could provide this information with any reliability.
Hope this helps!
Adam


q:
I'm embedding an IE control into my C++ application. The problem is that although system-wide, ClearType is disabled, IE7 has its own separate setting, and unless I specifically disable that too, text inside the IE control will be antialiased while the rest of the app will not.

The same goes for IE7's font size setting.

It wouldn't be a problem for me to set up IE7 accordingly, but it would affect the experience of users of my app. Can the IE control's cleartype usage and font size be programmatically controlled?


q: SQL Server 2000: Is there a way to find out server memory / CPU parameters in Query Analyzer?

[A]
Not that I know of. You'll have to look in
```
perfmon
```
.


q:
We have a system where customers, mainly European enter texts (in UTF-8) that has to be distributed to different systems, most of them accepting UTF-8, but now we must also distribute the texts to a US system which only accepts US-Ascii 7-bit

So now we'll need to translate all European characters to the nearest US-Ascii. Is there any Java libraries to help with this task?

Right now we've just started adding to a translation table, where Å (swedish AA)->A and so on and where we don't find any match for an entered character, we'll log it and replace with a question mark and try and fix that for the next release, but it seems very inefficient and somebody else must have done something similair before.

[A]
There are some built in functions to do this. The main class involved is
```
CharsetEncoder
```
, which is part of the
```
nio
```
package. A simpler way is
```
String.getBytes(Charset)
```
that can be sent to a
```
ByteArrayOutputStream
```
.


q:
To be able to upload large files from a HTML page to a FTP server, I am looking for a Java/Flash FTP upload applet.

I really like the way dhtmlxVault works, but I need it to upload to a FTP server instead of a HTTP file upload.

It would be really nice if the applet has no GUI of it's own, but instead is fully scriptable using Javascript so I can use HTML/CSS for it's appearance.

I hopefully looked into Yahoo!'s YUI Uploader since it requires Flash, but the documentation only mentions HTTP upload and no FTP upload.

[A]
I tried the
ZUpload
Java applet.
Pro's:
The user interface works as easy as I could hope it to work.
It is a Java applet with it's own GUI, but I was able to implement some Javascript callbacks in it to update progress information in HTML. I would be able to minimize the GUI further.
Con's:
When an upload failes (when the FTP server tells it it is to busy, please retry in a moment) it thinks the upload succeeded and goes on with the next file. I tried to catch the exceptions but was unable to do so because of either the way j-ftp is used in the applet or my own lack of knowledge.
The project seems to be dead since 2003, so I don't expect any updates.
So my conclusion it that it is not ready to be used in a production environment. I still need a better solution.


q:
Firstly I'm extending an existing class structure and cannot alter the original, with that caveat:

I would like to do this:

class a
{
   int val;

   ... // usual constructor, etc...

   public int displayAlteredValue(int inp)
   {
     return (val*inp);
   }
}

class b extends a
{
   ... // usual constructor, etc...

   public in displayAlteredValue(int inp1, int inp2)
   {
     return (val*inp1*inp2);
   }
}

As I said before I cannot alter class a and I want to maintain the function name displayAlteredValue rather than making a new function.
If this can be done I only have to change a few instantiations of a to instantiations of b. I don't want to spend a lot of time replacing the many function calls to displayAlteredValue. (And yes I do realise there are such things as search and replace however for other reasons, doing that would be problematic).

Any ideas?

[A]
what if you add this to your derived class
```
```
public int displayAlteredValue(int inp)
{
  return super.displayAlteredValue(inp);
}
```
```


q:
What are differences between enabling and disabling "Enable 32-Bit applications" in websites application pools under IIS7 on x64 machine?

Mostly I'm thinking about memory usage.

Thanks in advance

[A]
I believe the current "trend" for hosting like this is to have each site with its own Application Pool, and each application pool running in 32 bitness. This enables Application Pool isolation, and allows each site/application pool to be limited to 4gb of memory, which basically works out to about 2.4 GB before asp.net recycles given the 60% memory threshold.
If you have an individual site that requires more memory, you'd change that application pool to x64, allowing for a much larger application pool.


q:
I have a number of string arrays. The string in every array are ordered the same way, according the same criteria. However, some string may be missing from some arrays, and there may be no array that has a complete set of strings. Moreover, the criteria used to compare the strings is not available to me: outside of the context of the array, I cannot tell which string should precede another.

I need a way to produce a complete set of strings, properly ordered. Or fail when the arrays do not have enough information for me to do so.

Is anyone familiar with this kind of problem? What is the proper algorithm?

Examples:

A B D
A C D

Can't order correctly, can't decide the order of B and C

A B D
A B C
A C D

This has enough information to order ABCD correctly.

[A]
How many sets will you have? Something that might work if they aren't too sparse is:
Iterate over the first element of
all arrays counting how common each
string is.
Whichever element is the most common
is selected.
Check each element of all
arrays for said string.
If it exists in any element other than the first of an array, the first element of
its parent array is selected and goto step 3.
Remove the selected element from the
first element of all arrays/trees
and add it to the end of your output
list.
Goto 1 until all elements are
removed.
If you dumped the arrays into
b-trees
the element search could be pretty fast. You may also be able to further speed up step 3 by playing with the order of the arrays. I'm still thinking about that.
If the arrays are very sparse the only thing I can think of is to use some kind of supervised machine learning to try to determine the proper method for ordering.


q:
I've got an SQL query that looks like this:

INSERT INTO DB..incident
(
    incident_number        --nvarchar(10)
)
VALUES
(
    N'I?'
)

What does the ? do in the value statement?

EDIT:: Turns out there's some funny business via triggers and custom datatypes that occur on insert (we've got a bit of a messed up DB.) Given normal settings I've marked the answer appropriately.

[A]
At the risk of sounding flippant... Nothing... It puts an I? into the field... Try this...
```
```
DECLARE @TestTable TABLE (test NVARCHAR(10))

INSERT INTO @TestTable (
    test
) VALUES (
    N'I?' )

SELECT *
FROM  @TestTable
```
```


q:
Is there a way to have the compile deduce the template parameter automatically?

template<class T>
struct TestA
{
    TestA(T v) {}
};
template<class T>
void TestB(T v)
{
}
int main()
{
    TestB (5);
}

Test B works fine, however when i change it to TestA it will not compile with the error " use of class template requires template argument list"

[A]
No, there isn't. Class templates are never deduced. The usual pattern is to have a
```
make_
```
free function:
```
```
template<class T> TestA<T> make_TestA(T v)
{
    return TestA<T>(v);
}
```
```
See
```
std::pair
```
and
```
std::make_pair
```
, for example.
In C++0x you will be able to do
```
```
auto someVariable = make_TestA(5);
```
```
to avoid having to specify the type for local variables.


q:
We have a web service that uses up more and more private bytes until that application stops responding.  The managed heap (mostly Gen2) will show some 200-250 MB, while private bytes shows over 1GB.  What are possible causes of a memory leak outside of the managed heap?

I've already checked for the following:

Prolific dynamic assemblies (Xml serialization, regex, etc.)

Session state (turned off)

System.Policy.Evidence memory leak (SP1 installed)

Threading deadlock (no use of Join, only lock)

Use of SQLOLEDB (using SqlClient)

What other sources can I check for?

[A] Make sure your app is complied in release mode.  If you compile under debug mode, and deploy that, simply instantiating a class that has an event defined (event doesn't even need to be raised), will cause a small piece of memory to leak.  Instantiating enough of these objects over a long enough period of time will cause all the memory to be used.  I've seen web apps that would use up all the memory within a matter of hours, simply because a debug build was used.  Compiling as a release build immediately and permanently fixed the problem.


q:
I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it.  Something like Date::Extract in Perl

Thank you in advance.

[A]
The nearest equivalent is probably the
dateutil
module.  Usage is:
```
```
>>> from dateutil.parser import parse
>>> parse("Wed, Nov 12")
datetime.datetime(2008, 11, 12, 0, 0)
```
```
Using the fuzzy parameter should ignore extraneous text.  ie
```
```
>>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True)
datetime.datetime(2006, 12, 1, 14, 30)
```
```


q:
I have some global variables in a Python script. Some functions in that script call into C - is it possible to set one of those variables while in C and if so, how?

I appreciate that this isn't a very nice design in the first place, but I need to make a small change to existing code, I don't want to embark on major refactoring of existing scripts.

[A]
I'm not a python guru, but I found this question interesting so I googled around.
This
was the first hit on "python embedding API" - does it help?
If the attributes belong to the global
  scope of a module, then you can  use
  "PyImport_AddModule" to get a handle
  to the module object. For  example, if
  you wanted to get the value of an
  integer in the
main
module named
  "foobar", you would do the following:
```
```
PyObject *m = PyImport_AddModule("__main__");
PyObject *v = PyObject_GetAttrString(m,"foobar");

int foobar = PyInt_AsLong(v);

Py_DECREF(v);
```
```


q:
Hi Guys I'm very new to regex, can you help me with this.

I have a string like this "<input attribute='value' >" where attribute='value' could be anything and  I want to get do a preg_replace to get just <input />

How do I specify a wildcard to replace any number of any characters in a srting?

like this? preg_replace("/<input.*>/",$replacement,$string);

Many thanks

[A]
What you have:
```
```
.*
```
```
will match "any character, and as many as possible.
what you
mean
is
```
```
[^>]+
```
```
which translates to "any character, thats not a ">", and there must be at least one
or altertaively,
```
```
.*?
```
```
which means
"any character, but only enough to make this rule work"
BUT DONT
Parsing HTML with regexps is
Bad
use any of the existing html parsers, DOM librarys, anything, Just NOT NAïVE  REGEX
For example:
```
```
<foo attr=">">
```
```
Will get grabbed wrongly by regex as
```
```
'<foo attr=" ' with following text of '">'
```
```
Which will lead you to this regex:
```
```
`<[a-zA-Z]+( [a-zA-Z]+=['"][^"']['"])*)>  etc etc
```
```
at which point you'll discover this lovely gem:
```
```
<foo attr="'>\'\"">
```
```
and your head will explode.
( the syntax highlighter verifies my point, and incorrectly matches thinking i've ended the tag. )


q:
If I have 2 DataTables (dtOne and dtTwo) and I want to merge them and put them in another DataTable (dtAll).  How can I do this in C#?  I tried the Merge statement on the datatable, but this returns void.  Does Merge preserve the data?  For example, if I do:

 dtOne.Merge(dtTwo);

Does dtOne change or does dtTwo change and if either one changes, do the changes preserve?

I know I can't do this because Merge returns void, but I want to be able to store the Merger of both dtOne and dtTwo in dtAll:

//Will Not work, How do I do this
dtAll = dtOne.Merge(dtTwo);

[A]
The
```
Merge
```
method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.
If you want to preserve both of the original tables, you could copy the original first, then merge:
```
```
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);
```
```


q:
I have a little c# console program that outputs some text using Console.WriteLine. I then pipe this output into a textfile like:

c:myprogram > textfile.txt

However, the file is always an ansi text file, even when I start cmd with the /u switch.
cmd /? says about the /u switch:

/U    Causes the output of internal
  commands to a pipe or file to be Unicode

And it indeed makes a difference, when I do an

c:echo "foo" > text.txt

the text.txt is unicode (without BOM)

I wonder why piping the output of my console program into a new file does not create an unicode file likewise and how i could change that?

I just use Windows Power Shell (which produces a unicode file with correct BOM), but I'd still like to know how to do it with cmd.

Thanks!

[A]
The /U switch, as the documentation says, affects whether
internal
commands generate Unicode output. Your program is not one of cmd.exe's internal commands, so the /U option does not affect it.
To create a Unicode text file, you need to make sure your program is generating Unicode text.
Even that may not be enough, though. I came across
this blog from Junfeng Zhang
describing how to write Unicode text in a console program. It checks the file type of the standard output handle. For character files (a console or LPT port), it calls WriteFileW. For all other types of handles (including disk files and pipes), it converts the output string to the console's current code page. I'm afraid I don't know how that translates into .Net terms, though.


q:
I am binding an SPGridView to a SPList. As code samples suggest, I am using the following code to create a dataview based on the list.

dim data as DataView = myList.Items.GetDataTable.DefaultView
grid.DataSource = data
etc...

What I am finding is that the column names in the resulting dataview do not always match the source fields defined in the SPList. For example I have columns named

Description

ReportItem

ReportStatus

these show up in the resulting dataview with column names like

ReportType0

ReportStatus1

This leads me to think that I have duplicate field names defined, but that does not seem to be the case.

Seems like I am missing something fundamental here?
Thanks.

[A]
The
```
GetDataTable
```
method is returning the
```
internalName
```
(or
```
staticName
```
-- I can't remember for sure which but they are frequently the same) representation of the columns, rather than the
```
Title
```
representation, which is what you see in the Web interface. I believe
```
GetDataTable
```
does a CAML query under the covers, and you have to use that
```
internalName
```
for field references in CAML.
This
blog
talks about it in a little more detail.