q:
I've always used a *.h file for my class definitions, but after reading some boost library code, I realised they all use *.hpp. I've always had an aversion to that file extension, I think mainly because I'm not used to it.

What are the advantages and disadvantages of using *.hpp over *.h?

[A]
It does not matter which extension you use. Either one is OK.
I use
```
*.h
```
for C and
```
*.hpp
```
for C++.


q:
How do I check if an object is of a given type, or if it inherits from a given type?

How do I check if the object o is of type str?

Beginners often wrongly expect the string to already be "a number" - either expecting Python 3.x input to convert type, or expecting that a string like '1' is also simultaneously an integer. This is the wrong canonical for those questions. Please carefully read the question and then use How do I check if a string represents a number (float or int)?, How can I read inputs as numbers? and/or Asking the user for input until they give a valid response as appropriate.

[A]
```
```
isinstance(o, str)
```
```
Link to docs

s: huggingface

c: devops

d: intermediate


q: What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $_GET and $_POST variables in PHP?

[A]
You can use the
```
request.get?
```
and
```
request.post?
```
methods to distinguish between HTTP Gets and Posts.
See
http://api.rubyonrails.org/classes/ActionDispatch/Request.html


q:
For an std::map<std::string, std::string> variables, I'd like to do this:

BOOST_CHECK_EQUAL(variables["a"], "b");

The only problem is, in this context variables is const, so operator[] won't work :(

Now, there are several workarounds to this; casting away the const, using variables.count("a") ? variables.find("a")->second : std::string() or even making a function wrapping that. None of these seem to me to be as nice as operator[]. What should I do? Is there a standard way of doing this (beautifully)?

Edit: Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.

[A]
```
find
```
is the idiomatic form. Casting away
```
const
```
is almost always a bad idea. You'd have to guarantee that no write operation is performed. While this can be reasonably expected of a read access on a map, the specification doesn't say anything about this.
If you
know
that the value exists you can of course forego the test using
```
count
```
(which is quite inefficient, anyway, since it means traversing the map twice. Even if you don't know whether the element exists I wouldn't use this. Use the following instead:
```
```
T const& item(map<TKey, T> const& m, TKey const& key, T const& def = T()) {
    map<TKey, T>::const_iterator i = m.find(key);
    return i == m.end() ? def : i->second;
}
```
```
/EDIT: As Chris has correctly pointed out, default-construction of objects of type
```
T
```
might
be expensive, especially since this is done even if this object isn't actually needed (because the entry exists). If this is the case, don't use the default value for the
```
def
```
argument in the above case.


q: I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?

[A]
Have a look at the
ItemTemplateSelector
property of your list control. You can point it to a custom TemplateSelector and decide which template to use in code.
Here's a blog post describing TemplateSelectors:
http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20463.aspx
Edit: Here's a better post:
http://blog.paranoidferret.com/index.php/2008/07/16/wpf-tutorial-how-to-use-a-datatemplateselector/


q:
Is it possible to prevent the Windows Installer from running every time Access 2003 and Access 2007 are started, when they are both installed on the same machine at the same time..?

Like many developers I need to run more than 1 version of MS Access.  I have just installed Access 2007.  If I open Access 2003 and then open Access 2007 I have to wait 3mins for the 'Configuring Microsoft Office Enterprise 2007..." dialog.  Then if I open Access 2003 again it takes another 30secs or so to configure that.

PLEASE NOTE: I am using shortcuts to open the files that include the full path to Access.  Eg to open Access 2007:

 "C:\program files\microsoft office 12\office12\msaccess.exe" "C:\test.accdb"

and for 2003:

 "C:\program files\microsoft office 11\office11\msaccess.exe" "C:\test.mdb"

[A]
This is caused by Windows Installer, which is used by both installers. Advertised shortcuts as used by both Office 2003 and Office 2007 invoke Windows Installer to check that the entire feature is installed properly; the installer detects that something else (in this case the other product) has registered the file extensions used by Access (possibly the ProgIds as well) and decides that a repair is necessary, so it invokes the 'Configuring Office' dialog and proceeds to reinstall various components.
To avoid this, run Access from Program Files directly; create shortcuts if you'll be doing this frequently.


q:
There is probably is simple fix for this but I currently have code similar to

dim dr as dbDataReader

try
      dr = connection.getDataReader(sql_str)
Catch ex as sqlClientException
     log.error(ex)
finally

  if not IsNothing(dr) then
    dr.close
  end if
end try

However Visual Studio still warns me that the

if not IsNothing(dr) then
        dr.close
      end if

Can cause a NullReferenceException. What is the best way to mitigate this? I can't move the declaration into the try block.

[A]
Your code is correct. In the
```
finally
```
statement, as long as you check to make sure your objects are not null, it won't throw a null reference exception based on what happens in your code.


q:
I have an if condition which checks for value and the it throws new NumberFormatException

Is there any other way to code this

if (foo)
{
    throw new NumberFormatException
}

// ..

catch (NumberFormatException exc)
{
    // some msg...
}

[A]
If your aim is to avoid to throw a new exception:
```
```
if(foo)
{
  //some msg...
} else
{
  //do something else
}
```
```


q:
I'm setting up a new project using CruiseControl.net 1.4.

I see from ccnet contributions
that there are two options for a subversion repository number labeller - a
feature that I would really like to make use of.

1) SVNLabeller available from jcxsoftware

and

2) Svnrevisionlabeller available from google code

My problem is that (1) claims support for ccnet 1.4 but I can't find
any documentation on how to configure it.

(2) comes with documentation but does not claim to support ccnet 1.4

Can anyone help me with either how to configure SVNLabeller or tell me
if Svnrevisionlabeller works with 1.4?

[A]
Have you looked at
David Keaveny’s Blog Post
regarding the SVNRevisionLabeller? The link will take you to a detailed post on it's usage.
We are currently testing this utility against the current release (1.4) of CCNet without any problems, i.e. it's producing the correct revision and build labels appended to the major/minor digits we specify.
Hope this helps


q:
In Python, you can do this:

import webbrowser
webbrowser.open_new("http://example.com/")

It will open the passed in url in the default browser

Is there a ruby equivalent?

[A]
Windows Only Solution:
```
```
require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
shell.ShellExecute(...)
```
```
Shell Execute on MSDN


q:
I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using find piped with xargs grep:

find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN'

But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.

[A]
So I discovered
pcregrep
which stands for
Perl Compatible Regular Expressions GREP
.
the -M option makes it possible to search for patterns that span line boundaries.
For example, you need to find files where the '
_name
' variable is followed on the next line by the '
_description
' variable:
```
```
find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description'
```
```
Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...


q:
I am relatively new to matchers. I am toying around with hamcrest in combination with JUnit and I kinda like it.

Is there a way, to state that one of multiple choices is correct?

Something like

assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest

The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java?

(I am open to hamcrest-alternatives)

[A]
```
```
assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3)))
```
```
From
Hamcrest tutorial
:
```
anyOf
```
- matches if any matchers match, short circuits (like Java ||)
See also
Javadoc
.
Moreover, you could write your own Matcher, which is quite easy to do.


q:
If you use Image.Save Method to save an image to a EMF/WMF, you get an exception (http://msdn.microsoft.com/en-us/library/ktx83wah.aspx)

Is there another way to save the image to an EMF/WMF?
Are there any encoders available?

[A]
A metafile is a file which records a sequence of GDI operations. It is scalable because the original sequence of operations that generated the picture are captured, and therefore the co-ordinates that were recorded can be scaled.
I think, in .NET, that you should create a
```
Metafile
```
object, create a
```
Graphics
```
object using
```
Graphics.FromImage
```
, then perform your drawing steps. The file is automatically updated as you draw on it. You can find a small sample in the documentation for
Graphics.AddMetafileComment
.
If you really want to store a bitmap in a metafile, use these steps then use
```
Graphics.DrawImage
```
to paint the bitmap. However, when it is scaled it will be stretched using
```
StretchBlt
```
.


q:
in Erlang I have a supervisor-tree of processes, containing one that accepts tcp/ip connections. For each incoming connection I spawn a new process. Should this process be added to the supervisor tree or not?

Regards,
 Steve

[A]
If you expect these processes to be many, it could be a good idea to add a supervisor under your main supervisor as to separate responsibility (and maybe use the
```
simple_one_for_one
```
setting to make things simpler, maybe even simpler than your current case).
The thing is, if you need to control these processes, it's always nice to have a supervisor. If it doesn't matter if they succeed or not, then you might not need one. But then again, I always argue that that is sloppy coding. ;-)
The only thing I
wouldn't
do, is to add them to your existing tree, unless it is very obvious where they come from and they're fairly few.


q: I am wondering whether it is safe to mix jdk 1.5 and 1.6 (Java 6) object serialization (biderctional communication). I searched for an explicit statement from sun concerning this question but did not succeed. So, besides the technical feasability I am searching for an "official" statement concerning the problem.

[A] After testing with a serialized object written to a file using the ObjectOutputStream in a Java 1.5 program, then running a read with a ObjectInputStream in a Java 1.6 program I can say this worked without any issue.


q: I need to understand the differences between windows main/mdi/child/dialogs.... how win32 messages should be propagated... why some messages are present in one type and not other...

[A]
Im not a windows developer, but heres what I understand:
main window - toplevel container which you can active/see in the taskbar.
dialog - little box locking (if modal) your window, not seeable in the taskbar. Mostly used to display message to the user.
mdi (Multiple Document Interface) - Not directly a window but more a simple container for storing child windows. Each child window can be maximized/minimized/closed inside this container, but you wont find any of these in the taskbar.
http://en.wikipedia.org/wiki/Multiple_document_interface


q:
Is there any facility of transposing rows to columns in SQL Server (it is possible in MS-Access)?
I was befuddled because this facility is available in MS-Access but not in SQL Server. Is it by design that this feature has not been included in SQL Server?

[A]
The example at
http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm
only works if you know in advance what the row values can be.   For example, let's say you have an entity with custom attributes and the custom attributes are implemented as rows in a child table, where the child table is basically variable/value pairs, and those variable/value pairs are configurable.
```
```
color red
size  big
city  Chicago
```
```
I'm going to describe a technique that works.  I've used it.  I'm NOT promoting it, but it works.
To pivot the data where you don't know what the values can be in advance, create a temp table on the fly with no columns.  Then use a cursor to loop through your rows, issuing a dynamically built "alter table" for each variable, so that in the end your temp table has the columns, color, size, city.
Then you insert one row in your temp table, update it via another cursor through the variable, value pairs, and then select it, usually joined with its parent entity, in effect making it seem like those custom variable/value pairs were like built-in columns in the original parent entity.


q:
What's the best way to trim a DateTime object to a specific precision?  For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this?

private static DateTime TrimDateToMinute(DateTime date)
{
    return new DateTime(
        date.Year,
        date.Month,
        date.Day,
        date.Hour,
        date.Minute,
        0);
}

What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.

[A]
You could use an enumeration
```
```
public enum DateTimePrecision
{
  Hour, Minute, Second
}

public static DateTime TrimDate(DateTime date, DateTimePrecision precision)
{
  switch (precision)
  {
    case DateTimePrecision.Hour:
      return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
    case DateTimePrecision.Minute:
      return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0);
    case DateTimePrecision.Second:
      return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
    default:
      break;
  }
}
```
```
and expand as required.


q:
I want something like this:

<msxsl:script language="C#">
   ??? getNodes() { ... return ... }
</msxsl:script>

<xsl:for-each select="user:getNodes()">
    ...
</xsl:for-each>

What return type should i use for getNodes() and what should i put in it's body?

[A]
A quick google for C# xslt msxml revealed a link to the following page which gives many examples of extending XSLT in microsoft environments.
http://msdn.microsoft.com/en-us/magazine/cc302079.aspx
Specifically the section on Mapping Types between XSLT and .Net gives you exactly the information you need:
W3C XPath Type -  Equivalent .NET Class (Type)
String - System.String
Boolean - System.Boolean
Number - System.Double
Result Tree Fragment - System.Xml.XPath.XPathNavigator
Node Set - System.Xml.XPath.XPathNodeIterator
So in your example I would try XPathNodeLiterator.


q:
How can I write an insert statement which includes the & character?  For example, if I wanted to insert "J&J Construction" into a column in the database.

I'm not sure if it makes a difference, but I'm using Oracle 9i.

[A]
If you are using sql plus then I think that you need to issue the command
```
```
SET SCAN OFF
```
```


q:
I just got started using Adobe Flex SDK.  I was very excited because it's the first time I've found a good, free way to create Flash applications.  But then I noticed something: Flex doesn't seem to be much about making animations or designs.  It seems more like an application to build forms and menus and the like... which I can already do in (D)HTML.

What features does Flex have that make it better than HTML in some cases?

Also, are there any techniques/software programs that would allow me to add the flash/design components that I mentioned earlier?

Thanks!

[A]
Flex, like Silverlight, is marketed for the creation of something called RIA = rich internet application. The idea being that (D)HTML isn't really well-suited to create large-scale, well-responding applications on the web. I'm not sure whether this is really (still) true but historically, it fits.
Flex and Silverlight attempt to correct this by providing two things: a different, extensible technology along with a large library and an adapted toolset for the creation of applications. The disadvantage in both cases is the dependency from further (non-free, non-standard) components. The advantage is a potentially much more productive workflow and better performance.


q:
It is easy to highlight a selected datagrid row, by for example using toggleClass in the tr's click event.  But how best to later remove the highlight after a different row has been selected?   Iterating over all the rows to unhighlight them could become expensive for larger datagrids.  I'd be interested in the simplest solution, as well as the most performant.

Thanks,

Mike

[A]
If you just want to find items that have
toggledClass
and turn that off using jQuery:
```
```
$('.toggledClass').removeClass('toggledClass');
```
```


q:
When loading XML into an XmlDocument, i.e.

XmlDocument document = new XmlDocument();
document.LoadXml(xmlData);

is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol)

Thanks

[A]
I confess things get a little confusing with XML documents and encodings, but I'd hope that it would get set appropriate when you save it again, if you're still using ISO-8859-1 - but that if you save with UTF-8, it wouldn't need to. In some ways, logically the document really contains the symbol rather the entity reference - the latter is just an encoding matter. (I'm thinking aloud here - please don't take this as authoritative information.)
What are you doing with the document after loading it?


q:
I'm a VMware user and far too often I use keyboard shortcuts while programming. However, this has proved to be quite distressing as sometimes the VMware gets hold of it and turns off / pauses (Ctrl+Z) the virtual machine.

Is there a way to disable keyboard shortcuts on VMware? Has anyone here ever found a workaround?

[A]
I use AutoHotKey (are you running VMWare on Windows ?) to disable certain shortcuts. You can find this tool here:
http://www.autohotkey.com/
It's open source and I quite like it. Can be used for automation tasks, but you can also have it respond differently to different windows. With some AHK scripting, I think you should be able to fix your problem.
The site had got loads of tutorials too on writing handy scripts.
Good luck.


q:
In Visual Studio with TFS as source control, when I view the history and double click a cs file, the file is loaded in notepad. How can i change the application to be notepad++?

I also would like the OS's default application for the file to still be visual studio

[A]
I don't see any options in Visual Studio for changing that, so I'm guessing it uses the system's default text editor.
Try assigning Notepad++ as the default handler for *.cs files.
You can do this from withing Notepad++ by going to Settings/Preference/File Association.
You can also do it by right-clicking on a .cs file in explorer, go to Open With/Choose Program..., then select Notepad++ and check the "Always use the selected program to open this kind of file" box before hitting OK.


q:
There is a GUI ADM2 Progress v9 application using AppServer.

It needs to give users an ability to view MS Excel files stored on the AppServer. So far it:

Pulls .xls file from AppServer to a local drive.

Fires up a copy of MS Excel and opens the file.

The problem is that the temporary file on the local drive needs to be removed once it's no longer required. Any hints?

[A]
If you are "firing up a copy of Excel", is there any special reason you can't just point that "fired-up" Excel application at the file on your App Server?
If you are starting Excel from a command-line shell, you could just go
```
Excel.exe "http://myserver/myexcelbook.xls"
```
right?
If you are opening it via something like Office Interop Assemblies, then you can key off of the
```
Application.WorkBookBeforeClose
```
event like
```
```
ThisMethodHandlesTheWorkbookBeforeCloseEvent()
{
  DeleteTheFile();
}
```
```


q:
I'm wondering if a Java library can be called from a VB.net application.

(A Google search turns up lots of shady answers, but nothing definitive)

[A]
No, you can't. Unless you are willing to use some "J#" libraries (which is not nearly the same as Java) or
IKVM
which is a Java implementation that runs on top of .NET, but as their documentation says:
IKVM.OpenJDK.ClassLibrary.dll: compiled version of the Java class libraries derived from the OpenJDK class library with some parts filled in with code from GNU Classpath and IcedTea, plus some additional IKVM.NET specific code.
So it's not the real deal.


q:
Do you know an easy and straight-forward method/sub/module which allows me to convert a number (say 1234567.89) to an easily readable form - something like 1.23M?

Right now I can do this by making several comparisons, but I'm not happy with my method:

if($bytes > 1000000000){
   $bytes = ( sprintf( "%0.2f", $bytes/1000000000 )). " Gb/s";
}
elsif ($bytes > 1000000){
   $bytes = ( sprintf( "%0.2f", $bytes/1000000 )). " Mb/s";
}
elsif ($bytes > 1000){
   $bytes = ( sprintf( "%0.2f", $bytes/1000 )). " Kb/s";
}
else{
   $bytes = sprintf( "%0.2f", $bytes ). "b/s";
}

Thank you for your help!

[A]
The
Number::Bytes::Human
module should be able to help you out.
An example of how to use it can be found in its synopsis:
```
```
use Number::Bytes::Human qw(format_bytes);

  $size = format_bytes(0); # '0'
  $size = format_bytes(2*1024); # '2.0K'

  $size = format_bytes(1_234_890, bs => 1000); # '1.3M'
  $size = format_bytes(1E9, bs => 1000); # '1.0G'

  # the OO way
  $human = Number::Bytes::Human->new(bs => 1000, si => 1);
  $size = $human->format(1E7); # '10MB'
  $human->set_options(zero => '-');
  $size = $human->format(0); # '-'
```
```


q:
I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.

The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface.

What's the best way around this?  Should I just use instance methods (which seems wrong) or is there another solution?

[A]
I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.
i.e. in your class with the static method have:
```
```
private static final MethodObject methodObject = new MethodObject();

public static void doSomething(){
    methodObject.doSomething();
}
```
```
and your method object can be a very simple, easily-tested:
```
```
public class MethodObject {
    public void doSomething() {
        // do your thang
    }
}
```
```


q: I need to change the app name based on what configuration I'm using in Visual Studio. For example, if I'm in Debug configuration, I want the app name to show as 'App_Debug' in the Application field in the Elmah_Error table. Does anyone have any experience with this? Or is there another way to do it?

[A]
By default, Elmah uses the AppPool's application GUID as the default application name.  It uses this as the key to identify the errors in the Elmah_Error table when you look at the web interface that's created through it's HTTP Module.
I was tasked to explore this option for my company earlier this year.  I couldn't find a way to manipulate this by default since Elmah pulls the application name from
```
HttpRuntime.AppDomainAppId
```
in the ErrorLog.cs file.  You could manipulate it by whatever key you want; however, that is the AppPool's GUID.
With that said, I was able to manipulate the ErrorLog.cs file to turn Elmah into a callable framework instead of a handler based one and allow for me set the ApplicationName.  What I ended up doing was modifying ErrorLog.cs to include a property that allowed me to set the name as below:
```
```
public virtual string ApplicationName
{
    get
    {
        if (_applicationName == null) {  _applicationName = HttpRuntime.AppDomainAppId; }
        return _applicationName;
    }
    set { _applicationName = value; }
}
```
```
What you will probably need to do is adjust this differently and set the ApplicationName not to
```
HttpRuntime.AppDomainAppId
```
but, instead, a value pulled from the web.config.  All in all, it's possible.  The way I did it enhanced the
```
ErrorLog.Log(ex)
```
method so I could use Elmah has a callable framework beyond web applications.  Looking back I wish I did the app/web.config approach instead.
One thing to keep in mind when changing the application name in Elmah.  The http handler that generates the /elmah/default.aspx interface will no longer work. I'm still trying to find time to circle back around to such; however, you may need to look into creating a custom interface when implementing.


q:
I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example:

void function(MESSAGE_ID id, void* param)
{
    if(id == FOO) {
        int real_param = (int)param;
        // ...
    }
}

Of course, on a 64 bit machine, I get the error:

error: cast from 'void*' to 'int' loses precision

I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?

[A]
Use
```
intptr_t
```
and
```
uintptr_t
```
.
To ensure it is defined in a portable way, you can use code like this:
```
```
#if defined(__BORLANDC__)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
    typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
#else
    #include <stdint.h>
#endif
```
```
Just place that in some .h file and include wherever you need it.
Alternatively, you can download Microsoft’s version of the
```
stdint.h
```
file from
here
or use a portable one from
here
.


q:
The interop library is slow and needs MS Office installed.
Many times you don't want to install MS Office on servers.

I'd like to use Apache POI, but I'm on .NET.

I need only to extract the text portion of the files, not creating nor "storing information" in Office files.

I need to tell you that I've got a very large document library, and I can't convert it to newer XML files.

I don't want to write a parser for the binaries files.
A library like Apache POI does this for us. Unfortunately, it is only for the Java platform. Maybe I should consider writing this application in Java.

I am still not finding an open source alternative to POI in .NET, I think I'll write my own application in Java.

[A]
What do you need to do with those file?  If you just want to stream them to the user, then the basic file streams are fine.  If you want to create new files (perhaps based on a template) to send to the user that the user can open in Office, there are a variety or
work-arounds
.
If you're actually keeping data in Office documents for use by your web site, you're doing it wrong.  Office documents, even Excel spreadsheets and access databases, are not really an appropriate choice for use with an interactive web site.


q:
I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers?

After a quick google, I found only the WMI solution and a suggestion to PInvoke GetSecurityInfo

[A]
No need to P/Invoke.
System.IO.File.GetAccessControl
will return a
FileSecurity
object, which has a
GetOwner
method.
Edit: Reading the owner is pretty simple, though it's a bit of a cumbersome API:
```
```
const string FILE = @"C:\test.txt";

var fs = File.GetAccessControl(FILE);

var sid = fs.GetOwner(typeof(SecurityIdentifier));
Console.WriteLine(sid); // SID

var ntAccount = sid.Translate(typeof(NTAccount));
Console.WriteLine(ntAccount); // DOMAIN\username
```
```
Setting the owner requires a call to SetAccessControl to save the changes. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership.
```
```
var ntAccount = new NTAccount("DOMAIN", "username");
fs.SetOwner(ntAccount);

try {
   File.SetAccessControl(FILE, fs);
} catch (InvalidOperationException ex) {
   Console.WriteLine("You cannot assign ownership to that user." +
    "Either you don't have TakeOwnership permissions, or it is not your user account."
   );
   throw;
}
```
```


q:
I would like to be able to step through an application deployed to a remote location which as yet has nothing bar version 3.5 of the .Net framework.

What steps do I need to go through to achieve this and how long would you envisage this taking?

[A]
How to: Set Up Remote Debugging
Screencast for Visual Studio 2008 - Remote Debugging with MSVSMON.EXE
This is also a
good KB
showing some troubleshooting scenarios..


q:
I am looking for pointers to the solution of the following problem: I have a set of rectangles, whose height is known and x-positions also and I want to pack them in the more compact form. With a little drawing (where all rectangles are of the same width, but the width may vary in real life), i would like, instead of.

-r1-
  -r2--
     -r3--
       -r4-
        -r5--

something like.

-r1-  -r3--
  -r2-- -r4-
         -r5--

All hints will be appreciated. I am not necessarily looking for "the" best solution.

[A]
Something like this?
Sort your collection of rectangles by x-position
write a method that checks which rectangles are present on a certain interval of the x-axis
```
```
Collection<Rectangle> overlaps (int startx, int endx, Collection<Rectangle> rects){
...
}
```
```
loop over the collection of rectangles
```
```
Collection<Rectangle> toDraw;
Collection<Rectangle> drawn;
foreach (Rectangle r in toDraw){
Collection<Rectangle> overlapping = overlaps (r.x, r.x+r.width, drawn);
int y = 0;
foreach(Rectangle overlapRect in overlapping){
y += overlapRect.height;
}
drawRectangle(y, Rectangle);
drawn.add(r);
}
```
```


q:
I recently upgraded my oracle client to 10g (10.2.0.1.0).

Now when I try to connect to a legacy 8.0 database, I get

ORA-03134: Connections to this server version are no longer supported.

Is there any workaround for this problem, or do I have to install two clients on my local machine?

[A]
I had to connect a C# code to an Oracle 7 (I know you it's 8...)... the only way I get it was to get the CD to install the Oracle Server and to go in the "Optional Configuration Component" and to use the Oracle73 Ver2.5.
I think you should go check the CD of the Oracle 8 Server and check if an ODBC is still available.


q:
I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes.

How do I resize the iframes to fit the height of the iframes' content?

I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far.

Update: Please note that content is loaded from other domains, so the same-origin policy applies.

[A] This is slightly tricky as you have to know when the iframe page has loaded, which is difficuly when you're not in control of its content. Its possible to add an onload handler to the iframe, but I've tried this in the past and it has vastly different behaviour across browsers (not guess who's the most annoying...). You'd probably have to add a function to the iframe page that performs the resize and inject some script into the content that either listens to load events or resize events, which then calls the previous function. I'm thinking add a function to the page since you want to make sure its secure, but I have no idea how easy it will be to do.


q:
When I call

help(Mod.Cls.f)

(Mod is a C extension module), I get the output

Help on method_descriptor:

f(...)
    doc_string

What do I need to do so that the help output is of the form

Help on method f in module Mod:

f(x, y, z)
    doc_string

like it is for random.Random.shuffle, for example?

My PyMethodDef entry is currently:

{ "f", f, METH_VARARGS, "doc_string" }

[A]
You cannot. The inspect module, which is what 'pydoc' and 'help()' use, has no way of figuring out what the exact signature of a C function is. The best you can do is what the builtin functions do: include the signature in the first line of the docstring:
```
```
>>> help(range)
Help on built-in function range in module __builtin__:

range(...)
    range([start,] stop[, step]) -> list of integers

...
```
```
The reason random.shuffle's docstring looks "correct" is that it isn't a C function. It's a function written in Python.


q:
I have an MS SQL database and have a varchar field that I would like to do queries like  where name like '%searchTerm%'.  But right now it is too slow, even with SQL enterprise's full text indexing.

Can someone explain how Lucene .Net might help my situation?   How does the indexer work? How do queries work?

What is done for me, and what do I have to do?

[A]
This
article
(strangely enough it's on the top of the Google search results :) has a fairly good description of how the Lucene search could be optimised.
Properly configured Lucene should easily beat SQL (pre 2005) full-text indexing search. If you on MS SQL 2005 and your search performance is still too slow you might consider checking your DB setup.


q:
In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number.
e.g long x = 0l;

How can I tell the C# compiler that a number is a byte?

[A]
```
```
byte b = (byte) 123;
```
```
even though
```
```
byte b = 123;
```
```
does the same thing. If you have a variable:
```
```
int a = 42;
byte b = (byte) a;
```
```


q:
Summary for the impatient: I'm searching for good references on generating code for common language constructs but not parsing.

I am interested in programming languages and try to read the literature as much as possible. But most of them covers the topic in a functional and theoretical perspective that, I find them hard to understand let alone implement the ideas.

So the question is; Which resources do you suggest about programming language implementations that covers the topic in a more imperative and practical fashion?

For example, I find "The Implementation of Lua 5.0" paper very instructive.

Note that, I am not seeking articles about parsing or tokenizing.

[A]
Here are a bunch of good textbooks:
Modern Compiler Implementation in Java (Tiger book)
A.W. Appel
Cambridge University Press, 1998
ISBN 0-52158-388-8
A textbook tutorial on compiler implementation, including techniques for many language features
Compilers: Principles, Techniques and Tools (Dragon book)
Aho, Lam, Sethi and Ullman
Addison-Wesley, 2006
ISBN 0321486811
The classic compilers textbook, although its front-end emphasis reflects its age.
Advanced Compiler Design and Implementation (Whale book)
Steven Muchnick
Morgan Kaufman Publishers, 1997
ISBN 1-55860-320-4
Essentially a recipe book of optimizations; very complete and suited for industrial practitioners and researchers.
Engineering a Compiler (Ark book)
Keith D. Cooper, Linda Torczon
Morgan Kaufman Publishers, 2003
ISBN 1-55860-698-X
A modern classroom textbook, with increased emphasis on the back-end and implementation techniques.
Optimizing Compilers for Modern Architectures
Randy Allen and Ken Kennedy
Morgan Kaufman Publishers, 2001
ISBN 1-55860-286-0
A modern textbook that focuses on optimizations including parallelization and memory hierarchy optimizations.
Programming Languages Pragmatics
Michael L. Scott
Morgan Kaufmann Publishers, 2005
ISBN 0126339511


q:
I have a class Animal and an interface it inherits from IAnimal.

@MappedSuperclass
public class Animal implements Serializable, IAnimal{...}.

@Entity
public class Jaguar extends Animal{...}

My first question is, do I need to annotate the interface?

I asked this because I am getting this error when I run my tests:

Error compiling the query [SELECT s
  FROM  animal s WHERE s.atype =
  :atype].
  Unknown abstract schema type
  [animal]

If I remember correctly, before I added this interface it was working.


q: Microsoft has come out with this fairly new technology that I am considering using for a .NET 3.5 application.  I am curious, is anyone using this technology already?  I am worried that the use of the secure virtual machine will negatively affect performance.  Also, the way Microsoft advertises the product, it seems as though the licensing integration is very seamless and does not require any development work in the code.  It seems like a great product but I want to make sure I know of any pitfalls before committing to it.

[A]
It seems that SLP does not support .NET 3.5 at the moment.
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3526285&SiteID=1
Your best bet would be to implement an auxiliary DLL containing SLP API calls in .NET 2.0 or 3.0, secure it and add it as a reference to your .NET 3.5 app.


q:
I am trying to create a StringNameSpaceBinding using the wsadmin tool of Websphere 6.1

Here are the steps i take
set cell [$AdminConfig getid /Cell:cell/]
$AdminConfig create StringNameSpaceBinding $cell { {name bindname}  {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }

But when i run this last step i get an error like this:
WASX7015E: Exception running command: "$AdminConfig create StringNameSpaceBinding $cell { {name bindname}  {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }"; exception information:
 com.ibm.ws.scripting.ScriptingException: WASX7444E: Invalid parameter value "" for parameter "parent config id" on command "create"

Any idea what could be up with this?

Thanks
Damien

[A]
I'm betting that the following command:
```
```
set cell [$AdminConfig getid /Cell:cell/]
```
```
Doesn't work. Most likely,
```
cell
```
is not the name of your cell.
You don't need to specify a cell name; there's only one cell in the WAS topology. I would change this to:
```
```
set cell [$AdminConfig getid /Cell:/]
```
```
Good luck.


q:
I'm starting a project using a Restful architecture implemented in Java (using the new JAX-RS standard)

We are planning to develop the GUI with a Flex application. I have already found some problems with this implementation using the HTTPService component (the response error codes, headers access...).

Any of you guys have some experience in a similar project. Is it feasible?

[A]
There are definite shortcomings of Flex's ability to act as a pure RESTful client.
The comments below are from this
blog
:
The problem is HTTPService class has
  several major limitations:
Only GET and POST methods are supported out of the box (unless you
  use FDS and set useProxy attribute to
  true)
Not able to set request headers and there is no access to response
  headers. Therefore I am not able to
  access the response body in the case
  of an error.
It HTTPService gets a status code anything other 200, it consider
  an error. (event 201, ouch!!). The
  FaultEvent doesn’t provide information
  about the status code any response
  body. The Flex client will have no
  idea what went wrong.
Matt Raible
also gave a
nice presentation on REST with Rails, Grails, GWT and Flex
that have some good references linked from it.
Whether it's feasible or not really depends on how much your willing to work around by proxying, etc.


q:
Most applications only have "Restore, Move, Size, Minimize, Maximize and Close", however MS SQL offers extra options "Help, Customize view". Along those lines, is it possible to add to the right click menu of an application in the task bar?

Note: I'm not referring to an icon in the notification area next to the clock.

[A]
This is a simpler
answer
I found.  I quickly tested it and it works.
My code:
```
```
private const int WMTaskbarRClick = 0x0313;

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WMTaskbarRClick:
                {
                    // Show your own context menu here, i do it like this
                    // there's a context menu present on my main form so i use it

                    MessageBox.Show("I see that.");

                    break;
                }
            default:
                {
                    base.WndProc(ref m);
                    break;
                }
        }
    }
```
```


q:
I notice that Rails 2.2 (currently edge) supports setting HttpOnly on the session cookie.

Is there a way of setting it on a Rails 2.1 application without moving to edge/2.2?

[A]
Set the
```
http_only
```
option to true in the cookie's options hash:
```
```
cookies['visits'] = { :value => '20', :http_only => true }
```
```


q:
.Net Compact Framework

Scenario: User is on a screen. Device can't finds a printer and asks the user if they want to try again. If they click "No", the current screen is closed and they are returned to the parent menu screen. If they click the "No" button multiple times, the first click will be used by the No button and the next click will take effect once the screen has completed redrawing. (In effect clicking a menu item which then takes the user to another screen.)

I don't see a good place to put a wait cursor...there isn't much happening when the user clicks "No" except a form closing. But the CF framework is slow to redraw the screen.

Any ideas?

[A]
Random thoughts:
Disable the some of the controls on the parent dialog while a modal dialog is up.  I do not believe that you can disable the entire form since it is the parent of the modal dialog.
Alternatively I would suggest using a Transparent control to catch the clicks but transparency is not supported on CF.
How many controls are on the parent dialog?  I have not found CF.Net that slow in updating.  Is there any chance that the dialog is overloaded and could be custom drawn faster that with sub controls?
override the DialogResult property and the Dispose method of the class to handle adding/remvoing a wait cursor.


q:
How do I calculate the position of an accelerating body (e.g. a car) after a certain time (e.g. 1 second)?

For a moving body that it not accelerating, it is a linear relationship, so I presume for an accelerating body it involves a square somewhere.

Any ideas?

[A]
The equation is: s = ut + (1/2)a t^2
where s is position, u is velocity at t=0, t is time and a is a constant acceleration.
For example, if a car starts off stationary, and accelerates for two seconds with an acceleration of 3m/s^2, it moves (1/2) * 3 * 2^2 = 6m
This equation comes from integrating analytically the equations stating that velocity is the rate-of-change of position, and acceleration is the rate-of-change of velocity.
Usually in a game-programming situation, one would use a slightly different formulation: at every frame, the variables for velocity and position are integrated not analytically, but numerically:
```
```
s = s + u * dt;
u = u + a * dt;
```
```
where dt is the length of a frame (measured using a timer: 1/60th second or so). This method has the advantage that the acceleration can vary in time.
Edit
A couple of people have noted that the Euler method of numerical integration (as shown here), though the simplest to demonstrate with, has fairly poor accuracy. See
Velocity Verlet
(often used in games), and
4th order Runge Kutta
(a 'standard' method for scientific applications) for improved algorithms.


q:
What is the ideal code to logging ratio? I'm not used to writing logs as most of the applications I've developed have not had much logging.

Recently though I've changed job, and I've noticed that you can't see the application code for the calls to log4net. I appreciate that this is useful but surely having too many debug statements is just as bad as not having any at all?

There are logging statements that tell you when every method starts and finishes and what they are returning. and when pretty much anything is done.

Would it not be easier to have some addon that used reflection to add the logging statements in at compile time so they didn't get in the way as you were trying to look at the code?

Also in these days of powerful IDEs and remote debugging is that much logging really nescisary?

[A]
There is actually a nice library for adding in logging after the fact as you say,
PostSharp
. It lets you do it via attribute-based programming, among many other very useful things beyond just logging.
I agree that what you say is a little excessive for logging.
Some others bring up some good points, especially the banking scenario and other mission critical apps. It may be necessary for extreme logging, or at least be able to turn it on and off if needed, or have various levels set.


q:
I have a page that contains a form. This page is served with content type text/html;charset=utf-8. I need to submit this form to server using ISO-8859-1 character encoding. Is this possible with Internet Explorer?

Setting accept-charset attribute to form element, like this, works for Firefox, Opera etc. but not for IE.

<form accept-charset="ISO-8859-1">
  ...
</form>

Edit: This form is created by server A and will be submitted to server B. I have no control over server B.

If I set server A to serve content with charset ISO-8859-1 everything works, but I am looking a way to make this work without changes to server A's encoding. I have another question about setting the encoding in server A.

[A]
I am pretty sure it won't be possible with older versions of IE. Before the
```
accept-charset
```
attribute was devised, there was no way for
```
form
```
elements to specify which character encoding they accepted, and the best that browsers could do is assume the encoding of the page the form is in will do.
It is a bit sad that you need to know which encoding was used -- nowadays we would expect our web frameworks to take care of such details invisibly and expose the text data to the application as Unicode strings, already decoded...


q:
Take the following C# class:

c1 {
 event EventHandler someEvent;
}

If there are a lot of subscriptions to c1's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.

Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences.

[A]
Add a method to c1 that will set 'someEvent' to null.
```
```
public class c1
{
    event EventHandler someEvent;
    public ResetSubscriptions() => someEvent = null;
}
```
```


q: Is it possible to assign a global hotkey to a specific feature in an Adobe AIR app, i.e. the app feature responds to the hotkey whether the app is active or not (it must be running of course, but only in the system tray).

[A]
I don't this it's possible with Adobe AIR itself. The only method I can think of:
Install 3rd party hotkey application (like
AutoHotkey
or
HotKeyBind
)
Configure hotkey application to make
CTRL
+
ALT
+
Q
to launch
"
```
c:\programs\thvo42\coolapp.exe --hotkey q
```
"
In your AIR application, register for the
NativeApplication.invoke
event, and watch for arguments like '--hotkey q' to know that the Q hotkey was pressed, and then act accordingly.
Of course, this is kind of a hassle, maybe with some hacking you can roll it all into a single install file.


q:
In MS Transact SQL, let's say I have a table (Orders) like this:

 Order Date       Order Total     Customer #
 09/30/2008       8.00            1
 09/15/2008       6.00            1
 09/01/2008       9.50            1
 09/01/2008       1.45            2
 09/16/2008       4.50            2
 09/17/2008       8.75            3
 09/18/2008       2.50            3

What I need out of this is: for each customer the average order amount for the most recent two orders.  So for Customer #1, I should get 7.00 (and not 7.83).

I've been staring at this for an hour now (inside a larger problem, which I've solved) and I think my brain has frozen.  Help for a simple problem?

[A]
This should make it
```
```
select avg(total), customer
from orders o1
where orderdate in
  ( select top 2 date
    from orders o2
    where o2.customer = o1.customer
    order by date desc )
group by customer
```
```


q:
What are my options for programmatically accessing a Microsoft Project file? What are the pros and cons of each approach?

I will basically need to import all data from the file into another data structure. Using the Office Interop assembies is low on the preference scale.

[A]
The Microsoft Office API provides programmatic access to MS Project. I have only used it for Word and Excel so I don't know how rich the interface is - you will have to do some digging around on MSDN to find out what you can and can't do.
One of the Java projects at my company uses a commerical product by
Aspose
which allows applications to manipulate Office documents including Project. It works well for their purposes, but again, they have only used it for Word and Excel so can't offer much advice on Project.
EDIT (2019)
: I can confirm that it is a very capable product.


q:
What would be the most efficient way of recording to a log (.txt) from a console program on C# and .NET 2.2? My program loops multiple times always outputting different data based on what the user wants, so I'm searching for the most efficient way to achieve this.

I know I can always reopen a stream and then close it, but everytime I do that it would be writing just one line, then next time around (seconds later) the program reloops and needs tor write again. In my opinion, that doesn't seem very resourse friendly.

I'm using multiple threads that all have output data that I want to log (opening/closing the same file or accessing the same file on different threads might be bad). The "holds a reference to a stream writer that auto-flushes" sounds like a good idea, however I don't know how to do that.

[A]
Consider using
log4net
:
a tool to help the programmer output log statements to a variety of output targets... We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the .NET runtime. For more information on log4net see the
features
document...


q: How can I write a scheduler application in C# .NET?

[A]
It all depends on your requirements:
If you have access to a database you use a table as a queue and a service to poll the queue at regular intervals.
If your application is client only (CLI) you can use the system scheduler ("Scheduled Tasks").
Lastly, if your application is only in a database (using the CLR in SQL Server 2005 for example) then you can create a SQL Server job to schedule it.


q:
Unfortunately, I need to do this.  I'm using ELMAH for my error log.  Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception.  You used to be able to use

Elmah.ErrorLog.Default

However, this is now marked as obsolete.  The compiler directs me to use the method

Elmah.ErrorLog.GetDefault(HttpContext context)

MVC's context is of type HttpContextBase, which enables us to mock it (YAY!).  How can we deal with MVC-unaware libraries that require the old style HttpContext?

[A]
Try
```
System.Web.HttpContext.Current
```
. It should do the trick.
Gets HTTP-specific information about an individual HTTP request.
MSDN


q:
Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array @myarray and a hash %myhash, why do you need to do:

$x = $myarray[1];
$y = $myhash{'foo'};

instead of just doing :

$x = myarray[1];
$y = myhash{'foo'};

Why are the above ambiguous?

Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?

@var[0];
@var{'key'};
%var[0];
%var{'key'};

[A]
I can think of one way that
```
```
$x = myarray[1];
```
```
is ambiguous - what if you wanted a array called m?
```
```
$x = m[1];
```
```
How can you tell that apart from a regex match?
In other words, the syntax is there to help the Perl interpreter, well, interpret!


q: It seems to me that phpMyAdmin imports tables by default with collation latin1_swedish_ci, how i change this?

[A]
This is not a phpMyAdmin question.
Collations are part of recent MySQL releases, you must set the default collation of the server (or at least of the database) to change that behaviour.
To convert already imported tables to UTF-8 you can do (in PHP):
```
```
$dbname = 'my_databaseName';
mysql_connect('127.0.0.1', 'root', '');
mysql_query("ALTER DATABASE `$dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
$res = mysql_query("SHOW TABLES FROM `$dbname`");
while($row = mysql_fetch_row($res)) {
   $query = "ALTER TABLE {$dbname}.`{$row[0]}` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci";
   mysql_query($query);
   $query = "ALTER TABLE {$dbname}.`{$row[0]}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
   mysql_query($query);
}
echo 'all tables converted';
```
```
Code snippet taken from
here
.


q:
Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format (someone@domain.subdomain), but that's it's a real active e-mail address.

I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.

[A]
Without sending an email, it could be hard to get 100%, but if you
do a DNS lookup on the host
that should at least tell you that it is a viable destination system.


q:
How do I use the jQuery Datepicker with a textbox input:

$("#my_txtbox").datepicker({
  // options
});

that doesn't allow the user to input random text in the textbox.
I want the Datepicker to pop up when the textbox gains focus or the user clicks on it, but I want the textbox to ignore any user input using the keyboard (copy & paste, or any other). I want to fill the textbox exclusively from the Datepicker calendar.

Is this possible?

jQuery 1.2.6

Datepicker 1.5.2

[A]
You should be able to use the
readonly
attribute on the text input, and jQuery will still be able to edit its contents.
```
```
<input type='text' id='foo' readonly='true'>
```
```


q: As in subject... is there a way of looking at an empty table schema without inserting any rows and issuing a SELECT?

[A]
Are you looking for
DESCRIBE
?
```
db2 describe table user1.department
```
```
```
Table: USER1.DEPARTMENT

Column             Type        Type
name               schema      name               Length   Scale    Nulls
------------------ ----------- ------------------ -------- -------- --------
AREA               SYSIBM      SMALLINT                  2        0 No
DEPT               SYSIBM      CHARACTER                 3        0 No
DEPTNAME           SYSIBM      CHARACTER                20        0 Yes
```
```


q:
I am using a codebehind page in ASP.NET to perform a SQL query.  The query is loaded into a string, the connection is established (To Oracle), and we get it started by having the connection perform .ExecuteReader into a OleDBDataReader (We'll call it DataRead).  I'll try to hammer out an example below.  (Consider Drop as an ASP DropDownList control)

Dim LookFor as String = "Fuzzy Bunnies"

While DataRead.Read
    If LookFor = DataRead.Item("Kinds of Bunnies") Then
        'Meets special critera, do secondary function'

         Drop.Items.Add(DataRead.Item("Subgroup of Bunnies"))
         ...
    End if
    ...
End While

This is the only way I know of doing a dynamic add to a DropDownList.  However, each item in a DropDownList has a .text property and a .value property.  How can we define the .value as being different from the .text in code?

[A]
Pardon my possibly faulty VB
```
```
Dim item as New ListItem()
item.Value = "foo"
item.Text = "bar"

Drop.Items.Add(item)
```
```
You can also use the ListItem constructor (e.g. new ListItem("text", "value"))


q:
I am coming from the SQL server world where we had uniqueidentifier. Is there an equivalent in oracle? This column will be frequently queried so performance is the key.

I am generating the GUID in .Net and will be passing it to Oracle. For a couple reasons it cannot be generated by oracle so I cannot use sequence.

[A]
There is no uniqueidentifier in Oracle.
You can implement one yourself by using RAW (kind of a pain) or CHAR.  Performance on queries that JOIN on a CHAR field will suffer (maybe as much as 40%) in comparison with using an integer.
If you're doing distributed/replicated databases, the performance hit is worth it.  Otherwise, just use an integer.


q:
I've got the following query to determine how many votes a story has received:

SELECT s_id, s_title, s_time, (s_time-now()) AS s_timediff,

(
 (SELECT COUNT(*) FROM s_ups WHERE stories.q_id=s_ups.s_id) -
 (SELECT COUNT(*) FROM s_downs WHERE stories.s_id=s_downs.s_id)
) AS votes

FROM stories

I'd like to apply the following mathematical function to it for upcoming stories (I think it's what reddit uses) -
http://redflavor.com/reddit.cf.algorithm.png

I can perform the function on the application side (which I'm doing now), but I can't sort it by the ranking which the function provides.

Any advise?

[A]
y and z are the tricky ones. You want a specific return based on x's value. That sounds like a good reason to make a function.
http://dev.mysql.com/doc/refman/5.0/en/if-statement.html
You should make 1 function for y and one for z. pass in x, and expect a number back out.
```
```
DELIMINATOR //

CREATE FUNCTION y_element(x INT)
  RETURNS INT

BEGIN
    DECLARE y INT;

IF x > 0 SET y =  1;
ELSEIF x = 0 SET y =  0;
ELSEIF x < 0 SET y = -1;
END IF;

RETURN y;

END //;

DELIMINATOR;
```
```
There is y. I did it by hand without checking so you may have to fix a few typo's.
Do z the same way, and then you have all of the values for your final function.


q:
When I want to validate my XML docuemnts against a schema in my server-side Java, I use the built-in JRE Xerces implementation and javax.xml.validation.Schema.  It works fine, but when validation fails, Xerces gives error messages that are very close to useless, for example:

cvc-minLength-valid: Value '' with length = '0' is not facet-valid with respect to minLength '1' for type 'PopulatedStringType'

These can take an age to diagnose and track down to the particular part of the XML document that fails validation, and all because of a poor error message.

So my question is, do you use an alternative means of validating XML against Schema, that gives a more useful output on validation failure?

Please not that this is server-side Java, so please don't say "use XML Spy" or similar.

[A]
We use
Oracle's XDK (XML Development Kit)
which includes xmlparserv2.jar with a validating parser and XSLT 2.0.  It uses the JAXB API so you should only have to add it to your classpath and change your imports.  It throws errors that aren't perfect, but I would say more easily understood than your example.


q:
I am playing with a CAD application using MFC. I was thinking it would be nice to save the document (model) as an SQLite database.

Advantages:

I avoid file format changes (SQLite takes care of that)

Free query engine

Undo stack is simplified (table name, column name, new value
and so on...)

Opinions?

[A]
This is a fine idea.  Sqlite is very pleasant to work with!
But remember the old truism (I can't get an authoritative answer from Google about where it originally is from) that storing your data in a relational database is like parking your car by driving it into the garage, disassembling it, and putting each piece into a labeled cabinet.
Geometric data, consisting of points and lines and segments that refer to each other by name, is a good candidate for storing in database tables.  But when you start having composite objects, with a heirarchy of subcomponents, it might require a lot less code just to use serialization and store/load the model with a single call.
So that would be a fine idea too.
But serialization in MFC is not nearly as much of a win as it is in, say, C#, so on balance I would go ahead and use SQL.


q:
What do the brackets do in a sql statement?

For example, in the statement:

insert into table1 ([columnname1], columnname2) values (val1, val2)

Also, what does it do if the table name is in brackets?

[A]
They are meant to escape reserved keywords or invalid column identifiers.
```
```
CREATE TABLE test
(
  [select] varchar(15)
)

INSERT INTO test VALUES('abc')

SELECT [select] FROM test
```
```


q:
See: Understanding Pointers

In many C flavoured languages, and some older languages like Fortran, one can use Pointers.

As someone who has only really programmed in basic, javascript, and actionscript, can you explain to me what a Pointer is, and what it is most useful for?

Thanks!

[A]
A pointer is a variable that contains the address of another variable.  This allows you to reference another variable indirectly.  For example, in C:
```
```
// x is an integer variable
int x = 5;
// xpointer is a variable that references (points to) integer variables
int *xpointer;
// We store the address (& operator) of x into xpointer.
xpointer = &x;
// We use the dereferencing operator (*) to say that we want to work with
// the variable that xpointer references
*xpointer = 7;
if (5 == x) {
    // Not true
} else if (7 == x) {
    // True since we used xpointer to modify x
}
```
```


q:
As part of a build setup on a windows machine I need to add a registry entry and I'd like to do it from a simple batch file.

The entry is for a third party app so the format is fixed.

The entry takes the form of a REG_SZ string but needs to contain newlines ie. 0xOA characters as separators.

I've hit a few problems.

First attempt used regedit to load a generated .reg file.  This failed as it did not seem to like either either long strings or strings with newlines.  I discovered that export works fine import fails.  I was able to test export as the third party app adds similar entries directly through the win32 api.

Second attempt used the command REG ADD but I can't find anyway to add the newline characters everything I try just ends up with a literal string being added.

[A]
You could create a VBScript(.vbs) file and just call it from a batch file, assuming you're doing other things in the batch other than this registry change.  In vbscript you would be looking at something like:
```
```
set WSHShell = CreateObject("WScript.Shell")
WSHShell.RegWrite "HKEY_LOCAL_MACHINE\SOMEKEY", "value", "type"
```
```
You should be able to find the possible type values using Google.


q: Assuming a MySQL datastore, when would you NOT want to use memcached in a Ruby on Rails app?

[A]
Don't use memcached if your application is able to handle all requests quickly. Adding memcached is extra mental overhead when it comes to coding your app, so don't do it unless you need it.
Scaling's "
one swell problem to have
".


q:
I'm trying to find a good way to print leading 0, such as 01001 for a ZIP Code. While the number would be stored as 1001, what is a good way to do it?

I thought of using either case statements or if to figure out how many digits the number is and then convert it to an char array with extra 0's for printing, but I can't help but think there may be a way to do this with the printf format syntax that is eluding me.

[A]
```
```
printf("%05d", zipCode);
```
```
The
```
0
```
indicates what you are padding with and the
```
5
```
shows the width of the integer number.
Example 1: If you use
```
"%02d"
```
(useful for dates) this would only pad zeros for numbers in the ones column. E.g.,
```
06
```
instead of
```
6
```
.
Example 2:
```
"%03d"
```
would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to
```
007
```
and number 17 padded to
```
017
```
.


q:
I have a link that I dynamically create which looks something like the following:

<a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a>

with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there is a single quote in the text being passed. The obvious problem being that the link then looks something like:

<a onclick="Edit('I'm a jelly donut')" href="javascript:void(null);">Edit</a>

Any suggestions on what I can do? I'd rather not stray too far from the structure I am currently using because it is something of a standard (and maybe the standard sucks, but that's another question altogether).

Note: I am using ASP as my server side language.

[A]
Convert quote charaters to their HTML equivalents,
```
"
```
etc. before you insert them into the HTML. There's a
long list
of HTML/XML character codes on wikipedia.
There may well be a function to do this for you, depending on how you're dynamically generating the code: PHP has
htmlspecialchars
, and though I'm not familiar with ASP etc, I'm sure there are similar routines.


q:
My Django app has a Person table, which contains the following text in a field named details:

<script>alert('Hello');</script>

When I call PersonForm.details in my template, the page renders the script accordingly (a.k.a., an alert with the word "Hello" is displayed).  I'm confused by this behavior because I always thought Django 1.0 autoescaped template content by default.

Any idea what may be going on here?

UPDATE: Here's the snippet from my template. Nothing terribly sexy:

{{ person_form.details }}

UPDATE 2: I have tried escape, force-escape, and escapejs.  None of these work.

[A]
You need to mark the values as | safe I think (I'm guessing that you're filling in the value from the database here(?)):
```
```
{{ value|safe }}
```
```
Could you post a sample of the template? Might make it easier to see what's wrong
[Edit]
..or are you saying that you
want
it to escape the values (make them safe)? Have you tried manually escaping the field:
```
```
{{ value|escape }}
```
```
[Edit2]
Maybe
escapejs from the Django Project docs
is relevent:
```
```
escapejs

New in Django 1.0.

Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.
```
```
[Edit3]
What about force_escape:
```
```
{{ value|force_escape }}
```
```
...and I know it's an obvious one, but you're absolutely certain you've not got any caching going on in your browser? I've tripped over that one a few times myself ;-)


q:
Pattern pattern = Pattern.compile("^[a-z]+$");
String string = "abc-def";
assertTrue( pattern.matcher(string).matches() ); // obviously fails

Is it possible to have the character class match a "-" ?

[A]
Escape the minus sign
```
```
[a-z\\-]
```
```


q: Is there a string.Empty in JavaScript, or is it just a case of checking for ""?

[A]
Empty string, undefined, null, ...
To check for a
truthy value
:
```
```
if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}
```
```
To check for a
falsy value
:
```
```
if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}
```
```
Empty string (only!)
To check for exactly an empty string, compare for strict equality against
```
""
```
using the
```
===
```
operator
:
```
```
if (strValue === "") {
    // strValue was empty string
}
```
```
To check for not an empty string strictly, use the
```
!==
```
operator
:
```
```
if (strValue !== "") {
    // strValue was not an empty string
}
```
```


q:
I have a Virtual Machine in Virtual PC 2007.

To start it from the desktop, I have the following command in a batch file:

"c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch

But that leaves a dos prompt on the host machine until the virtual machine shuts down, and I exit out of the Virtual PC console.  That's annoying.

So I changed my command to use the START command, instead:

start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch

But it chokes on the parameters passed into Virtual PC.

START /? indicates that parameters do indeed go in that location.  Has anyone used START to launch a program with multiple command-line arguments?

[A]
have you tried:
```
```
start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" "-pc MY-PC -launch"
```
```
?


q:
When I open a file in eclipse it shows with the improper line spacing showing an extra line break between every line. When I open the file with notepad or wordpad it doesn't show these extra line breaks that only eclipse shows. How do I get eclipse to read these files like notepad and wordpad without those line breaks?

-edit: I don't have this problem with all files but only a select few where I have made local changes > uploaded them to our sun station > then pulled those files back to my local workstation for future modifications.

[A]
Eclipse should have a
```
File -> Convert Line Delimiters To...
```
option that may correct this for you. (If it doesn't work on your file,
this article
may help.)
Really, though, you should have your file transfer program treat your source files as ascii instead of binary. Then your line ending problem should be moot.


q: Anyone know how to programmatically mute the Windows XP Volume using C#?

[A]
Declare this for P/Invoke:
```
```
private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
private const int WM_APPCOMMAND = 0x319;

[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
```
```
And then use this line to mute/unmute the sound.
```
```
SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr) APPCOMMAND_VOLUME_MUTE);
```
```


q:
I've switched computers a few times recently, and somewhere along the way I lost my .emacs.  I'm trying to build it up again, but while I'm at it, I thought I'd pick up other good configurations that other people use.

So, if you use Emacs, what's in your .emacs?

Mine is pretty barren right now, containing only:

Global font-lock-mode! (global-font-lock-mode 1)

My personal preferences with respect to indentation, tabs, and spaces.

Use cperl-mode instead of perl-mode.

A shortcut for compilation.

What do you think is useful?

[A]
```
```
(put 'erase-buffer 'disabled nil)
(put 'downcase-region 'disabled nil)
(set-variable 'visible-bell t)
(set-variable 'tool-bar-mode nil)
(set-variable 'menu-bar-mode nil)

(setq load-path (cons (expand-file-name "/usr/share/doc/git-core/contrib/emacs") load-path))
 (require 'vc-git)
 (when (featurep 'vc-git) (add-to-list 'vc-handled-backends 'git))
 (require 'git)
 (autoload 'git-blame-mode "git-blame"
           "Minor mode for incremental blame for Git." t)
```
```


q:
We have a fairly large .NET solution with multiple executable projects (winforms and command line programs). Currently each of these projects has its own app.config that contains connection strings, mail server settings and the like. As you can imagine it's not that convenient to make a change in every app.config file whenever a particular setting needs to be updated.

What do you reckon is the best practice for centralized management of these settings? So far I've thought about two different approaches. The first is using a custom class (or classes) that contains the settings and is serialized into and deserialized from XML. The second approach is defining an app.config file only for a single project and using ConfigurationManager.OpenExeConfiguration() to access it.

[A]
Create the App.config on your startup project and link statically to it on the other projects.
You can link statically by going to Add->Existing Item, and when clicking the Add button on the File Browser Window, there is a small down arrow on the Add button. Click there and the "Add as link" option will be shown. That will place the same App.Config on both projects, with only one actual file.
If your projects have different App.Config with only 'some' settings that are the same, consider checking the file parameter; I mean, you can have more than one App.Config in a project:
http://weblogs.asp.net/pwilson/archive/2003/04/09/5261.aspx
Just create a central common.config file and point to it.


q:
When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods or properties that will generate compiler warnings that give messages that I write. Something like this

[MyAttribute("This code sux and should be looked at")]
public void DoEverything()
{
}

<MyAttribute("This code sux and should be looked at")>
Public Sub DoEverything()
End Sub

I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio.

[A]
In some compilers you can use #warning to issue a warning:
```
```
#warning "Do not use ABC, which is deprecated. Use XYZ instead."
```
```
In Microsoft compilers, you can typically use the message pragma:
```
```
#pragma message ( "text" )
```
```
You mentioned .Net, but didn't specify whether you were programming with C/C++ or C#. If you're programming in C#, than you should know that
C# supports the #warning format
.


q:
In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless do while loop.  Here are examples.

#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else

I can't see what the do while is doing.  Why not just write this without it?

#define FOO(X) f(X); g(X)

[A]
The
```
do ... while
```
and
```
if ... else
```
are there to make it so that a
semicolon after your macro always means the same thing.  Let's say you
had something like your second macro.
```
```
#define BAR(X) f(x); g(x)
```
```
Now if you were to use
```
BAR(X);
```
in an
```
if ... else
```
statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.
```
```
if (corge)
  BAR(corge);
else
  gralt();
```
```
The above code would expand into
```
```
if (corge)
  f(corge); g(corge);
else
  gralt();
```
```
which is syntactically incorrect, as the else is no longer associated with the if.  It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.
```
```
if (corge)
  {f(corge); g(corge);};
else
  gralt();
```
```
There are two ways of fixing the problem.  The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.
```
```
#define BAR(X) f(X), g(X)
```
```
The above version of bar
```
BAR
```
expands the above code into what follows, which is syntactically correct.
```
```
if (corge)
  f(corge), g(corge);
else
  gralt();
```
```
This doesn't work if instead of
```
f(X)
```
you have a more complicated body of code that needs to go in its own block, say for example to declare local variables.  In the most general case the solution is to use something like
```
do ... while
```
to cause the macro to be a single statement that takes a semicolon without confusion.
```
```
#define BAR(X) do { \
  int i = f(X); \
  if (i > 4) g(i); \
} while (0)
```
```
You don't have to use
```
do ... while
```
, you could cook up something with
```
if ... else
```
as well, although when
```
if ... else
```
expands inside of an
```
if ... else
```
it leads to a "
dangling else
", which could make an existing dangling else problem even harder to find, as in the following code.
```
```
if (corge)
  if (1) { f(corge); g(corge); } else;
else
  gralt();
```
```
The point is to use up the semicolon in contexts where a dangling semicolon is erroneous.  Of course, it could (and probably should) be argued at this point that it would be better to declare
```
BAR
```
as an actual function, not a macro.
In summary, the
```
do ... while
```
is there to work around the shortcomings of the C preprocessor.  When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.


q: I have heard this concept used frequently, but I don't have a really good grasp of what it is.

[A]
I beg to differ, Wikipedia is pretty clear on this.
In computer science, marshalling
  (similar to serialization) is the
  process of transforming the memory
  representation of an object to a data
  format suitable for storage or
  transmission. It is typically used
  when data must be moved between
  different parts of a computer program
  or from one program to another.
http://en.wikipedia.org/wiki/Marshalling_(computer_science)


q:
Is there any way to change the default tab size in a .NET RichTextBox?
It currently seems to be set to the equivalent of 8 spaces which is kinda large for my taste.

Edit:  To clarify, I want to set the global default of "\t" displays as 4 spaces for the control.  From what I can understand, the SelectionTabs property requires you to select all the text first and then the the tab widths via the array.  I will do this if I have to, but I would rather just change the global default once, if possible, sot that I don't have to do that every time.

[A]
You can set it by setting the
SelectionTabs
property.
```
```
private void Form1_Load(object sender, EventArgs e)
{
    richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };
}
```
```
UPDATE:
The sequence matters....
If you set the tabs prior to the control's text being initialized, then you don't have to select the text prior to setting the tabs.
For example, in the above code, this will keep the text with the original 8 spaces tab stops:
```
```
richTextBox1.Text = "\t1\t2\t3\t4";
richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };
```
```
But this will use the new ones:
```
```
richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };
richTextBox1.Text = "\t1\t2\t3\t4";
```
```


q:
I am trying to use a DynamicResource in Storyboard contained within a ControlTemplate.

But, when I try to do this, I get a 'Cannot freeze this Storyboard timeline tree for use across threads' error.

What is going on here?

[A]
No, you can't use a DynamicResource in a Storyboard that is contained within a Style or ControlTemplate. In fact, you can't use a data binding expression either.
The story here is that everything within a Style or ControlTemplate must be safe for use across threads and the timing system actually tries to freeze the Style or ControlTemplate to make them thread-safe. However, if a DynamicResource or data binding expression is present, it is unable to freeze them.
For more info see:
MSDN Link
. Check out the 'Animate in a Style' and the 'Animate in a ControlTemplate' sections (this documentation page is rather long).
And for a workaround (at least for my scenario) see:
WPF Forum Post
.
Hope this helps someone. I've lost more than enough hair on it.
Cory


q: Ok, this is a bit of a cheeky question. I want to build a simple text editor (using my own text mode screen handling). I just want a good example of data structures that can be used to represent the text buffer, and some simple examples of char/text insertion/deletion. I can handle all the rest of the code myself (file i/o, console i/o etc). A link to a nice simple editor source would be great (C or C++).

[A]
The "Gang of Four" book (
Design Patterns
) has a GUI-based text editor as it's main source of examples and is a worthwhile book to own.
The general "pure text" editor probably uses ropes, which SGI's STL has an
implementation
of. Basically, they are a linked list of character buffers. That way, inserting/deleting characters involves changing smaller buffers and a few pointers, instead of storing the entire document in a single buffer and having to shift everything.


q:
Possible Duplicate:

  C#: How to enumerate an enum?

The subject says all. I want to use that to add the values of an enum in a combobox.

Thanks

vIceBerg

[A]
```
```
string[] names = Enum.GetNames (typeof(MyEnum));
```
```
Then just populate the dropdown withe the array


q:
I frequently run into problems of this form and haven't found a good solution yet:

Assume we have two database tables representing an e-commerce system.

userData (userId, name, ...)
orderData (orderId, userId, orderType, createDate, ...)

For all users in the system, select their user information, their most recent order information with type = '1', and their most recent order information with type = '2'. I want to do this in one query.  Here is an example result:

(userId, name, ..., orderId1, orderType1, createDate1, ..., orderId2, orderType2, createDate2, ...)
(101, 'Bob', ..., 472, '1', '4/25/2008', ..., 382, '2', '3/2/2008', ...)

[A]
Their newest you mean all new in the current day? You can always check with your createDate and get all user and order data if the createDate >= current day.
```
```
SELECT * FROM
"orderData", "userData"
WHERE
"userData"."userId"  ="orderData"."userId"
AND "orderData".createDate >= current_date;
```
```
UPDATED
Here is what you want after your comment here:
```
```
SELECT * FROM
"orderData", "userData"
WHERE
"userData"."userId"  ="orderData"."userId"
AND "orderData".type = '1'
AND "orderData"."orderId" = (
SELECT "orderId" FROM "orderData"
WHERE
"orderType" = '1'
ORDER "orderId" DESC
LIMIT 1
```
```
)


q:
I am debugging a VB6 executable. The executable loads dlls and files from it's current directory, when running. When run in debugger, the current directory seems to be VB6's dir.

How do I set working directory for VB6?

[A]
Will this work?
```
```
'Declaration
Private Declare Function SetCurrentDirectory Lib "kernel32" _
Alias "SetCurrentDirectoryA" (ByVal lpPathName As String) As Long

'syntax to set current dir
SetCurrentDirectory App.Path
```
```


q:
I'm using mysqldump to replicate a database between accounts on a particular machine.  Everything works just great, except when we get to our defined views.  Because the dump includes a line like the following ...

/*!50013 DEFINER=`user_a`@`localhost` SQL SECURITY DEFINER */

... when loading the dump into mysql on user_b we receive an error:

ERROR 1227 (42000) at line 657: Access denied; you need the SUPER privilege for this operation

Needless to say, I don't have SUPER privilege on this mysql instance.  Is there a way to convince mysqldump to dump the views in a user-agnostic way?  I can't find anything in the manual on this point.   Do I have to actually parse the dumpfile to replace the usernames?  Or am I missing something?

[A]
The SQL SECURITY clauses determine which MySQL account to use when checking access privileges for the view (as you have probably figured out).
When you create a view you can define a couple of options for security for that view.  You can read more
here
, but essentially by default access is restricted to the 'definer' of the view, i.e. the user who created it.


q:
I'm trying to get something very subtle to work, it looks pretty awful right now. I'm trying to paint the background of a TGroupBox which I have overloaded the paint function of so that the corners are show through to their parent object.  I've got a bunch of nested group boxes that look very decent without XPThemes.

Is there a way to paint part of a background transparent at runtime.  I'm programming the form generator, not using Delphi design view.

[A]
I'm trying to duplicate this problem with the following steps:
1 - Set theme to Windows XP default
2 - Drop a TGroupBox on an empty form (align = alNone)
3 - Drop two TGroupBoxes inside the first one, with align = alBottom and align = alClient
But visually it looks just fine for me.
Can you provide some more info on exactly how you've designed the form?  Some code pasted from the .DFM would be fine.
Here's the relevant part of my DFM:
```
```
object GroupBox1: TGroupBox
    Left = 64
    Top = 56
    Width = 481
    Height = 361
    Margins.Left = 10
    Caption = 'GroupBox1'
    ParentBackground = False
    TabOrder = 0
    object GroupBox2: TGroupBox
      Left = 2
      Top = 254
      Width = 477
      Height = 105
      Align = alBottom
      Caption = 'GroupBox2'
      TabOrder = 0
    end
    object GroupBox3: TGroupBox
      Left = 2
      Top = 15
      Width = 477
      Height = 239
      Align = alClient
      Caption = 'GroupBox3'
      TabOrder = 1
    end
  end
```
```


q:
I am having trouble getting Team Build to execute my MbUnit unit tests. I have tried to edit TFSBuild.proj and added the following parts:

<Project ...>
  <UsingTask TaskName="MbUnit.MSBuild.Tasks.MbUnit" AssemblyFile="path_to_MbUnit.MSBuild.Tasks.dll" />
  ...
  ...
  <ItemGroup>
    <TestAssemblies Include="$(OutDir)\Project1.dll" />
    <TestAssemblies Include="$(OutDir)\Project2.dll" />
  </ItemGroup>
  <Target Name="Tests">
    <MbUnit
      Assemblies="@(TestAssemblies)"
      ReportTypes="html"
      ReportFileNameFormat="buildreport{0}{1}"
      ReportOutputDirectory="." />
  </Target>
  ...
</Project>

But I have yet to get the tests to run.

[A]
The way ItemGroups in MSBuild work is that they are evaluated at the very start of the MSBuild scripts, before any targets are ran.  Therefore if the assemblies don't exist yet (which they will not because they have not been built yet) then the ItemGroups will not find any files.
The usual pattern in MSBuild to work around this is to re-call MSBuild again at this point so that when the item groups get evaluated in the inner MSBuild execution, the assemblies will exist.
For example, something like:
```
```
<PropertyGroup>
    <TestDependsOn>
      $(TestDependsOn);
      CallMbUnitTests;
    </TestDependsOn>
  </PropertyGroup>

  <Target Name="CallMbUnitTests">
    <MSBuild Projects="$(MSBuildProjectFile)"
             Properties="BuildAgentName=$(BuildAgentName);BuildAgentUri=$(BuildAgentUri);BuildDefinitionName=$(BuildDefinitionName);BuildDefinitionUri=$(BuildDefinitionUri);
                         BuildDirectory=$(BuildDirectory);BuildNumber=$(BuildNumber);CompilationStatus=$(CompilationStatus);CompilationSuccess=$(CompilationSuccess);
                         ConfigurationFolderUri=$(ConfigurationFolderUri);DropLocation=$(DropLocation);
                         FullLabelName=$(FullLabelName);LastChangedBy=$(LastChangedBy);LastChangedOn=$(LastChangedOn);LogLocation=$(LogLocation);
                         MachineName=$(MachineName);MaxProcesses=$(MaxProcesses);Port=$(Port);Quality=$(Quality);Reason=$(Reason);RequestedBy=$(RequestedBy);RequestedFor=$(RequestedFor);
                         SourceGetVersion=$(SourceGetVersion);StartTime=$(StartTime);Status=$(Status);TeamProject=$(TeamProject);TestStatus=$(TestStatus);
                         TestSuccess=$(TestSuccess);WorkspaceName=$(WorkspaceName);WorkspaceOwner=$(WorkspaceOwner);
                         SolutionRoot=$(SolutionRoot);BinariesRoot=$(BinariesRoot);TestResultsRoot=$(TestResultsRoot)"
             Targets="RunMbUnitTests"/>
  </Target>

  <ItemGroup>
    <TestAssemblies Include="$(OutDir)\Project1.dll" />
    <TestAssemblies Include="$(OutDir)\Project2.dll" />
  </ItemGroup>
  <Target Name="RunMbUnitTests">
    <MbUnit
      Assemblies="@(TestAssemblies)"
      ReportTypes="html"
      ReportFileNameFormat="buildreport{0}{1}"
      ReportOutputDirectory="." />
  </Target>
```
```
Hope that helps, good luck.
Martin.


q:
My computer has two external audiocards and one in the motherboard with windows vista. In Vista it sees two entities for the same soundcard, a digital- and a analog output.

When i try to play an videofile with digital audio, say an dvd, it chooses 'Default DirectSound' whereas i want it to use 'Digital Output Auzentech'. So i thought easy enough, i just change the merit for 'Digital Output Auzentech' to a value higher than the others, so it would be picked, when a application tries to build an play-graph.

The problem i have is that all audio entities has the same id, so by changing 'Digital Output Auzentech', the 'Default Direct Sound' gets the same merit. I believe to have searched google-dry for information about merit, directshow and audiorenders, but still haven't found an answer.

Maybe some of the bright minds, who hang out here could help me

(tools i have used is GSpot and GraphEdit on a Vista Ultimate 32bit)

[A]
Why would you want to tinker with "merit" of directshow filters? Won't that be a bit overkill. Digital audio or not in your video file, you can use any output device here. So you can even stick your 'Digital Output Auzentech' for all the audio on your system, not just for dvd.
If you just want to select 'Digital Output Auzentech' for a particular apps, then I believe most decent apps let you do that. If you want to do and overrides all your apps (not the apps setting but it's windows' default setting), then head to "Sound and Audio Devices" under control panel (this is for xp, vista had something similiar, but I can't recall it's name), under audio tabs, change your Sound Playback Default device to 'Digital Output Auzentech', that's it. Then all your audio will be output from it.
Personally I use Media Player Classic, if I have AC3 or ACC track on the movie, and prefer to enjoy full digital output, I can easily switch from the Sound Filter settings.


q:
I need to store encrypted data (few small strings) between application runs. I do not want the user to provide a passphrase every time (s)he launches the application. I.e. after all it goes down to storing securely the encryption key(s).

I was looking into RSACryptoServiceProvider and using PersistentKeyInCsp, but I'm not sure how it works. Is the key container persistent between application runs or machine restarts? If yes, is it user specific, or machine specific. I.e. if I store my encrypted data in user's roaming profile, can I decrypt the data if the user logs on a different machine?

If the above does not work, what are my options (I need to deal with roaming profiles).

[A]
The Data Protection API (DPAPI) does exactly what you want.  It provides symmetric encryption of arbitrary data, using the credentials of the machine or (better) the user, as the encryption key.  You don't have to worry about managing the keys; Windows takes care of that for you.  If the user changes his password, Windows will re-encrypt the data using the user's new password.
DPAPI is exposed in .NET with the System.Security.Cryptography.ProtectedData class:
```
```
byte[] plaintextBytes = GetDataToProtect();
byte[] encodedBytes = ProtectedData.Protect(plaintextBytes, null, DataProtectionScope.CurrentUser);
```
```
The second parameter of the Protect method is an optional entropy byte array, which can be used as an additional application-specific "secret".
To decrypt, use the ProtectedData.Unprotect call:
```
```
byte[] encodedBytes = GetDataToUnprotect();
byte[] plaintextBytes = ProtectedData.Unprotect(encodedBytes, null, DataProtectionScope.CurrentUser);
```
```
DPAPI works correctly with roaming profiles (as described
here
), though you'll need to store the encrypted data in a place (network share, IsolatedStorage with
IsolatedStorageScope.Roaming
, etc.) that your various machines can access.
See the ProtectedData class in MSDN for more information.  There's a DPAPI white paper
here
, with more information than you'd ever want.


q: How do you get spreadsheet data in Excel to recalculate itself from within VBA, without the kluge of just changing a cell value?

[A]
The following lines will do the trick:
```
```
ActiveSheet.EnableCalculation = False
ActiveSheet.EnableCalculation = True
```
```
Edit:
The
```
.Calculate()
```
method will not work for all functions. I tested it on a sheet with add-in array functions.  The production sheet I'm using is complex enough that I don't want to test the
```
.CalculateFull()
```
method, but it may work.


q: Can I run the python interpreter without generating the compiled .pyc files?

[A]
As far as I know python will compile all modules you "import". However python will NOT compile a python script run using: "python script.py" (it will however compile any modules that the script imports).
The real questions is why you don't want python to compile the modules? You could probably automate a way of cleaning these up if they are getting in the way.


q:
A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:

namespace {
    int cannotAccessOutsideThisFile() { ... }
} // namespace

You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces are accessible within the file they're created in, as if you had an implicit using-clause to them.

My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?

[A]
The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:
The use of the static keyword is
deprecated when declaring objects in a
namespace scope, the unnamed-namespace
provides a superior alternative.
Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
Edit:
The decision to deprecate this use of the
```
static
```
keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (
ref
).  In this case using a
```
static
```
or an unnamed
```
namespace
```
are back to being essentially two ways of doing the exact same thing.  For more discussion please see
this
SO question.
Unnamed
```
namespace
```
's still have the advantage of allowing you to define translation-unit-local types.  Please see
this
SO question for more details.
Credit goes to
Mike Percy
for bringing this to my attention.


q: I've been trying this a few different ways, but I'm reaching the conclusion that it can't be done. It's a language feature I've enjoyed from other languages in the past. Is it just something I should just write off?

[A]
No, static indexers aren't supported in C#. Unlike other answers, however, I see how there could easily be point in having them. Consider:
```
```
Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)
Encoding y = Encoding["Foo"]; // Equivalent to Encoding.GetEncoding("Foo")
```
```
It would be relatively rarely used, I suspect, but I think it's odd that it's prohibited - it gives asymmetry for no particular reason as far as I can see.


q: I'm having issues with color matching css background colors with colors in images on the same html page. What gives?

[A]
Three possibilities spring to mind:
check that your monitor colour depth is set to 32- or 24-bit, not 16-bit
check that the image isn't being assigned a palette (such as the web-safe palette). This might be the case for a .gif or 8-bit .png image.
check for .png gamma correction issues in IE - see other posts for details
A workaround that I have used in the distant past is to set the background colour by repeating a small image, instead of setting it in the HTML. This kind of trick was useful in the days of web-safe palettes and so on, but less useful now.


q: What is the best way to bind WPF properties to ApplicationSettings in C#?  Is there an automatic way like in a Windows Forms Application? Similar to this question, how (and is it possible to) do you do the same thing in WPF?

[A]
Kris, I'm not sure this is the best way to bind ApplicationSettings, but this is how I did it in
Witty
.
1) Create a dependency property for the setting that you want to bind in the window/page/usercontrol/container. This is case I have an user setting to play sounds.
```
```
public bool PlaySounds
    {
        get { return (bool)GetValue(PlaySoundsProperty); }
        set { SetValue(PlaySoundsProperty, value); }
    }

    public static readonly DependencyProperty PlaySoundsProperty =
        DependencyProperty.Register("PlaySounds", typeof(bool), typeof(Options),
        new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnPlaySoundsChanged)));

    private static void OnPlaySoundsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
        Properties.Settings.Default.PlaySounds = (bool)args.NewValue;
        Properties.Settings.Default.Save();
    }
```
```
2) In the constructor, initialize the property value to match the application settings
```
```
PlaySounds = Properties.Settings.Default.PlaySounds;
```
```
3) Bind the property in XAML
```
```
<CheckBox Content="Play Sounds on new Tweets" x:Name="PlaySoundsCheckBox" IsChecked="{Binding Path=PlaySounds, ElementName=Window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
```
```
You can download the full
Witty source
to see it in action or browse just the
code for options window
.


q:
I have used Photoshop CS2's "Save for Web" feature to create a table of images for my site layout.

This HTML appears fine in a web browser, however when imported into Visual Studio and viewed in the site designer, the metrics are wrong and there are horizontal gaps between images (table cells).

The output from Photoshop does not refer to any stylesheets.

The table attributes set border, cellpadding and cellspacing to 0.

Here is how it looks in the Designer:

And here is how it looks in the browser:

Is Visual Studio picky about layout of tables and images?  Is this a bug in Visual Studio 2005?