q:
I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display:

Display(BasePage page) {
    ResourceManager manager = new ResourceManager(page.GetType());
}

In my project structure I have a default resource file and a psuedo-translation resource file. If I set try something like this:

Display(BasePage page) {
    ResourceManager manager = new ResourceManager(typeof(Login));
}

it returns the translated page.  After some research I found that page.GetType().ToString() returned something to the effect of "ASP_login.aspx" How can I get the actual code behind class type, such that I get an object of type "Login" that is derived from "BasePage"?

Thanks in advance!

[A]
It depends where you're calling Display() from. If you're calling it from the ASPX, then you'llse "ASP_login.aspx". If you're calling it from the code-behind (i.e. the Page_Load() method) you should get the Login page type.
Instead of passing the Page in, you might consider just using the Page property (i.e. this.Page.GetType()) which should always be the current page/codebehind type, if I recall correctly.
I should also make the point that you might consider moving this sort of stuff out of the ASPX/codebehind and into some sort of service. It's generally a good idea to minimize the amount of things you do in a code behind and, instead, push logic into a presenter class and follow the MVP pattern for ASP.NET Web Forms development.


q: Cells in DataGridViewComboBoxColumn have ComboBoxStyle DropDownList. It means the user can only select values from the dropdown. The underlying control is ComboBox, so it can have style DropDown. How do I change the style of the underlying combo box in DataGridViewComboBoxColumn. Or, more general, can I have a column in DataGridView with dropdown where user can type?

[A]
```
```
void dataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
    {
        DataGridViewComboBoxEditingControl cbo =
            e.Control as DataGridViewComboBoxEditingControl;
        cbo.DropDownStyle = ComboBoxStyle.DropDown;
    }
}
```
```
Problem with combobox and databound datagridview

s: huggingface

c: devops

d: intermediate


q: For the past few years whenever I learn something I tend to spend way too much time researching on the best materials for the subject than actually studying it. What should I do to get over this mentality? I am stuck. How to stop worrying about getting or using the BEST books, training videos and online materials on .net and just start learning?

[A]
There is no single best resource on anything. The best way to learn is to practice. Get any book to get yourself started. Then just start writing some code at home. Play with the language and the platform. Read blogs, browse the questions here. You will start discovering and learning nuggets of information.
Others mentioned buying Visual Studio 2008. It can be an expensive investment although it is totally worth it if you are a independent developer/consultant. However, if you just need something to get you started with coding, get the free
Visual C# Express
. You can always grow into the professional SKUs when you need it.


q:
Linux provides the stime(2) call to set the system time.  However, while this will update the system's time, it does not set the BIOS hardware clock to match the new system time.

Linux systems typically sync the hardware clock with the system time at shutdown and at periodic intervals.  However, if the machine gets power-cycled before one of these automatic syncs, the time will be incorrect when the machine restarts.

How do you ensure that the hardware clock gets updated when you set the system time?

[A]
After calling stime(), do this:
```
```
system("/sbin/hwclock --systohc");
```
```
See the hwclock(8) man page for more information.


q:
We have a few developers working on the same VS2005 solution, but our source control is very bad.  (Our company uses Harvest, which we give a vote of no confidence).

Right now, we're all just working off of the files on a shared lan drive.  Obviously, this causes some problems. But we think it's better than working locally, and tracking the files we touched in a spreadsheet and merging everything manually.  Does anybody have a strategy for merging our changes?

Some of the problems exist because of corporate beaurocracy (like mandating Harvest).  Those same policies prevent introducing new tools into our environment.  So, strategies that avoid buying/downloading new software would work best for us.

[A]
Treat the share as if it were your source control system. Make the share read-only, which will force developers to get local copies in order to make changes. You then have a somewhat stable version to compare against. This would help facilitate being able to do "merges". "Checking" code in would have to consist of some sort of backup strategy for the file (possibly making a copy of the file with a timestamp and username as part of the new file name) and replacing the original with the new version.
That being said, doing this type of activity without a real source control system that is reliable is going to be difficult and error-prone.


q:
Is there a way to start another application from within Compact .Net framework 1.0 similar to

System.Diagnostics.Process.Start

on the Windows side?

I need to start a CAB file for installation.


q: My PM just stopped by and he wanted a copy of all of our pages... Is there a way to do this for all pages without having to go to each one?

[A]
This is a really crazy idea but how about this:
Get a list of all the pages in an array and use JavaScript to load each page with an interval of like 20 seconds. When the page gets loaded fire the window.print() Javascript function. The print job will be finished within 20 seconds and the new page gets loaded and the same thing will again happen.


q: One of the responses to a question I asked yesterday suggested that I should make sure my database can handle UTF-8 characters correctly. How I can do this with MySQL?

[A]
Update:
Short answer - You should almost always be using the
```
utf8mb4
```
charset and
```
utf8mb4_unicode_ci
```
collation.
To alter database:
```
```
ALTER DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```
```
See:
Aaron's comment on this answer
How to make MySQL handle UTF-8 properly
What's the difference between utf8_general_ci and utf8_unicode_ci
Conversion guide:
https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-conversion.html
Original Answer:
MySQL 4.1 and above has a default character set of UTF-8. You can verify this in your
```
my.cnf
```
file, remember to set
both
client and server (
```
default-character-set
```
and
```
character-set-server
```
).
If you have existing data that you wish to convert to UTF-8, dump your database, and import it back as UTF-8 making sure:
use
```
SET NAMES utf8
```
before you query/insert into the database
use
```
DEFAULT CHARSET=utf8
```
when creating new tables
at this point your MySQL client and server should be in UTF-8 (see
```
my.cnf
```
). remember any languages you use (such as PHP) must be UTF-8 as well. Some versions of PHP will use their own MySQL client library, which may not be UTF-8 aware.
If you do want to migrate existing data remember to backup first! Lots of weird choping of data can happen when things don't go as planned!
Some resources:
complete UTF-8 migration
(cdbaby.com)
article on
UTF-8 readiness of php functions
(note some of this information is outdated)


q:
I need to detect the device resolution automatically, right now I have a global var & hardwire the resolution:

Public gDeviceRes As String = "640"
'Public gDeviceRes As String = "320"

then recompile for each device, does anyone have a quick snippit of code for this??

[A]
Depending on your exact needs, you can check the current screen dimensions with
Screen.PrimaryScreen
or you can P/Invoke
GetSystemMetrics
with SM_CXSCREEN or
GetDeviceCaps
with HORZRES. Vertical dimesions are similarly available.


q:
I am trying to write a stored procedure which selects columns from a table and adds 2 extra columns to the ResultSet. These 2 extra columns are the result of conversions on a field in the table which is a Datetime field.

The Datetime format field has the following format 'YYYY-MM-DD HH:MM:SS.S'

The 2 additional fields which should be in the following format:

DDMMM

HHMMT, where T is 'A' for a.m. and 'P' for p.m.

Example: If the data in the field was '2008-10-12 13:19:12.0' then the extracted fields should contain:

12OCT

0119P

I have tried using CONVERT string formats, but none of the formats match the output I want to get. I am thinking along the lines of extracting the field data via CONVERT and then using REPLACE, but I surely need some help here, as I am no sure.

Could anyone well versed in stored procedures help me out here?
Thanks!

[A]
If dt is your datetime column, then
For 1:
```
```
SUBSTRING(CONVERT(varchar, dt, 13), 1, 2)
    + UPPER(SUBSTRING(CONVERT(varchar, dt, 13), 4, 3))
```
```
For 2:
```
```
SUBSTRING(CONVERT(varchar, dt, 100), 13, 2)
    + SUBSTRING(CONVERT(varchar, dt, 100), 16, 3)
```
```


q:
I can currently to the following:

class SubClass extends SuperClass {
  function __construct() {
    parent::__construct();
  }
}

class SuperClass {
  function __construct() {
    // this echoes "I'm SubClass and I'm extending SuperClass"
    echo 'I\'m '.get_class($this).' and I\'m extending '.__CLASS__;
  }
}

I would like to do something similar with the filenames (__FILE__, but dynamically evaluated); I would like to know what file the subclass resides in, from the superclass. Is it possible in any elegant way?

I know you could do something with get_included_files(), but that's not very efficient, especially if I have numerous instances.

[A]
Uh, not really, that I can think of.  Each subclass would need to have an explicitly implemented method that returned
```
__FILE__
```
, which completely defeats the point of inheritance in the first place.
I'm also really curious as to why something like this would be useful.


q:
How can I AutoIncrement the assembly (build) number in Visual Studio?

Duplicate:

/questions/650/automatically-update-version-number

[A]
You can just use a wildcard in the
AssemblyVersionAttribute
:
```
```
[assembly: AssemblyVersion("1.0.*")]
```
```
This will cause build to be equal to the number of days since January 1, 2000 local time.


q: In this Wikipedia article about SVM there are a number of links to different implementations of MATLAB toolboxes for Support Vector Machines. Could anyone suggest which of these is best in terms of speed, ease of use, etc.?

[A]
I've used
libSVM
. It is pretty fast and easy, and provides some useful tools, too. There are some examples of it in use
here
. The other nice thing is that there are implementations in C++ and Java, too, so if you find yourself needing to develop outside of Matlab (to turn a prototype into something speedy, for example), you will have a familiar interface to work with.


q:
Does anyone know of a system for automatic error reporting in java? We have a server product that is installed on client servers. The idea is that our server would phone home with the details of an error to one of our servers, which then enters a bug in our bug tracker. Preferable, this would happen over http. It wouldn't happen for all exceptions, just the more serious and any that are not otherwise handled.

I'm trying to avoid rolling my own. We'll catch the exceptions ourselves, but I'm hoping this system would handle as much as possible between exception handler and the bug tracker back home.

[A]
Not conventional, but maybe you could use
Log4J
appenders to do it.
The
SocketAppender
allows you to send an event to a remote a log server.  You can also communicate via mail using SMTPAppender (a little tricky but easy to implement).  I don't know if there is any other appender to communicate with the server via HTTP (you could even implement it if needed, I suppose it is pretty easy).
Lets see if other users at stackoverflow have a better idea.


q: I know you can do a trick of putting an HTML element on top of a Silverlight app, but that will not work full screen.  Is there anyway to show an html page inside a Silverlight application?

[A]
The answer is, you can't. At least right now you can't - in the future it might be added but that's certainly not going to occur for a number of years (2.0 RTW was released today).
However, this link may be of some interest:
http://blogs.msdn.com/delay/archive/2007/09/10/bringing-a-bit-of-html-to-silverlight-htmltextblock-makes-rich-text-display-easy.aspx
It basically parses some "HTML text" and displays it as it can in a text block. Works for simple stuff, but may not be as complex as you need.


q:
I have found many pieces of documentations and recommendations about IEnumerator, IEnumerable, ICollection, IList and their generic counterparts. Sadly, I didn't find yet a tutorial or book which explains the whole hierarchy of interfaces, generic implementations of those interfaces and the best usage of each type of those.

What was your best source of knowledge about the generics, their interfaces, and examples of recommended usage of those in C#?

[A]
The main way I came to understand them was just by looking at their interfaces.
The inheritance goes like this:
IList : ICollection : IEnumerable
When you look up IEnumerable's interface, notice that it only has the bare minimum necessary to be able to loop through a bunch of items. It doesn't have count or anything else. IEnumerable works well even if what you're looking at is just a stream coming over a wire.
ICollection adds Count. If you are implementing some kind of collection, and if it's easy to know the size of it, then you should implement this. In this case, the generic interface is a little different. ICollection<T> also has methods to modify the collection by adding and removing members. An unordered set would be a good candidate for ICollection.
IList adds the ability to get and set collection members by index. Use this when the order of items is significant. When you have indexes, you can do things like swap the 4th and 5th items to change their order.


q:
I'm writing an ASP.NET application. I have a textbox on a webform, and I want to force whatever the user types to upper case. I'd like to do this on the front end. You should also note that there is a validation control on this textbox, so I want to make sure the solution doesn't interfere with the ASP.NET validation.

Clarification:
It appears that the CSS text transform makes the user input appear in uppercase. However, under the hood, it's still lower case as the validation control fails. You see, my validation control checks to see if a valid state code is entered, however the regular expression I'm using only works with uppercase characters.

[A]
Use a CSS style on the text box. Your CSS should be something like this:
```
```
.uppercase
{
    text-transform: uppercase;
}

<asp:TextBox ID="TextBox1" runat="server" Text="" CssClass="uppercase"></asp:TextBox>;
```
```


q:
In my user model, I have an attribute called "nickname" and validates as such:

validates_format_of :nickname, :with => /[a-zA-Z0-9]$/, :allow_nil => true

However, it is currently letting this string pass as valid:

a?c

I only want to accept alphanumeric strings - does anyone know why my regular expression is failing?  If anybody could suggest a better regular expression, I'm all ears.

[A]
You need to anchor the pattern on both sides:
```
```
/^[a-zA-Z0-9]+$/
```
```


q:
When I shrink a sql server database using the GUI (All Tasks->Shrink Database->Accept all defaults, click OK), it finishes quickly.

But if I run this command, it takes a very very long time.

DBCC SHRINKDATABASE('my_database')

What am I missing?

This is in SQL Server 2000.

[A]
If I recall correctly the interface will leave about 20% grown space, running DBCC SHRINKDATABASE without any parameters shrinks it to as small as possible.
I don't have Enterprise Manager handy to check the defaults.  But you should notice a smaller database file with the manual run than the GUI run, thus the time difference


q: How can I detect the current text formatting at the cursor position in a WPF RichTextBox?

[A]
Try the code below where rtb is the RichTextBox:
```
```
TextRange tr = new TextRange(rtb.Selection.Start, rtb.Selection.End);
object oFont = tr.GetPropertyValue(Run.FontFamilyProperty);
```
```


q:
Is it correct to say that typically user_dump_dest is on a local drive?

If so, are there issues with mounting a NAS volume to both Unix and Windows and pointing user_dump_dest at that?

If so, what are they?

Are any issues worth not doing this in prod?

[A]
Yes, typically (and by default), user_dump_dest is on a local drive.  I wouldn't expect there are any specific issues with putting it on NAS; but it would have all the potential issues that any application might:  (1) If the NAS could not be reached, Oracle would not be able to write out user dump files, and (2) the write latency would be increased.  The latency issue is probably only important if you're doing large-scale tracing to diagnose performance issues, as the write latency would impact the timing measurements.  I would expect that if the NAS because unreachable and Oracle tried to write to it, it would silently fail.
I don't think I would do it unless space constraints on the local disk forced me to.  But generally the contents of this directory should be insignificant relative to your data.


q: In a script, when a command-let or other executable statement errors out, is there a try/catch type of mechanism to recover from these errors? I haven't run across one in the documentation.

[A]
You use a
```
Trap [exception-type] {}
```
block before the code you want to handle exceptions for.


q:
I'm trying to subclass NSCell for use in a NSTableView. The cell I want to create is fairly complicated so it would be very useful if I could design it in Interface Builder and then load the NSCell from a nib.

Is this possible? How do I do it?

[A]
I do it like this:
```
```
/* example of a silly way to load a UITableViewCell from a standalone nib */

+ (CEntryTableViewCell *)cell
{
// TODO -- this is really silly.
NSArray *theObjects = [[NSBundle mainBundle] loadNibNamed:@"EntryTableViewCell" owner:self options:NULL];
for (id theObject in theObjects)
    if ([theObject isKindOfClass:self])
        return(theObject);
NSAssert(NO, @"Could not find object of class CEntryTableViewCell in nib");
return(NULL);
}
```
```
However it isn't very efficient and if you're loading lot of data it might hurt you. Of course you should be using a reuseIdentifier which should force this code to only run a handful of times per table.


q: How can I use HttpWebRequest (.NET, C#) asynchronously?

[A]
Use
```
HttpWebRequest.BeginGetResponse()
```
```
```
HttpWebRequest webRequest;

void StartWebRequest()
{
    webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}

void FinishWebRequest(IAsyncResult result)
{
    webRequest.EndGetResponse(result);
}
```
```
The callback function is called when the asynchronous operation is complete. You need to at least call
```
EndGetResponse()
```
from this function.


q:
Is there a way to automatically increment the "minimum required version" fields in a ClickOnce deployment to always equal the current build number? Basically, I always want my deployment to be automatically updated at launch.

I suspect I'm going to need a some pre-/post-build events, but I hope there's an easier way.

[A]
Are you looking for Application Updates?
Right clicking on the project in the Solution Explorer and then clicking Publish... is the wrong way to get Application Updates. You have to right-click your project and the click Properties, then click the Publish tab. Click the Updates... button and then check the "The application should check for updates" check box. There you can also specify a
minimum required version for the application.
(I haven't used that functionality but the Updates functionality is the core reason I use ClickOnce and it works great.)


q:
Rather than population said DOM object with an external page such as HTML CFM or PHP, what if I simply want to send text?

I've tried:

$("#myDOMObject").val("some text");

No errors, but the object value doesn't update either.

[A]
What element is "myDOMObject"? If it's a text input, your code should be working fine. If it's something else, use
```
$("#myDOMObject").text("some text");
```


q: Anyone know of a link to a good article/tutorial for getting started using jQuery for AJAX calls rather than ASP.NET AJAX? I'm trying to avoid using UpdatePanels entirely in this app, which I haven't been able to accomplish in the past.

[A]
Here are a few links:
A Look Into JQuery API (archived)
Using FireBug Profiler to Dig Deep into MS AJAX and JQuery API
(archived)
On Demand Loading Using JQuery Ajax API (archived)


q:
We have a customer that is trying to call our web service written in C# from PHP code. The web service call takes a long as parameter.

This call works fine for other customers calling from C# or Java but this customer is getting an error back from the call. I haven't debugged their specific call but I am guessing that the 64bit integer is getting truncated somehow from PHP. The customer says they are just making the web service call with a string but is there a wrapper in PHP that does type conversion. Could this be losing the number information?

Thanks for any info.

[A]
Most PHP installations won't support 64 bit integers - 32 is the max.  You can check this by reading the PHP_INT_SIZE constant (4 = 32bit, 8 = 64bit) or read the PHP_INT_MAX value.
```
```
<?php

echo PHP_INT_SIZE, "\n", PHP_INT_MAX;

?>
```
```
If the web service class he is using is trying to type-convert a string representation of a 64 bit integer, then yes, it's mostly likely being truncated or converted into a float.  You can sort of see this behavior with this simple test
```
```
<?php

echo intval( "12345678901234567890" );
// prints 2147483647, the max value for a 32 bit signed int.
```
```
Without knowing the details of his implementation, it's difficult to postulate on what a good solution/workaround might be.


q:
Has anyone had this problem.  You install Silverlight 2 RTW, and open your old project.  Everything loads fine in the designer.  You have to change a few properties of your DataGrid because "DisplayMemberBinding" was changed to "Binding".  Press F5, and receive a Win32 exception in IEXPLORE.EXE.  You go check out the event viewer and see this in the log:

Application: IEXPLORE.EXE

CoreCLR Version: 2.0.31005.0

Description: The process was terminated due to an internal error in the .NET Runtime at IP 7B8F898E with exit code 8013150a.

Any help?

[A]
Ok,
I'm happy to report I figured it out.  There are many breaking changes in Silverlight 2 RTW, I suggest you read this
document
.  The compiler doesn't tell you everything you need to know when you compile your solution, so it can still build but blow up when you run it.
The property causing the problem was "TextWrapping" on the "TextBlock" control.  The property was removed in RTW.  Why it was crashing the browser process, I have no idea, it's just a simple Xaml parse exception.  I only found this out when I put my "App.xaml.cs" into debug by setting a breakpoint in the constructor.
I hope this helps someone else.
Cheers!


q: Can anyone recommend a ready-to-use class/library compatible with C/C++/MFC/ATL that would parse iCal/vCal/Google calendar files (with recurrences)? It can be free or commercial.

[A]
there is a
parser in PHP for iCal
, you can downloaded and check the code to suit your language.
for vCal/vCard parsing
there's a C Library
.
for Google Calendar I couldn't find any exact answer, so, try to Google it.


q:
How do you get a pointer to the .text section of memory for a program from within that program?  I also need the length of the section to do a "Flash to Memory" compare as part of a continuous selftest that runs in the background.

The toolset automatically generates the linker .cmd file for the tools I'm using, and the Board Support Package for the board I'm using requires I use the generated .cmd file instead of making my own.  (No make file either to add a script to muck with it afterwords.)

Edit:
I'm working with a TI TMS 6713 DSP using the code composer 3.1 environment. The card I'm using was contracted by our customer and produced by another organization so I can't really point you to any info on it. However the BSP is dependant upon TI's "DSP BIOS" config tool, and I can't really fudge the settings too much without digging into an out of scope effort.

[A]
You need to put "variables" in the linker script.
In one of my projects I have this in one of my sections:
```
```
__FlashStart = .;
```
```
In the C program I have this:
```
```
extern unsigned long int _FlashStart;
unsigned long int address = (unsigned long int)&_FlashStart;
```
```


q:
So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields.

One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:

var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg");

As for static fields, is creating singelton-objects their best use?

[A]
It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning.  For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.
EDIT
: From stevemegson in the comments
A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.


q: I'd like the web service proxy class to wait more than 2 minutes

[A]
Just set the
timeout property
on the proxy


q:
What is the best or most concise method for returning a string repeated an arbitrary amount of times?

The following is my best shot so far:

function repeat(s, n){
    var a = [];
    while(a.length < n){
        a.push(s);
    }
    return a.join('');
}

[A]
```
```
function repeat(s, n) { var r=""; for (var a=0;a<n;a++) r+=s; return r;}
```
```


q:
I have two scripts that often need to be run with the same parameter:

$ populate.ksh 9241 && check.ksh 9241

When I need to change the parameter (9241 in this example), I can go back and edit the line in history.  But since I need to change the number in two places, I sometimes make a typo.  I'd like to be able to change the parameter just once to change it in both places.

[A]
One solution is to simply create a wrapper script (
populate_check.ksh
) that calls the scripts in turn:
```
```
r=$1
populate.ksh $r && check.ksh $r
```
```
Or for multiple parameters:
```
```
for r; do
   populate.ksh $r && check.ksh $r
done
```
```
For tasks that are more transient, you can also parametrize the command so that it's easier to edit in history:
```
```
$ r=9241; populate.ksh $r && check.ksh $r
```
```
Or to do several at once:
```
```
$ for r in 9241 9242; do populate.ksh $r && check.ksh $r; done
```
```


q:
Is there an Oracle equivalent to MS SQL's full text search service?

If so, has anyone implemented it and had good / bad experiences?

[A]
Oracle Text
is the equivalent functionality.
I've had good experiences with it.  Assuming that you are maintaining the text index asynchronously, that tends to be the first source of problems, since it may be a bit between a change being made and the index getting updated, but that's normally quite reasonable during normal operation.


q:
How do I determine if an object reference is null in C# w/o throwing an exception if it is null?

i.e. If I have a class reference being passed in and I don't know if it is null or not.

[A]
```
```
(YourObject != Null)
```
```
you can compare to null?
If it's null instead of throwing an exception you can initialize your object. You can use the Null Pattern.


q:
I'm working on a project in C#. The previous programmer didn't know object oriented programming, so most of the code is in huge files (we're talking around 4-5000 lines) spread over tens and sometimes hundreds of methods, but only one class. Refactoring such a project is a huge undertaking, and so I've semi-learned to live with it for now.

Whenever a method is used in one of the code files, the class is instantiated and then the method is called on the object instance.

I'm wondering whether there are any noticeable performance penalties in doing it this way? Should I make all the methods static "for now" and, most importantly, will the application benefit from it in any way?

[A]
It seems silly to me to create an object JUST so you can call a method which seemingly has no side effects on the object (from your description i assume this). It seems to me that a better compromise would be to have several global objects and just use those. That way you can put the variables that normally would be global into the appropriate classes so that they have slightly smaller scope.
From there you can slowly move the scope of these objects to be smaller and smaller until you have a decent OOP design.
Then again, the approach that
I
would probably use is different ;).
Personally, I would likely focus on structures and the functions which operate on them and try to convert these into classes with members little by little.
As for the performance aspect of the question, static methods should be slightly faster (but not much) since they don't involve constructing, passing and deconstructing an object.


q:
e.g, Is the user playing a movie full screen, or looking at powerpoint in full screen mode?

I could have sworn I saw a IsFullScreenInteractive API before, but can't find it now

[A]
Use GetForegroundWindow to get a handle to the window the user is working with.  GetClientRect will give the dimensions of the active part of the window sans borders; use ClientToScreen to convert the rectangle to monitor coordinates.
Call MonitorFromRect or MonitorFromWindow to get the monitor that the window is in.  Use GetMonitorInfo to get the coordinates of the monitor.
Compare the two rectangles - if the window rectangle completely covers the monitor rectangle, it's a full screen window.


q:
From an earlier post about trying to improve my sites performance I have been looking at HTTP compression. I have read about setting it up in IIS but it seems to be a global thing for all IIS application pools I may not be allowed to do this as there is another site running on it as well. I then saw some code to put in global.asax to achieve the same thing on a per website basis.

See Here http://www.stardeveloper.com/articles/display.html?article=2007110401&page=1]1

Is this as good as the setup in IIS? How dramatic is the effect? Any known issues?

[A]
I think the Global.asax option will be a good if you are in a shared hosting environment for example, where you don't have access to IIS configuration.
IIS 6 provides basic compression support, but if you're already in IIS 7, it provides you great
HTTP compression
support, you can define which files get compressed based on their MIME type in your configuration files...


q:
In Google Chrome, I can provide the command-line argument --user-data-dir="..." to have Chrome use a different directory for state like cookies, cache, and so forth.  This makes it possible to trivially load web pages from a "fresh" browser and simulate multiple independent users.

How can I do the same thing with Internet Explorer (either 6, 7, or 8)?

Edit:  It's looking like IE always uses the current user's profile, so you have to set up multiple users on the system and switch between them.  What a pain.

[A]
Heh.
With Chrome, FF, etc. I can actually have multiple
versions
on a single machine and test them without interference. IE requires me to set up VMs. Hence, the bulk of the code i churn out only gets tested rigorously on IE6 (since that's the install on the host OS). IE, if you'll pardon my slang, is a bitch - i've no idea how they manage to test it effectively within MS.
That said... You can
sort of
get what you want. If you're running XP and
aren't
on a domain, or are running Vista, you can configure "
Fast User Switching
". Then, configure multiple user accounts. Finally, log into each one, launch IE in each one, and rest assured they're using different profiles / data directories. Alternately, if you're running one of the Server versions of Windows (i'm partial to 2k3 r2), you can set up Terminal Services and simply use
RDC
to create multiple concurrent logins.


q: What is .net dynamic data and why would I use it?

[A]
From
ScottGu's Blog
a great article on how to use Dynamic Data.
One of the cool new features is something we call "ASP.NET Dynamic Data Support". In a nutshell this enables you to
  really quickly build data driven
  web-sites that work against a LINQ to
  SQL (and in the future LINQ to
  Entities) object model - and
  optionally allows you to-do this
  without having to build any pages
  manually.
See this
screencast
. It is very enlightening.
From more official
ASP.NET Dynamic Data site
:
ASP.NET Dynamic Data provides a
  framework that enables you to quickly
  build a functional data-driven
  application, based on a LINQ to SQL or
  Entity Framework data model. It also
  adds great flexibility and
  functionality to the DetailsView,
  FormView, GridView, and ListView
  controls in the form of smart
  validation and the ability to easily
  change the display of these controls
  using templates.


q:
I'm not sure why the TSpeedButton has this property but when a TSpeedButton is the only button of a given groupindex, it doesn't stay pressed, whether or not "AllowAllUp" is pressed.  Maybe a Jedi control would suffice, but hopefully there's some fix.  Any help or anecdotes are appreciated.

BTW, I'm (still) using Delphi 7, not sure if this is an across the board conundrum.

[A]
Hm, strange, I remember using this quite a few times with success. Perhaps you should try playing with the SpeedButton's
```
Down
```
property? I don't think it toggles automatically when you click it --- you should explicitly toggle
```
Down
```
, I guess...
[edit: replaced
```
Checked
```
with
```
Down
```
--- TSpeedButton doesn't have a
```
Checked
```
property, sorry!]


q: Can I set timeouts for JSP pages in tomcat either on a per page or server level?

[A]
For server level, you can try this.
you have to change
```
catalina.bat
```
/
```
catalina.sh
```
file
```
```
jvm OPTIONS : -Dsun.net.client.defaultConnectTimeout=60000 -Dsun.net.client.defaultReadTimeout=60000
```
```


q:
I have a web application (asp.net) where work items are submitted and allocated to users according to their workload.

A user's workload is calculated using an algorithm based on the number of items currently allocated to the user (and some other factors). Each new item is allocated to the user with the lowest current workload, increasing their workload. A user's workload decreases when they finish an item. Items will be submitted, allocated and finished concurrently - hence workload levels will be continually changing. Work items are stored in a SQL database.

I need a way to ensure that every allocation decision is made using an up-to-date picture of workload across the user base.

My idea is to provide a read/write synchronized store of workload information in the Cache.

Is this the best approach? Or should I use the database to control locking? How do I avoid bottle-necks in my application?

Advice much appreciated.

[A]
I would use a database to control this, as it's highly unlikely users will be completing work quickly enough to need a more real-time approach.
So I would have a series of tables, relating to work items, which you can query to calculate current work levels, and thus determine the next person to receive a particular work item.
You could then have a series of stored procedures to mark work items as complete, or to allocate a work item to someone.
To minimize bottle-necks ensure your database is normalised well, and your stored procedures do not use many tables, and this should ramp up nicely.
To check this, you could write some test harnesses to ensure the allocation of work items, and performance is what you desire under high usage.


q:
I have an "ldquo", "rdquo" and several other entities under my RSS feed. Seems like if I add

<!DOCTYPE rss [
  <!ENTITY % HTMLspec PUBLIC
  "-//W3C//ENTITIES Latin 1 for XHTML//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent">
  %HTMLspec;

below the xml tag and above the rss tag then I'll be able to include those entities. I added but it doesn't seem to work. Does anyone knows what I missing? Thanks

[A]
it doesn't seem likely that many feed readers will know what to do with that.  i would recommend sticking with numbered entity references.  for example, change
```
“
```
to
```
“
```
.  you can get the full entity reference
right here from w3c
.
additionally, you can read
this article
and
this one
which gives some good tips on this topic.


q:
I use emacs for viewing and editing code and other text files. I wanted to know if there is a way to search forward or backward for text which is marked in the current buffer. Similar to what I can do in notepad or wordpad. As in can I mark some text in the buffer and do a C-s or C-r and be able to search with the marked text without actually typing in the whole search text?

Thank you,

Rohit

[A]
Yes.
```
M-W
```
(to get a copy of the selected text)
```
C-s <RET> C-y <RET>
```
.  Then repeat
```
C-s
```
as needed.  Similarly for
```
C-r
```
.


q:
Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:

int[] terms;

for(int runs = 0; runs < 400; runs++)
{
    terms[] = runs;
}

For those who have used PHP, here's what I'm trying to do in C#:

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;
}

[A]
You have to allocate the array first:
```
```
int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
    terms[runs] = value;
}
```
```


q:
i'm having a problem to create a text_field without a method association. Maybe i even don't need it :-)

I have two radio_buttons associated to the same method:

<%= radio_button :comment, :author, "anonymous" %> Anonymous <br>
<%= radio_button :comment, :author, "real_name" %> Name <br>

What i would like to do is to have an text_field which when the user click on the radio_button "real_name" i can verify the value in this new text_field.

Basically my Controller would be something like:

@comment = Comment.new(params[:comment])

if @comment.author == "real_name"
 @comment.author = "value-from-the-new-textfield
end

There is any way to do it?

Regards,

Victor

[A]
If you want to generate a text_field without an associated object/method, use
```
text_field_tag
```


q:
I have a storyboard(1) that does some basic animations in 2 seconds.  I want the storyboard(1) to do all the property animations I have set it up to do (this all works fine).  But at 3 seconds into the storyboard(1) I want to begin storyboard(2) and exit storyboard(1) without user interaction at all.

Only thing I've seen that allows me to do this is when the user clicks on something.  I want this to be automatic based on the position of the current storyboard(1) timeline.

I hope this makes enough sense.  Please let me know if you need me to explain something in more detail.

Thanks.

Edit: Please post the answer in XAML or VB.net language. :)

[A]
Normally in order to control animations during the timeline you would use "keyframes". Keyframe animations allow you to define specific values for the property you are animating at specific times. In WPF every animation has a corresponding keyframe animation, like 'DoubleAnimation' has 'DoubleAnimationUsingKeyFrames'.
I don't think it's possible to start a new storyboard from within an animation. However you could achieve the same result by having both storyboards on the same timeline and starting storyboard(2) with a specific delay based on the duration of storyboard(1). Something like:
```
```
<StackPanel>
    <Rectangle Name="recProgressBar"
               Fill="Orange"
               Width="1"
               Height="25"
               Margin="20"
               HorizontalAlignment="Left" />
    <Button Content="Start Animation"
            Width="150"
            Height="25">
        <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="recProgressBar"
                                         Storyboard.TargetProperty="Width"
                                         From="0"
                                         To="250"
                                         Duration="0:0:2" />
                        <Storyboard BeginTime="0:0:3">
                            <ColorAnimation Storyboard.TargetName="recProgressBar"
                                            Storyboard.TargetProperty="Fill.Color"
                                            To="DarkGreen"
                                            Duration="0:0:1" />
                        </Storyboard>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Button.Triggers>
    </Button>
</StackPanel>
```
```
Here the color animation will start 1 second after the width animation has finished. It could be worth a try.


q:
I've got a PHP-based site where we allow users to upload a comma-separated text file of data to be imported by some server side scripts. However, sometimes we need to adjust the column order of the data that is uploaded, and it would be immensely helpful if we could identify the columns in the CSV file before the upload takes place.

The only way I can think of to access local file I/O is with a Java plugin or an embedded Flash script, and I'd much prefer the latter. Is there any way in Flash to select a text file on the local hard drive, and then use ActionScript to examine only the first line (which corresponds to the column headings, in this example)?

Sometimes these files can be >100 MB, so loading the whole thing into memory and then throwing out all but the first line probably wouldn't work efficiently, so I'm wondering if there's syntax in ActionScript to limit the amount of data read in at a time.

[A]
Flash movies don't have access to the local file system, except to do a file upload to the server.
I think your options are:
Process the class on the client side with Java (trivial), using an applet. However, as you rightly assert the user would need to grant permissions to the applet.
Provide a small client side application written with Adobe Air, using the
file system API
.


q:
I'm working on an application that makes extensive use of ComponentOne's C1FlexGrid. Of the dozens we use, three are missing their licenses.licx file and cause the demo splash screen to pop up while I'm starting the application.

Is there any way to determine which forms are causing this behavior. Short of checking hundreds of directories by hand, I don't see a way.

[A]
According to Microsoft documentation only the executable assembly requires a licenses.licx. Dll assemblies with forms in them will still create one but it is ignored. This has been my experience as well. I would suggest opening each form in the designer view and rebuilding while in that view. This will usually add any missing license entries to the licenses.licx. It will not, however, update existing entries. This can be a problem if you've updated your components. For ComponentOne, you can usually edit the licenses.licx and remove the version information after the assembly name. Some other third party components are more finicky and touching their version info causes errors when you compile.
In my opinion the .NET licensing framework is cumbersome and an unnecessary burden on developers. There are far easier ways to ensure component licenses are respected.


q: How do I connect to a MSSQL database using Perl's DBI module in Windows?

[A]
Couldn't find this anywhere reliable. Use Perl code similar to
```
```
use DBI;
my $dbs = "dbi:ODBC:DRIVER={SQL Server};SERVER={ServerName}";
my ($username, $password) = ('username', 'password');

my $dbh = DBI->connect($dbs, $username, $password);

if (defined($dbh))
{
    #write code here
    $dbh->disconnect;
}
else
{
    print "Error connecting to database: Error $DBI::err - $DBI::errstr\n";
}
```
```


q:
Suppose I have a dataset with those two immortal tables: Employee & Order

Emp -> ID, Name

Ord -> Something, Anotherthing, EmpID

And relation Rel: Ord (EmpID) -> Emp (ID)

It works great in standard master/detail scenario

(show employees, follow down the relation, show related orders),

but what when I wan't to go the opposite way (show Ord table with Emp.Name)?

Something like this:

<stackpanel>   // with datacontext set from code to dataset.tables["ord"]
   <TextBox Text="{Binding Something}"/>
   <TextBox Text="{Binding Anotherthing}"/>
   <TextBox Text="{Binding ???}"/> // that's my problem, how to show related Emp.Name
</stackpanel>

Any ideas? I can create value converter, but if I wan't to use dataset instance which I get from parent module it gets tricky.

[A]
Assuming that you are using a strongly-typed DataSet, in order to bind the TextBox to the 'EmpRow.Name' property, you will probably have to expose it as a property on the 'OrdDataTable' class.
Since Visual Studio generates the typed DataSet code with partial classes, you could add the property to the 'OrdDataTable' class this way:
```
```
using System.Data;

public partial class OrdDataTable : DataTable
{
    public string EmpName
    {
        get { return this.EmpRow.Name; }
    }
}
```
```
Then you would be able to bind to the 'EmpName' property of the 'OrdDataTable' object in the data context.


q:
I'm writing a simple CMS.

I want to be able to load a View, having it included inside a master page, and then scan the HTML so that I can replace some custom tags (like {{blog}} with my own blog output) and then serve it up to the browser.

How can I get access to the HTML from the ViewResult in order to intercept it?

[A]
Sounds like you want to write an
```
ActionFilterAttribute
```
.  This attribute has the following methods:
OnActionExecuting
- called just before the decorated action is executed
OnActionExecuted
- called after the action method is called, but before the
```
ActionResult
```
is rendered.
OnResultExecuting
- callled before the result is rendered
OnResultExecuted
- called after the result is rendered
There is an example here which returns either JSON or XML data depending on the "Content-type" header:
Create REST API using ASP.NET MVC that speaks both Json and plain Xml


q:
I want to get a list of files in a directory, but I want to sort it such that the oldest files are first.  My solution was to call File.listFiles and just resort the list based on File.lastModified, but I was wondering if there was a better way.

Edit: My current solution, as suggested, is to use an anonymous Comparator:

File[] files = directory.listFiles();

Arrays.sort(files, new Comparator<File>(){
    public int compare(File f1, File f2)
    {
        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
    } });

[A]
I think your solution is the only sensible way.  The only way to get the list of files is to use
File.listFiles()
and the documentation states that this makes no guarantees about the order of the files returned.  Therefore you need to write a
Comparator
that uses
File.lastModified()
and pass this, along with the array of files, to
Arrays.sort()
.


q:
I've a windows service that updates our product. It copies the product files into a temp directory, usually "C:\Windows\Temp", patches the binaries, and then uses MoveFileEx to copy the files back to the install directory on a reboot, usually "C:\Program Files\Product". The files in the install directory are inheriting their security attributes from the parent folder. After the copy, patch, and reboot, the files in the install directory are missing some ACLs. Specifically the files don't have the ACL for the Users group anymore so users can no longer run the program after the reboot.

Can anyone explain whats going on here? It seems that copying from the install directory to the temp directory, the files inherit the ACLs of the temp directory. On the MoveFileEx/Reboot, though, the files only inherit the ACLs that both the install and temp directories have in common.

[A]
In Windows if you copy a file the file takes on the ACLs of the destination directory.  If you move a file the ACL goes with it overriding any it might inherit from that directory.  I'm not sure how MoveFileEx might operate differently on a file.
The temp directory is usually located under the user profile (both %TMP% and %TEMP% usually point here) so copying files here will have permissions for that user.  Moving those files to the program files directory will take only that users rights with them and therefore only runnable by the installing user.


q: Reading on another forum I've came across the world of CSS Frameworks. The one I've been specifically looking at is BluePrint. I was wondering if anyone else had come across CSS frameworks, suggest which is the best and if they are worth the effort?

[A]
CSS 'frameworks' are completely missing the point.
CSS is not like JavaScript, where you can include a base library/framework and then call functions and objects from it to do higher-level work. All a CSS framework can give you is declarative rules: some default browser-rule-reset stuff, some class styles to be forced to author your page to, and layout rules using 'float' and 'clear'. You can write that in a few lines of CSS yourself rather than pulling in the bloat of a hundred framework rules.
The 'grid layout' stuff in particular goes back to the bad old days of mixing your presentation into your markup. 'div class="span-24"' is no better than a table, you'll have to go back in there and change the markup to affect the layout. And all the frameworks I've seen are based around fixed-pixel floated boxes, making it impossible to create a liquid layout accessible on a wide range of window sizes.
It's backwards authoring, of use only for someone too scared to write a CSS rule.


q: How can I make my compilation optimized for Windows 64 bit?

[A]
A managed project is automatically built according to the architecture selected => default C# project created on AMD64 will be AMD64, X86 on X86.  The native one is always 32-bit by default.
To explicitly set a platform:
1 open the solution explorer, select solution, right click->Configuration Manager.
2 go to 'Active Solution Platform', click New.
3 in the 'New Solution Platform' dialog that comes up select the new platform say Itanium. Set 'Copy Settings From' to 'Any CPU' which was the default setting in the 'Active Solution Platform'.
4 click OK.
This is from
WebLog


q:
I created an Interop user control in VS2005. When the user control is shown inside VB6, it does not pickup/use the XP styles (The buttons and the tabs look like VB6 buttons/tabs).

How do I get the XP styles to work with my control while it is in VB6?

[A]
This is what I've used:
```
```
::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%
```
```
If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas:
http://wittman.org/ziparcy/


q:
Here's another C#/.NET question based merely on curiousity more than an immediate need ...

If you had a Socket instance and you wanted to wrap it in the higher-level TcpClient class, is that possible and how would you do it?

Conversely if you have an instance of TcpClient, is it possible to get the underlying Socket?

[A]
From TcpClient to Socket is very easy.
```
tcpClientInstance.Client
```
is the underlying Socket instance.


q:
I have a report that uses a TChart that I am maintaining.  One of the TLineSeries that gets added automatically gets assigned the color clWhite, which is too close to the background (clBtnFace).

If I change it, then the next series that gets added takes clWhite.  So short of going back and changing it after all the other series are created, is there some way to tell the TChart that I don't want any of my series to be clWhite?

When a series is added to the TChart the TChart assigns it a color.  I want it to not assign clWhite.

[A]
Near as I can tell from the TeeCharts module; no you can't specify a color that it should not be as it ships.
You can programatically walk through all the TLineSeries entries making sure at run-time that they don't use clWhite.
Say you have an array of acceptable colors clArray, you can use the following code to set the colors of each of the tLineSeries entries at run time.
```
```
procedure TForm1.setColors(aChart: TChart; aColorArray: array of TColor);
var
  chi : Integer;
  coi : Integer;
begin
  coi := low(aColorArray);
  for chi := 0 to aChart.SeriesList.Count - 1 do begin
    aChart.SeriesList[chi].Color := aColorArray[coi];
    inc(coi);
    if coi > high(aColorArray) then
      coi := low(aColorArray);
  end;
end;

procedure TForm1.FormShow(Sender: TObject);
var
  ca : array of TColor;
begin
  setLength(ca, 3);
  ca[0] := clRed;
  ca[1] := clBlue;
  ca[2] := clGreen;
  setColors(Chart1, ca);
end;
```
```


q:
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouse on/off.

This happens on page ready and works just fine.

The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.

I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.

[A]
You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.
```
```
var mouseOverHandler = function() {
    // Do stuff
};
var mouseOutHandler = function () {
    // Do stuff
};

$(function() {
    // On the document load, apply to existing elements
    $('select').hover(mouseOverHandler, mouseOutHandler);
});

// This next part would be in the callback from your Ajax call
$("<select></select>")
    .append( /* Your <option>s */ )
    .hover(mouseOverHandler, mouseOutHandler)
    .appendTo( /* Wherever you need the select box */ )
;
```
```


q: I tried but I guess Message Box only works with win forms. What is the best alternative to use in web forms?

[A]
```
```
result = confirm('Yes or no question here.')
```
```


q:
I got a program with a fscanf like this:

fscanf(stdin, "%d %d,....

I got many fscanf and files that I'd like to test, the files are like this

10485770 15 51200000
 -2 10
10 10485760 10485760
10 10485760 10485760
10 10485760 10485760

Well my question is how can I tell to the program or the compiler to take the inputs not from the keyboard, but from those files. These programs are benchmarks and in the files I got the inputs, I'm sure there is a way to do this automatic because in some case there are many inputs. Thank you in advance.

[A]
Try freopen. Eg.
```
```
freopen( "somefile.txt", "r", stdin );
```
```


q:
I'm a PHP developer who knows a little bit of Ruby. I want to learn Ruby on Rails, but most of the resources I've come across treat RoR functionality as "magic" -- i.e., it has a certain internal consistency, but don't bother asking how it works in terms of Ruby, MySQL, etc.

Anyway, I want a deep understanding of how RoR works, the design decisions that went into building it, etc. In particular I'm interested in ActiveRecord, but really I'm looking for the whole package.

Any books / sites / advice welcome.

[A]
I found this site a good starting reference:
http://www.tutorialspoint.com/ruby-on-rails-2.1/index.htm
It assumes MySQL in its examples.
I am sure you can find heaps and heaps by just googling for "ruby on rails tutorials", though.


q:
I have a table in my database which stores a tree structure. Here are the relevant fields:

mytree (id, parentid, otherfields...)

I want to find all the leaf nodes (that is, any record whose id is not another record's parentid)

I've tried this:

SELECT * FROM mytree WHERE `id` NOT IN (SELECT DISTINCT `parentid` FROM `mytree`)

But that returned an empty set. Strangely, removing the "NOT" returns the set of all the non-leaf nodes.

Can anyone see where I'm going wrong?

Update: Thanks for the answers folks, they all have been correct and worked for me. I've accepted Daniel's since it also explains why my query didn't work (the NULL thing).

[A]
No clue why your query didn't work.  Here's the identical thing in left outer join syntax - try it this way?
```
```
select a.*
from mytree a left outer join
     mytree b on a.id = b.parentid
where b.parentid is null
```
```


q:
I'm trying to figure out how to consume a WCF service in BizTalk 2006 R2 (sending a request and receiving a response).

I've gotten as far as going through the "Add Generated Items" wizard.  Now I am trying to find out how to use the items it generated in an orchestration.

How should the request be made?

[A]
BizTalk is overkill if you are just using it to orchestrate WCF services. You can use WCF services in .NET 3.5 inside of Windows Workflow Foundation a bit more easily.
That said, here is a screencast that should help:
http://www.pluralsight.com/community/blogs/aaron/archive/2007/11/15/49172.aspx


q: What is the equivalent of the extended procedure 'xp_dirscan' in SQL Server 2005?

[A]
```
xp_dirscan
```
seems to be an extended stored proc that performs a recursive directory search. If you have access to the DLL you could register it as an extended stored proc in SQL 2005.
Alternatively, you could code something that performs the same action using
```
xp_cmdshell
```
or a managed extended stored proc.


q: How would one create a Singleton class using PHP5 classes?

[A]
```
```
/**
 * Singleton class
 *
 */
final class UserFactory
{
    private static $inst = null;

    // Prevent cloning and de-serializing
    private function __clone(){}
    private function __wakeup(){}

    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        if ($inst === null) {
            $inst = new UserFactory();
        }
        return $inst;
    }

    /**
     * Private ctor so nobody else can instantiate it
     *
     */
    private function __construct()
    {

    }
}
```
```
To use:
```
```
$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();
```
```
```
$fact == $fact2;
```
But:
```
```
$fact = new UserFactory()
```
```
Throws an error.
See
http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static
to understand static variable scopes and why setting
```
static $inst = null;
```
works.


q: How do you get the max value of an enum?

[A]
Enum.GetValues() seems to return the values in order, so you can do something like this:
```
```
// given this enum:
public enum Foo
{
    Fizz = 3,
    Bar = 1,
    Bang = 2
}

// this gets Fizz
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Last();
```
```
Edit
For those not willing to read through the comments: You can also do it this way:
```
```
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max();
```
```
... which will work when some of your enum values are negative.


q:
I'm running a MySQL database locally for development, but deploying to Heroku which uses Postgres. Heroku handles almost everything, but my case-insensitive Like statements become case sensitive. I could use iLike statements, but my local MySQL database can't handle that.

What is the best way to write a case insensitive query that is compatible with both MySQL and Postgres? Or do I need to write separate Like and iLike statements depending on the DB my app is talking to?

[A]
```
```
select * from foo where upper(bar) = upper(?);
```
```
If you set the parameter to upper case in the caller, you can avoid the second function call.


q: I'd like to upload (via ftp) a website when doing a release build in visual studio 2008.  I don't want any source code files to be uploaded and it would be nice to configure which folders should get uploaded.  I'm using either ASP.NET Web Applications or MVC.  How do I configure VS.NET to automatically upload (and overwrite) the last deployed website?

[A]
You can use the
Visual Studio Web Deployment Project
Add In from Microsoft.
I use this with MSBuild as part of CruiseControl, its very nice, and with some of the
Community Tasks for MS Build
you can do *.config (or any XML file) substitutions as part of your build process.
Edit: I also see that the MSBuild Community Tasks includes an FtpUpload action.  This should be exactly what you need.


q:
What's the ASP equivalent to PHP's .= when concatenating strings? I'm referring to asp NOT asp.net.

I meant to specify that I'm in a for-loop. So I want to know the equivalent for .= (in php) not standard concatenation.

Example:

For Each Item In Request.Form
    If (Item = "service") then
        For x=1 To Request.Form(item).Count
            service = "&service="&Request.Form(Item)(x)
        Next
    End If
Next

[A]
In VBScript:
```
```
Variable = Variable & "something more"
```
```
In JScript I believe you can use:
```
```
variable += "something more";
```
```
Specifically:
```
```
service = service & "&service=" & Request.Form(Item)(x)
```
```
assuming you want your result to look something like...
```
```
&service=blah1&service=blah2&service=blah3
```
```
Though you may need to URL encode your Request.Form(Item)(x) values because any "&" (and other characters) could really muck up what you are trying to do.  Also be careful when using unsanitized input like this directly from an HTML form, its very dangerous.


q:
I can get the executable location from the process, how do I get the icon from file?

Maybe use windows api LoadIcon(). I wonder if there is .NET way...

[A]
```
```
Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);
```
```


q:
How do you use enums in Oracle using SQL only? (No PSQL)

In MySQL you can do:

CREATE TABLE sizes (
   name ENUM('small', 'medium', 'large')
);

What would be a similar way to do this in Oracle?

[A]
Reading a bit about the
MySQL enum
, I'm guessing the closest equivalent would be a simple check constraint
```
```
CREATE TABLE sizes (
  name VARCHAR2(10) CHECK( name IN ('small','medium','large') )
);
```
```
but that doesn't allow you to reference the value by the index.  A more complicated foreign key relationship would also be possible
```
```
CREATE TABLE valid_names (
  name_id   NUMBER PRIMARY KEY,
  name_str  VARCHAR2(10)
);

INSERT INTO valid_sizes VALUES( 1, 'small' );
INSERT INTO valid_sizes VALUES( 2, 'medium' );
INSERT INTO valid_sizes VALUES( 3, 'large' );

CREATE TABLE sizes (
  name_id NUMBER REFERENCES valid_names( name_id )
);

CREATE VIEW vw_sizes
  AS
  SELECT a.name_id name, <<other columns from the sizes table>>
    FROM valid_sizes a,
         sizes       b
   WHERE a.name_id = b.name_id
```
```
As long as you operate through the view, it would seem that your could replicate the functionality reasonably well.
Now, if you admit PL/SQL solutions, you can create custom object types that could include logic to limit the set of values they can hold and to have methods to get the IDs and to get the values, etc.


q:
I have a Crystal Report that looks like:

Date | Person | Ticket | Summary

Date | Person | Ticket | Summary

Date | Person | Ticket | Summary

I would like it to look like:

Date

Person | Ticket | Summary

Person | Ticket | Summary

Date

Person | Ticket | Summary

All values are pulled from a MS SQL 2000 database, the application that will ultimately use the report is a VB 6 app that I unfortunately have to support.


q:
My organization is working on building RESTful webservices on JBoss appserver. The QA team is used to testing SOAP webservices so far using SoapUI. SoapUI has a new version that has REST capabilities. We're considering using that.

Are there any publicly available RESTful services available on the net for free that someone could test ?

What tools are available(and used) for testing RESTful web services ?

[A]
CURL Gets you halfway there.  The other half is checking the headers, response codes and entity content to make sure its good.  You could use a variety of tools for that (in shell scripting land, piping the header and contents to files, and diffing them might just do the trick).   It wouldn't be that difficult to further refine the toolset, maybe stacking curl up with the unit-testing framework of your choice.
I built a rest webservice testing panel with AJAX.  It wasn't that difficult at all actually.  You have some security issues to work out (i.e. making sure that you have the test suite on the same server, or maybe signed Javascript.)


q:
When I build XML up from scratch with XmlDocument, the OuterXml property already has everything nicely indented with line breaks.  However, if I call LoadXml on some very "compressed" XML (no line breaks or indention) then the output of OuterXml stays that way.  So ...

What is the simplest way to get beautified XML output from an instance of XmlDocument?

[A]
As adapted from
Erika Ehrli's
blog, this should do it:
```
```
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
}
```
```


q: I recently had to work on a project where the previous developer modified the wp-admin directory. It seems like a bad idea to me, since Wordpress is constantly updated. Am I just not at that level of expertise with modifying Wordpress?

[A]
Being open source, I think it's a common thing for software like WordPress to be modified and extended at any point.
To modify or not to modify is a choice between trade-offs. New features can be encapsulated as modules, which may, perhaps, cause their functionality to be less integrated than desired. However, fully integrating changes may hinder easily updating the software as new versions are released.
It does require that someone be very familiar with the software to modify the software directly, but this isn't necessarily a bad idea.
On a side note, I think modifying WordPress is almost a necessity, especially if you want it to have a decent architecture or to actually be secure (ok, that was a jab, sue me).


q:
I've been getting this undefined symbol building with this command line:

$ gcc test.cpp
Undefined symbols:
  "___gxx_personality_v0", referenced from:
  etc...

test.cpp is simple and should build fine.  What is the deal?

[A]
Use
```
```
g++ test.cpp
```
```
instead, since this is c++ code.
Or, if you
really
want to use
```
gcc
```
, add
```
-lstdc++
```
to the command line, like so:
```
```
gcc test.cpp -lstdc++
```
```
Running
```
md5
```
against the
```
a.out
```
produced under each scenario shows that it's the same output.
But, yeah,
```
g++
```
probably makes your world a simpler place.


q: I've looked at both the Named Parameter Idiom and the Boost::Parameter library. What advantages does each one have over the other? Is there a good reason to always choose one over the other, or might each of them be better than the other in some situations (and if so, what situations)?

[A]
Implementing the Named Parameter Idiom is really easy, almost about as easy as using Boost::Parameter, so it kind of boils down to one main point.
-Do you already have boost dependencies? If you don't, Boost::parameter isn't special enough to merit adding the dependency.
Personally I've never seen Boost::parameter in production code, 100% of the time its been a custom implementation of Named Parameters, but that's not necessarily a good thing.


q: I need to parse recipe ingredients into amount, measurement, item, and description as applicable to the line, such as 1 cup flour, the peel of 2 lemons and 1 cup packed brown sugar etc. What would be the best way of doing this? I am interested in using python for the project so I am assuming using the nltk is the best bet but I am open to other languages.

[A]
Can you be more specific what your input is? If you just have input like this:
```
```
1 cup flour
2 lemon peels
1 cup packed brown sugar
```
```
It won't be too hard to parse it without using any NLP at all.


q: When you create an instance of a class with the new operator, memory gets allocated on the heap. When you create an instance of a struct with the new operator where does the memory get allocated, on the heap or on the stack ?

[A]
As with all value types, structs always go where they were
declared
.
See this question
here
for more details on when to use structs.
And this question
here
for some more info on structs.
Edit:
I had mistankely answered that they
ALWAYS
go in the stack. This is
incorrect
.


q: Ok, so at some point in time, somebody checked in some files with names that require a case sensitive file system into the trunk of a repository that I constantly check out.  This of course leads to my local working copy locking up when I try to check it out (on my Windows computer).  Is there any way that I can set my local subversion copy so that it will ignore any files whose names differ only in case?

[A]
You can use the repository browser to remove/rename the offending file then update your working copy as per normal, fix up any references to the file you renamed that may need fixing up, and commit the fixes.
Then drag up a shotgun and shoot whoever did this in the first place. Case sensitivity abuse is one of the few bad smells that I have trouble forgiving.
(edit: This assumes TortoiseSVN, but the solutions work for any SVN implementation. You just don't get to use a pretty browser.)
Edit:
The other option is to rename the local version of the file, then use the repository browser to check out the second version of the clashing files, move things around, sort out references as above, then commit the changes.
This has the advantage of only requiring one commit, and not messing around with other people unnecessarily who may or may not be working with the two files.


q:
The following two forms of jQuery selectors seem to do the same thing:

$("div > ul.posts")

$("div ul.posts")

which is to select all the "ul" elements of class "posts" under "div" elements.

Is there any difference?

[A]
The first only selects ul.posts whose parentNode is div.
The second would also select:
```
```

```
```


q: Is there a acts as taggable solution out there for merb users already?

[A]
Looks like the answer to your question as asked is "No".
I did find
this
which at least shows some interest, but it's a few months old now with no apparent progress.
Maybe you could get some more information by rephrasing the question? Something like "what options are available for tagging in Merb?"


q:
"foo" instanceof String //=> false
"foo" instanceof Object //=> false

true instanceof Boolean //=> false
true instanceof Object //=> false
false instanceof Boolean //=> false
false instanceof Object //=> false

12.21 instanceof Number //=> false
/foo/ instanceof RegExp //=> true

// the tests against Object really don't make sense

Array literals and Object literals match...

[0,1] instanceof Array //=> true
{0:1} instanceof Object //=> true

Why don't all of them? Or, why don't they all not?

And, what are they an instance of, then?

It's the same in FF3, IE7, Opera, and Chrome. So, at least it's consistent.

[A]
Primitives are a different kind of type than objects created from within Javascript. From the
Mozilla API docs
:
```
```
var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)
```
```
I can't find any way to construct primitive types with code, perhaps it's not possible. This is probably why people use
```
typeof "foo" === "string"
```
instead of
```
instanceof
```
.
An easy way to remember things like this is asking yourself "I wonder what would be sane and easy to learn"? Whatever the answer is, Javascript does the other thing.


q:
I have an object, that is facing a particular direction with (for instance) a 45 degree field of view, and a limit view range. I have done all the initial checks (Quadtree node, and distance), but now I need to check if a particular object is within that view cone, (In this case to decide only to follow that object if we can see it).

Apart from casting a ray for each degree from Direction - (FieldOfView / 2) to Direction + (FieldOfView / 2) (I am doing that at the moment and it is horrible), what is the best way to do this visibility check?

[A]
Compute the angle between your view direction (understood as a vector) and the vector that starts at you and ends at the object. If it falls under FieldOfView/2, you can view the object.
That angle is:
```
```
arccos(scalarProduct(viewDirection, (object - you)) / (norm(viewDirection)*norm(object - you))).
```
```


q: Are there any limitations on the amount of memory that the Flash player can use? If you have a SWF that over time gets a lot of data from the server, then more and more data will be kept in memory. Is there a limitation on this?

[A]
Not in any version of Flash that runs on desktop PCs. As long as your application keeps using more memory, desktop Flash will keep requesting it from the OS, until the OS runs out of memory or something crashes. Of course you the developer should limit your memory usage as appropriate, but Flash won't force you to do so.
In Flash Lite (the mobile version designed for cell phones), the host application imposes preconfigured limits on memory usage, but that's probably not what you care about. :)


q:
I am trying to use a StreamReader to read a file, but it is always in use by another process so I get this error:

The process cannot access the file
  '\arfjwknasgmed17\C$\FLAG
  CONDITION\CP-ARFJN-FLAG.XLS' because
  it is being used by another process.

Is there a way I can read this without copying it?  Or is that my only option?

[A]
You can read the file only if the program that opened the file first specified read sharing rights on that file.
If the file does indeed have no read sharing rights though, you wouldn't be able to copy it in the first place.
You may not be able to access a file if you are specifying a sharing right that conflicts with the sharing right of a program that already has the file opened.  For example you can't grant write access if the program that already has it opened isn't granting write access.
If the program that opened the file in the first place supports Volume Shadow Copy (VSS), you can also use VSS to gain access to the file.
There are commercial software drivers that allow you to access such files, even when they are in use.  You used to be able to get Open File Manager by St-Bernards, and you can also  use
File Access Manager (FAM)
by VisionWorks Solutions Inc.  These drivers are typically OEM'ed to backup software companies for inclusion in their products.
VSS works by telling the program that has the file opened already that another program would like to read from the file.  VSS then does a copy of the file and lets you read from this copy.   VSS does not work for legacy applications.
FAM transparently works for legacy and non-legacy programs alike by specifying an 'allowed list' of applications that can access exclusively opened and locked files.  Only programs in this list are allowed access to these files.  When a file is being opened, it goes into cache mode so that you will obtain a copy of the file as it was when the 'backup/open' of the file started.   At this point the program that originally opened the file sees the file as it actually is, and the second program in the allowed list, sees the file as it was when the 'open/backup' of the file happened.  This ensures consistency of the file.


q:
Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:

http://www.google.com/

How do I get markdown to add  tags to URLs when I format a block of text?

[A]
This isn't a feature of Markdown -- what you should do is run a post-processor against the text looking for a URL-like pattern. There's a good example in the
Google app engine example code
-- see the
```
AutoLink
```
transform.


q:
I am getting this warning: "Missing XML comment for publicly visible type or member".

How to solve this?

[A]
Insert an XML comment. ;-)
```
```
/// <summary>
/// Describe your member here.
/// </summary>
public string Something
{
    get;
    set;
}
```
```
This may appear like a joke at the first glance, but it
may actually
be useful. For me it turned out to be helpful to think about what methods do even for private methods (unless really trivial, of course).


q:
I'm fairly new to Visual Studio and am wondering how best to plan for translation in a new project I'm starting. I need to provide English, German and French.

I have used Eclipse a lot in the past and there I just developed a new app and when it was complete I could just start a wizard to externalise strings into a resource file. The strings would be given to someone for translation.

What is your experience with VS? (I'm currently using VS2005 Express) What is your best advice for planning for translation?

[A]
Head to
Microsoft's I18n
page
There is a nice article on
msdn
about the more general aspects of i18n in the Microsoft world.
Visual Studio specifically:
MSDN VS
landing page
for internationalization (
your best bet
)
And
this
msdn article deals with it on a more technical level.


q:
How do I generate an audio sine or square wave of a given frequency?

I am hoping to do this to calibrate equipment, so how precise would these waves be?

[A]
You can use
NAudio
and create a derived WaveStream that outputs sine or square waves which you could output to the soundcard or write to a
WAV
file. If you used 32-bit floating point samples you could write the values directly out of the sin function without having to scale as it already goes between -1 and 1.
As for accuracy, do you mean exactly the right frequency, or exactly the right wave shape? There is no such thing as a true square wave, and even the sine wave will likely have a few very quiet artifacts at other frequencies. If it's accuracy of frequency that matters, you are reliant on the stability and accuracy of the clock in your sound card. Having said that, I would imagine that the accuracy would be good enough for most uses.
Here's some example code that makes a 1 kHz sample at a 8 kHz sample rate and with 16 bit samples (that is, not floating point):
```
```
int sampleRate = 8000;
short[] buffer = new short[8000];
double amplitude = 0.25 * short.MaxValue;
double frequency = 1000;
for (int n = 0; n < buffer.Length; n++)
{
    buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate));
}
```
```


q:
Kinda long title, but anyways...

I've been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams

http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html

http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html

But I can't seem to figure it out in C#.

StreamWriter writer = new StreamWriter(tcpClient.GetStream());
writer.Write(data.Length + data);

This doesn't work very well at all. Could someone give me a nudge in the right direction?

[A]
Instead of
```
data.Length
```
, try:
```
```
writer.Write(chr(data.Length) + data);
```
```
This will prefix every data block with one byte indicating its length (up to 255 bytes long). As you requested, this is only a nudge. :)
Update: I just remembered that C# is all Unicode and stuff, so chr() probably gives you more than one byte. Adjust to fit.


q:
How do you get an instance of the actionscript class Class from an instance of that class?

In Python, this would be x.__class__; in Java, x.getClass();.

I'm aware that certain terrible hacks exist to do this, but I'm looking for a built-in language facility, or at least a library routine built on something reliable.

[A]
Any reason you couldn't do this?
```
```
var s:Sprite = new flash.display.Sprite();

var className:String = flash.utils.getQualifiedClassName( s );
var myClass:Class = flash.utils.getDefinitionByName( className ) as Class;

trace(className ); // flash.display::Sprite
trace(myClass); // [class Sprite]

var s2 = new myClass();
trace(s2); // [object Sprite]
```
```
I don't know a way to avoid round-tripping through a String, but it should work well enough.


q: I have an ArrayList<String>, and I want to remove repeated strings from it. How can I do this?

[A]
If you don't want duplicates in a
```
Collection
```
, you should consider why you're using a
```
Collection
```
that allows duplicates. The easiest way to remove repeated elements is to add the contents to a
```
Set
```
(which will not allow duplicates) and then add the
```
Set
```
back to the
```
ArrayList
```
:
```
```
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
```
```
Of course, this destroys the ordering of the elements in the
```
ArrayList
```
.


q:
I'm writing a C++ client which is using libcurl for communicating with a PHP script.

The communication should be session based, and thus the first task is to login and make the PHP script set up a session.

I'm not used to working with sessions either from C++ or PHP. I basically know that it has to do with cookies and communicating session id.

I can't find any example on the curl homepage which demonstrates a simple session management use case.

I'm assuming it has something to do with one or many of the following options in curl:

CURLOPT_COOKIE
CURLOPT_COOKIEFILE
CURLOPT_COOKIEJAR
CURLOPT_COOKIESESSION
CURLOPT_COOKIELIST

But I can't really see the big picture just from the documentation of CURLOPT_COOKIESESSION for instance.

Anybody who has done this, please share a simple piece of code which shows the concept.

Regards

Robert

[A]
A session in PHP has the purpose of preserving some state over several requests, since HTTP in itself is stateless. To get a session from PHP, simply request a php page that starts a session, and keep the cookie you get back for subsequent requests.
Starting a session in php is simple - call the session_start() function. That function will resume an existsing session if the cookie exists in the request. When the session is started, persistent variables can be set using the superglobal array $_SESSION. It's a good idea to store a 'is logged in'-token there =) To end the PHP session, set $_SESSION to array(), so that the token is destroyed.


q:
how can i figure out the last modified date of a html file im importing into my web app?

The html file is on another server and different users can make updates, when i retrieve the page i want to be able see when it was last updated so i can label the updated date on my homepage. I

[A]
Use the
```
document.lastModified
```
Javascript property.
quirksmode has a nice function to format the date too:
http://www.quirksmode.org/js/lastmod.html


q:
In my asp.net mvc app I want to check if a certain url returns a valid response.
Therefor I send the url to a method that tests the HttpWebRequest.GetResponse()

On my dev server (vs2008) it works just fine.
When deployed on production server however, it returns a Bad Request.
The method is never hit and my asp.net custom error pages are not used.

any ideas?

[A]
Perhaps you are running into the
ValidateRequest
feature of ASP.NET? You can disable this for the page in question by modifying the first line in the aspx file to have the ValidateRequest="false" parameter.
Example:
```
```
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %>
```
```
You probably don't want to leave it in that state though, as the request validation helps prevent XSS attacks. Using HttpUtility.UrlEncode may also be worth trying, if you aren't already.


q:
Since some time, my Delphi debugger became much slower than I was used to before.

I noticed this in both Delphi 2007 and 2009, so it seems it's something outside of Delphi itself...

What causes this behaviour, and how can I prevent this?

[A]
After weeks of searching for an answer, I found this Microsoft knowledge base article fixes my problem :
http://support.microsoft.com/kb/321410/nl
The point is, I installed Microsoft Script Editor a while back to do some server-side javascript debugging. This also installs a service called "Machine Debug Manager" (Mdm.exe), which is the cause for the slowdown. After disabling this service, debugger speed returned to normal!


q:
I know a role name and want to find all users in this role.
How do I acheive this in SQL Server 2000 (in the SQL script, not in Management Studio or other tool)?

[A]
You can use the following stored procedures:
For fixed server roles, the stored procedure is
sp_helpsrvrolemember
:
```
```
exec sp_helpsrvrolemember 'role'
```
```
For general roles, the stored procedure is
sp_helprolemember
:
```
```
exec sp_helprolemember 'role'
```
```


q:
I would like to create (in code) tree of controls that would render as a table with several TBODY tags, i.e.:

<TBODY>
    <TR>
        <TD></TD>
    </TR>
    <TR>
        <TD></TD>
    </TR>
</TBODY>

I tried both Table and HtmlTable controls but had no success. Any clues?

[A]
How are you generating your data? You could use a templated control like a Repeater or ListView as that gives you full control of the HTML you're generating.
If you're wanting to create the controls purely in C# you can use the HtmlGenericControl (
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspx
), you'll need to provide a tag type in the constructor.


q:
So there seems to be this problem with GNU Make's $(wildcard) function keeping a directory open on Windows. See (unasnwered) post "make is holding a directory open". Google does not provide much information on the topic.

In short: the Makefile uses the $(wildcard) function at some point, and keeps a directory open, which typically prevents the "make clean" rule to do its work correctly. Re-running "make clean" a second time usually solves it.

I'm using GNU Make version 3.81 under a standard DOS-Box. The author of the post linked to above is using Cygwin.

Has anyone found a fix for this?

[A]
Sounds like a file descriptor leak, all right -- harmless for very-short-lived processes (like make) on UNIX, but a right PITA on Windows.
As this is allegedly a bug in make, as opposed to a problem with its usage, it should be addressed first by validating that it still exists when built from source on the newest upstream version, and then by
filing a bug report
with the GNU make project (or with any distributor with whom you have an appropriate support contract), or diving into the source and attempting to fix it yourself.
It wouldn't hurt to try to reproduce on Linux -- checking for file descriptor leaks are much easier here, as one can just look at
```
/proc/self/fd
```
(or, for a child of make,
```
/proc/$PPID/fd
```
) for things that don't belong.


q:
I am cloning a hidden table row then populating it and after validation I want to show the row using a jquery effect ... say .show("slow")

var baseRow = $("#tasks tr#baseTaskLine");
var newRow = baseRow.clone();
var lastRow = $("#tasks tr[id^='TaskLine_']" + dayClass + ":last");

var newRowId;
if (lastRow.length == 0) {
   newRowId = "TaskLine_new0";
}
else {
   newRowId = "TaskLine_new" + lastRow[0].rowIndex;
}

newRow.attr("id", newRowId);

:
[populate new row]
:

if (lastRow.length == 0) {
   baseRow.after(newRow);
}
else {
   lastRow.after(newRow);
}
newRow.hide();
:

:
[validate via webservice call]
:
newRow.show("slow");

This does show the row but it appears instantly. I have tried hiding all the <td> elements of the row then showing those and that does seem to work but some strange styles get added to each <td> which interfere with the formatting i.e. style="display: block;"

[A]
This is not going to work this way. Table rows and cells are not meant to be displayed as blocks so the show/fade effects are not going to work on table rows directly.
You could, however, put a
 in each of the cells, something like this:
```
```

Cell1:1

Cell2:1

Cell1:2

Cell2:2

```
```
and then to the following:
```
```
$('#row2 td div').show('slow');
```
```
This will yield the expected behaviour.


q: How can I move items from one list box control to another listbox control using JavaScript in ASP.NET?

[A]
If you're happy to use jQuery, it's very, very simple.
```
```
$('#firstSelect option:selected').appendTo('#secondSelect');
```
```
Where #firstSelect is the ID of the select box.
I've included a working example here:
http://jsbin.com/aluzu
(to edit:
http://jsbin.com/aluzu/edit
)


q:
So I need to update a text field.  Neither the UPDATE statement or the WRITETEXT statement work when used below

CREATE TABLE MyTable (IDField int, MyField text)
INSERT INTO MyTable (IDField) SELECT 1

DECLARE @Data1 varchar(8000), @Data2 varchar(8000), @ptrval binary(16)

SELECT @Data1 = REPLICATE('1',8000)
SELECT @Data2 = REPLICATE('2',8000)

-- this sets MyField to string of only 8000 characters
UPDATE MyTable SET MyField = @Data1 + @Data2 WHERE IDField = 1

SELECT @ptrval = TEXTPTR(MyField )
FROM MyTable
WHERE IDField = 1

-- this causes an error: Incorrect syntax near '+'.
--WRITETEXT MyTable.MyField @ptrval @Data1 + @Data2

How am I supposed to do this when local variables cannot be of type TEXT?  (If I had SSQL Server 2005 I would use varchar(max) - but I don't)

[A]
Try using UPDATETEXT instead
```
```
WRITETEXT MyTable.MyField @ptrval @Data1
UPDATETEXT MyTable.MyField @ptrval 8000 NULL @Data2
```
```
The insert offset is zero based so 8000 should write into the 8001st character.
The delete offset is null as a value of NULL deletes all data from the insert_offset position to the end of the existing text.
Ref:
http://msdn.microsoft.com/en-us/library/ms189466.aspx
Do not forget nvarchar (which you should use with ntext field) have a maximum capacity of half the varchar fields that you are using so your block sizes need to be reduced to 4000 in that case.


q:
How can I turn off certificate revocation for a WCF service's client?
The client proxy was generated by wsdl.exe and inherits SoapHttpClientProtocol.

[A]
I think you're looking for
```
ServicePointManager.ServerCertificateValidationCallback
```
:
http://msdn.microsoft.com/en-gb/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx
Which takes a
```
RemoteCertificateValidationCallback
```
Delegate:
http://msdn.microsoft.com/en-gb/library/system.net.security.remotecertificatevalidationcallback.aspx
I've never dealt with a revoked certificate before (I have hand to handle other issues such as expired SSL's), but I'm guessing you'd just do something like:
```
```
class Program
{
    static void Main(string[] args)
    {
        ServicePointManager.ServerCertificateValidationCallback +=
            new RemoteCertificateValidationCallback(ValidateCertificate);

        // Do WCF calls...
    }

    public static bool ValidateCertificate(object sender, X509Certificate cert,
                              X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if(sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
        {
            foreach(X509ChainStatus chainStatus in chain.ChainStatus)
            {
                if(chainStatus.Status == X509ChainStatusFlags.Revoked)
                {
                    return true;
                }
            }
        }

        /*
         WARNING!

         You should perform other cert validation checks here and not blindly
         override your cert validation by returning true.

         Otherwise the secure channel between your client and service
         may not be secure.

        */

        return false;
    }
}
```
```


q:
What does it mean:
"First-chance exception at  in : 0x000006BA: The RPC server is unavailable"
?

this debug message appears in Debug output of visual studio debugger when I using socket connection, but I don't know what operation initiates this message...

[A]
"First-chance exception" occurs when the exception is thrown, before anyone catches it. Usually, these are benign, and can be ignored (because someone is going to catch it).
You can get the debugger to break when the exception is thrown, whether or not someone later catches it.
In Visual Studio, this is done by choosing Debug / Exceptions and putting a check in the "Thrown" column for the exceptions you're interested in. Then, when the exception is thrown, the debugger will break at the relevant place.
Note that you might end up in the middle of nowhere (i.e. in disassembly), so make sure that you've got your debugging symbols configured correctly.
Also note that some exceptions aren't in the list by default, so you'll have to click the "Add..." button in that dialog.


q:
I've got two applications I'm developing using Qt on windows. I want the user to be able to press a button in one application which makes the other application come to the foreground. (The programs communicate using QLocalSocket and named pipes.)

Currently I'm using Qt's QWidget::activateWindow() which occasionally brings the application to the foreground, but most of the time it just highlights the program on the taskbar.

Can someone please tell me how to do this, preferably using Qt although failing that using the WIN32 API would be fine.

Unfortunately, I couldn't find a way to do this only with Qt. I solved it using Chris Becke's suggestion of calling SetForegroundWindow from the currently active application.

[A]
On top of the
```
QWidget::activateWindow
```
method, you should call
```
QWidget::raise
```
!
This is what is said
here
.


q:
In writing some test code I have found that Selector.select() can return without Selector.selectedKeys() containing any keys to process. This is happening in a tight loop when I register an accept()ed channel with

SelectionKey.OP_READ | SelectionKey.OP_CONNECT

as the operations of interest.

According to the docs, select() should return when:

1) There are channels that can be acted upon.

2) You explicitly call Selector.wakeup() - no keys are selected.

3) You explicitly Thread.interrupt() the thread doing the select() - no keys are selected.

If I get no keys after the select() I must be in cases (2) and (3). However, my code is not calling wakeup() or interrupt() to initiate these returns.

Any ideas as to what is causing this behaviour?

[A]
Short answer: remove
```
OP_CONNECT
```
from the list of operations you are interested in for the accepted connection -- an accepted connection is already connected.
I managed to reproduce the issue, which might be exactly what's happening to you:
```
```
import java.net.*;
import java.nio.channels.*;

public class MyNioServer {
  public static void main(String[] params) throws Exception {
    final ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(true);
    serverChannel.socket().bind(new InetSocketAddress("localhost", 12345));
    System.out.println("Listening for incoming connections");
    final SocketChannel clientChannel = serverChannel.accept();
    System.out.println("Accepted connection: " + clientChannel);

    final Selector selector = Selector.open();
    clientChannel.configureBlocking(false);
    final SelectionKey clientKey = clientChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
    System.out.println("Selecting...");
    System.out.println(selector.select());
    System.out.println(selector.selectedKeys().size());
    System.out.println(clientKey.readyOps());
  }
}
```
```
After the above server receives a connection, the very first
```
select()
```
on the connection exits without blocking and there are no keys with ready operations. I don't know why Java behaves in this way, but it appears many people get bitten by this behavior.
The outcome is the same on Sun's JVM 1.5.0_06 on Windows XP as well as Sun's JVM 1.5.0_05 and 1.4.2_04 on Linux 2.6.


q:
I have a JSP accessed through JBoss. It renders a list (a search result).
If the response gets big, approximately larger than 200k the response is truncated. I can see how the page just ends in the middle of a tag in Firefox. IE totally freaks out an so does Fiddler.
Responses smaller than 200k are no problem.

Anyone has experienced this?
I don't know where to look for the problem... any suggestions are welcome.

[A]
Maybe it has something to do with flushing the buffer? thath number (200k) ringed the bell of a problem I had with it. Place a page directive like this:
```
```
<%@page buffer="500kb" autoFlush="true" %>
```
```
and play with the buffer size and autoflush values.


q: Why does a Boolean consume 4 bytes and a char 2 bytes in the .NET framework? A Boolean should take up 1bit or at least be smaller than a char.

[A]
It is a question of memory alignment.  4-byte variables work faster than 2-byte ones.  This is the reason why you should use int instead of byte or short for counters and the like.
You should use 2-byte variables only when memory is a bigger concern than speed.  And this is the reason why char (which is Unicode in .NET) takes two bytes instead of four.