Question:
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!

Answer:
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.


Question:
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?

Answer:
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.


Question: 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?

Answer:
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.


Question:
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?

Answer:
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).


Question: 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?

Answer:
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.


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

Thanks in advance...

Answer:
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


Question:
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);
}

Answer:
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);
}
```
```


Question:
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.

Answer:
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.


Question:
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.

Answer:
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.


Question:
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?

Answer:
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.


Question:
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?

Answer:
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();
```
```


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

Answer:
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


Question:
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?

Answer:
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.)


Question:
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.

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


Question:
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

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


Question:
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]

Answer:
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>
```
```


Question:
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++;
}

Answer:
```
```
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());
```
```


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

Answer:
Use
ChangeServiceConfig
to change the display name; you can use
ChangeServiceConfig2
to change the description.


Question:
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?

Answer:
```
```
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)


Question:
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)?

Answer:
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.


Question:
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.

Answer:
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)


Question: 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?

Answer:
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:


Question:
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

Answer:
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.


Question: 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.

Answer:
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.


Question:
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.

Answer:
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 );
```
```


Question:
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.

Answer:
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.


Question:
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.

Answer:
```
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);
  }
}
```
```


Question:
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

Answer:
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));
    }
}
```
```
};


Question: 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.

Answer:
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.


Question:
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.

Answer:
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
```
```


Question:
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?.

Answer:
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.


Question:
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?

Answer:
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


Question:
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.

Answer:
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!


Question: 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"?

Answer:
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>)
```
```


Question: 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?

Answer:
What about
```
element.tagName
```
?
See also
```
tagName
```
docs on MDN
.


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

Answer:
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):
   ...
```
```


Question:
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?

Answer:
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.


Question:
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

Answer:
```
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.


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

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


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

Answer: 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)


Question:
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 ?

Answer:
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
```
```


Question:
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?

Answer:
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.


Question:
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... */ %>

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


Question:
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( );

Answer:
Just do
```
```
.OrderBy(doc => doc.Name)
```
```


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

Answer:
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);
}
```
```


Question:
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?

Answer:
```
```
include 'header.php';

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


Question:
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?

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


Question:
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,

Answer:
```
```
dbms_output.put_line(varHere);
```
```


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

Answer:
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.


Question: 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?

Answer:
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.


Question:
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?

Answer:
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.


Question: 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?

Answer:
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.


Question:
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?

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


Question: 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.

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

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


Question:
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)

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


Question:
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!

Answer:
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


Question:
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

Answer:
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');
```
```


Question: 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?

Answer:
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.


Question:
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.

Answer:
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


Question:
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

Answer:
```
```
<%@ 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.


Question: 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.

Answer:
```
```
import time, datetime

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


Question:
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

Answer:
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);
    }
}
```
```


Question:
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');

Answer:
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();
}
```
```


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

Answer:
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


Question:
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?

Answer:
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.


Question:
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?

Answer:
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]}++
}
```


Question:
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.

Answer:
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


Question:
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.

Answer:
```
```
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.


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

Answer:
```
```
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).


Question:
I am making a site that publishes articles in issues each month. It is straightforward, and I think using a Markdown editor (like the WMD one here in Stack Overflow) would be perfect.

However, they do need the ability to have images right-aligned in a given paragraph.

I can't see a way to do that with the current system - is it possible?

Answer:
You can embed HTML in Markdown, so you can do something like this:
```
```
<img style="float: right;" src="whatever.jpg">

Continue markdown text...
```
```


Question:
If I have a type defined as a set of an enumerated type, it's easy to create an empty set with [], but how do I create a full set?

EDIT:  Yeah, the obvious solution is to use a for loop.  That's also a really bad solution if there's another way. Does anyone know of a way that'll work in constant time?

Answer:
Per Barry's suggestion:
```
```
FillChar(VarSet, SizeOf(VarSet), $FF);
```
```


Question:
I keep seeing references to the visitor pattern in blogs but I've got to admit, I just don't get it.  I read the wikipedia article for the pattern and I understand its mechanics but I'm still confused as to when I'd use it.

As someone who just recently really got the decorator pattern and is now seeing uses for it absolutely everywhere I'd like to be able to really understand intuitively this seemingly handy pattern as well.

Answer:
The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent
1
!) programmers have stumbled over this problem. What it actually does is implement
double dispatching
in languages that don't support it natively (most of them don't).
1)
My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his
most important C++ aha! moments
ever
.


Question:
So far, I've only been passing javascript strings to my web methods, which get parsed, usually as Guids. but now i have a method that accepts an IList... on the client, i build this array of objects and then attempt to pass it like:

$.ajax({
  type: 'POST',
  url: 'personalization.aspx/SetPersonalization',
  data: "{'backerEntries':" + backerEntries + "}",
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: postcardManager.SetPersonalizationComplete
});

The post:

{'backerEntries':[object Object],[object Object],[object Object]}

The error response:

Invalid JSON primitive: object.

For some reason, jquery doesn't seem to convert my array into a json string? Any ideas why? I tried putting [] around the backerEntries, and {}, as well as {[]} just in sheer desperation. Am I missing something obvious here?

Answer:
The data you are passing you are trying to pass it as a string already.  If you want jQuery to transform it leave the whole thing as an object, e.g.
```
```
data:{backerEntries: backerEntries }
```
```
Assuming of course backerEntries is an array.  jQuery should transform this and will append it to the querystring as that is its default behaviour.  Your current code is relying on default JavaScript behaviour which won't by default convert an array into its string representation.


Question:
Hoping some of you TinyXML++ people can help me out. Really, since you recomended to me before I think you owe me ;)

I have the following code:

   //ticpp::Iterator< ticpp::Element > child( "SetPiece" );
    ticpp::Iterator< ticpp::Node > child("SetPiece");
    GLuint lc_SPieces = 0;
    for(child = child.begin( this ); child != child.end(); child++ )
    {
        lc_SPieces++;
    }

If I use the top declaration for child I get the error:

Unhandled exception at 0x7c812aeb in
  Drawing.exe: Microsoft C++ exception:
  __non_rtti_object @ 0x0012f7b4.

And I get it in dbgheap.c at this line:

pvBlk = _heap_alloc_dbg(nSize, nBlockUse, szFileName, nLine);

What's weird is it works with Node, and I know that there are elements in there(I checked using the TinyXML iteration methods).

Has anyone run into this before?

Answer:
just poking in the dark, i don't know tinyxml, but it seems that a dynamic_cast went wrong.
If you dynamic_cast<> a pointer, you get a NULL-pointer on failure. However, if you cast to a reference type, there is no concept of a NULL-reference, so the runtime throws this  exception (or bad_type).
MSDN on dynamic_cast, and why it can go wrong
The line you pasted for the exception to occur does not help to clear up the situation, since it identifies the symptom rather than the cause.
Try to identify the cast that went wrong, you should be able to find it if you walk up the stack and find the last method in tinyxml libs or headers. Then you can decide whether tinyxml is worng, or you just applied it the wrong way.
good luck!


Question:
It's easy to get the value of a key from a .NET generic Dictionary:

Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
string secondGreek = greek[2];  // Beta

But trying to get the keys given a value is not as straightforward because there could be multiple keys:

int[] betaKeys = greek.WhatDoIPutHere("Beta");  // expecting single 2

Answer:
revised: okay to have some kind of find you would need something other than dictionary, since if you think about it dictionary are one way keys.  that is, the values might not be unique
that said it looks like you're using c#3.0 so you might not have to resort to looping and could use something like:
```
```
var key = (from k in yourDictionary where string.Compare(k.Value, "yourValue", true)  == 0 select k.Key).FirstOrDefault();
```
```


Question:
There's not a lot to add to the subject really.

I am after a free task board/ burndown reporting tool for Windows.

Answer:
Well, without knowing more about your situation, I have to
highly
recommend a wall of index cards and a handdrawn chart on flip chart paper. Works much better than any software in the standard situation.
If you really have to use software, there is none that I could recommend unreservedly, let alone a free one. You might want to keep in mind that some of the commercial ones are free for open source or academic projects, too. Which one's right for you will depend, besides other things, on how much you want it to define your process.


Question:
I'm trying to make a page in php that takes rows from a database, displays them, and then give the viewer a chance to upvote or downvote a specific entry. Here is a snippet:

echo("<form action=\"vote.php\" method=\"post\"> \n");
echo("<INPUT type=\"hidden\" name=\"idnum\" value=\"".$row[0]."\">");
echo("<INPUT type=\"submit\" name=\"up\" value=\"Upvote.\">  \n");
echo("<INPUT type=\"submit\" name=\"down\" value=\"Downvote\"> ");
echo("<form/>\n");

The problem is when I hit a submit button, the value for idnum that gets sent is based on the one farthest down it seems. So my questions is, when a submit button is pressed, are the values for all inputs on a page sent?

Answer:
Your form is not closed properly. Use
```
</form>
```
instead of
```
<form/>
```
.


Question:
I would like to create an HTML table with row colors changing based on position and content.  But instead of alternating every row, I'd like to be able to group rows together, so that I can have some XML like this:

<itemlist>
   <item group="0">Conent...blah blah</item>
   <item group="0">Content...who cares</item>
   <item group="1">Content</item>
   <item group="2">Content</item>
   <item group="2">Content</item>
</itemlist>

And all of the items with group=0 are one color, and items with group=1 are another, and group=2 are either toggled back to the first color, or are their own color.

All I can seem to find out there is ways to alternate every row, but I can't seem to "get it" when it comes to actually using the node data to help me make the decision.

Answer:
The first two groups are simple as you can parse them based on their group number.
To handle group 2, consider using the
preceding
function to get a list of proir notes, and use
count
to determine how many there are. You can can then alternate values based on whether the count is even or odd.


Question:
I seem to remember being able to print out (or locate) the specific switches that each -O<num> option turns on.  Can you remind?

Thanks!

Answer:
You may also try the good ol' manual
```
```
$ man gcc
```
```
at the subsection "Options That Control Optimization".


Question:
I would like to know if it is possible to determine if a function parameter with a default value was passed in Python.
For example, how does dict.pop work?

>>> {}.pop('test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
>>> {}.pop('test',None)
>>> {}.pop('test',3)
3
>>> {}.pop('test',NotImplemented)
NotImplemented

How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?

Thanks

Answer:
You can do it like this:
```
```
def isdefarg(*args):
    if len(args) > 0:
        print len(args), "arguments"
    else:
        print "no arguments"

isdefarg()
isdefarg(None)
isdefarg(5, 7)
```
```
See the Python documentation on
calls
for full information.


Question:
Does anyone have any suggestions (or a regular expression) for parsing the HTTP Accept header?

I am trying to do some content-type negotiation in ASP.NET MVC. There doesn't seem to be a built in way (which is fine, because there are a lot of schools of thought here), but the parsing is not entirely trivial and I would rather not re-invent the wheel if someone has already done it well and is willing to share.

Answer:
The
RFC
is quite complex. If the regex where to follow these rules to the letter, it would become several lines long.
If you already have the Accept-header, and ignore the quotes and the parameters, you could do something like this to match each pair:
```
```
/([^()<>@,;:\\"\/[\]?={} \t]+)\/([^()<>@,;:\\"\/[\]?={} \t]+)/
```
```
```
*
```
is included in the character class, so it does not need any special case in the regex.


Question:
As the title describes, what are the different doctypes available and what do they mean? I notice that the layout looks a little different in IE7 when I switch from

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

to

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Are there any others and what are the effects or ramifications?

Thanks!

Answer:
Here is the official explanation of the various DTD's from the W3C:
http://www.w3.org/QA/2002/04/valid-dtd-list.html
You might also find the following beneficial:
http://www.freedivs.com/tutorials/Choosing%20a%20DOCTYPE/


Question:
I used the method

$("#dvTheatres a").hover(function (){
        $(this).css("text-decoration", "underline");
    },function(){
        $(this).css("text-decoration", "none");
    }
);

Is there a more elegant method?(single line)

Answer:
Why not just use CSS?
```
```
#dvTheatres a {
    text-decoration: none;
}

#dvTheatres a:hover {
    text-decoration: underline;
}
```
```


Question: I would like to construct a query that displays all the results in a table, but is offset by 5 from the start of the table. As far as I can tell, MySQL's LIMIT requires a limit as well as an offset. Is there any way to do this?

Answer:
As you mentioned it LIMIT is required, so you need to use the biggest limit possible, which is 18446744073709551615 (maximum of unsigned BIGINT)
```
```
SELECT * FROM somewhere LIMIT 18446744073709551610 OFFSET 5
```
```


Question:
I'm interested to know what are the "must have" JSP tag libraries apart from JSTL. All I've found so far are

ccc - for accessing static constants in JSP (without scriptlet)

displaytag - for generating sophisticated HTML tables that includes data paging, grouping, sorting, exporting etc.

What other indispensible tag libs are out there?

Answer:
I use displaytag, and have been quite happy with it. The only other tag library I use is the one that comes with the Stripes Action Framework.
But my truly indispensable Tag library is the one we wrote.
At the office we must have over 50 of them by now for our internal framework.
The key behind them, though, is that they're JSP 2.0 Tag Files rather than class JSP Tags written in Java. Tag files are powerful and very easy to use.
Where classic JSP tag discouraged tag development because it was so difficult, Tag Files encourage it to where it's trivial for refactoring JSP pages now.
I think Tag Files and JSTL turned JSP as a page markup technology from mediocre to one of the best out there.


Question:
I'm using autotools to build a shared object.

Using pkglib_LTLIBRARIES in my Makefile.am causes a libtest.la AND libtest.so to be built.

I only want it to build/install libtest.so.

Is this possible?

Answer:
The details of generating libraries varies widely from platform to platform. For example, on OS X, your library would be called libtest.dylib rather then libtest.so. libtool is part of the autotools suite, and its job is to abstract away all the messy platform dependent details. To do this, it creates a high-level, platform independent description of the library. This is is the libtest.la file you are seeing. libtools uses this platform independent description of the library to put together the final native library.
If you are using the autotools I don't think you are going to be able to avoid generating libtest.la. I suppose you could hack your local libtool shell script to remove it at completion, but you'd just have to generate it again the next time you ran make.
I found the
GNU documentation on libtool
somewhat opaque. Here is a
less opaque but kind of dated description
.


Question:
I've heard that it's possible with extension methods, but I can't quite figure it out myself. I'd like to see a specific example if possible.

Thanks!

Answer:
It really depends on what you mean by "mixin" - everyone seems to have a slightly different idea. The kind of mixin I'd
like
to see (but which isn't available in C#) is making implementation-through-composition simple:
```
```
public class Mixin : ISomeInterface
{
    private SomeImplementation impl implements ISomeInterface;

    public void OneMethod()
    {
        // Specialise just this method
    }
}
```
```
The compiler would implement ISomeInterface just by proxying every member to "impl" unless there was another implementation in the class directly.
None of this is possible at the moment though :)


Question:
I'm a newbie at networking.  I understand the concept of multicast, but was wondering if it's reliable on the open/public internet?

It seems like sort of an edge case that different backbones or ISPs might intentionally break to reduce router load or generally segment the network for practical high-use applications.

Is my fear reasonable?

P.S. Follow-up question here:
Best tutorial for application multicasting?

Answer:
IP multicast in the internet doesn't really work. From the
Wikipedia article
:
For both these reasons, and also
  reasons of economics, IP Multicast is
  not in general use in the commercial
  Internet.
People who desire to participate in the global IP multicast need to attach themselves to the MBONE. The Wikipedia article points out that application-level multicast infrastructures do work, e.g. IRC.


Question:
Which sql data type should we use for number bases primary key:

int

bigint

numeric

float

Answer:
Generally,
```
int
```
.
```
bigint
```
if you think you'll have more rows than there are atoms in the universe.
```
uniqueidentifier
```
is useful if you need
globally
unique keys (keys that are guaranteed to be unique across all tables in your schema, maybe even universally unique (I don't remember))
The other two I wouldn't use they're not integral types (they have fractions, which just don't make a lot of sense as keys)


Question:
I am having some trouble manipulating images using CodeIgniter 1.7.  With the following code, the image is uploaded correctly. Alas, instead of a new image being made, and then modified; the existing image is modified. Any help?

//Upload image first
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp';

$this->load->library('upload', $config);
$this->upload->do_upload();

//Now fix the image
$picloc = $this->upload->data();
$picloc = $picloc['file_name'];

$thumbnail = "thumb_".$picloc;

$imagemanip['image_library'] = 'gd2';
$imagemanip['source_image'] = './uploads/'.$picloc;
$imagemanip['new_img'] = './uploads/'.$thumbnail;
$imagemanip['maintain_ratio'] = TRUE;
$imagemanip['width'] = 250;
$imagemanip['height'] = 250;

$this->load->library('image_lib', $imagemanip);

$this->image_lib->resize();

Answer:
The problem is simple, you have a typo in the line:
```
```
$imagemanip['new_img'] = './uploads/'.$thumbnail;
```
```
The the index should be "new_image", not "new_img", so the line becomes..
```
```
$imagemanip['new_image'] = './uploads/'.$thumbnail;
```
```


Question:
What is the best way to store a large number of data points?

For example temperature values which are measured every minute over lots of locations?

SQL databases with one row per data points doesn't seem very efficient.

Answer:
I would like to know why you reckon it to be "not efficient". Probably you need to explain your data model and schema to give a better context of the scenario.
Storing multiple data points into a single row, when they are not related to each other, and should indeed stand on their own, is not a good approach. Meshing together will result in very counter-intuitive and quirky query statements to pull out the correct data points you need for a given scenario.
We have done work in a power station before, collecting data from various systems and metering equipment a wide variety of gas and electrical parameters that need to be monitored and aggregated. They can come in every 3-5 minutes to 30-60 minutes depending on the type of parameters. These naturally results in millions of records per month.
The key is indexing the tables properly so that their physical order is tied to sequence in which the records came in. (Clustered index)  New pages and extents are created and filled sequentially by incoming data. This should prevent massive page splits and reshuffling.


Question:
I am working on a PHP application that intends to ease company workflow and project management, let's say something like Basecamp and GoPlan.

I am not sure on what the best approach is, database-wise. Should I use a single database and add client-specific columns to each of the tables, or should I create a database for each new client? An important factor is automation: I want it to be dead simple to create a new client (and perhaps opening the possibility to signing up for yourself).

Possible cons I can think of using one database:

Lack of extensibility

Security problems (although bugs shouldn't be there in the first place)

What are your thoughts on this? Do you have any ideas what solution the above companies are most likely to have chosen?

Answer:
For multitenancy, performance will typically increase the more resources you manage to share across tenants, see
http://en.wikipedia.org/wiki/Multitenancy
So if you can, go with the single database. I agree that security problems would only occur due to bugs, as you can implement all access control in the application. In some databases, you can still use the database access control by careful use of views (so that each authenticated user gets a different view).
There are ways to provide extensibility also. For example, you could create a single table with extension attributes (keyed by tenant, base record, and extension attribute id). Or you can create per-tenant extension tables, so that each tenant has his own extension schema.


Question:
While using Vim (at home and at work), I often find myself doing similar things repeatedly. For example, I may turn a bunch of CSV text into a series of SQL inserts. I've been using Vim for years, but only recently have I tried to seriously think about how I could improve my productivity while using it.

My question is.. Is there a good way (or right way) to store commonly used commands or command sequences? And how is the best way to execute them? It would be nice to be able to use the same script on a live session and also over the command line against some file.

I'm hoping that I can store them in a .vim file so that I can hand them to coworkers (who are not as proficient with vim) for them to use.

Answer:
You can store your common task macros in .vim files, like
this
for example, and then you can load them with the command
:so file.vim
Here
you can find a bunch of useful macros, also I recommend you to learn well the useful
q
macro recording
command, it's very very powerful...
The macros created with the
q
command are stored in a register, qq stores the macro in the q register, so when you end the recording you can simply paste the macro, with
"qp
and save it, later you can load it by simply yanking the macro into a register i.e.:
"qY
, the macros are only text and remember you can use any register instead of q. There is a Vim Script for storing
q
macros:
marvim : Macro Persistent Storage and Shareable Repository for VIM
Also take a look to the
Vim Scripting Language
.


Question: How can I count operations in C++? I'd like to analyze code in a better way than just timing it since the time is often rounded to 0 millisec.

Answer: If you are timing code, it's worth running it a lot of times in a loop to avoid the effect of the timer resolution. So you might run the thing you're timing 10,000 times and measure the amount of time it takes to run all the iterations. It will probably only take a few seconds to run and you'll get better timing data.


Question: How do I enable assembly bind failure logging (Fusion) in .NET?

Answer:
Set the following registry value:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion!EnableLog] (DWORD) to 1
To disable, set to 0 or delete the value.
[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in
Windows Registry Editor Format:
```
```
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"EnableLog"=dword:00000001
```
```
Then run the file from windows explorer and ignore the warning about possible damage.


Question:
So I've got a Ruby method like this:

def something(variable, &block)
  ....
end

And I want to call it like this:

something 'hello' { do_it }

Except that isn't working for me, I'm getting a syntax error. If I do this instead, it works:

something 'hello' do
  do_it
end

Except there I'm kind of missing the nice look of it being on one line.

I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. Is there?

Answer:
If you want "def something" to to accept a block, you need to yield data to that block. For example:
```
```
#to uppercase string
def something(my_input)
 yield my_input.upcase
end

# => "HELLO WORLD"
something("hello world") { |i| puts i}
```
```


Question: I'm new to the VxWorks Environment are there any good sources of information out there?

Answer:
If your budget allows it, I would recommend taking one of the courses offered by WindRiver.  My company brought in one of their trainers to teach a class on-site and it was excellent.  They provided hands-on programming activities and a lot of information.  If you are new to the concepts of real-time or embedded programming, they provided the necessary background information, and even if you were already familiar with these (as I was), there was plenty of useful training specific to VxWorks and Workbench.  I believe they also organize their own courses, in addition to coming to companies.
Course Schedule


Question: I'm new to the VxWorks environment, I'm wondering what C and C++ compilers are available for use with VxWorks?

Answer:
As far as i know Tornado VxWorks IDE using gcc toolchain.
Any way i suggest to use the compiler provided by WindRiver (which i believe their version
of gcc)  to avoid compatibility problems.
It's probably worth to menation the VxWorks version you having in mind.
I guess gcc version will be depend on VxWorks version and probably on target platform.


Question:
In a web application I am developing, I wish to implement wiki-style edits (where each and every edit is saved, can be compared, and users can rollback edits easily).

What is a good way of implementing this without re-inventing the wheel too much?

Thank you in advance.

Answer:
I believe you're really seeking a
Content Management System
(CMS), of which a Wiki is a specialization (IMHO).
Googling '
CMS Open Source
' brings as its top hit:
Open Source CMS
, try before you install
Joomla
Drupal
Wordpress
And a
lot
of other information.
Commercially, I really like Atlassian's
Confluence
.  Wiki like markup, editing history, easily attach documents and now supporting editing in Word, Excel & Powerpoint.


Question:
I have the following line:

"14:48 say;0ed673079715c343281355c2a1fde843;2;laka;hello ;)"

I parse this by using a simple regexp:

if($line =~ /(\d+:\d+)\ssay;(.*);(.*);(.*);(.*)/) {
    my($ts, $hash, $pid, $handle, $quote) = ($1, $2, $3, $4, $5);
}

But the ; at the end messes things up and I don't know why. Shouldn't the greedy operator handle "everything"?

Answer:
Try making the first 3
```
(.*)
```
ungreedy
```
(.*?)
```


Question: I've been writing a lot recently about Parallel computing and programming and I do notice that there are a lot of patterns that come up when it comes to parallel computing. Noting that Microsoft already has released a library along with the Microsoft Visual C++ 2010 Community Technical Preview (named Parallel Patterns Library) I'm wondering what are the common parallel programming patterns you have been using and encountering that may be worth remembering? Do you have any idioms you follow and patterns that you seem to keep popping up as you write parallel programs with C++?

Answer:
First you have to chose between shared-memory computing, and shared-nothing computing. Shared memory is easier, but doesn't scale that well - you will use shared-nothing if you either
a) have a cluster, rather than a multiprocessor system, or
b) if you have many CPUs (say, > 60), and a high degree of non-uniform memory
For shared-memory, the common solution is to use threads; they are easy to understand as a concept, and easy to use in the API (but difficult to debug).
For shared-nothing, you use some kind of messaging. In high-performance computing, MPI is established as the messaging middleware.
You then also need to design an architecture for the parallel activities. The most common approach (again because it's easy to understand) is the farmer-worker-pattern (a.k.a. master-slave).


Question: I am trying to insert an image (jpg) in to a word document and the Selection.InlineShapes.AddPicture does not seem to be supported by win32old or I am doing something wrong.  Has anyone had any luck inserting images.

Answer:
Running on WinXP, Ruby 1.8.6, Word 2002/XP SP3, I recorded macros and translated them, as far as I could understand them, into this:
```
```
require 'win32ole'

begin
  word = WIN32OLE::new('Word.Application')   # create winole Object
  doc = word.Documents.Add
  word.Selection.InlineShapes.AddPicture "C:\\pictures\\some_picture.jpg", false, true
  word.ChangeFileOpenDirectory "C:\\docs\\"
  doc.SaveAs "doc_with_pic.doc"
  word.Quit
rescue Exception => e
  puts e
  word.Quit
ensure
  word.Quit unless word.nil?
end
```
```
It seems to work. Any use?


Question:
I want to make an MVC route for a list of news, which can be served in several formats.

news -> (X)HTML

news.rss -> RSS

news.atom -> ATOM

Is it possible to do this (the more general "optional extension" situation crops up in several places in my planned design) with one route? Or do I need to make two routes like this:

routes.MapRoute("News-ImplicitFormat",
                "news",
                new { controller = "News", action = "Browse", format = "" });

routes.MapRoute("News-ExplicitFormat",
                "news.{format}"
                new { controller = "News", action = "Browse" });

It seems like it would be useful to have the routing system support something like:

routes.MapRoute("News",
                "news(.{format})?",
                new { controller = "News", action = "Browse" });

Answer:
I made a method to support adding pairs like this as follows:
```
```
public static void MapRouteWithOptionalFormat(this RouteCollection routes,
                                              string name,
                                              string url,
                                              object defaults)
{
    Route implicitRoute = routes.MapRoute(name + "-ImplicitFormat",
                                          url,
                                          defaults);
    implicitRoute.Defaults.Add("format", string.Empty);

    Route explicitRoute = routes.MapRoute(name + "-ExplicitFormat",
                                          url + ".{format}",
                                          defaults);
}
```
```


Question: For a requirement i was asked to export information into a custom entity that was created in MS CRM 4.0. I am trying to do this programmatically and I have not found a single code that actually accomplishes this. I wrote code to check if a certain value for a field exists in the entity but creating a new entity seems to be a little bit of puzzle for me. Any help on this would be appreciated.

Answer:
This is my experience when I had a similar requirement in MS CRM 3.0. I started using the CRM sdk to import data but found it was not easy.
Then I ended up using
Scribe adapter for CRM
. It is not free but will easily solve your problem for importing to custom entities. Will post some links on that. need to go through some old bookmarks.
Not sure if this feature exist out of the box for CRM 4.0.


Question:
I'm writing an iOS app with a table view inside a tab view. In my UITableViewController, I implemented -tableView:didSelectRowAtIndexPath:, but when I select a row at runtime, the method isn't being called.  The table view is being populated though, so I know that other tableView methods in my controller are being called.

Does anyone have any ideas what I may have screwed up to make this happen?

Answer:
It sounds like perhaps the class is not the
```
UITableViewDelegate
```
for that table view, though
```
UITableViewController
```
is supposed to set that automatically.
Any chance you reset the delegate to some other class?


Question:
Returning to WinForms in VS2008 after a long time.. Tinkering with a OOD problem in VS2008 Express Edition.

I need some controls to be "display only" widgets. The user should not be able to change the value of these controls... the widgets are updated by a periodic update tick event. I vaguely remember there being a ReadOnly property that you could set to have this behavior... can't find it now.

The Enabled property set to false: grays out the control content. I want the control to look normal.
The Locked property set to false: seems to be protecting the user from accidentally distorting the control in the Visual Form Designer.

What am I missing?

Answer:
For some typical winforms controls:
http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/
This is also a good tip to preserve the appearance:
```
```
Color clr = textBox1.BackColor;
    textBox1.ReadOnly = true;
    textBox1.BackColor = clr;
```
```


Question:
I'm struggling with Test::Unit.  When I think of unit tests, I think of one simple test per file.  But in Ruby's framework, I must instead write:

class MyTest < Test::Unit::TestCase
   def setup
   end

   def test_1
   end

   def test_1
   end
end

But setup and teardown run for every invocation of a test_* method.  This is exactly what I don't want.  Rather, I want a setup method that runs just once for the whole class.  But I can't seem to write my own initialize() without breaking TestCase's initialize.

Is that possible?  Or am I making this hopelessly complicated?

Answer:
That's how it's supposed to work!
Each test should be completely isolated from the rest, so the
```
setup
```
and
```
tear_down
```
methods are executed once for every test-case. There are cases, however, when you might want more control over the execution flow. Then you can group the test-cases in
suites
.
In your case you could write something like the following:
```
```
require 'test/unit'
require 'test/unit/ui/console/testrunner'

class TestDecorator < Test::Unit::TestSuite

  def initialize(test_case_class)
    super
    self << test_case_class.suite
  end

  def run(result, &progress_block)
    setup_suite
    begin
      super(result, &progress_block)
    ensure
      tear_down_suite
    end
  end

end

class MyTestCase < Test::Unit::TestCase

  def test_1
    puts "test_1"
    assert_equal(1, 1)
  end

  def test_2
    puts "test_2"
    assert_equal(2, 2)
  end

end

class MySuite < TestDecorator

  def setup_suite
    puts "setup_suite"
  end

  def tear_down_suite
    puts "tear_down_suite"
  end

end

Test::Unit::UI::Console::TestRunner.run(MySuite.new(MyTestCase))
```
```
The
```
TestDecorator
```
defines a special suite which provides a
```
setup
```
and
```
tear_down
```
method which run only once before and after the running of the set of test-cases it contains.
The drawback of this is that you need to tell
Test::Unit
how to run the tests in the unit. In the event your unit contains many test-cases and you need a decorator for only one of them you'll need something like this:
```
```
require 'test/unit'
require 'test/unit/ui/console/testrunner'

class TestDecorator < Test::Unit::TestSuite

  def initialize(test_case_class)
    super
    self << test_case_class.suite
  end

  def run(result, &progress_block)
    setup_suite
    begin
      super(result, &progress_block)
    ensure
      tear_down_suite
    end
  end

end

class MyTestCase < Test::Unit::TestCase

  def test_1
    puts "test_1"
    assert_equal(1, 1)
  end

  def test_2
    puts "test_2"
    assert_equal(2, 2)
  end

end

class MySuite < TestDecorator

  def setup_suite
    puts "setup_suite"
  end

  def tear_down_suite
    puts "tear_down_suite"
  end

end

class AnotherTestCase < Test::Unit::TestCase

  def test_a
    puts "test_a"
    assert_equal("a", "a")
  end

end

class Tests

  def self.suite
    suite = Test::Unit::TestSuite.new
    suite << MySuite.new(MyTestCase)
    suite << AnotherTestCase.suite
    suite
  end

end

Test::Unit::UI::Console::TestRunner.run(Tests.suite)
```
```
The
Test::Unit
documentation
documentation provides a good explanation on how suites work.


Question:
Is std::string size() a O(1) operation?

The implementation of STL I'm using is the one built into VC++

Answer:
```
```
size_type __CLR_OR_THIS_CALL size() const

{   // return length of sequence

    return (_Mysize);

}
```
```
So it eventually might be like this, but you can never be sure.