q: I want to examine the contents of a std::vector in GDB, how do I do it?  Let's say it's a std::vector<int> for the sake of simplicity.

[A]
With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:
```
```
print *(myVector._M_impl._M_start)@myVector.size()
```
```
To print only the first N elements, do:
```
```
print *(myVector._M_impl._M_start)@N
```
```
Explanation
This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:
```
```
myVector._M_impl._M_start
```
```
And the GDB command to print N elements of an array starting at pointer P is:
```
```
print P@N
```
```
Or, in a short form (for a standard .gdbinit):
```
```
p P@N
```
```


q:
I've decided to integrate NUnit with VWD2008.

I did the following-
1) Installed NUnit - Ran a Sample project that was included with the installation all the tests were fine.
2) Installed TestDriven.Net 2.0 - Personal distribution.
3) I have written on an MVC Project a test and when I try to right click the context and run the Test it fails.
In addition I had to add reference the NUnit.framework dll in order to write the tests.

What have I done wrong?

[A]
Testdriven.Net doesn't work with the express editions of visual studio. Previous versions of Testdriven.Net did work with the Visual Studio Express editions but Microsoft didn't like that and put their lawyers on it.
http://weblogs.asp.net/nunitaddin/archive/2007/07/06/microsoft-amp-testdriven-net.aspx
You could try sharpdevelop if you want a free ide with unit-testing support.

s: huggingface

c: devops

d: intermediate


q:
In CSS, you can specify the spacing between table cells using the border-spacing property of a table.

However, this results in uniform spacing between columns and rows, and I am finding more situations where the designs I am using call for gaps between rows, but not columns, or visa versa.

If I have a solid background, I can simulate spacing using borders the same colour as the background colour.

I could also make a div (for example) the first child of every table cell, and using either padding or margins to get the desired results, but that is a lot of extra markup just to accommodate the style.

Given that that the data I am displaying is tabular data, is there a sensible way to achieve this style using tables?

[A]
You
can
specify different spacings for horizontal and vertical edges for
```
border-spacing
```
or related properties. Just specify more than one measurement. e.g.,
```
```
border-spacing: 1px 2px;
```
```


q: Does anyone know how I can add a class to the link rendered using the Html.RouteLink helper method in ASP.Net MVC, it has the htmlAttributes object as the last parameter which I assumed I would be able to use, but since class is obviously a reserved word, I cannot supply this as one of the properties on the object.

[A]
Just use uppercase for html attribute, like this:
```
```
<%= Html.RouteLink("Default", "Default",null, new { Class="css_class"}) %>
```
```


q:
Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke.

We have tried a number of different approaches, all to no avail.

For example:

myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });

where someParameter is local to this method

The above will result in a compiler error:

Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

[A]
```
```
myControl.Invoke(new MethodInvoker(delegate() {...}))
```
```


q:
I'd like to post some form variables into a classic ASP page. I don't want to have to alter the classic ASP pages, because of the amount of work that would need to be done, and the amount of pages that consume them.

The classic ASP page expects form variables Username and Userpassword to be submitted to them.

username = Request.Form("UserName")
userpassword = Request.Form("Userpassword")

It then performs various actions and sets up sessions, going into an ASP application.

I want to submit these variables into the page from ASP.NET, but the login control is nested inside usercontrols and templates, so I can't get the form element's names to be "username" and "UserPassword".

Any ideas?

[A]
I found this on
another site
.
I will build up a small form with just the variables you want, and output it to the client and submit itself. It's pretty neat, but it comes with the problem of breaking the back button, and sending the password back to the client in a form unencrypted.
```
```
public class  RemotePost{
     private  System.Collections.Specialized.NameValueCollection Inputs
     = new  System.Collections.Specialized.NameValueCollection() ;

    public string  Url  =  "" ;
    public string  Method  =  "post" ;
    public string  FormName  =  "form1" ;

    public void  Add( string  name, string value ){
        Inputs.Add(name, value ) ;
     }

     public void  Post(){
        System.Web.HttpContext.Current.Response.Clear() ;

         System.Web.HttpContext.Current.Response.Write( "" ) ;

         System.Web.HttpContext.Current.Response.Write( string .Format( "" ,FormName)) ;

         System.Web.HttpContext.Current.Response.Write( string .Format( "<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >" ,

        FormName,Method,Url)) ;
            for ( int  i = 0 ; i< Inputs.Keys.Count ; i++){
            System.Web.HttpContext.Current.Response.Write( string .Format( "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;
         }
        System.Web.HttpContext.Current.Response.Write( "</form>" ) ;
         System.Web.HttpContext.Current.Response.Write( "" ) ;
         System.Web.HttpContext.Current.Response.End() ;
     }
}
```
```


q: Is there a way to resize a std::vector to lower capacity when I no longer need previously reserved space?

[A]
Effective STL, by Scott Meyers, Item 17: Use the
```
swap
```
trick to trim excess capacity.
```
```
vector<Person>(persons).swap(persons);
```
```
After that,
```
persons
```
is "shrunk to fit".
This relies on the fact that
```
vector
```
's copy constructor allocates only as much as memory as needed for the elements being copied.


q: Can anyone give me pointers to good books or web sites that teach how to do Flex programming?

[A]
Check out
Ten Great Ways to Learn Flex
, but I think number one should be to use the
Quickstarts on the Adobe Site
.


q: pl give vb code for custom paging and sorting in asp:repeater using stored procedure

[A]
Here is step
one
and
two
from 4guys that gives a very clear explanation along with zip download available of all code in VB and sample t-sql too.
It deals with ObjectDataSource  from which then it should be straigtforward enough to bind your repeater to.


q: I have now 1gb ram at work(i hope that will change soon) and jboss takes almost half of it and that is too much, i turned off logging to file, what more can i do to reduce memory usage ?

[A]
Which configuration are you using? JBoss comes with 3
standard server configurations
The
minimal
configuration starts the core server container without any of the enterprise services. It is a good starting point if you want to build a customized version of JBoss AS that only contains the services you need.
The
default
configuration is the mostly common used configuration for application developers. It supports the standard J2EE 1.4 and most of the Java EE 5.0 programming APIs (e.g., JSF and EJB3).
The
all
configuration is the default configuration with clustering support and other enterprise extensions.
If you only want a specific subset of JBoss services, then start with the minimal?
Or you can
configure your own
?


q:
Has anyone managed to get subsonic or a variant working on Windows Mobile? We cant get it to work as it has a dependency on System.Configuration.

Any suggestions on an alternate ORMs that would work on a windows mobile device?

[A]
Is the System.Configuration dependency the only issue?  If so, you could always try to get around it by adding that capability.  For example
OpenNETCF's SDF
has an OpenNETCF.Configuration namespace that mirrors a lot of the System.Configuration namespace.  You might be able to eitehr modify subsonic to use that namespace, or modify and recompile the SDF's assembly to use System.Configuration as a namespace.


q: How are assertions done in c++? Example code is appreciated.

[A]
Assertion are boolean expressions which should typically always be true.
They are used to ensure what you expected is also what happens.
```
```
void some_function(int age)
{
     assert(age > 0);
}
```
```
You wrote the function to deal with ages, you also 'know' for sure you're always passing sensible arguments, then you use an assert. It's like saying "I know this can never go wrong, but if it does, I want to know", because, well, everyone makes mistakes.
So it's not to check for sensible user input, if there are scenario's where something can go wrong, don't use an assert. Do real checks and deal with the errors.
Asserts are typically only for debug builds, so don't put code with side effects in asserts.


q:
I have an interface - here's a nicely contrived version as an example:

public interface Particle {

    enum Charge {
        POSITIVE, NEGATIVE
    }

    Charge getCharge();

    double getMass();

    etc...
}

Is there any difference in how implementations of this would behave if I defined the Charge enum as static - i.e. does this have any effect:

public interface Particle {

    static enum Charge {
        POSITIVE, NEGATIVE
    }

    Charge getCharge();

    double getMass();

    etc...
}

[A]
No, it makes no difference. From the
language spec, section 9.5
:
Interfaces may contain member type
  declarations (
§8.5
). A member type
  declaration in an interface is
  implicitly
```
static
```
and
```
public
```
.


q:
I have a query where i have a date column (time) which tells about "IN" & "OUT" timing of the people attendance by this single column

My queries are :-

1) How to get the daily attendance of each employee
2) How to come to know if the employee is present less than 5 hours

Please let me know the queries in SQL server.

[A]
```
```
select
      datediff(minute, TimeFrom, TimeTo) as AttendedTimeInMinutes,
      case when datediff(minute, sTimeFrom, sTimeTo) < 5 * 60
         then
          'less than 5 hours'
         else '5 hours or more'
      end
   from YourTable
```
```


q:
Yesterday I was having a heated debate with a coworker on what would be the preferred error reporting method. Mainly we were discussing the usage of exceptions or error codes for reporting errors between application layers or modules.

What rules do you use to decide if you throw exceptions or return error codes for error reporting?

[A]
I normally prefer exceptions, because they have more contextual information and can convey (when properly used) the error to the programmer in a clearer fashion.
On the other hand, error codes are more lightweight than exceptions but are harder to maintain. Error checking can inadvertently be omitted. Error codes are harder to maintain because you have to keep a catalog with all error codes and then switch on the result to see what error was thrown. Error ranges can be of help here, because if the only thing we are interested in is if we are in the presence of an error or not, it is simpler to check (e.g., an HRESULT error code greater or equal to 0 is success and less than zero is failure). They can inadvertently be omitted because there is no programmatic forcing that the developer will check for error codes. On the other hand, you cannot ignore exceptions.
To summarize I prefer exceptions over error codes in almost all situations.


q:
I need a smart way to get the data types out of INFORMATION_SCHEMA.COLUMNS in a way that could be used in a CREATE TABLE statement.  The problem is the 'extra' fields that need to be understood, such as NUMERIC_PRECISION and NUMERIC_SCALE.

Obviously, I can ignore the columns for INTEGER (precision of 10 and scale of 0), but there are other types I would be interested in, such as NUMERIC.  So without writing lots of code to parse the table, any ideas on how to get a sort of field shorthand out of the column definition?

I would like to be able to get something like :
int,
datetime,
money,
numeric**(10,2)**

[A]
SMO Scripting should take care of the script generations. I believe that this is what MS uses in SQL Management Studio for script generations.
http://msdn.microsoft.com/en-us/library/ms162153.aspx
@YourComment -
```
I need a smart way to get the data types out of INFORMATION_SCHEMA.COLUMNS in a way that could be used in a CREATE TABLE statement
```
This is what you asked for. Short of that, you will have to parse the info schema view results.


q:
I am writing a Java Application for Data Entry using Eclipse and SWT. Naturally it has a great many Text objects.

What I would like to happen is that when user enters something into one field focus automatically changes to the next field.

Thanks in advance

[A]
```
```
final Text textBox = new Text(shell, SWT.NONE);
textBox.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
        if (x.getText().length() == 1); {
            x.traverse(SWT.TRAVERSE_TAB_NEXT);
        }
    }
});
```
```


q:
Can anyone suggest which of the Redmine or Tracd would be a better option for project management? Currently I am planning to deploy it on a one project setup but plan to use it across multiple projects in the fututre. Which of the two is easier to deploy? I use windows. Any other software which is web based and comes with its own web server?

Thanks...

[A]
If you plan to do multi-project management in the future, choose redmine. With trac you can have multi-project setups as well (having a separate environment for each project), but in the end it's a workaround. Redmine has builtin support for multi-project environments.
I previously used trac to manage my projects, but I switched to redmine. I didn't find any effective way of importing all my tickets and wiki pages. Redmine uses textile markup, but trac uses markdown, so I had a couple of troubles there.
Finally, I heard that redmine has some some issues on windows. I haven't tried running redmine on that platform so you'd better give it a try or google around.


q:
In Vim, how do I  insert characters at the beginning of each line in a selection?

For instance,  I want to comment out a block of code by prepending // at the beginning of each line assuming my language's comment system doesn't allow block commenting like /* */.  How would I do this?

[A]
This replaces the beginning of
each line
with "//":
```
```
:%s!^!//!
```
```
This replaces the beginning of
each selected line
(use visual mode to select) with "//":
```
```
:'<,'>s!^!//!
```
```
Note
that
```
gv
```
(in normal mode) restores the last visual selection, this comes in handy from time to time.


q:
I need to add a row to a spreadsheet using VBScript on a PC that does not have Microsoft Office installed.

I tried [Set objExcel = CreateObject("Excel.Application")]

Since Excel does not exist on the PC I cannot create this object.

Is there a way to modify a spreadsheet without Excel?

[A]
Without Excel installed I cannot see how you will be able to change an Excel document.
However, If your are using Excel 2007 spreadsheets (xslx) then you should able to use the OpenXML functionality of the .NET Framework to update the contents without Excel physically being installed.
Take a look
here
for more information on Office OpenXML.


q:
Delphi (and probably a lot of other languages) has class helpers. These provide a way to add extra methods to an existing class. Without making a subclass.

So, what are good uses for class helpers?

[A]
At first I was kind of sceptic about class helpers. But then I read an interesting
blog entry
and now I'm convinced that they are indeed useful.
For example, if you want extra functionality for an existing instance class and for some reason you are not able to change the existing source. You can create a class helper to add this functionality.
Example:
```
```
type
  TStringsHelper = class helper for TStrings
  public
    function IsEmpty: Boolean;
  end;

function TStringsHelper.IsEmpty: Boolean;
begin
  Result := Count = 0;
end;
```
```
Every time, we now use an instance of (a subclass of) TStrings, and TStringsHelper is within the scope. We have access to the method IsEmpty.
Example:
```
```
procedure TForm1.Button1Click(Sender: TObject);
begin
  if Memo1.Lines.IsEmpty then
    Button1.Caption := 'Empty'
  else
    Button1.Caption := 'Filled';
end;
```
```
Notes:
Class helpers can be stored in a separate unit, so you can add your own nifty class helpers. Be sure to give these units a easy to remember name like ClassesHelpers for helpers for the Classes unit.
There are also record helpers.
If there are multiple class helpers within scope, expect some problems, only one helper can be used.


q:
Alright, I know how the fieldset/legend works out in HTML. Say you have a form with some fields:

<form>
    <fieldset>
        <legend>legend</legend>
        <input name="input1" />
    </fieldset>
</form>

What should I use the legend for? It's being displayed as a title, but isn't a legend semantically an explanation of the contents? In my view, preferably you'd do something like this:

<form>
    <fieldset>
        <legend>* = required</legend>
        <label for="input1">input 1 *</label><input id="input1" name="input1" />
    </fieldset>
</form>

But that doesn't really work out with how fieldsets are rendered. Is this just a ambigious naming in HTML, or is it my misunderstanding of the English word 'legend'?

Edit: fixed some errors ;-)

[A]
Yes, the naming is ambiguous. It’s best to consider it as a caption for the fieldset.
See
the HTML spec on
```
FIELDSET
```
and
```
LEGEND
```
elements
if you haven’t already:
The
```
LEGEND
```
element allows authors to assign a caption to a
```
FIELDSET
```
. The legend improves accessibility when the
```
FIELDSET
```
is rendered non-visually.


q:
I have a WPF control, that has a list of "Investors", and in the right column of the list, a "Delete" button.

I could either waste some time making an image of an "x" in photoshop. Or, I could just use Wingdings font and set the content to "Õ" (which makes a cool looking delete button).

Is this appropriate? My thinking is... while not every font family is on every computer, I'm pretty sure that it's safe to say that if you're running my WPF Windows Forms program, then you have Wingdings.

What do you think? Please try to give statistics (not just feelings) on the matter. Should I worry about font size? etc.

[A]
Honestly, if you're using WPF, it's probably just as easy to use a path to make an 'x' shape:
```
```
<Style x:Key="DeleteButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="HorizontalAlignment" Value="Stretch"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Cursor" Value="Hand"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
                        <Path Name="Circle" Data="F1 M 0 7.5 A 7.5 7.5 0 1 1 15 7.5 A 7.5 7.5 0 1 1 0 7.5"/>
                        <Path Fill="White" Data="F1 M 7.5 6 L 10.5,3 12,4.5 9,7.5 12,10.5 10.5,12 7.5,9 4.5,12 3,10.5 6,7.5 3,4.5 4.5,3 Z"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Fill" TargetName="Circle" Value="SlateGray"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="False">
                            <Setter Property="Fill" TargetName="Circle" Value="DarkGray"/>
                        </Trigger>
                        <DataTrigger Binding="{Binding}" Value="{x:Null}">
                            <Setter Property="Visibility" Value="Hidden"/>
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ToolTip" Value="Delete This Item"/>
    </Style>
```
```
Just apply this style to a button, and you get an instant "delete" button!


q:
What is their use if when you call the method, it might not exist?

Does that mean that you would be able to dynamically create a method on a dynamic object?

What are the practical use of this?

[A]
You won't really be able to dynamically create the method - but you can get an implementation of
```
IDynamicMetaObject
```
(often by extending
```
DynamicObject
```
) to respond
as if the method existed
.
Uses:
Programming against COM objects with a weak API (e.g. office)
Calling into dynamic languages such as Ruby/Python
Potentially making "explorable" objects - imagine an XPath-like query but via a method/property calls e.g.
```
document.RootElement.Person[5].Name["Attribute"]
```
No doubt many more we have yet to think of :)


q:
I know how to capture a camera snaphot on Windows Mobile 5.0/6 using SHCameraCapture. But is there something more extensive that allows me much finer control? Namely to get available zoom levels and to set the zoom level programmatically, also e.g. different ISO modes / lightsensitivity and setting of macro mode if available. (I.e. similar to what JSR 234 offers).

My project is probably going to be written in C++.

Update: It is supposed to run on all available WM 5.0 and 6 devices. I am looking for a generic solution that is not specific to a particular model.

[A]
For the ISO modes, light sensitivity and other advanced controls etc. it is usually device specific from everything I've seen. I know different manufacturers will expose their imager libraries through their SDKs. What sort of mobile device are you using? Check with the manufacturer for an API exposed through their SDK.
For simple stuff you've probably already had a look at the following Class:
CameraCaptureDialog Class
And for things like image quality this one:
CameraCaptureStillQuality Enumeration
** Note: These are for Windows Mobile 6.


q:
I want to create a subclass of TabPage that contains some control, and I want to control the layout and properties of those controls through the designer.  However, if I open my subclass in the designer, I can't position them like I could on a UserControl.  I don't want to have to create a TabPage with an UserControl instance on it, I want to design the TabPage directly.

How do I do that?  I've tried changing the Designer and DesignerCategory attributes, but I haven't found any values that help.

[A]
I've had a similar problem in the past.
What i did first was switch from inheriting Usercontrol to tabpage like so
class UserInterface : UserControl // Do designer bit then change it to
class UserInterface : TabPage
Second i Just put all my controls and stuff in the usercontrol and docked that into a tabpage.
third i've made a generic class that takes any usercontrol and does the docking automatically.
so you can take your 'UserInterface' class and just get a type that you can add to a System.Windows.Forms.TabControl
```
```
public class UserTabControl<T> : TabPage
    where T : UserControl, new ()
{
    private T _userControl;
    public T UserControl
    {
        get{ return _userControl;}
        set
        {
            _userControl = value;
            OnUserControlChanged(EventArgs.Empty);
        }
    }
    public event EventHandler UserControlChanged;
    protected virtual void OnUserControlChanged(EventArgs e)
    {
        //add user control docked to tabpage
        this.Controls.Clear();
        UserControl.Dock = DockStyle.Fill;
        this.Controls.Add(UserControl);

        if (UserControlChanged != null)
        {
            UserControlChanged(this, e);
        }
    }

    public UserTabControl() : this("UserTabControl")
    {
    }

    public UserTabControl(string text)
        : this( new T(),text )
    {
    }

    public UserTabControl(T userControl)
        : this(userControl, userControl.Name)
    {
    }

    public UserTabControl(T userControl, string tabtext)
        : base(tabtext)
    {
        InitializeComponent();
        UserControl = userControl;
    }

    private void InitializeComponent()
    {
        this.SuspendLayout();
        //
        // UserTabControl
        //

        this.BackColor = System.Drawing.Color.Transparent;
        this.Padding = new System.Windows.Forms.Padding(3);
        this.UseVisualStyleBackColor = true;
        this.ResumeLayout(false);
    }
}
```
```


q:
I have a line (actually a cube) going from (x1,y1,z1) to (x2,y2,z2). I would like to rotate it so that it is aligned along another line going from (x3,y3,z3) to (x4,y4,z4). Presently I am using Math::Atan2 along with Matrix::RotateYawPitchRoll. Any better ways to do this?

Edit: I think I've worded this post very badly. What I am actually looking for is a Rotation Matrix from two Vectors.

[A]
Yes you can do this without needing to think in terms of angles at all.
Since you have a cube, suppose you pick one corner and then define the 3 edges radiating out from it as vectors f0, f1, f2 (these are direction vectors, relative to the corner you've picked).  Normalise those and write them as columns in a matrix F
```
```
(f0x f1x f2x)
(f0y f1y f2y)
(f0z f1z f2z)
```
```
Now do the same thing for the vectors t0, t1, t2 of the cube you want to rotate to and call it matrix T.
Now the matrix R = T * Inverse(F) is the matrix which rotates from the orientation of the first cube to the orientation of the second (because inverse F maps e.g f0 to (1 0 0)', and then T maps (1 0 0)' to t0).
If you want to know why this works, think in terms of coordinate system basis vectors: if you want to rotate the X Y and Z axes to a new coordinate system, well the columns of the rotation matrix are just the vectors you want (1 0 0)', (0 1 0)' & (0 0 1)' to be mapped to.  T*Inverse(F) is effectively rotating your cube from its original orientation to axis aligned, and then to the desired orientation.
(Sorry, above is for column vectors and transforms on the left, OpenGL style.  I seem to remember Direct3D is row vectors and transforms on the right, but it should be obvious how to switch it around).
It also applies equally well to 4x4 matrices with a translation component too.


q: I've written some custom model binders (implementing IModelBinder) in our ASP.NET MVC application. I'm wondering what is a good approach to unittest them (binders)?

[A]
I did it this way:
```
```
var formElements = new NameValueCollection() { {"FirstName","Bubba"}, {"MiddleName", ""}, {"LastName", "Gump"} };
var fakeController = GetControllerContext(formElements);
var valueProvider = new Mock<IValueProvider>();

var bindingContext = new ModelBindingContext(fakeController, valueProvider.Object, typeof(Guid), null, null, null, null);

private static ControllerContext GetControllerContext(NameValueCollection form) {
    Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();
    mockRequest.Expect(r => r.Form).Returns(form);

    Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
    mockHttpContext.Expect(c => c.Request).Returns(mockRequest.Object);

    return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
}
```
```
And then I just passed in the bindingContext variable to the BindModel method of the object that implements the IModelBinder interface.


q:
Since DBs do not reuse numbers of deleted records it is possible to run out of numbers, especially if you pick not really a big integer type for this column.

What would happen and how to prevent it if it's bad?

// SQL Server, MySQL //

[A]
For MySQL, it is documented that:
The behavior of the auto-increment mechanism is not defined if a user assigns a negative value to the column or if the value becomes bigger than the maximum integer that can be stored in the specified integer type.


q:
I'm looking for an OpenSource server monitoring tool that allows the following:

Monitor a variety of services on TCP, UDP.

Supports custom port numbers.

Supports some basic response checking (beyond initial connection checking).

Basic dashboard overview of health status.

Alert notifications via e-mail.

I could roll my own, but want to make sure I don't reinvent the wheel if there's a complete suite out there that does what I want (and maybe more!).

EDIT: Preferably software that runs on Windows.


q:
What is the slowest (therefore best) hash algorithm for passwords in ASP Classic?

EDIT: For those unaware, when hashing passwords, slower hashes are preferred to faster to help slow rainbow table style attacks.

EDIT2: And yes, of course speed isn't the only valid concern for hash selection. My question assumes that All other things being equal, the slowest hash method is preferred when hashing a password. Though collision/reverse engineering is of course a concern too, I'm prioritizing speed in this question since it is arguably the most critical factor to consider when comparing popular hash algorithms for use on passwords.

Thanks!

[A]
psuedocode for the slowest method:
```
```
function hashPassword(password)
    sleep for 10 seconds
    return password
end function
```
```
This certainly isn't the most secure (or at all) but it's slow...
(I'm just pointing out that making it slower is not the answer...)


q:
I am making an expand/collapse call rates table for the company I work for. I currently have a table with a button under it to expand it, the button says "Expand". It is functional except I need the button to change to "Collapse" when it is clicked and then of course back to "Expand" when it is clicked again. The writing on the button is a background image.

So basically all I need is to change the background image of a div when it is clicked, except sort of like a toggle.

[A]
```
```
$('#divID').css("background-image", "url(/myimage.jpg)");
```
```
Should do the trick, just hook it up in a click event on the element
```
```
$('#divID').click(function()
{
  // do my image switching logic here.
});
```
```


q:
I am trying to start WebLogic within Eclipse

When it starts it complains like this.

Unable to load performance pack. Using Java I/O instead. Please ensure that wlntio.dll is in: 'C:\bea81\jdk142_04\bin;.;C:\WINDOWS\system32;C:\WINDOWS;C:\bea81\jdk142_04\jre\bin;C:\Program Files\Java\jre1.6.0\bin\client;C:\Program Files\Java\jre1.6.0\bin;C:\sybase\JS-12_5\bin;C:\sybase\OCS-12_5\lib3p;C:\sybase\OCS-12_5\dll;C:\sybase\OCS-12_5\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Common Files\Roxio Shared\DLLShared\;C:\Program Files\Common Files\Roxio Shared\DLLShared\;C:\Program Files\Common Files\Roxio Shared\9.0\DLLShared\;C:\Program Files\cvsnt;C:\Program Files\Executive Software\DiskeeperWorkstation\;'

[A] Make sure that wlintio.dll is in the path. The location may vary depending on Weblogic version; in 9.2 it is in $BEA_HOME/server/native/win/32


q: I have a web application that allows a user to search on some criteria, select an object, edit it and then return to the previous search.  All the editing takes place on a separate page linked to the datagrid of returned results.  I was wondering what is the best way to store the previous search parameters so that when they return to the grid they have the same search they previously used.  The best option I came up with is to use a NameValue collection of each of the selected paramters and store that to Session or a cookie when the user presses the search button.  Any other ideas as to a better way to approach this?

[A]
In our app, we have dozens of lists with search fields. We've designed a simple utility class that generates a unique string based on the current Page and stores it in the session.
```
```
public static string GenerateSessionKeyFromPage(Page page)
    {
        return "__" + page.Request.Path;
    }
```
```
This allows us to store the search field without having to maintain a NameValue collection every time we add a new page.


q:
I have a dropdown list that stores name/value pairs. The dropdown appears in each row of a gridview.

The values in the dropdown correspond to a third attribute (data type) not persisted in the dropdown list. I'd like to create a client-side "lookup" table so that when a user chooses a dropdown value, the proper data type populates next to it.

What's the best way to accomplish this in an ASP.NET application? The List of value/attributes could potentially range from 1 to 100 members in a list...

[A]
If you want it all  to run client side, then your only option is probably JavaScript.
```
```
var oVals = new Array('1','2','3','4','5');

document.getElementById("cell1").innerHTML = oVals[document.getElementById("dropdown1").selectedIndex];
```
```


q:
When building static libraries with VS2005 I keep getting linker warnings that VC80.pdb cant be found with my library.lib. Apparently, as a result, the edit and continue feature of the IDE fails to work any project that incorporates library.lib

What magic is needed to tell VS2005 to produce a static lib with edit and continue debug info that does NOT reference or require vs80.pdb when linked into a project?

--Upon Further Understanding--
So, In order to get edit-and-continue to function with a pre-compiled static lib, we need to place the vs80.pdb and vs80.pdb file into SVN along with the .lib, AND rename the pdb/idb to prevent conflicts when doing this with multiple pre-compiled libs.

[A]
vc80.pdb is the file that contains the debug information for your lib.  In the ide Property pages:configuration properties:c\c++:output files allows you to rename this to something more appropriate, such as the name of your lib.  When the linker links your lib into the target exe it looks for this pdb (there is a pointer to it in the lib) and extracts the info from that pdb and drops it in the exe's pdb.
/Fd[name] is the option for renaming the pdb
/ZI is the option for compiling with a pdb that includes Edit and Continue information.
All linked libs and the final taget exe or dll need /ZI, to enable edit and continue.
I made a tiny testlib.lib and used "dumpbin /all" to get the following showing the pointer to the debug info (this is a tiny excerpt):
```
```
SECTION HEADER #7
.debug$T name
       0 physical address
       0 virtual address
      48 size of raw data
     838 file pointer to raw data (00000838 to 0000087F)
       0 file pointer to relocation table
       0 file pointer to line numbers
       0 number of relocations
       0 number of line numbers
42100040 flags
         Initialized Data
         Discardable
         1 byte align
         Read Only

RAW DATA #7
  00000000: 04 00 00 00 42 00 15 15 D5 EA 1E C9 7C 10 3A 40  ....B...Õê.É|.:@
  00000010: 93 63 CE 95 77 15 49 4A 03 00 00 00 64 3A 5C 64  .cÎ.w.IJ....d:\d
  00000020: 65 76 5C 74 65 73 74 5C 74 65 73 74 6C 69 62 5C  ev\test\testlib\
  00000030: 74 65 73 74 6C 69 62 5C 64 65 62 75 67 5C 76 63  testlib\debug\vc
  00000040: 38 30 2E 70 64 62 00 F1                          80.pdb.ñ
```
```


q:
I have a web page that has a web form for signing up. I want to remove fields. I've tried removing the field code from the .asp file but obviously there are other things that I need to remove along those lines. I have full access to all the code but I need help knowing where things are linked as far as making the form work again. Our programmer bailed.

A step by step guide would be great on this. thanks.

[A]
If they're just .ASP files, you should be fine removing the field tag, along with any references to it.
I.e. you'd delete this line:
```
```
<asp:TextBox id="text1" runat="server" />
```
```
and do a search for the 'id' attribute in the rest of the file (a find on 'text1' in this case), and remove those lines.


q:
I have a report that is used by a windows service and a form application.  So, I want to put embed the report in a DLL file that can be used by both.

The problem is that if I try to set the ReportEmbeddedResource property of a ReportViewer control in my windows form app, it will search the windows form app for the resource, not the dll file.

e.g.: Code from the windows form app:

rv.LocalReport.ReportEmbeddedResource = "MyReportInMyDLLFile.rdlc"

How can I make the above command look for the embedded resource in my DLL file?

[A]
Probably the best thing to do would be to get a stream to the RDLC resource from the other assembly, then pass that to the "LoadReportDefinition" method of the Report Viewer control.
Details of how to get a stream from an embedded resource in a different assembly can be found here :
Retrieving Resources with the ResourceManager Class
Additionally, you will need to refer to the embedded resource using it's full namespace path.
E.g. if you have an application with a default namespace of
TheApp
, and you keep a report called "
MyReport.rdlc
" in a folder called "
Reports
", the report reference call would be:-
```
```
rv.LocalReport.ReportEmbeddedResource = "TheApp.Reports.MyReport.rdlc";
```
```


q:
Having not done ASP.NET since v1.1, and now blitzing through the Wrox Pro ASP.NET v3.5 book, what other resources are available to get me developing enterprise ASP.NET apps the fastest?

I've been developing in DotNet since Beta and have been doing Winform & middle-layer architecture/design/dev for 3.5 years now (as this has been my client's desires). But I'm finding my falling behind has hurt me concerning a new client. :(

I'd appreciate any advice on moving forward as fast as possible. I'm looking for anything RAD related or even just great books on the subject that you recommend. Right now, I'm having fun consuming the Wrox book though. Thanx much!

[A]
Take a look to the
ASP.NET Dynamic Data
Scaffolding Framework (included in the .NET Framework 3.5 SP1), it allows you to build   really quickly data driven web applications.
Here
you can find more good videos and resources about this RAD feature.


q:
In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class:

public class A
{
    public event EventHandler SomeEvent;

    public void someMethod()
    {
        if(SomeEvent != null) SomeEvent(this, someArgs);
    }
}

public class B : A
{
    public void someOtherMethod()
    {
        if(SomeEvent != null) SomeEvent(this, someArgs); // << why is this not possible?
//Error: The event 'SomeEvent' can only appear on the left hand side of += or -=
//(except when used from within the type 'A')
    }
}

Why isn't it possible?

And what is the common solution for this kind of situation?

[A]
The standard practice here is to have a protected virtual method OnSomeEvent on your base class, then call that method in derived classes. Also, for threading reasons you will want to keep a reference to the handler before checking null and calling it.
For an explanation of the why read
Jon Skeet's
answer or the
C# specification
which describes how the compiler automatically creates a private field.
Here is one possible work around.
```
```
public class A
{
    public event EventHandler SomeEvent;

    public void someMethod()
    {
        OnSomeEvent();
    }

    protected void OnSomeEvent()
    {
        EventHandler handler = SomeEvent;
        if(handler != null)
            handler(this, someArgs);
    }
}

public class B : A
{
    public void someOtherMethod()
    {
        OnSomeEvent();
    }
}
```
```
Edit:
Updated code based upon
Framework Design Guidelines section 5.4
and
reminders
by others.


q: I believe that Agile is nothing but another implementation of Spiral Model. I am a big supporter of Spiral (The spiral model is a software development process combining elements of both design and prototyping-in-stages, in an effort to combine advantages of top-down and bottom-up concepts) since its beginnings and have seen that lot of projects implement Spiral without knowing that they are operating in a Spiral world. Since the day Agile started gaining popularity the concept of spiral started getting overlooked a little bit. I am sure that for complex projects spiral is still the best alternative but I would like to get a better understanding of the similarities and differences between Agile and Spiral techniques.   Can anyone explain their differences/similarities?

[A]
Agile
is
spiral.  Totally.  In part, the name was changed for marketing purposes.
The problem is that spiral tends to imply "big design up front" -- where you plan out many spirals, each in order of risk.  Spiral, however, isn't Agile -- it's just incremental execution in order of risk.
One big distinction that Agile adds is the "don't overplan things you can't know yet."
Agile
is
spiral, but you create detailed plans for just
one
increment at a time.
Agile adds a lot of other things, also.  Spiral is a very technical approach.  Agile, however, recognizes that technology is built by people.  The
Agile Manifesto
has four principles that are above and beyond the Boehm's simple risk management approach.


q:
We all know to keep it simple, right?

I've seen complexity being measured as the number of interactions between systems, and I guess that's a very good place to start. Aside from gut feel though, what other (preferably more objective) methods can be used to determine the level of complexity of a particular design or piece of software?

What are YOUR favorite rules or heuristics?

[A]
If your app is built, you can measure it in terms of time (how long a particular task would take to execute) or computations (how much code is executed each time the task is run).
If you just have designs, then you can look at how many components of your design are needed to run a given task, or to run an average task. For example, if you use MVC as your design pattern, then you have at least 3 components touched for the majority of tasks, but depending on your implementation of the design, you may end up with dozens of components (a cache in addition to the 3 layers, for example).


q: Much searching has lead me to find several descriptions of how to create a bootstrapping msi, but these solutions all assume the msi is local or a standard Windows component.  Is there a way to make an msi that downloads an installer (which is also an msi) with normal MSI or Wix code rather than by having the bootstrapper execute some non-native program to do so?

[A]
My experience with msi's has been it's not possible to run 2 at the same time. (could be wrong though)
What I ended up doing was to instead make an installer exe using Inno Setup (
http://www.jrsoftware.org
) and ISTool (
http://www.istool.org
) which downloads and installs the various msi's.  With ISTool it's very easy to do.
I know it's not as chic or sexy as Wix, but it worked for me very well.


q:
I'm sorry, but this keyword doesn't mean anything to me... Can someone give me a definition?

Thanks in advance...

[A]
It's a brand.
http://pervasive.com/
And here is a link to their DB products
http://www.pervasivedb.com/Pages/PDBProducts.aspx
including Pervasive PSQL


q:
What is the best way to refresh a DataGridView when you update an underlying data source?

I'm updating the datasource frequently and wanted to display the outcome to the user as it happens.

I've got something like this (and it works), but setting the DataGridView.DataSource to null doesn't seem like the right way.

List<ItemState> itemStates = new List<ItemState>();
dataGridView1.DataSource = itemStates;

for (int i = 0; i < 10; i++) {
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = itemStates;
    System.Threading.Thread.Sleep(500);
}

[A]
Try this Code
```
```
List itemStates = new List();

for (int i = 0; i < 10; i++)
{
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}
```
```


q:
Using MSSQL2005, can I truncate a table with a foreign key constraint if I first truncate the child table (the table with the primary key of the FK relationship)?

I know that I can either

Use a DELETE without a where clause and then RESEED the identity (or)

Remove the FK, truncate the table, and recreate the FK.

I thought that as long as I truncated the child table before the parent, I'd be okay without doing either of the options above, but I'm getting this error:

Cannot truncate table 'TableName' because it is being referenced by a FOREIGN KEY constraint.

[A]
Correct; you cannot truncate a table which has an FK constraint on it.
Typically my process for this is:
Drop the constraints
Trunc the table
Recreate the constraints.
(All in a transaction, of course.)
Of course, this only applies if the
child has already been truncated.
Otherwise I go a different route, dependent entirely on what my data looks like. (Too many variables to get into here.)
The original poster determined WHY this is the case; see
this answer
for more details.


q:
In a WPF app, is there a object I can assign to FileSystemWatcher.SynchronizingObject?

I can make my own, but if there is one available, I would like to use it.

[A]
Reflector shows that the only class that implements
```
ISynchronizeInvoke
```
(i.e., the type of the
```
FileSystemWatcher.SynchronizingObject
```
property) is
```
System.Windows.Form.Control
```
(and its subclasses); there do not appear to be any WPF objects that implement this interface.


q:
I've looked for references on the Audible format, and it appears that people are only interested in cracking/converting out of it.  I've got a collection of MP3 files that I want to convert into Audible format for use on my Kindle and iPod.

Does anybody have a good reference on the Audible or protected AAC formats and how section markers and metadata are expressed?  Better yet, a utility or code sample?

[A]
The Audible format is a DRM protected proprietary format only available from Audible.  They protect their format diligently.  From what I understood, they used to charge handsomely for the right to use it.  I am not aware of any publicly available encoders that will create audible formatted files (for free or not).  Since Amazon bought Audible I am not sure if they would even sell the right to anyone else anymore.
I do not own a Kindle, but from what I can tell, it only supports Audible formatted files with full audiobook functionality.  MP3's can be played , but they are not treated the same way (no support for chapters etc).
Creating audiobooks with chapter support for the iPod requires creating a M4B file with a text track and making sure the audio track has the proper track reference to the text track.  M4B is a version of MP4 that uses AAC audio. There are several programs to do this on the MAC and recently a few have surfaced for the PC.
I have created a freeware software package with a Graphical User Interface (GUI) for the PC which is in Beta test now.  It is called "Chapter and Verse" and it will be available on
lodensoftware.com
shortly. Two other options with GUI's are: "
Chapter Master
" from Rightword Enterprises ($15) and "
iPod Audio Book Converter
" (freeware) from
sjhaley.com
which is in Beta test as well.
Several command line utilities exist as well. One is called Slide Show Assembler (SSA) that can be used to create podcasts as well as audiobooks.  SSA is available from
jrlearnsmedia.com
.  Another is a command line utility for manipulating MP4 files called mp4creator.  mp4creator can add chapters to a MP4 file.


q:
I have a case that keeps coming up where I'm using a ListView or similar control with a simple array such as string[].

Is there a way to use the DataKeyNames property when you are binding to simple collections?

[A]
Try using a Generic List with objects object.  The example below is C# 3.0.  Say you want a list of letters:
```
```
public class LettersInfo
{
    public String Letter { get; set; }
}
```
```
then make a list:
```
```
List<LettersInfo> list = new List<LettersInfo>();
list.add(new LettersInfo{ Letter = "A" });
list.add(new LettersInfo{ Letter = "B" });
list.add(new LettersInfo{ Letter = "C" });
```
```
then bind it to the listview
```
```
lv.DataKeyNames = "Letter";
lv.DataSource = list;
lv.DataBind();
```
```


q: I want to have CListCtrl.EditLabel() for any column of the list. How can I implement such a feature?

[A]
Description is a reserved word - put some [] brackets around it in the SELECT statement
EDIT
Try naming the column something besides Description
Also are you sure you are using the same values in the where clause - because it is a left join so the Description field will be blank if there is no corresponding record in dbo_part
EDIT AGAIN
If you are getting funny results - try a Compact/Repair Database - It might be corrupted


q:
If I wanted to find checked check boxes on an ASP.NET page I could use the following LINQ query.

var checkBoxes = this.Controls
                     .OfType<CheckBox>()
                     .TakeWhile<CheckBox>(cb => cb.Checked);

That works fine if the checkboxes are nested in the current control collection, but I'd like to know how to extend the search by drilling down into the control collections of the top-level controls.

The question was asked here:

Finding controls that use a certain interface in ASP.NET

And received non-LINQ answers, I already have my own version of a recursive control search on type and ID as extension methods, but I just wondered how easy this is to do in LINQ?

[A]
Take the type/ID checking out of the recursion, so just have a "give me all the controls, recursively" method, e.g.
```
```
public static IEnumerable<Control> GetAllControls(this Control parent)
{
    foreach (Control control in parent.Controls)
    {
        yield return control;
        foreach(Control descendant in control.GetAllControls())
        {
            yield return descendant;
        }
    }
}
```
```
That's somewhat inefficient (in terms of creating lots of iterators) but I doubt that you'll have a
very
deep tree.
You can then write your original query as:
```
```
var checkBoxes = this.GetAllControls()
                     .OfType<CheckBox>()
                     .TakeWhile<CheckBox>(cb => cb.Checked);
```
```
(EDIT: Changed AllControls to GetAllControls and use it properly as a method.)


q:
select max(DELIVERY_TIMESTAMP) from DOCUMENTS; will return the time that the latest document was delivered. How do I return the other columns for the latest document? For example I want DOC_NAME for the document that was most recently delivered?

I'm not sure how to form the WHERE clause.

[A]
```
```
Select Max(DELIVERY_TIMESTAMP),
       Doc_Name
From TableName
Group By Doc_Name
```
```
That should do it, unless I missed something in the question.


q:
I am looking for an expression for the .hgignore file, to ignore all files beneath a specified folder.

eg: I would like to ignore all files and folders beneath bin

Actually any advice on how the expressions are formed would be great

[A]
Nevermind, I got it
```
```
syntax: regexp
bin\\*
```
```
expressions follow standard perl regular expression syntax.


q:
I am using the EMMA tool for code coverage yet despite my best efforts, EMMA is refusing to see the original .java files and generate coverage on a line-by-line basis.

We are using ANT to build the code and debug is set to true. I know that EMMA is measuring coverage as the .emma files seem to be generating and merging correctly. The reports are able to present high level method coverage with percentages.

But why won't it see the .java files? All I get is:
[source file 'a/b/c/d/e/f/code.java' not found in sourcepath]

[A]
Are you setting the
```
sourcepath
```
in your
```
report
```
element?
```
```
<report>
    <sourcepath>
        <pathelement path="${java.src.dir}" />
    </sourcepath>
    <fileset dir="data">
        <include name="*.emma" />
    </fileset>

    <txt outfile="coverage.txt" />
    <html outfile="coverage.html" />
</report>
```
```


q:
This probably has a simple answer, but I must not have had enough coffee to figure it out on my own:

If I had a comma delimited string such as:

string list = "Fred,Sam,Mike,Sarah";

How would get each element and add quotes around it and stick it back in a string like this:

string newList = "'Fred','Sam','Mike','Sarah'";

I'm assuming iterating over each one would be a start, but I got stumped after that.

One solution that is ugly:

int number = 0;
string newList = "";
foreach (string item in list.Split(new char[] {','}))
{
    if (number > 0)
    {
        newList = newList + "," + "'" + item + "'";
    }
    else
    {
        newList = "'" + item + "'";
    }
    number++;
}

[A]
```
```
string s = "A,B,C";
string replaced = "'"+s.Replace(",", "','")+"'";
```
```
Thanks for the comments, I had missed the external quotes.
Of course.. if the source was an empty string, would you want the extra quotes around it or not ? And what if the input was a bunch of whitespaces... ? I mean, to give a 100% complete solution I'd probably ask for a list of unit tests but I hope my gut instinct answered your core question.
Update
: A LINQ-based alternative has also been suggested (with the added benefit of using String.Format and therefore not having to worry about leading/trailing quotes):
```
```
string list = "Fred,Sam,Mike,Sarah";
string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList());
```
```


q: Where can I set the display name in the Service Control Manager of a c++ app?

[A]
Use
ChangeServiceConfig
to change the display name; you can use
ChangeServiceConfig2
to change the description.


q:
I am using the SoundEngine sample code from Apple in the CrashLanding sample to play back multiple audio files. Using the sample caf files included with CrashLanding everything works fine but when I try and use my own samplesconverted to CAF using afconvert all I get is a stony silence ;)

Does anyone have settings for afconvert that will produce a CAF file capable of being played back through OpenAL?

[A]
```
```
afconvert -f caff -d LEI16@44100 -c 1 in.wav out.caf
```
```
References:
Apple's
Multimedia Programming Guide: Using Audio: Preferred Audio Formats in iOS
afconvert(1) man page
(use
```
afconvert -h
```
for complete info)


q:
In .Net (VB more specifically, but that doesn't really matter), is there a way to change the format of a number from one culture to another strictly through the that number's type?

The issue is this: In English, the number is say, 123.45.  Whereas in Sweden, the number would be 123,45

Is there a way to convert 123,45 to 123.45 without having to convert it to a string (and then use the formatting methods) then convert it back to the correct type (single, double, etc)?

[A]
Leave it as a number.  Change the cultureInfo of the thread and it will display accordingly with no need of conversion.
E.g.
```
```
Thread.CurrentThread.CurrentCulture = New CultureInfo("se-SE")
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture
```
```
Never try and specifically format numbers or dates into strings or you will be on your way to hell.
UPDATE: Jon makes a point to be aware of in comments, you'll know if it applies to your situation or not.


q:
I'm writing a mapping app that uses a Canvas for positioning elements.  For each element I have to programatically convert element's Lat/Long to the canvas' coordinate, then set the Canvas.Top and Canvas.Left properties.

If I had a 360x180 Canvas, can I convert the coordinates on the canvas to go from -180 to 180 rather than 0 to 360 on the X axis and 90 to -90 rather than 0 to 180  on the Y axis?

Scaling requirements:

The canvas can be any size, so should still work if it's 360x180 or 5000x100.

The Lat/Long area may not always be (-90,-180)x(90,180), it could be anything (ie (5,-175)x(89,-174)).

Elements such as PathGeometry which are point base, rather than Canvas.Top/Left based need to work.

[A]
I'm pretty sure you can't do that exactly, but it would be pretty trivial to have a method which translated from lat/long to Canvas coordinates.
```
```
Point ToCanvas(double lat, double lon) {
  double x = ((lon * myCanvas.ActualWidth) / 360.0) - 180.0;
  double y = ((lat * myCanvas.ActualHeight) / 180.0) - 90.0;
  return new Point(x,y);
}
```
```
(Or something along those lines)


q: How can I display a sort arrow in the header of the sorted column in a list view which follows the native look of the operating system?

[A]
You can use the following extension method to set the sort arrow to a particular column:
```
```
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ListViewExtensions
{
    [StructLayout(LayoutKind.Sequential)]
    public struct HDITEM
    {
        public Mask mask;
        public int cxy;
        [MarshalAs(UnmanagedType.LPTStr)] public string pszText;
        public IntPtr hbm;
        public int cchTextMax;
        public Format fmt;
        public IntPtr lParam;
        // _WIN32_IE >= 0x0300
        public int iImage;
        public int iOrder;
        // _WIN32_IE >= 0x0500
        public uint type;
        public IntPtr pvFilter;
        // _WIN32_WINNT >= 0x0600
        public uint state;

        [Flags]
        public enum Mask
        {
            Format = 0x4,       // HDI_FORMAT
        };

        [Flags]
        public enum Format
        {
            SortDown = 0x200,   // HDF_SORTDOWN
            SortUp = 0x400,     // HDF_SORTUP
        };
    };

    public const int LVM_FIRST = 0x1000;
    public const int LVM_GETHEADER = LVM_FIRST + 31;

    public const int HDM_FIRST = 0x1200;
    public const int HDM_GETITEM = HDM_FIRST + 11;
    public const int HDM_SETITEM = HDM_FIRST + 12;

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref HDITEM lParam);

    public static void SetSortIcon(this ListView listViewControl, int columnIndex, SortOrder order)
    {
        IntPtr columnHeader = SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
        for (int columnNumber = 0; columnNumber <= listViewControl.Columns.Count - 1; columnNumber++)
        {
            var columnPtr = new IntPtr(columnNumber);
            var item = new HDITEM
                {
                    mask = HDITEM.Mask.Format
                };

            if (SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            if (order != SortOrder.None && columnNumber == columnIndex)
            {
                switch (order)
                {
                    case SortOrder.Ascending:
                        item.fmt &= ~HDITEM.Format.SortDown;
                        item.fmt |= HDITEM.Format.SortUp;
                        break;
                    case SortOrder.Descending:
                        item.fmt &= ~HDITEM.Format.SortUp;
                        item.fmt |= HDITEM.Format.SortDown;
                        break;
                }
            }
            else
            {
                item.fmt &= ~HDITEM.Format.SortDown & ~HDITEM.Format.SortUp;
            }

            if (SendMessage(columnHeader, HDM_SETITEM, columnPtr, ref item) == IntPtr.Zero)
            {
                throw new Win32Exception();
            }
        }
    }
}
```
```
Then, you can call the extension method like such:
```
```
myListView.SetSortIcon(0, SortOrder.Ascending);
```
```
It works by using P/Invoke to:
Get the handle to the header control for a list view using the
LVM_GETHEADER
message.
Get the information about a header column using the
HDM_GETITEM
message.
It then modifies the
```
fmt
```
to set / clear the
```
HDF_SORTDOWN
```
and
```
HDF_SORTUP
```
flags on the returned
HDITEM
structure.
Finally it re-sets the information usintg the
HDM_SETITEM
message.
This is what it looks like:


q:
I am wondering what are the possible value for *_la_LDFLAGS in Makefile.am ?

If I ask this question, it is because I would like the following :

Actual shared library : libA.so (or with the version number I don't care)
Symbolic links :        libA-X.Y.Z.so, libA-X.so, libA.so
soname :                libA-X.so

However here is what I get by using the -release flag :

Actual shared library : libA-X.Y.Z.so
Symbolic links :        libA.so
soname :                libA-X.Y.Z.so    !!! this is not what I want

I also tried with no flags at all and got

Actual shared library : libA-0.0.0.so    !!! 0.0.0 and not the real version
Symbolic links :        libA.so, libA-0.so
soname :                libA-0.so        !!! 0.0.0 and not the real version

How should I do ? which flag should I use ?

Thanks in advance

[A]
You should use the
```
-version-info
```
option of Libtool to specify the interface version of the library, but be sure to read
how versioning works
(or
here
for the official manual.)
You can additionally play with
```
-release
```
to make the version number of your package more apparent, but I doubt you will ever get the exact naming you'd like.  Libtool has its own set of rules to define how to name the file and what symlinks to create depending on the system: these should really be regarded as implementation details of how a shared library is installed.


q: My group has a source analysis tool that enforces certain styles that we have to comply with.  I can't change it, and some of the rules are just a pain.  One example is that all properties have to come before methods, and all constructors must come before properties.  It seems silly to me that I have to take time to do something to the program when to the compiler it is the same.  I would like some thing that is a plugin to VS that will let me do things like this automatically.  Also, it would be nice to have it automatically put using's inside the namespace block.

[A]
You have different possibilities, depending on what exactly you want to do:
Resharper: There is a auto-format function which formats the source code of a single file or all files in the project / solution depending on your selected rules. So you set the settings for braces, naming, whitespaces, operators, lamdas, ... For more information see
here
. Resharper also supports settings a source- code file for all solutions or a shared settings file which is the same for all persons in the team.
FxCop: I havn't ever used this at work, but it's also a great tool an you can also select the rules which you want to enforce.


q:
Currently I'm using

var x = dict.ContainsKey(key) ? dict[key] : defaultValue

I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like

var x =  dict[key] ?? defaultValue;

this also winds up being part of linq queries etc. so I'd prefer one-line solutions.

[A]
You can use a helper method:
```
```
public abstract class MyHelper {
    public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) {
        V ret;
        bool found = dic.TryGetValue( key, out ret );
        if ( found ) { return ret; }
        return default(V);
    }
}

var x = MyHelper.GetValueOrDefault( dic, key );
```
```


q:
I have a simple HTML upload form, and I want to specify a default extension ("*.drp" for example). I've read that the way to do this is through the ACCEPT attribute of the input tag, but I don't know how exactly.

<form enctype="multipart/form-data" action="uploader.php" method="POST">
Upload DRP File:
<input name="Upload Saved Replay" type="file" accept="*.drp"/><br />
<input type="submit" value="Upload File" />
</form>

Edit
I know validation is possible using javascript, but I would like the user to only see ".drp" files in his popup dialog. Also, I don't care much about server-side validation in this application.

[A]
The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you
might
have to accept a generic MIME type.
Additionally, it appears that most browsers may not honor this attribute.
The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.
Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.


q:
What I am looking for is the equivalent of System.Windows.SystemParameters.WorkArea for the monitor that the window is currently on.

Clarification:  The window in question is WPF, not WinForm.

[A]
```
Screen.FromControl
```
,
```
Screen.FromPoint
```
and
```
Screen.FromRectangle
```
should help you with this. For example in WinForms it would be:
```
```
class MyForm : Form
{
  public Rectangle GetScreen()
  {
    return Screen.FromControl(this).Bounds;
  }
}
```
```
I don't know of an equivalent call for WPF. Therefore, you need to do something like this extension method.
```
```
static class ExtensionsForWPF
{
  public static System.Windows.Forms.Screen GetScreen(this Window window)
  {
    return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);
  }
}
```
```


q:
Unsure if I've phrased this correctly, but in the callback how do I reference the controls property of the base class?

This has been bugging me for some time and I usually work around it, but I'd be grateful if anybody can enlighten me on how I should do this properly.

var base = function() {
    var controls = {};

    return {
        init: function(c) {
            this.controls = c
        },
        foo: function(args) {
            this.init(args.controls);
            $(this.controls.DropDown).change(function() {
                $(this.controls.PlaceHolder).toggle();
            });
        }
    }
};

Much Obliged,

Paul

[A]
You need to leverage closures here.
```
```
var base = function() {
var controls = {};

return {
    init: function(c) {
            this.controls = c
    },
    foo: function(args) {
            this.init(args.controls);
            $(this.controls.DropDown).change(function(controls) {
                    return function(){
                        $(controls.PlaceHolder).toggle();
                    }
            }(this.controls));
    }
}
```
```
};


q: Is there any good software that will allow me to search through my SVN respository for code snippets?  I found 'FishEye' but the cost is 1,200 and well outside my budget.

[A]
A lot of SVN repos are "simply" HTTP sites, so you might consider looking at some off the shelf "web crawling" search app that you can point at the SVN root and it will give you basic functionality. Updating it will probably be a bit of a trick, perhaps some SVN check in hackery can tickle the index to discard or reindex changes as you go.
Just thinking out loud.


q:
I have a table with columns

Index, Date

where an Index may have multiple Dates, and my goal is the following: select a list that looks like

Index, MinDate, MaxDate

where each Index is listed only once, and MinDate (MaxDate) represents the earliest (latest) date present in the entire table for that index.  That's easy enough, but then let's constrain this list to appear only for Indexes that are present in a given range of dates.

So far, I have the following:

SELECT
    Index,
    MIN([Date]),
    MAX([Date])
FROM myTable
WHERE
    Index IN
    (SELECT Index From myTable WHERE [Date] BETWEEN '1/1/2000' AND '12/31/2000')
GROUP BY Index
ORDER BY Index ASC

This is excruciatingly slow.  Any way to speed this up?  [I am running SQL Server 2000.]

Thanks!

Edited: For clarity.

[A]
You don't need the sub-select in the where clause.  Also, you could add indexes to the date column.  How many rows in the table?
```
```
SELECT
    [INDEX],
    MIN ( [Date] ),
    MAX ( [Date] )
FROM
    myTable
WHERE
    [Date] Between '1/1/2000' And '12/31/2000'
GROUP BY
    [Index]
ORDER BY
    [INDEX] ASC
```
```


q:
I need an easy way to allow users to upload multiple files at once (ie I need to allow a user to upload a folder).  I do not wish to put the burden of zipping on the user.

I would prefer to avoid Flash or variants if possible.  I'm looking for a straight javascript / HTML solution if it is possible.  Please note, this rules out the answers at: What is the best client side browser library to upload multiple files over http?.

[A]
If you're avoiding Flash (and presumably Java?) the JS/HTML-only solution still requires single-file
```
input
```
s, but essentially you attach an
```
onchange
```
event to your
```
input
```
, adding a new
```
input
```
to the DOM whenever a file is selected.


q:
I'm thinking about how to do this, but I have several different shapes of Data in my Database, Articles, NewsItems, etc.

They All have something in common, they all have IDs (in the DB they're named ArticleID, NewsID etc. )

They all have a Title

They all have BodyText.

They all have a Status

They all have a DateAdded

What I'd like to do is standard class inheritance.

I'd like a Master Class (I don't need to write this to the database) called Content with fields like:

ID

Title

SubTitle

BodyText

Status

AddedDate

I'm not sure how I can do this with the ORM. Why I want this is because then I can pass a list of COntent to my UserControl which is responsible for Rendering it.  It will only need the information that is common to all objects.

Is this even possible?

[A]
I'm not sure whether you're talking about LINQ to SQL, but there are a few resources online about how to create inheritance with it:
LINQ To SQL Discriminator Column Example - Inheritance Mapping Tutorial
Inheritance in LINQ to SQL Screencast
...and more.
HTH


q:
Why does this lambda expression not compile?

Action a = () => throw new InvalidOperationException();

Conjecture is fine, but I would really appreciate references to the C# language specification or other documentation.

And yes, I know that the following is valid and will compile:

Action a = () => { throw new InvalidOperationException(); };

The context where I would use something like this is described on this blog post.

[A]
All the references I can find, from here:
http://msdn.microsoft.com/en-us/library/ms364047(VS.80).aspx#cs3spec_topic4
show that you have two options:
```
```
Action a = () => { throw new InvalidOperationException(); };
```
```
or
```
```
Action a = () => throw new InvalidOperationException()
```
```
Note the missing ; on the end. Yes, it makes no sense to me either. The examples they give  in the spec are:
```
```
x => x + 1                     // Implicitly typed, expression body
x => { return x + 1; }         // Implicitly typed, statement body
(int x) => x + 1               // Explicitly typed, expression body
(int x) => { return x + 1; }   // Explicitly typed, statement body
(x, y) => x * y               // Multiple parameters
() => Console.WriteLine()      // No parameters
```
```
Dunno how much help that is - I can't tell what context you are using it in, and not putting a ; on the end makes no sense in C#
the difference may be that it's an expression body - not a statement - if it doesn't have the {}. Which means that your throw is not valid there, as it's a statement, not an expression!


q: In a table, I have three columns - id, name, and count. A good number of name columns are identical (due to the lack of a UNIQUE early on) and I want to fix this. However, the id column is used by other (4 or 5, I think - I would have to check the docs) tables to look up the name and just removing them would break things. So is there a good, clean way of saying "find all identical records and merge them together"?

[A]
Why can't you do something like
```
```
update dependent_table set name_id = <id you want to keep> where name_id in (
    select id from names where name = 'foo' and id != <id you want to keep>)
```
```


q: I need a way to determine the type of an HTML element in JavaScript. It has the ID, but the element itself could be a <div>, a <form> field, a <fieldset>, etc. How can I achieve this?

[A]
What about
```
element.tagName
```
?
See also
```
tagName
```
docs on MDN
.


q: I don't care what the differences are.  I just want to know whether the contents are different.

[A]
The low level way:
```
```
from __future__ import with_statement
with open(filename1) as f1:
   with open(filename2) as f2:
      if f1.read() == f2.read():
         ...
```
```
The high level way:
```
```
import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
   ...
```
```


q:
Knuth recently objected to 64-bit systems, saying that for  programs which fit in 4 gigs of memory, "they effectively throw away half of the cache" because the pointers are twice as big as on a 32-bit system.

My question is: can this problem be avoided by installing a 32-bit operating system on a 64-bit machine?  And are there any bandwidth-intensive benchmarks which demonstrate the advantage in this case?

[A]
The answer is: yes it can to a certain extent, although the performance difference is unlikely to be great.
Any benchmark to test this will have to do a lot of pointer resolution, which will be difficult to separate out from the noise.  Designing a benchmark that will not optimise away is difficult.
This article about flawed java benchmarks
was posted by someone in response to another question, but many of the principles described in it will apply to this.


q:
I want to simplify my execution of a Groovy script that makes calls to an Oracle database. How do I add the ojdbc jar to the default classpath so that I can run:

groovy RunScript.groovy

instead of:

groovy -cp ojdbc5.jar RunScript.groovy

[A]
```
groovy
```
is just a wrapper script for the Groovy JAR that sets up the Java classpath. You could modify that script to add the path to your own JAR, as well, I suppose.


q: I want to create a string that spans multiple lines to assign to a Label Caption property. How is this done in Delphi?

[A]
```
my_string := 'Hello,' + #13#10 + 'world!';
```
```
#13#10
```
is the CR/LF characters in decimal


q: What's the most appropriate type used to store the duration time information of a video in sql server?

[A] I would store it as an INT representing the number of seconds, but I suppose it all depends what you need to do with the information in your database (you wouldn't want to have to convert it to HH:MM:SS or something else in your DB)


q:
I have an aspx page which will upload images to server harddisk from client pc

But now i need to change my program in such a way that it would allow me to resize the image while uploading.

Does anyone has any idea on this ? I couldnt not find such properties/methods with Input file server control

Any one there to guide me ?

[A]
You will not be able to resize "on the fly" since you will need to have the full image before you perform any image transformations. However, after the upload is complete and before you display any results to your user, you can use this basic image resizing method that I've used in a couple of my apps now:
```
```
''' <summary>
   '''    Resize image with GDI+ so that image is nice and clear with required size.
   ''' </summary>
   ''' <param name="SourceImage">Image to resize</param>
   ''' <param name="NewHeight">New height to resize to.</param>
   ''' <param name="NewWidth">New width to resize to.</param>
   ''' <returns>Image object resized to new dimensions.</returns>
   ''' <remarks></remarks>
   Public Shared Function ImageResize(ByVal SourceImage As Image, ByVal NewHeight As Int32, ByVal NewWidth As Int32) As Image

      Dim bitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(NewWidth, NewHeight, SourceImage.PixelFormat)

      If bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format4bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format8bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Undefined Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.DontCare Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppArgb1555 Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppGrayScale Then
         Throw New NotSupportedException("Pixel format of the image is not supported.")
      End If

      Dim graphicsImage As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmap)

      graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
      graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
      graphicsImage.DrawImage(SourceImage, 0, 0, bitmap.Width, bitmap.Height)
      graphicsImage.Dispose()
      Return bitmap

   End Function
```
```


q:
I'm looking for the easiest free SVN implementation I can find.

I downloaded and installed VisualSVN Server - pretty easy.
Installed TortioseSVN - pretty easy - both work together.
Installed AnkhSVN, I can't get it to connect to the repository on the VisualSVN Server.

Is there anything special I need to do to get AnkhSVN to talk to the VisualSVN Server?

[A]
I have a repository in visualSVN.
I can see that repository with Tortoise.
However I can't connect to it with the 'repository explorer' feature of anhkSVN.
I thought I had read that there were some issues with anhkSVN using http/s - the repository on the server is at an
https://server:8443/svn/reponame
I have been able to get anhkSVN to work with a different server using the svn:// protocol, but not with the VisualSVN-Server using the https: protocol.


q:
I need to leave some instructional comments for other developers on a page/user control.  Is there a better way to do this besides the below?

  <% /* DO NOT rename control IDs here, because blah blah blah... */ %>

[A]
That is about it, barring a HTML comment.
Your options are:
```
```
<!-- Renders to ClientOutput too -->
```
```
or:
```
```
<% /* Your original idea */ %>
```
```


q:
What do I put in my order by??  I want to order by Name.  I have moved the orderby after the distinct because I read that it needs to be done last.

   var result = (from r in db.RecordDocs
                  where r.RecordID == recordID
                  select new
                             {
                                 DocTypeID = r.Document.DocType.DocTypeID,
                                 Name = r.Document.DocType.Name,
                                 Number = r.Document.DocType.Number
                             }
                 ).Distinct().OrderBy( );

[A]
Just do
```
```
.OrderBy(doc => doc.Name)
```
```


q: Is there a way to use a foreach loop to iterate through a collection backwards or in a completely random order?

[A]
you can do it backwards:
```
```
for (int i=col.count-1; i>0; i--){
      DoSomething ( col.item[i]) ;
}
```
```
Not certain about the exact syntax, but that's the paradigm.
As for completely random order, you can access a collection element via it's index.  To ensure you hit every item, you would need to keep track of which elements you had already processed (probably by copying the collection and then removing the element after access).
EDIT: More details for random access
The code for the random access could look something like this:
```
```
collection c = originalCollection;
 while (c.count > 0) {
     int i = randomNumber(seed) mod c.count
     element d = c[i];
     c.remove(d);
     DoSomething(d);
}
```
```


q:
I am wondering how I can break up my index.php homepage to multiple php pages (i.e. header.php, footer.php) and build a working index.php page using those separate php pages.  I know WordPress uses this with different functions like:

GetHeader();
GetFoodter();

But when I tried to use those functions, it errors.  I am guessing they are not native functions to PHP.

What would I need to do to get this functionality?

[A]
```
```
include 'header.php';

include 'footer.php';
```
```


q:
I've been working with some C# legacy code and I've been seeing a lot of @ symbols in front of variable names. What does this signify or do?

Currently I'm seeing it a lot in front of variables with common names that aren't reserved. E.g.:

MyProcedure(@step.LoadInstanceId, @step.ResultCode, @step.StatusCode);

Given that step isn't a reserved word, is there any reason that they should be escaped?

[A]
It's just a way to allow declaring reserved keywords as vars.
```
```
void Foo(int @string)
```
```


q:
I'm running a PL/SQL block that is supposed to be calling a stored procedure who's output parameters are supposed to be populating variables in the PL/SQL block.

The procedure compiles, and the PL/SQL block runs successfully. But I'd like to check the values of the variables populated by the procedure. Is there a way to output these values?

I'm using Free TOAD if that helps.

Thanks,

[A]
```
```
dbms_output.put_line(varHere);
```
```


q: Can I somehow disable spell-checking on HTML textfields (as seen in e.g. Safari)?

[A]
Update
: As suggested by a commenter (additional credit to
How can I disable the spell checker on text inputs on the iPhone
), use this to handle all desktop and mobile browsers.
```
```
<tag autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
```
```
Original answer: Javascript cannot override user settings, so unless you use another mechanism other than textfields, this is not (or shouldn't be) possible.


q: I recently downloaded Mono 2 for my new MacBook.  I'm trying to figure out how to compile Visual Studio solutions with xbuild, which is included in Mono.  Any ideas?

[A]
The last time I checked, solutions weren't supported by xbuild (they use a different file format), but *.*proj files are.
If you have a relatively simple solution, you may be able to get away with using xbuild on each project separately, but if your solution is very complex (with interdependencies between projects, etc.), you'll probably have to do a bit of hacking to make everything work.
Furthermore, it's worth noting the C++ projects in Visual Studio don't use msbuild, either (although Visual Studio 2010 is supposed to fix this), so if you need to compile any C++, you're totally on your own (of course, Mono doesn't have a C++/CLI compiler, so you wouldn't get very far with xbuild, anyway).
This question/answer
suggests that you may wish to use mdtool, instead.


q:
In JSP I can reference a bean's property by using the tag
${object.property}

Is there some way to deal with properties that might not exist? I have a JSP page that needs to deal with different types. Example:

public class Person {
    public String getName()
}
public class Employee extends Person {
    public float getSalary()
}

In JSP I want to display a table of people with columns of name and salary. If the person is not an employee then salary should be blank. The row HTML might look like:

<tr>
    <td><c:out value="${person.name}"></td>
    <td><c:out value="${person.salary}"></td>
</tr>

Unfortunately if person is not an employee then it can't find salary and an error occurs. How would I solve this in JSP?

Edit: Is there an instanceof check in JSP tag language?

[A]
You could always have a type field.
```
```
public class Person {
    public String getType() { return "Person"; }
    public String getName()
}
public class Employee extends Person {
    public String getType() { return "Employee"; }
    public float getSalary()
}
```
```
Your JSP would look like
```
```

    <c:out value="${person.name}">
    <c:if test="'Employee' eq person.type"><c:out value="${person.salary}"></c:if>

```
```
Of course the Class class already has this...
```
```

    <c:out value="${person.name}">
    <c:if test="'Employee' eq person.class.simpleName"><c:out value="${person.salary}"></c:if>

```
```
You could also have `isEmployee()' method.


q: What format do I use for Date/Time when writing to an XML file using .NET? Do I simply use DateTime.ToString(), or do I have to use a specific format?

[A]
What does the DTD have to say?
If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.
If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it.  In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans.  e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.


q:
The following code fails at runtime…

Dim Id As Guid = CType(e.CommandArgument, Guid)

It throws this exception…

System.InvalidCastException was unhandled by user code
Specified cast is not valid

Why can't I cast e.CommandArgument as a Guid?

[A]
Try:
```
```
Dim DeleteId As Guid = New Guid(Convert.ToString(e.CommandArgument))
```
```
This works...
```
Dim DeleteId As Guid = New Guid(DirectCast(e.CommandArgument, String))
```


q: I have a .Net CF 2.0 application and am using log4net to log errors.  I get a stack trace, but it doesn't have any line numbers.  I noticed that it doesn't appear to deploy the pdb file to the device, so I tried to manually place it in the same directory as the exe.  But that didn't help.

[A]
Have you tried to bubble up the exceptions with out wrapping them in a new exception;
link
```
```
try {
       //code..

     }
 catch
     {
        throw;
      }
```
```


q:
I was reading an article on MSDN Magazine about using the Enumerable class in LINQ to generate a random array. The article uses VB.NET and I'm not immediately sure what the equivalent is in C#:

Dim rnd As New System.Random()
Dim numbers = Enumerable.Range(1, 100). _
    OrderBy(Function() rnd.Next)

[A]
```
```
Random rnd = new Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
```
```


q:
I am looking for a clear, complete example of programmatically deleting all documents from a specific document library, via the Sharepoint object model.  The doclib does not contain folders.  I am looking to delete the documents completely (ie I don't want them in the Recycle Bin).

I know of SPWeb.ProcessBatchData, but somehow it never seems to work for me.

Thanks!

[A]
You just have to go through all the files of your Document Library.
```
```
foreach(SPListItem item in SPContext.Current.Web.Lists["YourDocLibName"].Items)
{
    //TODO: Verify that the file is not checked-out before deleting
    item.File.Delete();
}
```
```
Calling the delete method on a file from the API doesn't use the recycle bin. It's a straight delete. You still need to verify that the file is not checked-out.
Here is some reference:
SPList
SPListItem
SPFile


q:
does anybody know how could I get the TWO most largest values from the third column on the following array?

$ar = array(array(1, 1,   7.50,   'Hello'),
              array(1, 2,  18.90,   'Hello'),
              array(3, 5,  11.50,   'Hello'),
              array(2, 4,  15.90,  'Hello'));

Output should be:

15.90
18.90

Thanks in advance

[A]
If you're sure that the value (two) will never change, just iterate over the array and keep track of the two largest numbers. If not, sort the arrays using
```
usort
```
()
and providing an appropriate callback. Then take the first two values:
```
```
function cmp($a, $b) {
    $a = $a[2];
    $b = $b[2];
    return $a == $b ? 0 : $a < $b ? 1 : -1;
}

usort($ar, 'cmp');
```
```


q: I'm trying to figure out how to restrict access to a page unless the page is navigated to from a specific "gate" page. Essentially I want the page to be unaccessible unless you're coming from the page that comes before it in my sitemap. I'm not certain this is even possible. If possible, can you limit your suggestions to using either html or javascript?

[A]
If possible, can you limit your suggestions to using either html or javascript?
No.
Because there is no secure way
using only these two techniques. Everything that goes on on the client side may be manipulated (trivially easy). If you want to be sure, you have to enforce this on the server side by checking for the
```
REFERER
```
(sic!) header.
Mind, even this can be manipulated.
If you're using Apache with
```
mod_rewrite
```
enabled, the following code will restrict access according to the referring page:
```
```
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://www\.example\.com/.*
RewriteRule /* http://www.example.com/access-denied.html [R,L]
```
```
EDIT: I just checked
the manual
… unfortunately, giving a 401 status code isn't possible here. So the above solution isn't perfect because although it blocks access, it doesn't set the HTTP status accordingly. :-/ Leaves a bad taste in my mouth.


q:
Is it possible to automatically launch an application from a USB flash drive (bypassing windows prompt asking user what he wants to do)? on windows XP or vista.

I looked into "autorun.inf" and "open" entry seems to work only for CD drives for Windows XP SP2+ and Vista. Is it possible to launch program automatically on all windows versions?

I don't care if autorun is disabled by user in Windows settings.

[A]
I've had something set up on my USB keys for a while now. Using the autorun.inf file will work, depending on your system's settings for autorun. Some disable it altogether after that little debacle with Sony a couple years back installing rootkit software on peoples' machines. Here're a couple articles to check out.
Label a Flash Drive with Your Name and Number
Have Your Lost USB Drive Ask For Help (1)
or
2


q:
Is there any way to do the equivalent of the following in a JSP without using scriptlet?

<% response.setContentType("text/plain");  %>

I can't simply use

because I need to set the content-type in 2 places (each in a different branch of a ) and the JSP compiler will only allow one such directive.

Also, I can't write two separate JSPs and forward to one or the other in a servlet because the JSP is triggered by the container when an authentication failure occurs.

Cheers,
Don

[A]
```
```
<%@ page language="java" contentType="text/plain" %>
```
```
Edit:
If you need to set the MIME type conditionally, you could use
```
```
<%
if( branch condition ) {
  response.setContentType("text/plain");
} else {
  response.setContentType("text/html");
}
%>
```
```
Obviously the above is a scriptlet which goes against the original question. Is there a particular reason for not wanting to use a scriptlet?
A better approach may be to perform the branch logic in a servlet and forward the request to a JSP which only handles the display. You may choose to use two separate JSPs, one for each content type, if the content itself differs.


q: How do I convert a datetime or date object into a POSIX timestamp in python?  There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.

[A]
```
```
import time, datetime

d = datetime.datetime.now()
print time.mktime(d.timetuple())
```
```


q:
I have a standard .NET windows service written in C#.

Can it install itself without using InstallUtil?
Should I use the service installer class? How should I use it?

I want to be able to call the following:

MyService.exe -install

And it will have the same effect as calling:

InstallUtil MyService.exe

[A]
Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...
Here's an example:
```
```
[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}
```
```


q:
Would there a more elegant way of writing the following syntax?

        Thread t0 = new Thread(new ParameterizedThreadStart(doWork));
        t0.Start('someVal');
        t0.Join();

        Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
        t1.Start('someDiffVal');
        t1.Join();

Presuming we want to pass 20 different values, what would the best way of setting this up be? Looping through and joining at the end?

If a new thread isn't instantiated (like below), it errors that the thread can't be restarted. For example:

        Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
        t1.Start('someVal');
        t1.Start('someDiffVal');

[A]
Why would you start a thread and then join against it immediately?
I'd normally do something like this:
```
```
List<Thread> threads = new List<Thread>();

foreach (string item in items)
{
    string copy = item; // Important due to variable capture
    ThreadStart ts = () => DoWork(copy); // Strongly typed :)
    Thread t = new Thread(ts);
    t.Start();
    threads.Add(t);
}

foreach (Thread t in threads)
{
    t.Join();
}
```
```


q: What's the difference between a string and a symbol in Ruby and when should I use one over the other?

[A]
A symbol is something you use to represent names and strings.  You would want to use a symbol when you may have need to use a string several times as this far easier and more productive.
And just found this via google, which may offer greater detail:
Here you go


q:
I have a situation where another developer is including source files from a project that I maintain in a project that he maintains.  The nature of the files is such that each source file registers a "command" in an interpretive environment so all you have to do is link in a new source file to register a new "command".  We can't put these files in a static library because, unless the project makes explicit reference to the symbols in the file, the linker will optimise the file away.

It seems like a potential solution  is to have a file external to both projects that "includes" a list of source file names in both projects.  The problem is that I have no idea whether or how this could be done.  Suggestions, anyone?

[A]
Could you simply write a source file containing nothing but
```
#include
```
directives? I'm not sure if VS checks whether the dependent files have changed if they're not in the project proper, though.


q:
Let's make this very easy. What I want:

@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.

How to print duplicate values of a array/hash?

[A]
Use a dictionary, put the value in the key, and the count in the value.
Ah, just noticed you've tagged as perl
```
while ([...]) {
 $hash{[dbvalue]}++
}
```


q:
I have a large amount of data I need to store, and be able to generate reports on - each one representing an event on a website (we're talking over 50 per second, so clearly older data will need to be aggregated).

I'm evaluating approaches to implementing this, obviously it needs to be reliable, and should be as easy to scale as possible.  It should also be possible to generate reports from the data in a flexible and efficient way.

I'm hoping that some SOers have experience of such software and can make a recommendation, and/or point out the pitfalls.

Ideally I'd like to deploy this on EC2.

[A]
Wow.  You are opening up a huge topic.
A few things right off the top of my head...
think carefully about your schema for inserts in the transactional part and reads in the reporting part, you may be best off keeping them separate if you have really large data volumes
look carefully at the latency that you can tolerate between real-time reporting on your transactions and aggregated reporting on your historical data.  Maybe you should have a process which runs periodically and aggregates your transactions.
look carefully at any requirement which sees you reporting across your transactional and aggregated data, either in the same report or as a drill-down from one to the other
prototype with some meaningful queries and some realistic data volumes
get yourself a real production quality, enterprise ready database, i.e. Oracle / MSSQL
think about using someone else's code/product for the reporting e.g.
Crystal/BO
/
Cognos
as I say, huge topic.  As I think of more I'll continue adding to my list.
HTH and good luck


q:
In python, if I say

print 'h'

I get the letter h and a newline.  If I say

print 'h',

I get the letter h and no newline.  If I say

print 'h',
print 'm',

I get the letter h, a space, and the letter m.  How can I prevent Python from printing the space?

The print statements are different iterations of the same loop so I can't just use the + operator.

[A]
```
```
import sys

sys.stdout.write('h')
sys.stdout.flush()

sys.stdout.write('m')
sys.stdout.flush()
```
```
You need to call
```
sys.stdout.flush()
```
because otherwise it will hold the text in a buffer and you won't see it.


q: how do i determine what a mysql db's charset is set to? in the cli?

[A]
```
```
SHOW CREATE DATABASE db-name
```
```
Will show you the default character set for the database,
```
```
SHOW CREATE TABLE db-name.table-name
```
```
Will show you the character set for a specific table (along with a lot of other information).