Question:
I am trying to center a form in VB.net. Instead of centering the form, it ends up about halfway between center and 0,0(upper left).

I am using the code

Me.StartPosition = FormStartPosition.CenterScreen

Which is called from the IntializeDisplay Method, which in turn is called from the Form Load method.

I assume I'm setting some propertity along the way that messes up the center calculation, but I'm not sure what it could be.

If anyone has any ideas they would be much appreciated.

Thanks.

Answer:
Do you have any form resizing/positioning logic implemented? If so, comment it out and try again.
Try setting the
```
Form.StartPosition
```
in the designer (which will set it in
```
InitializeComponent()
```
) instead of in the Load event.
Try resetting the
```
Form.Location
```
and
```
Form.Size
```
value. If your form is localized, remove the
```
Form.Location
```
AND
```
Form.Size
```
entry in the resource file.


Question:
I'm reading all the files in a single directory and I want to filter on JPG,JPEG,GIF and PNG.

Both capital and small letters. Those are the only files to be accepted.

I am currently using this:

$testPics = takeFiles($picsDir, "([^\s]+(?=\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF))\.\2)");

and the function takeFiles looks like this:

function takerFiles($dir, $rex="") {
    $dir .= "/";
    $files = array();
    $dp = opendir($dir);
    while ($file = readdir($dp)) {
      if ($file == '.')  continue;
      if ($file == '..') continue;
      if (is_dir($file)) continue;
      if ($rex!="" && !preg_match($rex, $file)) continue;
      $files[] = $file;
    }
    closedir($dp);
    return $files;
  }

And it always returns nothing. So something must be wrong with my regex code.

Answer:
I think something is wrong with your regex. Try testing regexes here first:
https://www.regexpal.com/
I think this one might work for you:
```
/^.*\.(jpg|jpeg|png|gif)$/i
```
Note the /i at the end - this is the "case insensitive" flag, saves you having to type out all permutations :)


Question:
I have the following code:

var address;
getAddress(0,0);
function getAddress(latlng)
{
  if (latlng != null)
  {
    geocoder.getLocations(latlng,
    function(addresses)
    {
      if(addresses.Status.code == 200)
      {
        address = addresses.Placemark[0].address.toString();
        alert(address);  // Outputs something :)
      }
    });
   }
   return address;   //returns nothing :(
}

address always returns undefined but the alert does output something. Why is this?

(Geocoder is an instance of Google Maps APIs)

Answer:
I think that your problems are all related to scope. Generally speaking, you don't want to rely on a global declaration of a variable to be used within the scope of a function.
This should correct any scope issues with your function:
```
```
var address = getAddress(0,0);

function getAddress(latlng) {
    if (latlng != null) {
        var address = geocoder.getLocations(latlng, function(addresses) {
            if(addresses.Status.code == 200) {
                return addresses.Placemark[0].address.toString();
            }
        });
    }
return address;
}
```
```


Question:
My team works on a project in cvs containing about 20,000 Java files.  Because of the number of files, it takes a while to do a cvs update.  I typically keep about 5 copies of the entire tree checked out, to make it easy to check in different requests without worrying about which files were modified for each.  It's a real pain to keep all 5 trees up to date and in sync with each other.

I've read that it's fairly easy to use git locally with a remote cvs server, and that git is fast.  Will git significantly speed up the updating of my local trees?

I realize the lower bound is the time to do one cvs update.  But I'm thinking that once the first tree is up to date, it might possible to quickly sync the other 4 with the first, rather than to do 4 more cvs update commands.  Do I understand git correctly?

Answer:
We do something similar at work.  We basically use the
```
master
```
branch in git as a single, updated CVS version of the code; we don't do any development there, just CVS updates.  Then, all of our development projects happen on feature branches that we rebase.  When we do CVS updates on the
```
master
```
branch we commit those changes to
```
master
```
and then rebase our other development branches against
```
master
```
.
It's not ideal -- it makes sharing branches with other people difficult.  But, we can manage several development projects at once and do branches, merges, and diffs against them easily.  And, we only interact with CVS on the one
```
master
```
branch, as needed.


Question: Is there a way to send an email from an iSeries terminal, adding an attachment from the IFS? I know how to send a normal email using the SNDDST utility.

Answer:
There is two main methods of doing this.
The Do-It-Yourselfer will use QtmmSendMail API
Otherwise there are several other free and purchased products that you could use. The ones I would recommend are:
MAILTOOL
- Currently $399. Depending on what you are trying to do, I would recommend
SplTool Suite
if you want to email out spool files.
RPGMail
- Free API making use of JavaMail


Question:
I am trying to generate some code at runtime using the DynamicMethod class in the Reflection.Emit namespace but for some reason its throwing a "VerificationException". Here is the IL code I am trying to use...

ldarg.1
ldarg.0
ldfld, System.String FirstName
callvirt, Void Write(System.String)
ldarg.1
ldarg.0
ldfld, System.String LastName
callvirt, Void Write(System.String)
ldarg.1
ldarg.0
ldfld, Int32 Age
callvirt, Void Write(Int32)
ret

I need a way to debug the generated IL code. What options do I have? I am using VS2008 professional.

Answer:
Try using the
peverify
tool to check the IL. From MSDN:
peverify.exe performs comprehensive
  MSIL verification checks based on
  dataflow analysis plus a list of
  several hundred rules on valid
  metadata. For detailed information on
  the checks Peverify.exe performs, see
  the "Metadata Validation
  Specification" and the "MSIL
  Instruction Set Specification" in the
  Tools Developers Guide folder in the
  .NET Framework SDK.
You'll need to save the generated code to disk as an assembly for this to be useful though.


Question:
I am looking for a Visual Studio add-in that would analyze the text around the cursor position and navigate to the corresponding class definition.

For example I have this XML file that is currently open:

<object id="abc" type="MyProject.Foo.Bar, MyProject"/>

If I put the cursor somewhere between the double quotes on the type attribute the add-in should obtain the string "MyProject.Foo.Bar, MyProject" and search for all projects and project references in the current solution for the given type and if it finds one, it should navigate to the class definition (or metadata if the source code is not available in the current solution).

If such add-in doesn't exist I would greatly appreciate some pointers that could help me writing one.

Answer:
Well you could use the '
Code Definition Window
' that comes with the VS2008 IDE. When you place your cursor, the Code Def window dynamically updates with the source code for that type.
Works with regular source files.. don't have the IDE at hand to verify with XAML/XML
Also you could 'Jump to Symbol' key combo but you would need CodeRush Express add in for that. Shift+Ctrl+Q. More details
here
.


Question: I would like to be able to fusion an IEnumerable<IEnumerable<T>> into IEnumerable<T> (i.e. merge all individual collections into one). The Union operators only applies to two collections. Any idea?

Answer:
Try
```
```
var it = GetTheNestedCase();
return it.SelectMany(x => x);
```
```
SelectMany is a LINQ transformation which essentially says "For Each Item in a collection return the elements of a collection".  It will turn one element into many (hence SelectMany).  It's great for breaking down collections of collections into a flat list.


Question: I'd like to hide a div when user click anywhere on the page outside of that div. How can I do that using raw javascript or jQuery?

Answer:
First idea, in raw javascript (from
this post
):
```
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">

    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">

my div

```
```
Tested with IE6 and FireFox3.1, it does work as advertised.


Question:
I have a large legacy C++ project compiled under Visual Studio 2008.  I know there is a reasonably amount of 'dead' code that is not accessed anywhere -- methods that are not called, whole classes that are not used.

I'm looking for a tool that will identify this by static analysis.

This question: Dead code detection in legacy C/C++ project suggests using code coverage tools.  This isn't an option as the test coverage just isn't high enough.

It also mentions a  -Wunreachable-code. option to gcc. I'd like something similar for Visual Studio.  We already use the linker's /OPT:REF option to remove redundant code, but this doesn't report the dead code at a useful level (when used with /VERBOSE there are over 100,000 lines, including a lot from libraries).

Are there any better options that work well with a Visual Studio project?

Answer:
You'll want something along the lines of QA-C++ (
http://www.programmingresearch.com/QACPP_MAIN.html
), also see
http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
for similar products.
You're looking for a static code analysis tool that detects unreachable code; many coding guidelines (such as MISRA-C++, if I'm not mistaken) require that no unreachable code exists. An analysis tool geared specifically to enforce such a guideline would be your best bet.
And you'll like be able to find other uses for the tool as well.


Question:
I want to add the current month, and the previous two months to a prompt, for a user to select.

e.g. if this month is 2008 Nov, ddlbox should show the following:

112008
102008
092008

How can I do this?

Answer:
```
```
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>

for (int i = 0; i < 3; i++)
{
    ListItem item = new ListItem(string.Format("{0: MM/yyyy}", DateTime.Now.AddMonths(-i)));
    DropDownList1.Items.Add(item);
}
```
```
Try this :)


Question: My program receives large CSV files and transforms them to XML files. In order to have better performance I would like to split this files in smaller segments of (for example) 500 lines. What are the available Java libraries for splitting text files?

Answer:
What do you intend to do with those data ?
If it is just record by record processing then event oriented (SAX or StaX) parsing will be the way to go. For record by record processing, an existing "pipeline" toolkit may be applicable.
You can pre-process your file with a splitter function like
this one
or
this Splitter.java
.


Question:
I have a structure which I create a custom constructor to initialize the members to 0's.  I've seen in older compilers that when in release mode, without doing a memset to 0, the values are not initialized.

I now want to use this structure in a union, but get errors because it has a non-trivial constructor.

So, question 1.  Does the default compiler implemented constructor guarantee that all members of a structure will be null initialized?  The non-trivial constructor just does a memset of all the members to '0' to ensure a clean structure.

Question 2:  If a constructor must be specified on the base structure, how can a union be implemented to contain that element and ensure a 0 initialized base element?

Answer:
Can you do something like this?
```
```
class Outer
{
public:
    Outer()
    {
        memset(&inner_, 0, sizeof(inner_));
    }
private:
    union Inner
    {
        int qty_;
        double price_;
    } inner_;
};
```
```
...or maybe something like this?
```
```
union MyUnion
{
    int qty_;
    double price_;
};

void someFunction()
{
    MyUnion u = {0};
}
```
```


Question:
I'm looking for a very specific USB device for debugging systems that may use USB but not with a regular computer (proprietary hardware). I want a device that has a USB host controller and two USB device connections. The device to be debugged is connected to the USB host controller and one of the device connections is connected to another device with it's own host controller on it. The the other device connection is connected to a pc. The point being that all USB data travelling through the device (from the device connected to the host controller to the device connected to the first device connection) is reported to the pc.

I'll happily write software to do the logging (in fact I want to) but I can't seem to find a board like this anywhere. Can anyone help?

Answer:
Sniffing the USB shouldn't be too hard if you have the right hardware.  And that is the tricky question.  I haven't seen anything that describes the USB breakout box that you want.  However I can say that this is in the realm of the following two magazines:
Nuts and Volts
Circuit Cellar
If they don't have a USB breakout box project in their archives, then at least they will have advertisements for small cheap single board computers that would have multiple USB ports that you can use for buffering the signals and reporting it back to your PC.
Alternatively is it possible to just wire your PC up to the middle of your two devices and write a custom drive that echos data back and forth while sniffing off a stream for you?


Question: Can we convert a hex string to a byte array using a built-in function in C# or do I have to make a custom method for this?

Answer:
Here's a nice fun LINQ example.
```
```
public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}
```
```


Question:
This only happens with IE (all versions), on line 1120 in
jquery-1.2.6.js I get the following error:

Line 1120:
Invalid Property Value

The line in the js file is the following:

elem[name] = value;

It is inside attr: function( elem, name, value )

Does anybody have a problem similar to this?

Answer:
If
this
is also you, it sounds like you're trying to change the CSS of the element rather than give it an attribute.
If that is the case then try this instead;
```
```
jQuery.css('color', 'inherit');
```
```


Question:
I am using cocos2d-iphone to place Sprites onto a Layer to setup a game playfield.  At certain points in the game, certain Sprites need to be removed based upon game conditions.  What I would like to do is setup an array of Sprite pointers, but I have two questions:

What's the best way to place Sprite pointers in an array?

How does one remove the Sprite in cocos2d with only a pointer to the Sprite?  I know how to do it from its parent layer, but that is too runtime intensive for the main game loop.

Thanks in advance!

Answer:
The
```
Sprite
```
class inherits from
```
CocosNode
```
, so you should be able to call
```
spritePointer.parent.remove(spritePointer)
```


Question: How would I go about adding the "Spent Time" as a column to be displayed in the issues list?

Answer:
Since no one answered, I just poked the source until it yielded results.  Then I started a blog to explain how I did it.
Add spent time column to default issues list in Redmine


Question:
What the difference between LPCSTR, LPCTSTR and LPTSTR?

Why do we need to do this to convert a string into a LV / _ITEM structure variable pszText:

LV_DISPINFO dispinfo;
dispinfo.item.pszText = LPTSTR((LPCTSTR)string);

Answer:
Quick and dirty:
```
LP
```
==
L
ong
P
ointer.  Just think pointer or char*
```
C
```
=
C
onst, in this case, I think they mean the character string is a const, not the pointer being const.
```
STR
```
is
string
the
```
T
```
is for a wide character or char (TCHAR) depending on compiler options.
Bonus Reading
From
What does the letter "T" in LPTSTR stand for?
:
archive
What does the letter "T" in LPTSTR stand for?
October 17th, 2006
The “T” in LPTSTR comes from the “T” in TCHAR. I don’t know for certain, but it seems pretty likely that it stands for “text”. By comparison, the “W” in WCHAR probably comes from the C language standard, where it stands for “wide”.


Question: I'm trying to set the initial display order of the column headers in a silverlight datagrid by changing the column header DisplayIndex values. If I try to set the column order at page load time, I get an out of range exception. If I set the column order (same routine) at a later time like, in a button click handler, it works. Is this just a bug in the silverlight datagrid control? Suggestions for a possible work around?

Answer:
I'm guessing that you've got a problem modifying the DisplayIndex of the columns in the DataGrid from the Page Loaded event as they haven't yet been created at this point. You don't say but I assume you're getting the DataGrid to AutoGenerate your columns as otherwise you could just set the DisplayIndex in your XAML when defining the DataGrid columns.
When the DataGrid generates Columns it fires a AutoGeneratingColumn event for each Column allowing you to modify its properties. It's a little crude but one solution could be to set the DisplayIndex in a handler for this event using the PropertyName it is creating a column for.
```
```
private void grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    switch (e.PropertyName)
    {
        case "Name":
            e.Column.DisplayIndex = 1;
            break;

        case "Age":
            e.Column.DisplayIndex = 0;
            break;
    }
}
```
```


Question:
Are there any libraries or guides for how to read and parse binary data in C?

I am looking at some functionality that will receive TCP packets on a network socket and then parse that binary data according to a specification, turning the information into a more useable form by the code.

Are there any libraries out there that do this, or even a primer on performing this type of thing?

Answer:
You don't really need to parse binary data in C, just cast some pointer to whatever you think it should be.
```
```
struct SomeDataFormat
{
    ....
}

SomeDataFormat* pParsedData = (SomeDataFormat*) pBuffer;
```
```
Just be wary of endian issues, type sizes, reading off the end of buffers, etc etc


Question: In my WPF app, I call a WCF service to retrieve my business object.  I take that business object and bind it to a grid.  I want to now apply the INotifyPropertyChanged attribute, but am unsure if it would work from WCF.  My ultimate goal is to be able to edit items in a grid, click update and push those back through a WCF service.

Answer:
I think there is an option for the generated classes to implement that automatically.
```
svcutil /enableDataBinding
```
- Implement the System.ComponentModel.INotifyPropertyChanged
  interface on all Data Contract types
  to enable data binding.
                                       (Short Form: /edb)


Question:
So I have this app that checks for updates on the server getting a JSON response, each new update is put at the top of my list on a new div that is added via insertBefore using javascript.

All works just fine, but i'd like to add an animation effect when the div is added, i.e. "slowly" move the existing divs down, and add the new one at the top, Any pointers on how to do that ?

The application actually runs in facebook not using the iframe, I tried to use jquery but it does not seem to work on facebook, and looking at the code modifications that FB do, I assume other frameworks will have a similar problem.

Answer:
It depends on the JavaScript framework you're using; but look at
MooTools
,
Scriptaculous
,
jQuery
and
YUI Animation
. If you're just hammering out JavaScript on your own, you'll find that working with interval timers that modify the style of some element over time and then trigger an animation complete event to stop the timer and finally update the page is a fairly involved error prone process.
You're probably looking for something generally called
slide
down
(try the demos).


Question: Does anyone know of any documentation by MS or someone else that lays out the best practices for developing a 3 tier architecture in ASP.NET.  I am in the process of trying to convince my boss that the current architecture needs rethought and reworked to provide a flexible and reusable system.  I have found a lot of generic documentation that tells you at a high level the best practices as far as how to do this but little showing how you actually implement them.  I need to show him documentation as far as the advantages to using business objects versus data sets and things to that level of detail.  Any help would be appreciated.

Answer:
Microsoft's
Patterns & Practices group
has published various whitepapers and documents in the form of "architectural guidance" that can be helpful. They recently published a number of
"pocket guides"
as well. Even if you don't follow them to the letter, they're likely to be a great starting point for discussing your particular needs.
That they come from Microsoft may also help add credibility in the discussion with your boss. There's one on
Web Application Architecture
, in particular, that sounds like it may be relevant.


Question:
Is there any way to configure SQL Server 2000 Standard Edition (32 bit) to use more than 2Gb of memory on a server running Windows 2003 (64 bit)?

Thanks for any help.

Answer:
It appears that this Microsoft article is of relevance:
How to configure SQL Server to use more than 2 GB of physical memory


Question: Looking for tips, tutorials, books and other resources to get started with Constraint Programming.

Answer:
I recommend getting started with
mozart
.  It is an open-source constraint programming language and the site has plenty of documentation that will get you started.


Question:
What is the best way to convert a double to a long without casting?

For example:

double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);

Answer:
Assuming you're happy with truncating towards zero, just cast:
```
```
double d = 1234.56;
long x = (long) d; // x = 1234
```
```
This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.


Question:
I would like to return all rows from TableA table that does not exists in another table.

e.g.

select bench_id from TableA where bench_id not in (select bench_id from TableB )

can you please help me write equivalent LINQ query. Here TableA is from Excel and TableB is from a Database

I am loading Excel sheet data into DataTable, TableA. TableB I am loading from Database. In short, TableA and TableB is type of DataTable

Answer:
So if table A is from Excel, are you loading the data into memory first? If so (i.e. you're using LINQ to Objects) then I suggest you load the IDs in table B into a set and then use:
```
```
var query = tableA.Where(entry => !tableBIdSet.Contains(entry.Id));
```
```
If this isn't appropriate, please give more details.
Converting into a set is probably best done just by using
the HashSet constructor which takes an
```
IEnumerable<T>
```
. For example:
```
```
var tableBIdSet = new HashSet<string>(db.TableB.Select(entry => entry.Id));
```
```
(If the IDs aren't actually distinct, you could add a call to Distinct() at the end.)


Question:
I have Enitity Type, Name of Primary Key and Guid of Primary Id. I want to get element of such Id in LinqToSql.

model.GetTable<T>().Where(t => here equality  );

I think I need to generate that Expression myself, but I dont know how :(

Answer:
I look forward, and after searching through generated by compiler code, in Reflector I found this creation of lambda.
```
```
public static T GetById(Guid id)
    {
        Type entType = typeof(T);

        if (!CheckTable(entType)) {
            throw new TypeLoadException(string.Format(
                "{0} is not Table Entity, has no attribute Table", entType.FullName));
        }

        string property = GetPrimaryKeyName(entType).Name;

        ParameterExpression cs;
        var lambda = Expression.Lambda<Func<Personal, bool>>(
                Expression.Equal(
                        Expression.Property(
                                cs = Expression.Parameter(typeof(T), "p"),
                                entType.GetProperty(property).GetGetMethod()
                        ),
                        Expression.Constant(id),
                        false,
                        typeof(Guid).GetMethod("Equals")
                ), new ParameterExpression[] { cs }
        );

        return Connection.Model.GetTable<T>().Single(lambda);
    }
```
```
The thing what I need, but I have compiler exception:
Error 5   The type arguments for method
  'System.Linq.Enumerable.Single(System.Collections.Generic.IEnumerable,
  System.Func)' cannot be
  inferred from the usage. Try
  specifying the type arguments
  explicitly.   D:\Projects\Own\Yabeda\Source\trunk\med\Yabeda.Med.Mvc\Data\Oper.cs 48  20  Yabeda.Med.Mvc
Can't find what this Error means!


Question: Anyone know of a free xls to text converter that can be run from the unix command line?

Answer:
A quick search of
```
apt-cache
```
turned up the
Ubuntu package python-excelerator
for
excelerator
, which includes
```
py_xls2html
```
,
```
py_xls2csv
```
and
```
py_xls2txt
```
utlities. Will this work for you?


Question:
How does one read a data file in an iPhone project?  For example, lets say I have a static file called "level.dat" that is structured as follows:
obstacles: 10
time: 100
obstacle1: 10,20
...

I would like to read the contents of the file into a NSString then do the parsing.  How do I read the contents of a file into a string?  Also, where in the project should the "level.dat" file reside?  Should it be under "Resources" or just in the main directory?

Thanks in advance!

Answer:
See this answer:
How to fopen() on the iPhone?
which shows how to get access to resources in your bundle. Once you have the path, just use [NSString stringWithContentsOfFile:encoding:error:].
```
```
NSString   *path = [[NSBundle mainBundle] pathForResource: @"level" ofType: @"dat"]
NSError    *error = nil;
NSString   *data = [NSString stringWithContentsOfFile: path
                                             encoding: NSUTF8StringEncoding
                                                error: &error];
```
```


Question:
Given:

FieldInfo field = <some valid string field on type T>;
ParameterExpression targetExp = Expression.Parameter(typeof(T), "target");
ParameterExpression valueExp = Expression.Parameter(typeof(string), "value");

How do I compile a lambda expression to set the field on the "target" parameter to "value"?

Answer:
.Net 4.0
: now that there's
```
Expression.Assign
```
, this is easy to do:
```
```
FieldInfo field = typeof(T).GetField("fieldName");
ParameterExpression targetExp = Expression.Parameter(typeof(T), "target");
ParameterExpression valueExp = Expression.Parameter(typeof(string), "value");

// Expression.Property can be used here as well
MemberExpression fieldExp = Expression.Field(targetExp, field);
BinaryExpression assignExp = Expression.Assign(fieldExp, valueExp);

var setter = Expression.Lambda<Action<T, string>>
    (assignExp, targetExp, valueExp).Compile();

setter(subject, "new value");
```
```
.Net 3.5
: you can't,  you'll have to use System.Reflection.Emit instead:
```
```
class Program
{
    class MyObject
    {
        public int MyField;
    }

    static Action<T,TValue> MakeSetter<T,TValue>(FieldInfo field)
    {
        DynamicMethod m = new DynamicMethod(
            "setter", typeof(void), new Type[] { typeof(T), typeof(TValue) }, typeof(Program));
        ILGenerator cg = m.GetILGenerator();

        // arg0.<field> = arg1
        cg.Emit(OpCodes.Ldarg_0);
        cg.Emit(OpCodes.Ldarg_1);
        cg.Emit(OpCodes.Stfld, field);
        cg.Emit(OpCodes.Ret);

        return (Action<T,TValue>) m.CreateDelegate(typeof(Action<T,TValue>));
    }

    static void Main()
    {
        FieldInfo f = typeof(MyObject).GetField("MyField");

        Action<MyObject,int> setter = MakeSetter<MyObject,int>(f);

        var obj = new MyObject();
        obj.MyField = 10;

        setter(obj, 42);

        Console.WriteLine(obj.MyField);
        Console.ReadLine();
    }
}
```
```


Question: In Qt, when a widget receives focus, how can get a notification about it, so I can execute some custom code? Is there a signal or an event for that?

Answer:
There is a "focusChanged" signal sent when the focus changes, introduced in Qt 4.1.
It has two arguments, he widget losing focus and the one gaining focus:
```
```
void QApplication::focusChanged(QWidget * old, QWidget * now)
```
```


Question: I change the FontSize of Text in a Style trigger, this causes the Control containing the text to resize as well. How can I change the Fontsize without affecting the parent's size?

Answer:
What kind of control are you using? If this is a HeaderedControl like a GroupBox or TabItem then you need to specifically set the HeaderTemplate like this:
```
```
<DataTemplate x:Key="MyHeaderTemplate">
  <TextBlock Text="{Binding}" Fontsize="14" FontWeight="Bold" />
</DataTemplate>
```
```


Question: Say I'm extending a TextBox called CustomTextBox in .net. In certain situations I would like to force a tab to the next TabIndex on the form. Is there a way to do this beyond getting all the controls contained in CustomTextBox's parent, sorting them by their TabIndex, and then focusing the next ordinal one?

Answer:
I think you are looking for something like the following method:
```
```
form1.SelectNextControl(textBox1, true, true, true, true);
```
```
(All the trues are just different options, read the intellisense!)
You did say it is WinForms and not WebForms right?


Question:
I have an application that I want to export high-resolution (or rather, high pixel density?) images for printing - for example, I want images that print at 250 dots per inch (DPI), instead of the default, which I understand to be 72 DPI.

I'm using a BufferedImage with a Graphics2D object to draw the image, then ImageIO.write() to save the image.

Any idea how I can set the DPI?

Answer:
Kurt's answer showed the way, still it took me quite some time to get it run, so here is the code that sets DPI when saving a PNG. There is a lot to do to get the proper writers and such...
```
```
private BufferedImage gridImage;
 ...

 private void saveGridImage(File output) throws IOException {
    output.delete();

    final String formatName = "png";

    for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
       ImageWriter writer = iw.next();
       ImageWriteParam writeParam = writer.getDefaultWriteParam();
       ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
       IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
       if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
          continue;
       }

       setDPI(metadata);

       final ImageOutputStream stream = ImageIO.createImageOutputStream(output);
       try {
          writer.setOutput(stream);
          writer.write(metadata, new IIOImage(gridImage, null, metadata), writeParam);
       } finally {
          stream.close();
       }
       break;
    }
 }

 private void setDPI(IIOMetadata metadata) throws IIOInvalidTreeException {

    // for PMG, it's dots per millimeter
    double dotsPerMilli = 1.0 * DPI / 10 / INCH_2_CM;

    IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize");
    horiz.setAttribute("value", Double.toString(dotsPerMilli));

    IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize");
    vert.setAttribute("value", Double.toString(dotsPerMilli));

    IIOMetadataNode dim = new IIOMetadataNode("Dimension");
    dim.appendChild(horiz);
    dim.appendChild(vert);

    IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0");
    root.appendChild(dim);

    metadata.mergeTree("javax_imageio_1.0", root);
 }
```
```


Question:
Are the threadlocals variables global to all the requests made to the servlet that owns the variables?

I am using resin for the server.

Thanks for awnser.

I think I can make my self more clear.

The specific Case:

I want to:

initialize a static variable when the request starts the execution.

be able to query the value of the variable in the further executions of methods called from the servlet in a thread safety way until the request ends the execution

Answer:
I think they are global to all requests made with that specific thread only. Other threads get other copies of the
thread-local
data. This is the key point of thread-local storage:
http://en.wikipedia.org/wiki/Thread-local_storage#Java
.
Unless you check the appropriate option in the servlets config, the servlet container will use your servlet with multiple threads to handle requests in parallel. So effectively you would have separate data for each thread that's up serving clients.
If your WebApplication isn't distributed (runs on multiple Java Virtual Machines), you can use the
```
ServletContext
```
object to store shared data across requests and threads (be sure to do proper locking then).


Question:
I've seen a number of examples that have a thread procedure that looks like this.

    private void ThreadProc()
    {
        while (serviceStarted)
        {
            // do some work

            Thread.Sleep(new TimeSpan(0, 0, 5));
        }

        Thread.CurrentThread.Abort();
    }

Is the Abort() really necessary at the end?

There are number of arguments against calling Abort()

Once the procedure exited - it is expected it has already cleaned up after itself.

Calling Abort() throws an exception, which is generally more resource intensive than just exiting a procedure.

I'd like to read an explanation for why this is or isn't a good practice.

Answer:
Calling
```
Thread.Abort()
```
does raise an exception, and if you're writing code that will be re-used (or part of a base library) it's difficult for other developers to handle
```
ThreadAbortExcpetion
```
s.
It's explained in this article about
Reliability Best Practices
.
I've always heard that calling
```
Thread.Join()
```
is a better way to do it, if you can wait until the thread is completed processing.
I don't know if anyone thinks it's a good practice.  It can cause deadlocks (because unmanaged resources aren't properly cleaned up when you throw an exception)
Here's
another article about it
, and other methods to deal with the issue.


Question:
I'm trying to encrypt some integers in java using java.security and javax.crypto.

The problem seems to be that the Cipher class only encrypts byte arrays.  I can't directly convert an integer to a byte string (or can I?).  What is the best way to do this?

Should I convert the integer to a string and the string to byte[]?  This seems too inefficient.

Does anyone know a quick/easy or efficient way to do it?

Please let me know.

Thanks in advance.

jbu

Answer:
You can turn ints into a byte[] using a DataOutputStream, like this:
```
```
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
DataOutputStream dos = new DataOutputStream (baos);
dos.writeInt (i);
byte[] data = baos.toByteArray();
// do encryption
```
```
Then to decrypt it later:
```
```
byte[] decrypted = decrypt (data);
ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new DataInputStream (bais);
int j = dis.readInt();
```
```


Question: How do I convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t value in either C or C++?

Answer:
I'm afraid there isn't any in Standard C / C++ . There is the POSIX function
```
strptime
```
which can convert to
```
struct tm
```
, which can then be converted to
```
time_t
```
using
```
mktime
```
.
If you are aiming for cross platform compatibility, better use
```
boost::date_time
```
, which has sophisticated functions for this.


Question:
I was wondering in C++ if I have an enum can I access the value at the second index?  For example I have

enum Test{hi, bye};

if I want 'hi', can I do something like Test[0], thanks.

Answer:
Enumerations map names to values.  In your case, (int)hi would have a value of 0, and (int)bye a value of 1.  You can use a cast to get the value of hi:
```
```
int myInteger = 0;
Test myValue = (Test)myInteger;
```
```
Note, though, that myValue could be an invalid enum value if myInteger is out of range.


Question:
Is there a good equivalent implementation of strptime() available for Windows?  Unfortunately, this POSIX function does not appear to be available.

Open Group description of strptime - summary: it converts a text string such as "MM-DD-YYYY HH:MM:SS" into a tm struct, the opposite of strftime().

Answer:
An open-source version (BSD license) of
```
strptime()
```
can be found here:
http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/time/strptime.c?rev=HEAD
You'll need to add the following declaration to use it:
```
```
char *strptime(const char * __restrict, const char * __restrict, struct tm * __restrict);
```
```


Question:
I have a ‘page a’ using ‘css a’. This page has margins set in css.
I also have a ‘page b’ using ‘css b’. This page also has margins set in css, of the same size as in ‘css a’ (10px).

Is there any way I can make it so that when I am viewing ‘page a’ on its own it has margins, but when viewed in an iframe on ‘page b’ the margins don’t apply to ‘page a’. I know that’s kind of a long way of asking but the basic problem is that I am getting ‘double margins’ for the content in the iframe: the margin from ‘page a’ and then the margin from ‘page b’!

I guess one way of doing it would be to set the iframe not to be affected by ‘page a’s’ margins. Is there some way I can set ‘css a’ to exclude the iframe from the margins, that way only the margins from css b would apply and the page would still be in alignment. is that possible?

Thanks for any help

Matt

Answer:
Using one of the most fundamental XSLT design patterns: "Overriding the
identity transformation
" one will just write the following:
```
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="Element[@fruit='apple' and @animal='cat']"/>
</xsl:stylesheet>
```
Do note
how the second template overrides the identity (1st) template only for elements named "Element" that have an attribute "fruit" with value "apple" and attribute "animal" with value "cat". This template has empty body, which means that the matched element is simply ignored (nothing is produced when it is matched).
When this transformation is applied on the following source XML document:
```
<doc>...
    <Element name="same">foo</Element>...
    <Element fruit="apple" animal="cat" />
    <Element fruit="pear" animal="cat" />
    <Element name="same">baz</Element>...
    <Element name="same">foobar</Element>...
</doc>
```
the wanted result is produced:
```
<doc>...
    <Element name="same">foo</Element>...
    <Element fruit="pear" animal="cat"/>
    <Element name="same">baz</Element>...
    <Element name="same">foobar</Element>...
</doc>
```
More code snippets of using and overriding the identity template can be found
here
.


Question:
Does anybody know if it is possible to choose the order of the fields in Dynamic Data (of course, without customizing the templates of each table) ?

Thanks !

Answer:
You can do this by modifying the order of the public properties in your LINQ to SQL file.
For example, I went into Northwind.designer.cs which was my auto-generated LINQ to SQL file and moved the public property named Products above the public property CategoryName in the public partial class Category. Then I recompiled and the default template displayed the columns in my new order.
Of course, this means your editing auto-generated code and if you regenerate it, your changes are lost, so this technique is not without peril.


Question:
I am new to LINQ. I am trying to find the rows that does not exists in the second data table.

report_list and benchmark both type are : DataTable. Both these datatables are being populated using OleDbCommand,OleDbDataAdapter. I am getting an error "Specified cast is not valid."  in foreach ... loop. I would appreciate your help.

            var result = from a in report_list.AsEnumerable()
                         where !(from b in benchmark.AsEnumerable()
                                 select b.Field<int>("bench_id")
                                )
                                .Contains(a.Field<int>("BenchmarkID"))
                         select a;

            foreach (var c  in result)
            {
                Console.WriteLine(c.Field<string>("Name"));
            }

Answer:
I don't know if I understood your question. Are you trying to get the items that exists in the first table but not in the second?
```
```
var first = new string[] { "b", "c" };
var second = new string[] { "a", "c" };
//find the itens that exist in "first" but not in "second"
var q = from f in first
        where !second.Contains(f)
        select f;
foreach (var s in q) {
    Console.WriteLine(s);
}

//Prints:
//b
```
```
I suggest you to make the inner query first, once it does not depend on the outer record.


Question:
I currently working on an issue tracker for my company to help them keep track of problems that arise with the network. I am using C# and SQL.

Each issue has about twenty things we need to keep track of(status, work loss, who created it, who's working on it, etc). I need to attach a list of teams affected by the issue to each entry in my main issue table. The list of teams affected ideally contains some sort of link to a unique table instance, just for that issue, that shows the list of teams affected and what percentage of each teams labs are affected.

So my question is what is the best way to impliment this "link" between an entry into the issue table and a unique table for that issue? Or am I thinking about this problem wrong.

Answer:
If I understand the question correctly I would create....
ISSUE table containing the 20 so so items
TEAM table containing a list of teams.
TEAM_ISSUES table containing the link beteen the two
The TEAM_ISSUES table needs to contain a foriegn key to the ISSUE and TEAM tables (ie it should contain an ISSUE_ID and a TEAM_ID... it therefore acts as an intersection between the two "master" tables.  It sounds like this is also the place to put the percentage.
Does that make sense?


Question:
I'm serializing to XML my class where one of properties has type List<string>.

public class MyClass {
    ...
    public List<string> Properties { get; set; }
    ...
}

XML created by serializing this class looks like this:

<MyClass>
    ...
    <Properties>
        <string>somethinghere</string>
        <string>somethinghere</string>
    </Properties>
    ...
</MyClass>

and now my question. How can I change my class to achieve XML like this:

<MyClass>
    ...
    <Properties>
        <Property>somethinghere</Property>
        <Property>somethinghere</Property>
    </Properties>
    ...
</MyClass>

after serializing. Thanks for any help!

Answer:
Try
XmlArrayItemAttribute
:
```
```
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;

public class Program
{
    [XmlArrayItem("Property")]
    public List<string> Properties = new List<string>();

    public static void Main(string[] args)
    {
        Program program = new Program();
        program.Properties.Add("test1");
        program.Properties.Add("test2");
        program.Properties.Add("test3");

        XmlSerializer xser = new XmlSerializer(typeof(Program));
        xser.Serialize(new FileStream("test.xml", FileMode.Create), program);
    }
}
```
```
test.xml:
```
```
<?xml version="1.0"?>
<Program xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Properties>
    <Property>test1</Property>
    <Property>test2</Property>
    <Property>test3</Property>
  </Properties>
</Program>
```
```


Question:
I'm working on a college assignment where I must verify if a certain clause (as a fact or as a rule) exists in the current clause database.

The idea is to use a rule whose head  is verify(+name, +arguments). This rule should be true if in the database exists another rule whose head is name(arguments)

Any help would be greatly appreciated...

Answer:
Are you familiar with the concept of unification? What you have to do is: just call a predicate that looks like the one you're trying to find.
So, say in your database is:
```
```
father(abraham,isaac).
```
```
Now you want to call something like:
```
```
verify(father,[abraham,isaac]).
```
```
Your predicate body will then have to contain a mechanism of calling
```
father(abraham,isaac).
```
which should then return
```
true.
```
Calling
```
father(abraham,adam)
```
should fail.
You will need two predicates for this:
```
=../2
```
and
```
call/2
```
. If you are using SWI-Prolog, call
```
help(=..).
```
and
```
help(call)
```
from the interpreter's command line to access the documentation.
I hope I didn't spoil the assignment for you. You still have to find out what to do with partially instantiated predicates (so, say something like
```
verify(father,[abraham,X]).
```
on your own, but it shouldn't be hard from here.
Good luck.


Question: Exactly as the question states: How can you check if a variable in PHP contains a file pointer? Some like is_string() or is_object().

Answer:
You can use
```
stream_get_meta_data()
```
for this.
```
```
<?php
$f = fopen('index.php', 'r');
var_dump(stream_get_meta_data($f));
?>

array
  'wrapper_type' => string 'plainfile' (length=9)
  'stream_type' => string 'STDIO' (length=5)
  'mode' => string 'r' (length=1)
  'unread_bytes' => int 0
  'seekable' => boolean true
  'uri' => string 'index.php' (length=9)
  'timed_out' => boolean false
  'blocked' => boolean true
  'eof' => boolean false
```
```
You can prefix it with @ to supress warnings if the variable is not a resource - then just check if it returned false.


Question:
Given an ordered set of 2D pixel locations (adjacent or adjacent-diagonal) that form a complete path with no repeats, how do I determine the Greatest Linear Dimension of the polygon whose perimeter is that set of pixels? (where the GLD is the greatest linear distance of any pair of points in the set)

For my purposes, the obvious O(n^2) solution is probably not fast enough for figures of thousands of points. Are there good heuristics or lookup methods that bring the time complexity nearer to O(n) or O(log(n))?

Answer:
On this page:
http://en.wikipedia.org/wiki/Rotating_calipers
http://cgm.cs.mcgill.ca/~orm/diam.html
it shows that you can determine the maximum diameter of a convex polygon in O(n). I just need to turn my point set into a convex polygon first (probably using Graham scan).
http://en.wikipedia.org/wiki/Convex_hull_algorithms
Here is some C# code I came across for computing the convex hull:
http://www.itu.dk/~sestoft/gcsharp/index.html#hull


Question:
Is it possible?

I have a listview with several gridviewcolumns. The last column has a dynamic header. I dont know what the column header will be at design time. It's actually a number I want to display as a string.

    <GridViewColumn Header="{Binding Path=SomeValue}"
                    DisplayMemberBinding="{Binding Path=OtherValue}"/>

This doesn't seem to work. The data will bind fine just the header remains blank. Stepping through the code and it doesn't even break on the SomeValue property.

Answer: I think your problem is the source of the "SomeValue" property. If you are binding to a list of objects, it wouldn't make sense to have the header determined by a property on that object, because then you could have a different header for every object. Essentially what you are saying is "Bind the header of the column to the 'SomeValue' property which lives on the same object that my 'OtherValue' property does." The "SomeValue" needs to come from a different source other than the list your grid item is bound to. You need to either set the "RelativeSource" or the "ElementName" property in the binding.


Question: Our motor pool wants to scan drivers’ licenses and have the data imported into our custom system. We're looking for something that will allow us to programmatically get the data from the scanner (including the picture) and let us insert it into our application. I was wondering if anyone has had experience with this type of system and could recommend one or tell us which ones to avoid. Our application is written in PowerBuilder and uses a DB2 database.

Answer:
If your scanner is "twain compliant", You will then be able to manage it from your app through an ActiveX control you can buy on the net like
this one
. You'll be able to manage your basic scan parameters (quality, color, single/multiple pages can, output format, etc), start the scan from your app, save the result as a file and transfer this file wherever needed. We have been using it with VB code for the last 2 years. It works.


Question:
Looking to improve my IF statement, and I want to keep my code looking pretty

This is what I am currently doing, is it readable, any room for improvement?

SomeObject o = LoadSomeObject();

if( null == o
    ||
    null == o.ID || null == o.Title
    ||
    0 == o.ID.Length || 0 == o.Title.Length
 )

I don't have anyone to ask around. That's why I came here in first place. Please don't close my question :(

Answer:
Your verbosity is leading to a less readable code, I think the following format is best:
```
```
if ( null == o || null == o.ID || null.Title || 0 == o.ID.Length || 0 == o.Title.Length )
{
  // do stuff
}
```
```
We all have high resolution/widescreen displays for a reason, there's no reason to lock your code at some horribly short syntax.  Also, I would simply create a function named  IsIDEmpty so that the code could look like
```
```
if ( IsIDEmpty(o) )
{
  // do stuff
}
```
```
to keep the code simpler & cleaner.  The function would perform the actual checks and return a boolean.  I'm sure this is something you might have re-use for anyways, plus it serves as a simple way for code to be more self documenting/commenting.


Question:
I am trying to make IBM jre to use PCF fonts from default X11 installation on my linux box. In particular adobe-helvetica font. I have toyed to modify fontconfig.properties in jre/lib folder but no matter what I do Java seams to use some other fonts. I guess there is some algorithm how java VM tries to link java logical fonts to actual physical fonts in the system even in case when font specified in config could not be used. On Windows it is pretty straight forward, but on Linux I was unable to make it work with anything except TrueType fonts.

Anybody have experience with configuring fonts on IBM jre on Linux?

Answer:
Your verbosity is leading to a less readable code, I think the following format is best:
```
```
if ( null == o || null == o.ID || null.Title || 0 == o.ID.Length || 0 == o.Title.Length )
{
  // do stuff
}
```
```
We all have high resolution/widescreen displays for a reason, there's no reason to lock your code at some horribly short syntax.  Also, I would simply create a function named  IsIDEmpty so that the code could look like
```
```
if ( IsIDEmpty(o) )
{
  // do stuff
}
```
```
to keep the code simpler & cleaner.  The function would perform the actual checks and return a boolean.  I'm sure this is something you might have re-use for anyways, plus it serves as a simple way for code to be more self documenting/commenting.


Question:
I have read an example and tried to duplicate it's methods but with weird results. This is a 1 shot deal so I do not want to buy a package to do this. Also, it will be executed on a Multi-Valued database in a Basic that not many programmers write in anymore.
If anyone can post a small example of this It would be most helpful. Specifically, I need a box centered on an 8x11 paper with the left 1/3 filled in Green, the center 1/3 in Yellow and the last 1/3 in Red. Then Draw a line thru 3 points within each color of the box.

Thanks.

Answer:
The simplest way is to draw 3 boxes.  You'll have to position each one on your own doing your own math to determine where to start the first one to make it centered etc.
First position your cursor at the top left of the first box, draw it, move to the top left of the next box, draw it, and do the same for the last.  Here is some code:
```
```
<esc>&u300D<esc>*t300R<esc>*p300x300Y<esc>*r3U<esc>*v2S<esc>*c300a300b5P<esc>*p600x300Y<esc>*r3U<esc>*v3S<esc>*c300a300b5P<esc>*p900x300Y<esc>*r3U<esc>*v1S<esc>*c300a300b5P
```
```
Here is the explanation:
```
```
<esc>&u300D<esc>*t300R -- set the Unit of Measure and Resolution (in this case 300 dpi)
<esc>*p300x300Y -- move cursor to 300x 300y (1 inch x 1 inch)
<esc>*r3U<esc>*v2S -- set the color palette to RGB and use color 2 (green)
<esc>*c300a300b5P -- draw a box that is 300 wide and 300 tall, use current fill pattern
<esc>*p600x300Y -- move cursor to 600x 300y
<esc>*r3U<esc>*v3S -- set the color palette to RGB use color 3 (yellow)
<esc>*c300a300b5P -- draw a box that is 300 wide and 300 tall, use current fill pattern
<esc>*p900x300Y -- move cursor to 900x 300y
<esc>*r3U<esc>*v1S -- set the color palette to RGB use color 1 (red)
<esc>*c300a300b5P -- draw a box that is 300 wide and 300 tall, use current fill pattern
```
```
Here are the other colors and palettes, keep in mind this is the simple way, you can specify your own RGB etc.
```
```
RGB Palette
<esc>*r3U<esc>*v1S - Red
<esc>*r3U<esc>*v2S - Green
<esc>*r3U<esc>*v3S - Yellow
<esc>*r3U<esc>*v4S - Blue
<esc>*r3U<esc>*v5S - Magenta
<esc>*r3U<esc>*v6S - Cyan

CMYK Palette
<esc>*r-3U<esc>*v1S - Cyan
<esc>*r-3U<esc>*v2S - Magenta
<esc>*r-3U<esc>*v3S - Blue
<esc>*r-3U<esc>*v4S - Yellow
<esc>*r-3U<esc>*v5S - Green
<esc>*r-3U<esc>*v6S - Red
<esc>*r-3U<esc>*v7S - Black
```
```


Question:
I need to query for a list of available Wireless Access points. I only need their SSIDs.

The App is currently .Net CF 2.0, but it's not a problem going with 3.5 if we have to.

Answer:
Well the core of this is in the Windows Zero Config .dll otherwise known as WZC. However from a managed app you'll want to go via
OpenNETCF
as they have a managed wrapper that can provide this information for you.
The classes of interest are the Adapter or NetworkAdapter classes.
The obselete api was:
```
```
Networking.GetAdapters()
```
```
although this is now depreciated I think and I apologise but i've forgotten what they've replaced it with but there will be a new equivalent.


Question:
I'd like to write a script that (under certain conditions) will execute gdb and automatically run some program X with some set of arguments Y.  Once the program has finished executing the user should remain at gdb's prompt until s/he explicitly exits it.

One way to do this would be to have the script output the run command plus arguments Y to some file F and then have the script invoke gdb like this:

gdb X < F

But is there a way to do this without introducing a temporary file?

Answer:
```
cat F | gdb X
```
should be identical. So you can use anything that produces output and pipe that into gdb instead of the cat command here.
I'm assuming you're correct and gdb reads from stdin.


Question:
I'm new to ReSharper and am surprised that there isn't a template defined for

public void MethodName(<params>)
{

}

I realize I could create one, but I would have thought this would have been part of the standard product.  Perhaps I'm missing some other shortcut?

Answer:
I'm not aware of any such default template, but as you pointed out it's terribly easy to write:
```
```
public void $METHODNAME$($PARAMS$)
{
    $END$
}
```
```
However, I'm more that a tiny bit perplexed that you're interested in making all your methods both public and void
by default.


Question: I have recently started exploring Maven, but I feel a bit overwhelmed of all xml configuration in all the pom files. Are there any good tools i can use?

Answer:
When I edit any XML files, I use
vim
with the
xmledit
plugin.
Another good tool for XML editing is
XMLmind XML editor
.  It's free for non-commercial use.  It supports validating XML with W3C XML Schema (and other schema formats), so you can be sure to produce
valid POM format
.


Question:
The top of my web.xml file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
    version="2.5">

But I still get the warning from Eclipse (Ganymede) that no XML schema is detected, and schema violations are not being warned about.  Other XML files in my project (Spring Framework configuration files for example) don't have the warning and do give correct warnings about schema violations.

How do I get the schema checking working and hopefully the warning to go away?  The server does run correctly.  It just appears to be an IDE issue.

Answer:
Perhaps try:
```
```
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
```
```
Instead of:
```
```
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd
```
```
Also, the
```
<!DOCTYPE ...>
```
is missing:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app
  xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
  <!-- ... -->
</web-app>
```
```


Question:
I'm reviewing some Spring code, and I see a few bean defs that do not have an id or a name.
The person who did it is not around to ask.
The application is working fine.
I am not familiar what this necessarily means.
Anybody know if this means anything in particular?

Answer:
One possibility is that you can define a bean in place, and so you don't need an id since you don't need to refer to it from anywhere else.  Say I have a Foo object that takes a Bar property:
```
```
<bean id="foo" class="Foo">
     <property name="bar">
         <bean class="Bar">
     </property>
</bean>
```
```
The Bar bean doesn't need a name because it's only used to set that one property.


Question:
Tomcat documentation says:

The locations for Context Descriptors are;

$CATALINA_HOME/conf/[enginename]/[hostname]/context.xml

$CATALINA_HOME/webapps/[webappname]/META-INF/context.xml

On my server, I have at least 3 files floating around:

1 ...tomcat/conf/context.xml
2 ...tomcat/Catalina/localhost/myapp.xml
3 ...tomcat/webapps/myapp/META-INF/context.xml

What is the order of precedence?

Answer:
I haven't found any official documentation, but I have observed the load order to be:
```
```
1 tomcat_home/conf/context.xml
2 tomcat_home/webapps/myapp/META-INF/context.xml
```
```
Where #2 is the last one applied (so its settings override all previous ones, where applicable).
I have never used the webapp named context files (your option #2).


Question:
I'm currently trying to implement a marble maze game for a WM 5.0 device and have been struggling with developing a working prototype. The prototype would need the user to control the ball using the directional keys and display realistic acceleration and friction.

I was wondering if anyone has experience with this and can give me some advice or point me in the right direction of what is essential and the best way to go around doing such a thing.

Thanks in advance.

Frank.

Answer:
I would recommend checking out XNA Studio 3, it has built in support for PC, Xbox 360 and mobile devices, and it's an official & free spin-off of Visual Studio from Microsoft.
http://creators.xna.com/en-US/
http://blogs.msdn.com/xna/
If you search around, people have written tutorials using physics (velocity on this one)
http://www.xnamachine.com/2007/12/fun-with-very-basic-physics.html


Question:
Previously our SharePoint server was 32-bit and we used the web capture web part to display a bugzilla search results page. Since we've migrated to a 64-bit server the webpart no longer works. We're running the same versions of everything, the only change was moving from a Windows Server 2003 32-bit box to a Windows Server 2003 64-bit box.

Oddly enough, the logs don't contain anything. The pages where the webparts appear are the only place that error messages appear. Here is what I have:

-Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. The type could not be found or it is not registered as safe.

Error - An unexpected error has been encountered in this Web Part.

The reason I suspect the 64bit vs 32bit issue is that I saw numerous posts on the subject in various forums. It would appear that I am not the only one with this issue and all the troubleshooting has lead to this conclusion.

Answer:
Not strictly an answer to your question, but have you tried it using a sql server based session store? (Search on MSDN for the permanent script rather than the temp script that's provided with asp.net)
I've heard "bad things" about the executable session service, and consequently have not used it. Never had any problems web farming with the sql server based solution though.
Sorry it's not strictly an answer to your problem, but it should either (a) fix it, or (b) narrow it down significantly.


Question:
What is the command-line equivalent of "Switch Port Client User" as found in the p4win gui client?

I am already logged under one port but now I am attempting to connect to a different port on the same server in order to access a separate source control file depot. I assume it would involve using:

p4 login

However, reading the 'help' for 'login' does not show an option to specify the port #. Both user name and client name would remain the same but just need to change the port #.

Answer:
The P4PORT configuration variable stores the Perforce server name and port number to connect to. You can set this value as an environment variable or, if you're using Windows, in the registry using 'p4 set':
```
```
p4 set P4PORT=perforce:1669
```
```
To see what the current value of P4PORT is:
```
```
> p4 set P4PORT
P4PORT=perforce:1669
```
```


Question:
I've been testing out the performance and memory profiler AQTime to see if it's worthwhile spending those big $$$ for it for my Delphi application.

What amazes me is how it can give you source line level performance tracing (which includes the number of times each line was executed and the amount of time that line took) without modifying the application's source code and without adding an inordinate amount of time to the debug run.

The way that they do this so efficiently makes me think there might be some techniques/technologies used here that I don't know about that would be useful to know about.

Do you know what kind of methods they use to capture the execution line-by-line without code changes?

Are there other profiling tools that also do non-invasive line-by-line checking and if so, do they use the same techniques?

Answer:
I don't know about Delphi in particular, but a C application debugger can do line-by-line profiling relatively easily - it can load the code and associate every code path with a block of code. Then it can break on all the conditional jump instructions and just watch and see what code path is taken. Debuggers like gdb can operate relatively efficiently because they work through the kernel and don't modify the code, they just get informed when each line is executed. If something causes the block to be exited early (longjmp), the debugger can hook that and figure out how far it got into the blocks when it happened and increment only those lines.
Of course, it would still be tough to code, but when I say easily I mean that you could do it without wasting time breaking on each and every instruction to update a counter.


Question:
I have an iterator to a map element, and I would like gdb to show me the values of the "first" and "second" elements of that iterator.
For example:

std::map<int,double> aMap;
...fill map...
std::map<int,double>::const_iterator p = aMap.begin();

I can use p.first and p.second in the code, but can't see them in gdb. For what it's worth, in dbx one could do something like "print p.node.second_", but I can find anything similar in gbd.

I am totally willing to have a function into which I pass the object types, but I've been unable to get that to work either.

Any ideas?
Thanks!

Answer:
Here is how i do it:
```
```
This GDB was configured as "i686-pc-linux-gnu"...
(gdb) list
1       #include <iostream>
2       #include <map>
3
4       int main()
5       {
6           std::map<int, int> a;
7           a[10] = 9;
8           std::map<int, int>::iterator it = a.begin();
9           ++it;
10      }
(gdb) b test.cpp:9
Breakpoint 1 at 0x8048942: file test.cpp, line 9.
(gdb) r
Starting program: /home/js/cpp/a.out

Breakpoint 1, main () at test.cpp:9
9           ++it;
(gdb) set print pretty on
(gdb) p it
$1 = {
  _M_node = 0x94fa008
}
(gdb) p *it
$2 = (class std::pair<const int, int> &) @0x94fa018: {
  first = 10,
  second = 9
}
(gdb)
```
```


Question:
I want to examine the contents of a std::vector in gdb but I don't have access to _M_impl because I'm using icc, not gcc, how do I do it? Let's say it's a std::vector for the sake of simplicity.

There is a very nice answer here but this doesn't work if I use icc, the error message is "There is no member or method named _M_impl". There appears to be a nice debug toolset here but it also relies on _M_impl.

Answer:
The
```
std::vector
```
template
guarantees the data is stored contiguously
.  If you take the address of the front element (say,
```
&v[0]
```
, for instance), you can access any other element in the vector through a C-style array.  That doesn't require you to have the source code of the STL available to your debugger.
After messing with this some, it appears that
```
v.front()
```
and
```
v.begin()
```
are likely inlined and GDB isn't finding them.  I'll keep looking, but personally I would simply add the line
```
int* i = &v[0]
```
to the source file, and then use GDB commands on
```
i
```
while debugging.  Note that the compiler is free to remove that dead code.  You may need to output the value of
```
i
```
to avoid that, or simply not crank up optimizations.


Question:
I'm looking for a regular expression that will match all strings EXCEPT those that contain a certain string within.  Can someone help me construct it?

For example, looking for all strings that do not have a, b, and c in them in that order.

So

abasfaf3 would match, whereas

asasdfbasc would not

Answer:
in perl:
```
```
if($str !~ /a.*?b.*?.*c/g)
{
    print "match";
}
```
```
should work.


Question:
I feel that it should be something very simple and obvious but just stuck on this for the last half an hour and can't move on.

All I need is to split an array of elements into N groups based on element index.

For example we have an array of 30 elements [e1,e2,...e30], that has to be divided into N=3 groups like this:

group1: [e1, ..., e10]
group2: [e11, ..., e20]
group3: [e21, ..., e30]

I came up with nasty mess like this for N=3 (pseudo language, I left multiplication on 0 and 1 just for clarification):

for(i=0;i<array_size;i++) {
   if(i>=0*(array_size/3) && i<1*(array_size/3) {
      print "group1";
   } else if(i>=1*(array_size/3) && i<2*(array_size/3) {
      print "group2";
   } else if(i>=2*(array_size/3) && i<3*(array_size/3)
      print "group3";
   }
}

But what would be the proper general solution?

Thanks.

Answer:
```
```
const int g = 3;                      // number of groups
 const int n = (array_size + g - 1)/g; // elements per group

 for (i=0,j=1; i<array_size; ++i) {
    if (i > j*n)
        ++j;
     printf("Group %d\n", j);
 }
```
```


Question:
When editing an XML file in IntelliJ IDEA, if the document references a schema, IDEA will fetch the schema and use the information for auto-complete.  It knows which tags are valid in which contexts, so when you hit CTRL-space, it suggests only those tags.  It also highlights any tags that are invalid according to the schema.

Does anybody know of an extension for Vim that provides similar functionality?

Answer:
The closest thing that I've seen for Vim is the
XML Completion
script.
It contains XML definition files for DocBook 4.[234], XSL FO 1.0, XSLT 1.0, Relax NG 1.0, XML Schemas 1.0, SVG 1.1, XHTML 1.1, XInclude 1.0 and OpenOffice 1.0 XML format.


Question:
I noticed methods marked optional in several protocols defined in the iPhone SDK, such as the UIActionSheetDelegate protocol for example.

How can I define a protocol of my own, and set a few of the methods as optional?

Answer:
Use the
```
@optional
```
keyword before your method declaration to make it optional. Simple as that!
```
```
// myProtocol.h
@protocol myProtocol
- (void)myMandatoryMethod:(id)someArgument;
@optional
- (void)myOptionalMethod:(id)someArgument;
@end
```
```
```
```
// myClass.m
@interface myClass : someSuperClass <myProtocol>
    //...
@end
```
```


Question:
It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header to avoid any circular inclusions. I also understand that an #import is a simple ifndef so that an include only happens once.

My inquiry is this: When does one use #import and when does one use @class? Sometimes if I use a @class declaration, I see a common compiler warning such as the following:

warning: receiver 'FooController' is a forward class and corresponding @interface may not exist.

Would really love to understand this, versus just removing the @class forward-declaration and throwing an #import in to silence the warnings the compiler is giving me.

Answer:
Use a forward declaration in the header file if needed, and
```
#import
```
the header files for any classes you're using in the implementation. In other words, you always
```
#import
```
the files you're using in your implementation, and if you need to reference a class in your header file use a forward declaration as well.
The
exception
to this is that you should
```
#import
```
a class or formal protocol you're inheriting from in your header file (in which case you wouldn't need to import it in the implementation).


Question:
This question intends to provide a list of solutions to common pitfalls, "gotcha's", or design issues when developing WPF applications. This can also include proper design-patterns as long as there is an explanation as to why it works best. Responses should be voted up or down based on how common the type of issue is. Here are the rules:

One response per post. This will clearly give the most common issues the highest ranking.

It would be best to provide the link to the a related post or solution already living somewhere in SO land.

Answer:
Problem
: The major issue I have seen so far is that people start coding in WPF with the winform UI model in mind.
Solution
:
WPF is not WinForms/MFC/Win32
So Forget all the UI side assumptions and norms you have used and learned while developing Windows based UI for last 20+ years.
It is very important to understand the core ideas behind this platform, This link-
Major UI Development Breakthroughs in the new WPF platform
will give an in depth view of WPF. Which lists out the following points. The highlighted ones are my favorite features of this platform.
Advanced Graphics
Drawing Object Model
Rich Application Text
Adaptable UI Layout
Flexible Content Model
Lookless Controls
Data-Driven UI
Consistent Styles
Triggers
Declarative Programming


Question:
In jQuery, how do you select the <a> which href is pointing to the current URL

For example:

URL = http://server/dir/script.aspx?id=1

I want to select this <a>

<a href="/dir/script.aspx">...</a>

I tried this but it doesn't work:

var url = window.location.href;
$('#ulTopMenu a["'+url+'"*=href]').addClass("selected");

Probably wrong syntax. Anyone know the right way of doing it?

Thanks in advance

Answer:
I do not know the answer to your question but is that selector syntax valid?
```
```
'#ulTopMenu a["http://www.foo.com"*=href]'
```
```
I'd imagine if such a thing is possible it'd be written as
```
```
'#ulTopMenu a[href*="http://www.foo.com"]'
```
```


Question:
I'm using Parsley IoC in my current Flex project. So I'd like to embed the container configuration XML onto the result SWF.

How could I load embedded XML file into action script XML object?

Answer: I think the problem is that sendmail (your process) is talking to the local sendmail daemon.   The local sendmail daemon thinks that because it is website.com, it should know how to deliver the email.  Unfortunately, the actual address in the to field does not exist on the web server and thus it dumps it in the "catchall" mail box.  You should talk to your ISP and have them update their sendmail configuration so that mail addressed to ...@website.com gets forward to the mail exchanger instead of being handled locally.


Question:
Given an array of items, each of which has a value and cost, what's the best algorithm determine the items required to reach a minimum value at the minimum cost? eg:

Item: Value -> Cost
-------------------
A     20   -> 11
B     7    -> 5
C     1    -> 2

MinValue = 30
naive solution: A + B + C + C + C. Value: 30, Cost 22
best option: A + B + B.            Value: 34, Cost 21

Note that the overall value:cost ratio at the end is irrelevant (A + A would give you the best value for money, but A + B + B is a cheaper option which hits the minimum value).

Answer:
This is the knapsack problem. (That is, the decision version of this problem is the same as the decision version of the knapsack problem, although the optimization version of the knapsack problem is usually stated differently.) It is NP-hard (which means no algorithm is known that is polynomial in the "size" -- number of bits -- in the input). But if your numbers are small (the largest "value" in the input, say; the costs don't matter), then there is a simple dynamic programming solution.
Let best[v] be the minimum cost to get a value of (exactly) v. Then you can calculate the values best[] for all v, by (initializing all best[v] to infinity and):
```
```
best[0] = 0
best[v] = min_(items i){cost[i] + best[v-value[i]]}
```
```
Then look at best[v] for values upto the minimum you want plus the largest value; the smallest of those will give you the cost.
If you want the actual items (and not just the minimum cost), you can either maintain some extra data, or just look through the array of best[]s and infer from it.


Question:
I have a database of companies. My application receives data that references a company by name, but the name may not exactly match the value in the database. I need to match the incoming data to the company it refers to.

For instance, my database might contain a company with name "A. B. Widgets & Co Ltd." while my incoming data might reference "AB Widgets Limited", "A.B. Widgets and Co", or "A B Widgets".

Some words in the company name (A B Widgets) are more important for matching than others (Co, Ltd, Inc, etc). It's important to avoid false matches.

The number of companies is small enough that I can maintain a map of their names in memory, ie. I have the option of using Java rather than SQL to find the right name.

How would you do this in Java?

Answer:
Your database may suport the use of Regular Expressions (regex) - see below for some tutorials in Java - here's the link to the MySQL documentation (as an example):
http://dev.mysql.com/doc/refman/5.0/en/regexp.html#operator_regexp
You would probably want to store in the database a fairly complex regular express statement for each company that encompassed the variations in spelling that you might anticipate - or the sub-elements of the company name that you would like to weight as being significant.
You can also use the regex library in Java
JDK 1.4.2
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
JDK 1.5.0
http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html
Using Regular Expressions in Java
http://www.regular-expressions.info/java.html
The Java Regex API Explained
http://www.sitepoint.com/article/java-regex-api-explained/
You might also want to see if your database supports Soundex capabilities (for example, see the following link to MySQL)
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex


Question:
I've always been one to simply use:

List<String> names = new ArrayList<>();

I use the interface as the type name for portability, so that when I ask questions such as this, I can rework my code.

When should LinkedList be used over ArrayList and vice-versa?

Answer:
It's an efficiency question.
```
LinkedList
```
is fast for adding and deleting elements, but slow to access a specific element.
```
ArrayList
```
is fast for accessing a specific element but can be slow to add to either end, and especially slow to delete in the middle.
Array vs ArrayList vs LinkedList vs Vector
goes more in depth, as does
Linked List
.


Question: I’ve built a custom Maven2 plug-in using Ant. I would like to call another maven plug-in in particular the Cargo Maven2 plug-in immediately after the custom Ant plug-in successfully completes. However, I do not want to attach the Cargo plug-in to another goal or phase. Is there a way to have them run consecutively without having to write a batch script? Is there away to have the Custom Ant plug-in call out to the Cargo plug-in?

Answer:
The Ant script that the maven-ant-plugin executes is not really aware of Maven as such; this plugin is designed for backwards compatibility with custom Ant tasks. I cannot think of a clean way of doing what you want though there may be some kind of hack that allows you to do it.
It should also be possible to execute a second instance of Maven from inside Ant, which runs purely the Cargo goal, but in that case you might encounter problems with locked files and the like. The way to do it would be to just use an  tag in your Ant script and call the "mvn" executable with the appropriate goals as arguments.
The cleanest way is to simply bind the Cargo goal to a phase of the build, and have that run after Ant is finished. I do not see any disadvantage to that approach - you haven't really stated any specific reasons why you want to avoid it.


Question:
I have an enumeration of delivery status codes.  And when I save delivery data to the database they are stored with a foreign key to a table containing the same data (i.e. the same delivery codes)

What is the best strategy for keeping an enumeration in synch with data in a database?

Do you just remember to add to the enumeration when a new code is added to the database?

Or load the data into a dictionary when the application starts? And use the dictionary instead of an enumeration? Though this means that I don't have a strongly typed representation of the data - which I definitely want.

Or something else?

The data is not very volatile but new codes do get added once every blue moon

Would appreciate any suggestions.

thanks

Answer:
When I use a enumeration in the code, I usually store the formatted name as a varchar in the database rather than keep a table of the enumeration values in the database.  I realize that  this is not as normalized as one might like, but I believe it is better than trying to keep the database and my enumeration synched.  All that is needed is to format on insert/update and parse on select to reconstitute the value back into the enumeration.
I only do this when I believe that the enumeration is going to be fixed -- although, I too have made infrequent updates.  If I believe that it is likely that the data will be regularly updated, I won't use an enumeration and will have a separate table in the database with foreign key references.


Question:
I want to do this, but haven't figured it quite out yet...

    $(document).ready(function() {
        $("a.whateverclass").click(function() {
            $("div.whateverclass").show();
            return false;
        });

Basically when a link with a certain class is clicked all divs with that class are shown. The classes can be any class. And I won't know the name(s) of the classes in the application.js file so I need to match equal classes.

Answer:
```
```
$("a").click(function() {
        $("div." + $(this).attr('class')).show();
});
```
```


Question:
How to query to get count of matching words in a field, specifically in MySQL.
simply i need to get how many times a "search terms"appear in the field value.

for example, the value is "one two one onetwo" so when i search for word "one" it should give me 3

is it possible? because currently i just extract the value out of database and do the counting with server side language.

Thank you

Answer:
Are you looking to find a query that, given a list of words, returns the number of matching words in a database field?
eg:
Database table has
```
ID    Terms
1     cat, dog, bird, horse
```
then running a check on the words "cat, horse" returns 2?
If so, I suggest you do your checking
outside
of SQL, in whatever language you're doing the rest of your processing in. SQL isn't designed for this level of processing.
You could
possibly
use a stored procedure to cycle through what words you're needing to check, but I doubt it would be efficient or highly effective.
Of course, if I'm misinterpreting your request, I could be all wrong =)


Question:
One of the core fields present on several of my app's major database tables needs to be changed from varchar(5) to varchar(8). The list of stored procedures that depend on these tables is extremely long, not to mention the changes that would have to be made in my Data Access Layer (ASP.NET 2.0 DataSet with TableAdapters).

Is there any way to automatically (and safely) change the Type of the all-important field and have the changes propagate to all the stored procedures / Data Access Layer calls that depend on it?

I'm using a SQL Server 2005 database.

Answer:
You might be interested in this
essay
by Scott Ambler on Database Refactoring.  I think he also has a book on it.  The basic idea, I believe, will be to introduce a new column with the proper width, copy existing data to the new column, implement a trigger to synchronize any new inserts/updates, migrate your SP/DAL to use the new column, then remove the old column when you are completely done.  All new code uses the new column, obviously.  I don't know of any automated way to do the updates to your SP/DAL, unfortunately.


Question:
I'm getting the following error when trying to compile C++ projects using intel compiler version 10.0.025 on vista business edition (sp1) in vs2008:

unable to obtain mapped memory (see pch_diag.txt)

There is no such file as pch_diag, so that's a bit disheartening.

If I try to just use the microsoft compiler, all of my calls to intel's integrated performance primitives (ipp) are met with an access error into the program files directory where the ipp is stored.

Any ideas?

Thanks!

Answer:
It sounds like you are running the compiler as a standard user (good for you!), and the errors you get with the Microsoft compiler seem to point towards a permissions problem. You should use Windows Explorer to check the security properties for the directory you mentioned, if you haven't already. If the problem isn't apparent from the security properties page, here are some tools that may be useful for debugging permissions problems:
LUA Buglight
: a tool for finding the causes of "LUA" (Limited User Access) bugs
Sysinternals Process Monitor
: a tool for monitoring filesystem and registry access in real-time. You can filter out all processes other than the compiler, then look for "ACCESS DENIED" errors.


Question:
Using jQuery, how do you match elements that are prior to the current element in the DOM tree? Using prevAll() only matches previous siblings.

eg:

<table>
    <tr>
        <td class="findme">find this one</td>
    </tr>
    <tr>
        <td><a href="#" class="myLinks">find the previous .findme</a></td>
    </tr>
    <tr>
        <td class="findme">don't find this one</td>
    </tr>
</table>

In my specific case, I'll be searching for the first .findme element prior to the link clicked.

Answer:
Presumably you are doing this inside an onclick handler so you have access to the element that was clicked.  What I would do is do a prevAll to see if it is at the same level.  If not, then I would do a parent().prevAll() to get the previous siblings of the parent element, then iterate through those backwards, checking their contents for the desired element.  Continue going up the DOM tree until you find what you want or hit the root of the DOM.  This a general algorithm.
If you know that it is inside a table, then you can simply get the row containing the element clicked and iterate backwards through the rows of the table from that row until you find one that contains the element desired.
I don't think there is a way to do it in one (chained) statement.


Question:
How would you get a reference to an executing class several stack frames above the current one?  For example, if you have:

Class a {
    foo() {
        new b().bar();
    }
}

Class b {
    bar() {
        ...
    }
}

Is there a way to get the value that would be retrieved by using 'this' in foo() while the thread is executing bar()?

Answer:
```
this
```
is always a reference to the current instance of the object. So any usage of
```
this
```
in
```
foo()
```
will return an instance of Class A.


Question:
I'm trying to consolidate some build information by using a common makefile. My problem is that I want to use that makefile from different subdirectory levels, which makes the working directory value (pwd) unpredictable. For example:

# Makefile.common
TOP := $(shell pwd)
COMPONENT_DIR := $(TOP)/component
COMPONENT_INC := $(COMPONENT_DIR)/include
COMPONENT_LIB := $(COMPONENT_DIR)/libcomponent.a

If I include Makefile.common from a subdirectory, like so, the $(TOP) directory is incorrect and everything else follows suit:

# other_component/Makefile
include ../Makefile.common
# $(COMPONENT_LIB) is incorrectly other_component/component

What's the best way to get Makefile.common to use its own directory path instead of the more fickle pwd?

Answer:
Have you tried doing:
```
```
# Makefile.common
TOP ?= $(shell pwd)
COMPONENT_DIR := $(TOP)/component
COMPONENT_INC := $(COMPONENT_DIR)/include
COMPONENT_LIB := $(COMPONENT_DIR)/libcomponent.a

# other_component/Makefile
TOP ?= ..
include ../Makefile.common
```
```
Using the ?= construct will keep TOP from being redefined if it is already set.  You can set it to the appropriate value based on where you are in the tree when you invoke make.  I confess it's been awhile since I've used GNU make so this may not work or may need some tweaks.


Question:
Is there a particular scenario where a WriteOnly property makes more sense then a method? The method approach feels much more natural to me.

What is the right approach?

Using Properties:

Public WriteOnly Property MyProperty As String
   Set(ByVal value as String)
      m_myField = value
   End Set
End Property

public string MyProperty
{
   set{ m_myField = value;}
}

Using Methods:

Public Sub SetMyProperty(ByVal value as String)
   m_myField = value
End Sub

public void SetMyProperty(string value)
{
   m_myField = value;
}

EDIT
Just to clarify I am referring to "WriteOnly" properties.

Answer:
I think a property indicates something that can be read-only or read/write. The behaviour of a write-only property is not obvious so I avoid creating them.
As an example, setting a list of values in a drop-down on a view and accessing the selected item:
```
```
public interface IWidgetSelector
{
  void SetAvailableWidgets(string[] widgets);

  string SelectedWidget { get; set; }
}
```
```
Makes more sense than:
```
```
public interface IWidgetSelector
{
  string[] AvailableWidgets { set; }

  string SelectedWidget { get; set; }
}
```
```


Question:
Given my new understanding of the power of "includes" with PHP, it is my guess that ALL of my pages on my site will be .php extension.

Would this be considered strange?

I used to think that most pages would be .htm or .html, but in looking around the net, I am noticing that there really isn't any "standard".

I don't really think I have a choice, if I want to call my menus from a php file. It is just going to be that way, far as I can see... so just bouncing off you all to get a feel for what "real programmers" feel about such issues.

Answer:
It doesn't matter what your URLs end with,
```
.php
```
is fine, and fairly common.  The only thing people care about these days when it comes to URLs is making them pretty for Search Engine Optimisation, but that's a whole new question.


Question:
I'm at step 8 of the authentication overview found here: http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works

In particular, the user has logged into facebook via Facebook Connect and their web session has been created.  How do I use the facebook developer toolkit v2.0 (from clarity) to retrieve information about the user.  For example, I'd like to get the user's first name and last name.

Examples in the documentation are geared towards facebook applications, which this is not.

Update

Facebook recently released the Graph API. Unless you are maintaining an application that is using Facebook Connect, you should check out the latest API:   http://developers.facebook.com/docs/

Answer:
Facebook Connect actually isn't too difficult, there's just a lack of documentation.
Put the necessary javascript from here:
http://tinyurl.com/5527og
Validate the cookies match the signature provided by facebook to prevent hacking, see:
http://tinyurl.com/57ry3s
for an explanation on how to get started
Create an api object (Facebook.API.FacebookAPI)
On the api object, set the application key and secret Facebook provides you when you create your app.
Set
```
api.SessionKey
```
and
```
api.UserId
```
from the cookies created for you from facebook connect.
Once that is done, you can start making calls to facebook:
```
```
Facebook.Entity.User user = api.GetUserInfo();   //will get you started with the authenticated person
```
```


Question: When I create utility classes I typically create a class that has a private constructor and exposes all of it's methods and properties as static. What's the best approach for this? What's the difference between the way I do or creating a static class?

Answer:
Static classes are automatically sealed, so people can't inherit and override their behavior.
That is the only real difference (unless there is something special in the IL)
So if you use a static class, you save yourself the trouble of making the constructor private, and declaring the class sealed.
I would add, that defining a class as static, is "self-documenting" code. Users of your library will know that this class should not be instantiated, and only has static values.


Question: I want to generate a list in C#. I am missing python's list comprehensions. Is there a C# way to create collections on the fly like list comprehensions or generator expressions do in python?

Answer:
If you are using C# 3.0 (VS2008) then LINQ to Objects can do very similar things:
```
```
List<Foo> fooList = new List<Foo>();
IEnumerable<Foo> extract = from foo in fooList where foo.Bar > 10 select Foo.Name.ToUpper();
```
```


Question:
I have this html...

<select id="View" name="View">
   <option value="1">With issue covers</option>
   <option value="0">No issue covers</option>
 </select>

It won't let me insert code like this...

<select id="View" name="View">
   <option value="1" <% ..logic code..%> >With issue covers</option>
   <option value="0" <% ..logic code..%> >No issue covers</option>
 </select>

So whats the best way to set one to selected?

Update:
Without using the HTML Helpers.

Answer:
The "best" approach is probably to
use
the helpers:
```
```
var selectList = new SelectList(data, "ValueProp", "TextProp", data[1].ValueProp);
... Html.DropDownList("foo", selectList)
```
```
Where "data" could be an array of anonymous types, such as:
```
```
var data = new[] {
  new {Key=1, Text="With issue covers"},
  new {Key=0, Text="No issue covers"}
};
// todo: pick the selected index or value based on your logic
var selectList = new SelectList(data, "Key", "Text", data[1].Key);
Writer.Write(Html.DropDownList("foo", selectList));
```
```
Another approach might be to select the correct item client-side through script, but obviously that only works with script enabled.
Note it was missing comma and semicolon in data declaration, stopped it from working


Question:
Let's say that I have a record in the database and that both admin and normal users can do updates.

Can anyone suggest a good approach/architecture on how to version control every change in this table so it's possible to roll back a record to a previous revision?

Answer:
I think you are looking for versioning the content of database records (as StackOverflow does when someone edits a question/answer). A good starting point might be looking at some database model that uses
revision
tracking.
The best example that comes to mind is MediaWiki, the Wikipedia engine. Compare the database diagram
here
, particularly the
revision table
.
Depending on what technologies you're using, you'll have to find some good diff/merge algorithms.
Check
this question
if it's for .NET.


Question:
Searched stackoverflow for this and found no answer

Coming from Ruby On Rails and Rspec, I need a tool like rspec (easier transition). Installed it through PEAR and tried to run it but it's not working (yet)

Just wanna ask around if anyone's using it have the same problem, since it's not running at all

tried running it with an example from the manual - http://dev.phpspec.org/manual/en/before.writing.code.specify.its.required.behaviour.html

phpspec NewFileSystemLoggerSpec

returns nothing

even running

phpspec some_dummy_value

returns nothing

Answer:
I also couldn't get it to run, but you can also use BDD with PHPUnit. Check the
documentation
:


Question:
I have a site with over 100 pages. We need to go live with products that are soon available, however, many site pages will not be prepared at the time of release.

In order to move forward, I would like to reference a "coming soon" page with links to pages that are current and available.

Is there an easy way to forward a URL to a Coming Soon page?
Is this valid, or is there a better way?

Found this at:
http://www.web-source.net/html_redirect.htm

"Place the following HTML redirect code between the  and  tags of your HTML code.

   meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/index.html"

Does this negatively affect you if the search engines crawl through your site?

Thank you!

Answer:
Perhaps a better or "more correct way" would be to do the redirection at the header level. Using PHP, you would call
```
```
<?php
header("Location: http://www.yourdomain.com/index.html");
```
```
There's also ways to do this in Apache (assuming you are using it) and
```
.htaccess
```
-files. See
http://www.webweaver.nu/html-tips/web-redirection.shtml
for more info about that.


Question:
Please, I am new to webparts and I need help!!

I have a custom web part that I created. I added MS Ajax to it using an UpdatePanel which works fine. I add all my controls to the CreateChildControls method. As soon as I add a UpdateProgress control my page breaks with the following error:

Script controls may not be registered before PreRender

I do not use the OnPreRender event as what other posts suggest. Please, if anyone can give me advice it will be very much appreciated.

Thanks

Answer:
You might have forgotten to call the base method of an overrided event, which is not necessarily the OnPreRender event.
Check if the OnInit or OnLoad events are calling their base.On[...] method, e.g.:
```
```
protected override void OnLoad(EventArgs eventArgs)
{
    base.OnLoad(eventArgs);

    // your code...
}
```
```


Question:
There is a SqlServer2000 Database we have to update during weekend.

It's size is almost 10G.

The updates range from Schema changes, primary keys updates to some Million Records updated, corrected or Inserted.

The weekend is hardly enough for the job.

We set up a dedicated server for the job,
turned the Database SINGLE_USER
made any optimizations we could think of: drop/recreate indexes, relations etc.

Can you propose anything to speedup the process?

SQL SERVER 2000 is not negatiable (not my decision). Updates are run through custom made program and not BULK INSERT.

EDIT:

Schema updates are done by Query analyzer TSQL scripts (one script per Version update)

Data updates are done by C# .net 3.5 app.

Data come from a bunch of Text files (with many problems) and written to local DB.

The computer is not connected to any Network.

Answer:
What exactly does this "custom made program" look like? i.e. how is it talking to the data? Minimising the amount of network IO (from a db server to an app) would be a good start... typically this might mean doing a lot of work in TSQL, but even just running the app on the db server might help a bit...
If the app is re-writing large chunks of data, it might still be able to use bulk insert to submit the new table data. Either via command-line (bcp etc), or through code (
```
SqlBulkCopy
```
in .NET). This will typically be quicker than individual inserts etc.
But it really depends on this "custom made program".