Question: On the .Net WebBrowser control the only way I can see to load a page to it is to set the URL property.  But I would like to instead give it some HTML code that I already have in memory without writing it out to a file first.  Is there any way to do this?  Or are there any controls that will do this?

Answer:
You want the DocumentText Property:
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documenttext.aspx
?
from
http://www.codeguru.com/forum/showpost.php?p=1691329&postcount=9
:
Also you should provide a couple things:
Don't set DocumentText in the constructor. Use Form_Load or your own method.
If you set DocumentText in the constructor, you will not be able to set it again anywhere in the application. Be sure to check that the Form Designer hasn't set it either.
You can only set DocumentText once per method call. This is odd and most likely a bug, but it's true.
For example: setting DocumentText in a for-loop will only set properly on the first iteration of the loop.
You can however, create a small method to set DocumentText to the passed in string, then call this method in a for-loop.


Question:
Does anyone have a good technique (or tutorial) to implement rulers within a C# Windows Forms application? I want to display an image while showing rulers that indicate your mouse position to allow a more accurate positioning of the cursor. Just like the image below:

I tried using splitter controls to hold the tick marks but I don't know how to make the top-left the gray blank area. Any advice? Thanks.

Answer:
I would build a custom control to do this in both X and Y location and use two controls.
The control would have to override
```
Paint()
```
and use GDI methods to display the tick marks, it would then capture mouse events and update locations appropriately.


Question:
We have a Cash flow report which is basically in this structure:

Date |Credit|Debit|balance|
09/29| 20   | 10  | 10    |
09/30| 0    | 10  | 0     |

The main problem is the balance, and as we are using a DataSet for the Data, it's kinda hard to calculate the balance on the DataSet, because we always need the balance from the previous day.

Also this data comes from several tables and it's been hard to maintain this procedure, because the database metadata is changing frequently.

Anyone could give me some possible different solutions? for the problem?

This report is being displayed on a DataGrid.

Answer:
On the code side of things, you've got two relatively easy options, but they both involve iterating through the dataset.
option 1: For loop prior to databinding.
For each row in the datatable, add/subtract the credit/debits to the previous row's balance and assign it to the appropriate cell of your datatable.
Option 2: calculate during databinding.
First you'd have a global variable that you could hold your value in. Set it to zero right before the databind. For each item or altitem, add/subtract the credit/debits to the global variable and assign it to the appropriate cell of your datagrid.


Question:
I have tried this...

Dim myMatches As String() =
System.Text.RegularExpressions.Regex.Split(postRow.Item("Post"), "\b\#\b")

But it is splitting all words, I want an array of words that start with#

Thanks!

Answer:
Since you want to include the words in the split you should use something like
```
```
"\b#\w+\b"
```
```
This includes the actual word there in the expression. However I'm not sure that's what you want. Could you provide an example of input and the desired output?


Question: I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the  tag and for a page header. When I tried to do this with two  tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page?

Answer:
Title is actually an attribute on content pages, so you do something like:
```
```
<%@ Page Language="C#" MasterPageFile="~/default.master" Title="My Content Title" %>
```
```
on the content page. To get that into a header, on the master page just render the page title:
```
```

<%= this.Page.Title %>

```
```


Question:
Does anyone know how to get the name of the TARGET (/t) called from the MSBuild command line? There are a few types of targets that can be called and I want to use that property in a notification to users.

Example:

msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV

I want access to the target words ApplicationDeployment in my .Proj file.

Is there a property I can access? Any clue how to do this?

EDIT: I do not want to have to also pass in a property to get this.

UPDATE: This is based on deployment scripts using MSBuild scripts. My build server is not used for deploying code, only for building. The build server itself has build notifications that can be opted into.

Answer:
I'm not sure how to do exactly what you ask, but could you pass that string using the /p option?
```
```
msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV;MyValue=ApplicationDeployment
```
```
The only other way I can see to do it is to use a conditional property in each target, and thus establish the first target to be invoked.
```
```
<Target Name="ApplicationDeployment">
<PropertyGroup>
  <InvokedTarget Condition="'${InvokedTarget}'==''">ApplicationDeployment</InvokedTarget>
</PropertyGroup>

...
</Target>
```
```


Question:
How can I limit my post-build events to running only for one type of build?

I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode.

Answer:
You can pass the configuration name to the post-build script and check it in there to see if it should run.
Pass the configuration name with
```
$(ConfigurationName)
```
.
Checking it is based on how you are implementing the post-build step -- it will be a command-line argument.


Question:
mysql5.0 with a pair of databases "A" and "B", both with large innodb tables. "drop database A;" freezes database "B" for a couple minutes. Nothing is using "A" at that point, so why is this such an intensive operation?

Bonus points: Given that we use "A", upload data into "B", and then switch to using "B", how can we do this faster? Dropping databases isn't the sort of thing one typically has to do all the time, so this is a bit off the charts.

Answer:
By default, all innodb databases in a given mysql server installation use the same physical pool of data files, so conceivably "drop database A"  could affect database B.  Since "drop database" is likely to involve heavy reorgainsing of the innodb data files, it's conceivable that it's a blocking operation, either because of the intensity of the operation, or by design.
However, I think you can make each database use different physical files, although I haven't tried that myself, so you'll have to figure out the specifics for yourself. Failing that, then you may need to use two different mysql installs side-by-side on the same machine, which is perfectly doable.


Question:
I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response?

require 'rubygems'
require 'activeresource'

class Event < ActiveResource::Base
  self.site = "http://localhost:3000"
end

e = Event.create(
  :name => "Shortest Event Ever!",
  :starts_at => 1.second.ago,
  :capacity => 25,
  :price => 10.00)

e.destroy

Answer:
By default, all innodb databases in a given mysql server installation use the same physical pool of data files, so conceivably "drop database A"  could affect database B.  Since "drop database" is likely to involve heavy reorgainsing of the innodb data files, it's conceivable that it's a blocking operation, either because of the intensity of the operation, or by design.
However, I think you can make each database use different physical files, although I haven't tried that myself, so you'll have to figure out the specifics for yourself. Failing that, then you may need to use two different mysql installs side-by-side on the same machine, which is perfectly doable.


Question:
I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example:

foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0"
if goo =~ /value of foo here dynamically/
  puts "success!"
end

Answer:
Use Regexp.new:
```
```
if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/
```
```


Question:
I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this.

Which of these offers the best performance in which situations?

Parse(...)  // Crash if the case is extremely rare .0001%

If (SomethingIsValid) // Check the value before parsing
    Parse(...)

TryParse(...) // Using TryParse

try
{
    Parse(...)
}
catch
{
    // Catch any thrown exceptions
}

Answer:
Always use
T.TryParse(string str, out T value)
. Throwing exceptions is expensive and should be avoided if you can handle the situation
a priori
. Using a try-catch block to "save" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good coding practices. Follow sound software engineering development practices, write your test cases, run your application, THEN benchmark and optimize.
"We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil
. Yet we should not pass up our opportunities in that critical 3%" -Donald Knuth
Therefore you assign, arbitrarily like in carbon credits, that the performance of try-catch is
worse
and that the performance of TryParse is
better
. Only after we've run our application and determined that we have some sort of slowdown w.r.t. string parsing would we even consider using anything other than TryParse.
(edit: since it appears the questioner wanted timing data to go with good advice, here is the timing data requested)
Times for various failure rates on 10,000 inputs from the user (for the unbelievers):
```
```
Failure Rate      Try-Catch          TryParse        Slowdown
  0%           00:00:00.0131758   00:00:00.0120421      0.1
 10%           00:00:00.1540251   00:00:00.0087699     16.6
 20%           00:00:00.2833266   00:00:00.0105229     25.9
 30%           00:00:00.4462866   00:00:00.0091487     47.8
 40%           00:00:00.6951060   00:00:00.0108980     62.8
 50%           00:00:00.7567745   00:00:00.0087065     85.9
 60%           00:00:00.7090449   00:00:00.0083365     84.1
 70%           00:00:00.8179365   00:00:00.0088809     91.1
 80%           00:00:00.9468898   00:00:00.0088562    105.9
 90%           00:00:01.0411393   00:00:00.0081040    127.5
100%           00:00:01.1488157   00:00:00.0078877    144.6

/// <param name="errorRate">Rate of errors in user input</param>
/// <returns>Total time taken</returns>
public static TimeSpan TimeTryCatch(double errorRate, int seed, int count)
{
    Stopwatch stopwatch = new Stopwatch();
    Random random = new Random(seed);
    string bad_prefix = @"X";

    stopwatch.Start();
    for(int ii = 0; ii < count; ++ii)
    {
        string input = random.Next().ToString();
        if (random.NextDouble() < errorRate)
        {
           input = bad_prefix + input;
        }

        int value = 0;
        try
        {
            value = Int32.Parse(input);
        }
        catch(FormatException)
        {
            value = -1; // we would do something here with a logger perhaps
        }
    }
    stopwatch.Stop();

    return stopwatch.Elapsed;
}

/// <param name="errorRate">Rate of errors in user input</param>
/// <returns>Total time taken</returns>
public static TimeSpan TimeTryParse(double errorRate, int seed, int count)
{
    Stopwatch stopwatch = new Stopwatch();
    Random random = new Random(seed);
    string bad_prefix = @"X";

    stopwatch.Start();
    for(int ii = 0; ii < count; ++ii)
    {
        string input = random.Next().ToString();
        if (random.NextDouble() < errorRate)
        {
           input = bad_prefix + input;
        }

        int value = 0;
        if (!Int32.TryParse(input, out value))
        {
            value = -1; // we would do something here with a logger perhaps
        }
    }
    stopwatch.Stop();

    return stopwatch.Elapsed;
}

public static void TimeStringParse()
{
    double errorRate = 0.1; // 10% of the time our users mess up
    int count = 10000; // 10000 entries by a user

    TimeSpan trycatch = TimeTryCatch(errorRate, 1, count);
    TimeSpan tryparse = TimeTryParse(errorRate, 1, count);

    Console.WriteLine("trycatch: {0}", trycatch);
    Console.WriteLine("tryparse: {0}", tryparse);
}
```
```


Question:
The project I'm working on needs to render an ESRI shape file, which can have a large number of polygons/shapes.  When I add all these polygons, lines, points, etc to the canvas I'm using, it gets really slow.

To draw the shapes on the map, I'm creating a Path object, and setting it's Data property to a StreamGeometry.  I originally used a Polygon, but according to MSDN a StreamGeometry is much lighter weight.

How can I improve the performance?  Would converting the finished product to a Bitmap, or VisualBrush help?  Is there a more efficient way of to render all these shapes onto the canvas?

EDIT:  I forgot to mention that this needs to be able to work in a Partial-Trust XBAP.

Answer:
You are about to discover the motivation behind GPUs and insanely overclocked and cooled-down graphics cards. And double-buffering.
And: converting the thing to a bitmap: what's the difference to rendering it?
After all you have n objects that /somehow/ have to get rendered (unless you can figure out which objects are hidden behind other objects but that doesn't help you much since you'd have to look at n! object relations).
Besides: maybe it pays off to leave the orthodox OOP approach and go procedural instead.


Question:
I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers.

EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues.

function Pause-Host
{
    param(
            $Delay = 1
         )
    $counter = 0;
    While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay))
    {
        [Threading.Thread]::Sleep(1000)
    }
}

Answer:
Found something
here
:
```
```
$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
      [Threading.Thread]::Sleep( 1000 )
}
```
```


Question: How do I list and export a private key from a keystore?


Question: I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both?

Answer:
The docs
say that
If provided, at pickling time
```
__reduce__()
```
will be called with no
arguments, and it must return either a
string or a tuple.
On the other hand,
It is sometimes useful to know the
protocol version when implementing
```
__reduce__
```
. This can be done by
implementing a method named
```
__reduce_ex__
```
instead of
```
__reduce__
```
.
```
__reduce_ex__
```
, when it
exists, is called in preference over
```
__reduce__
```
(you may still provide
```
__reduce__
```
for backwards
compatibility). The
```
__reduce_ex__
```
method will be called with a single
integer argument, the protocol
version.
On the gripping hand,
Guido says
that this is an area that could be cleaned up.


Question:
I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem.

How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using:

request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server.

But that didn't work.

Any Ideas?

The site is on IIS 6.0.
We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.

Answer:
Update, you actually want to pick up:
VB.NET:
```
```
Request.QueryString("aspxerrorpath")
```
```
C#:
```
```
Request.QueryString["aspxerrorpath"];
```
```


Question: If I have variable of type IEnumerable<List<string>> is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an IEnumerable<string>?

Answer:
SelectMany - i.e.
```
```
IEnumerable<List<string>> someList = ...;
        IEnumerable<string> all = someList.SelectMany(x => x);
```
```
For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>.
These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):
```
```
static IEnumerable<TResult> SelectMany<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TResult>> selector) {

    foreach(TSource item in source) {
      foreach(TResult result in selector(item)) {
        yield return result;
      }
    }
}
```
```
Although that is simplified somewhat.


Question:
What is the best way to dynamically create RDLC xml as input to VS2005 Report Viewer?

I would like to autosize columns based on the data sizes.  I would also like to programmatically control what columns are displayed.

Answer:
Lisa Nicholls
gives a complete answer
in this thread
about dynamically defining a report. You'll want to scroll down some before you get to a useful answer. This thread most directly answers your question about controlling which columns are displayed.
These same techniques can be used to size the columns programmatically, but your code will have to figure out the appropriate column widths.


Question:
How do people approach mocking out TcpClient (or things like TcpClient)?

I have a service that takes in a TcpClient.  Should I wrap that in something else more mockable?  How should I approach this?

Answer:
When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the
Adapter
design pattern.
In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this:
```
```
public interface ITcpClient
{
   Stream GetStream();
   // Anything you need here
}
public class TcpClientAdapter: ITcpClient
{
   private TcpClient wrappedClient;
   public TcpClientAdapter(TcpClient client)
   {
    wrappedClient = client;
   }

   public Stream GetStream()
   {
     return wrappedClient.GetStream();
   }
}
```
```


Question:
I'm trying to use Exchange Web Services to update a calendar item.  I'm creating an ItemChangeType, and then an ItemIdType.  I have a unique ID to use for ItemIdType.Id, but I have nothing to use for the ChangeKey.  When I leave it out, I get an ErrorChangeKeyRequiredForWriteOperations.  But when i try to just put something in there, I get an ErrorInvalidChangeKey.

What can I use for this to get it to work?

I'm also trying to determine what is the best implementation of BaseItemIdType to use for ItemChangeType.Item.  So far, I'm using ItemIdType, and I'm guessing that's correct, but I haven't been able to find any particularly helpful documentation on this.

Answer:
If you have the ItemIdType.Id property you should also have access to the Changekey, it's also a property of ItemIdType:
```
ItemIdType.ChangeKey
```
Like the Id property it's a string, so you can grab it when you grab the Id.
Regards
Jesper Hauge


Question: What do you insert into Python source code to have it break into pdb (when execution gets to that spot)?

Answer:
```
```
import pdb; pdb.set_trace()
```
```
See
Python: Coding in the Debugger for Beginners
for this and more helpful hints.


Question:
I have a website in which I provide tool-tips for certain things using a hidden <span> tag and JavaScript to track various mouse events. It works excellently. This site somewhat caters towards people with vision issues, so I try to make things degrade as well as possible if there is no JavaScript or CSS and generally I would say that it is successful in this regard.

So my question is, is it possible for these <span> to only exist if CSS is being used? I have thought about writing out the tool-tips in JavaScript on document load. But I was wondering if there is a better solution.

Answer:
Perhaps you need to re-think the way you are providing tooltips.  Could the content be contained in the title attribute of a semantically appropriate element?
EDIT: If you provide more info, someone might be able to suggest more of a solution.  What sorts of elements are the tooltips popping up on?  Images?  Would the abbreviation tags be appropriate?
Quick Solution I just came up with:
```
<span>
```
has access to the
core attributes
, which include title, so you could include the tooltip text in the title, and use a javascript library like jQuery to display tooltips for all spans with a title.


Question:
I'm wondering if there are any architectural frameworks out there to create desktop or standalone applications, in Java or C# for instance. It seems that there are tons of them available for web applications but I can't find many good resources on frameworks or architectural best-practices for desktop development.

Ideally I would like to know if there is any source code available of desktop applications that would be considered to have a good architecture or are built with a certain framework.

Answer:
You can use some of the same approaches in client development that you use in web development, such as Model View Presenter. The System.Windows.Forms namespace has everything you need to build a client application in C#, with the rest of the .NET Framework available to provide the services you need (such as IO and remoting).
As far as source code for solid architectures in desktop apps, look at the code for
Paint.NET
and
SharpDevelop
. Both have very different approaches that will be interesting to you.
Sorry for the .NET slant of this reply. It's what I know best. :)


Question:
With our next major release we are looking to globalize our ASP.Net application and I was asked to think of a way to keep track of what code has been already worked on in this effort.

My thought was to use a custom Attribute and place it on all classes that have been "fixed".

What do you think?

Does anyone have a better idea?

Answer:
Using an attribute to determine which classes have been globalized would then require a tool to process the code and determine which classes have and haven't been "processed", it seems like it's getting a bit complicated.
A more traditional project tracking process would probably be better - and wouldn't "pollute" your code with attributes/other markup that have no functional meaning beyond the end of the globalisation project. How about having a defect raised for each class that requires work, and tracking it that way?


Question:
I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the HttpRequest object?

My HttpRequest.GET currently returns an empty QueryDict object.

I'd like to learn how to do this without a library, so I can get to know Django better.

Answer:
When a URL is like
```
domain/search/?q=haha
```
, you would use
```
request.GET.get('q', '')
```
.
```
q
```
is the parameter you want, and
```
''
```
is the default value if
```
q
```
isn't found.
However, if you are instead just configuring your
```
URLconf
```
**, then your captures from the
```
regex
```
are passed to the function as arguments (or named arguments).
Such as:
```
```
(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),
```
```
Then in your
```
views.py
```
you would have
```
```
def profile_page(request, username):
    # Rest of the method
```
```


Question:
I've got a C# program that's supposed to play audio files.  I've figured out how to play any sound file for which Windows has a codec by using DirectShow, but now I want to properly fill in the file type filter box on the Open dialog.  I'd like to automatically list any file format for which Windows has a codec.  If some random user installs a codec for an obscure format, its associated extension(s) and file type description(s) need to show up in the list.

Any ideas?

Answer:
If I remember correctly, a codec does not know which file types, i.e. file extensions, it supports, since a codec takes some stream as input and not actually a file. So if what you want is to display the file extensions of the supported audio file formats, you'll most likely be out of luck unless you have a extensive list of file extensions and associated codecs, but even then you'll get problems with container formats and all that.
For example, my Windows Media Player happily plays m4b files, but does not know anything about them. I had to manually associate it with the file type.


Question:
I have a form in HTML where our users fill in the data and then print it.  The data isn't saved anywhere.  These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet.  Normally another developer does them, but I have to do a few while he's out.  Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents.  It seems like there should be a better way.

I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it.  Any thoughts?

Answer:
```
```
<input type="text" style="border: 0; background-color: #fff;" />
```
```
Where #fff is your background color..


Question:
In the database I have a field named 'body' that has an XML in it. The
method I created in the model looks like this:

def self.get_personal_data_module(person_id)
    person_module = find_by_person_id(person_id)
    item_module = Hpricot(person_module.body)
    personal_info = Array.new
    personal_info = {:studies => (item_module/"studies").inner_html,
                            :birth_place => (item_module/"birth_place").inner_html,
                            :marrital_status => (item_module/"marrital_status").inner_html}
    return personal_info
end

I want the function to return an object instead of an array. So I can
use Module.studies instead of Model[:studies].

Answer:
This is relatively simple; you're getting an Array because the code is building one. If you wanted to return an object, you'd do something like this:
```
```
class PersonalData
  attr_accessor :studies
  attr_accessor :birth_place
  attr_accessor :marital_status

  def initialize(studies,birth_place,marital_status)
    @studies = studies
    @birth_place = birth_place
    @marital_status = marital_status
  end
end
```
```
And your translation code would look like:
```
```
def self.get_personal_data_module(person_id)
  person_module = find_by_person_id(person_id)
  item_module = Hpricot(person_module.body)
  personal_info = PersonalData.new((item_module/"studies").inner_html,
                                   (item_module/"birth_place").inner_html,
                                   (item_module/"marital_status").innner_html)
  return personal_info
end
```
```


Question: This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.

Answer:
Best thing I can think of is to encode it yourself.  How about this subroutine?
```
```
from urllib2 import Request, urlopen
from binascii import b2a_base64

def b64open(url, postdata):
  req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})
  return urlopen(req)

conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité")
# returns a file-like object
```
```
(Okay, so this code just sends POST-data.  But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right?  Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)


Question:
Using Restlet I needed to serve some simple static content in the same context as my web service. I've configured the component with a Directory, but in testing, I've found it will only serve 'index.html', everything else results in a 404.

router.attach("/", new Directory(context, new Reference(baseRef, "./content"));

So... http://service and http://service/index.html both work,

but http://service/other.html gives me a 404

Can anyone shed some light on this? I want any file within the ./content directory to be available.

PS: I eventually plan to use a reverse proxy and serve all static content off another web server, but for now I need this to work as is.

Answer:
Best thing I can think of is to encode it yourself.  How about this subroutine?
```
```
from urllib2 import Request, urlopen
from binascii import b2a_base64

def b64open(url, postdata):
  req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})
  return urlopen(req)

conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité")
# returns a file-like object
```
```
(Okay, so this code just sends POST-data.  But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right?  Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)


Question: How do you remove the jagged edges from a wide button in internet explorer?  For example:

Answer:
As a workaround, you can remove the blank spaces on each end of the button, which has the effect of decreasing the jagged edges. This is accomplished with the following css and a bit of jQuery:
```
```
input.button {
   padding: 0 .25em;
   width: 0; /* for IE only */
   overflow: visible;
}

input.button[class] { /* IE ignores [class] */
    width: auto;
}
```
```
```
```
$(function(){
    $('input[type=button]').addClass('button');
});
```
```
The jQuery is for adding the button class. A more in depth write up can be found
here
.


Question: I've used asp.net profiles (using the AspNetSqlProfileProvider) for holding small bits of information about my users. I started to wonder how it would handle a robust profile for a large number of users. Does anyone have experience using this on a large website with large numbers of simultaneous users? What are the performance implications? How about maintenance?

Answer:
As a workaround, you can remove the blank spaces on each end of the button, which has the effect of decreasing the jagged edges. This is accomplished with the following css and a bit of jQuery:
```
```
input.button {
   padding: 0 .25em;
   width: 0; /* for IE only */
   overflow: visible;
}

input.button[class] { /* IE ignores [class] */
    width: auto;
}
```
```
```
```
$(function(){
    $('input[type=button]').addClass('button');
});
```
```
The jQuery is for adding the button class. A more in depth write up can be found
here
.


Question:
In C, is it possible to forward the invocation of a variadic function? As in,

int my_printf(char *fmt, ...) {
    fprintf(stderr, "Calling printf with fmt %s", fmt);
    return SOMEHOW_INVOKE_LIBC_PRINTF;
}

Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf.

[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function without modifying that function's definition.]

Answer:
Use vfprintf:
```
```
int my_printf(char *fmt, ...) {
    va_list va;
    int ret;

    va_start(va, fmt);
    ret = vfprintf(stderr, fmt, va);
    va_end(va);
    return ret;
}
```
```


Question: In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it?

Answer:
If you use a
```
```
try
{

}
catch(Exception ex)
{

}
```
```
it will catch ALL exceptions, depending on how you call the external libraries you might get a com related exception that encapsulates the error but it will catch the error.


Question: If I have an instance of a System.Timers.Timer that has a long interval - say 1 minute, how can I find out if it is started without waiting for the Tick?

Answer:
```
System.Timer.Timer.Enabled
```
should work, when you call "Start" it sets Enabled to TRUE, "Stop" sets it to FALSE.


Question: Where can I test HTML 5 functionality today - is there any test build of any rendering engines which would allow testing, or is it to early? I'm aware that much of the spec hasn't been finalised, but some has, and it would be good to try it out!

Answer:
Ones that are built using a recent webkit build, and Presto.
Safari 3.1 for webkit
Opera for Presto.
I'm pretty sure firefox will start supporting html5 partially in 3.1
All support is extremely partial. Check
here for information on what is supported.


Question:
I have a website laid out in tables. (a long mortgage form)

in each table cell is one HTML object. (text box, radio buttons, etc)

What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)?

Answer:
Possibly:
```
```

<input type="..." onfocus="getParent(this,'td').style.backgroundColor='#400';" onblur="getParent(this,'td').style.backgroundColor='';">

```
```


Question:
I'm trying to do this

SELECT `Name`,`Value` FROM `Constants`
WHERE `Name` NOT IN ('Do not get this one'|'or this one');

But it doesn't seem to work.

How do I get all the values, except for a select few, without doing this:

SELECT `Name`,`Value` FROM `Constants`
WHERE `Name` != 'Do not get this one'
AND `Name` != 'or this one'

The first one works with int values, but doesn't work with varchar, is there a syntax like the first one, that performs like the second query?

Answer:
It's
```
IN('foo', 'bar')
```
, with a comma, not a pipe.


Question: I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online.

Answer:
Not sure if you need to stick with JXL, but the best library for handling Excel files is
Apache's POI HSSF
.
I think there are plenty of examples on the website I provided, but if you need further assistence, let me know. I may have a few examples laying around.
Just out of curiosity, POI stands for Poor Obfuscation Interface and HSSF is Horrible SpreadSheet Format. You see how much Apache loves Microsoft Office formats :-)


Question:
Do you use any of these technologies? Which ones are current and hence sensible to include in a site?

Documentation on any seems to be relatively sparse, and usage of any of them limited, as search engines get better, are they even relevant any more?

Answer:
I use microformats whenever I can.  Usually it just makes sense anyway, as frequently when I have an address block, I may want to style some elements differently then other elements, and that makes it super easy.  It's not like microformats are that hard to figure out.
There has been a couple of instances where, because I was using a microformat, I was able to re-use the markup of a certain portion of a site somewhere else (as an include), and not have to change the markup, only the styling.
Finally, ever since I really stated exploring microformats, I got better at writing semantic markup and better at naming CSS classes.


Question: It seems like Sql Reporting Services Server logs information in several places including web server logs and logging tables in the database. Where are all the locations SSRS logs to, and what type of errors are logged in each place?

Answer:
As far as I know SSRS logs to the Event Log, the filesystem and its own database.
The database is typically the most easily available one. You just login to the ReportServer database and execute
```
```
select * from executionlog
```
```
This only logs the executions though. If you want more information you can go to the Trace Log files, which are usually available at (location may of course vary):
```
```
C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\LogFiles
```
```
These are quite verbose and not really fun to look through. But they do log a lot of stuff.
If you're searching for an error you can go to the Windows Application Log (Under Administrative Tools in your control panel)
Edit
Found a nice link:
https://learn.microsoft.com/en-us/sql/reporting-services/report-server/reporting-services-log-files-and-sources


Question: I would like to write some data to a file in Ruby. What is the best way to do that?

Answer:
```
```
filey = File.new("/path/to/the/file", APPEND)
filey.puts "stuff to write"
```
```


Question: I'm working on a qnx device, and I want to be able to ssh into it.  Does anyone have a primer on getting something like openSSH up and running?

Answer:
Open Source Applications for QNX
provides ported open source
  tools/applications including their
  complete sources and/or ready to use
  binaries for QNX, like XFree86,
  Lesstif, DDD, VNC, Nedit and cluster
  middleware like PVM.
I have no idea what that means, but I hope it gives you something to start with.


Question:
Let me first say that being able to take 17 million records from a flat file, pushing to a DB on a remote box and having it take 7 minutes is amazing. SSIS truly is fantastic. But now that I have that data up there, how do I remove duplicates?

Better yet, I want to take the flat file, remove the duplicates from the flat file and put them back into another flat file.

I am thinking about a:

Data Flow Task

File source (with an associated file connection)

A for loop container

A script container that contains some logic to tell if another row exists

Thak you, and everyone on this site is incredibly knowledgeable.

Update: I have found this link, might help in answering this question

Answer:
I would suggest using SSIS to copy the records to a temporary table, then create a task that uses Select Distinct or Rank depending on your situation to select the duplicates which would funnel them to a flat file and delete them from the temporary table.  The last step would be to copy the records from the temporary table into the destination table.
Determining a duplicate is something SQL is good at but a flat file is not as well suited for.  In the case you proposed, the script container would load a row and then would have to compare it against 17 million records, then load the next row and repeat...The performance might not be all that great.


Question:
I have a file that lists filenames, each on it's own line, and I want to test if each exists in a particular directory. For example, some sample lines of the file might be

mshta.dll
foobar.dll
somethingelse.dll

The directory I'm interested in is X:\Windows\System32\, so I want to see if the following files exist:

X:\Windows\System32\mshta.dll
X:\Windows\System32\foobar.dll
X:\Windows\System32\somethingelse.dll

How can I do this using the Windows command prompt? Also (out of curiosity) how would I do this using bash or another Unix shell?

Answer:
In Windows:
```
```
type file.txt >NUL 2>NUL
if ERRORLEVEL 1 then echo "file doesn't exist"
```
```
(This may not be the best way to do it; it is a way I know of; see also
http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx
)
In Bash:
```
```
if ( test -e file.txt ); then echo "file exists"; fi
```
```


Question:
My company is heavily invested in the MS BI Stack (SQL Server Reporting Services, -Analysis Services and -Integration Services), but I want to have a look at what the seemingly most talked about open-source alternative Pentaho is like.

I've installed a version, and I got it up and running quite painlessly. So that's good. But I haven't really the time to start using it for actual work to get a thorough understanding of the package.

Have any of you got any insights into what are the pros and cons of Pentaho vs MS BI, or any links to such comparisons?

Much appreciated!

Answer:
I can't offer any input on the MS BI Stack but at the most recent
Barcamp Orlando
, the folks from Pentaho were there and spoke about their products and it was an extremely impressive demo.
The fact that it's an Open Source project that you can extend yourself as well as a paid package for really good service leaves you with a lot of options.  They demonstrated some paid work they did for a client and they definitely wow'd the crowd.
I also had a chance to chat a little bit with a developer working on the data warehousing side of things for Pentaho and he was extremely sharp and was very open to suggestions and had no problems answering any questions.
So as far as a company goes, Pentaho really impressed me with both their work and how friendly and approachable all of their developers were.


Question: I'd like to get at least one JRE/JDK level on my Windows machine where I have the JRE/JDK source that matches the exact level of the JRE/JDK. My purpose is to be able to go into the system classes while debugging. Any suggestions about how to do this? Thanks in advance.

Answer: The source code is included in the JDK 1.5+ installer. Just make sure that the option is not unchecked while installing.


Question:
I am creating a Windows Forms control derived from UserControl to be embedded in a WPF app. I have generally followed the procedures given in this link.

public ref class CTiledImgViewControl : public UserControl
{
...

virtual void OnPaint( PaintEventArgs^ e ) override;

...
};

And in my CPP file:

void CTiledImgViewControl::OnPaint( PaintEventArgs^ e )
{
    UserControl::OnPaint(e);
    // do something interesting...
}

Everything compiles and runs, however the OnPaint method is never getting called.

Any ideas of things to look for? I've done a lot with C++, but am pretty new to WinForms and WPF, so it could well be something obvious...

Answer:
The
```
OnPaint
```
won't normally get called in a
```
UserControl
```
unless you set the appropriate style when it is constructed using the
```
SetStyle
```
method. You need to set the
```
UserPaint
```
style to true for the
```
OnPaint
```
to get called.
```
```
SetStyle(ControlStyles::UserPaint, true);
```
```
Update
I recently encountered this issue myself and went digging for an answer. I wanted to perform some calculations during a paint (to leverage the unique handling of paint messages) but I wasn't always getting a call to
```
OnPaint
```
.
After digging around with Reflector, I discovered that
```
OnPaint
```
is only called if the clipping rectangle of the corresponding
```
WM_PAINT
```
message is not empty. My
```
UserControl
```
instance had a child control that filled its entire client region and therefore, clipped it all. This meant that the clipping rectangle was empty and so no
```
OnPaint
```
call.
I worked around this by overriding
```
WndProc
```
and adding a handler for
```
WM_PAINT
```
directly as I couldn't find another way to achieve what I wanted.


Question:
Anyone know a good Regex expression to drop in the ValidationExpression to be sure that my users are only entering ASCII characters?

<asp:RegularExpressionValidator id="myRegex" runat="server" ControlToValidate="txtName" ValidationExpression="???" ErrorMessage="Non-ASCII Characters" Display="Dynamic" />

Answer:
If you want to map the possible 0x00 - 0xff ASCII values you can use this regular expression (.NET).
```
```
^([\x00-\xff]*)$
```
```


Question:
How can an object be loaded via Hibernate based on a field value of a member object? For example, suppose the following classes existed, with a one-to-one relationship between bar and foo:

Foo {
    Long id;
}

Bar {
    Long id;
    Foo aMember;
}

How could one use Hibernate Criteria to load Bar if you only had the id of Foo?

The first thing that leapt into my head was to load the Foo object and set that as a Criterion to load the Bar object, but that seems wasteful. Is there an effective way to do this with Criteria, or is HQL the way this should be handled?

Answer:
You can absolutely use Criteria in an efficient manner to accomplish this:
```
```
session.createCriteria(Bar.class).
        createAlias("aMember", "a").
        add(Restrictions.eq("a.id", fooId));
```
```
ought to do the trick.


Question:
I'm used to doing basic password protection for Apache w/ the following method in Apache config files:

AuthType Basic

  AuthName "By Invitation Only"

  AuthUserFile /path/to/.htpasswd

  Require valid-user

However, I've been asked to put some protection on a subdirectory of a site running ColdFusion on top of IIS6, and I'm unfamiliar with how to do this.  How is this done?  What should I look out for?  I just need to password protect an administrative subdirectory, so I don't need a full user login system - just something that limits who can access the section of the site.

Answer: You can go into IIS 6 and the properties for your website's folder you want to protect. Click directory security tab and uncheck allow anonymous. Then you need to choose an authntication type. If its over SSL you can use basic, otherwise use another type. But since you mention basic, this may suffice regardless. Keep in mind basic auth will send password in plain text. Thsi will ask for a windows login in order to access that folder. You can create a limited wondows account for this purpose, reagrdless if its on the domain or local.One more thing, wether you use an existing account or create a new account make sure this folder has at least read permission to the folder and its sub folders.


Question:
What is the best way to replace all '&lt' with &lt; in a given database column? Basically perform s/&lt[^;]/&lt;/gi

Notes:

must work in MS SQL Server 2000

Must be repeatable (and not end up with &lt;;;;;;;;;;)

Answer:
Some hacking required but we can do this with
LIKE
,
PATINDEX
,
LEFT
AND
RIGHT
and good old string concatenation.
```
```
create table test
(
    id int identity(1, 1) not null,
    val varchar(25) not null
)

insert into test values ('< <- ok, &lt <- nok')

while 1 = 1
begin
    update test
        set val = left(val, patindex('%&lt[^;]%', val) - 1) +
                      '<' +
                      right(val, len(val) - patindex('%&lt[^;]%', val) - 2)
    from test
    where val like '%&lt[^;]%'

    IF @@ROWCOUNT = 0 BREAK
end

select * from test
```
```
Better is that this is SQL Server version agnostic and should work just fine.


Question: In my ActionScript3 class, can I have a property with a getter and setter?

Answer:
Ok, well you can just use the basic getter/setter syntax for any property of your AS3 class.  For example
```
```
package {

    public class PropEG {

        private var _prop:String;

        public function get prop():String {
            return _prop;
        }

        public function set prop(value:String):void {
            _prop = value;
        }
    }
}
```
```


Question: How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?

Answer:
You actually might want to check out the interop classes available in C# (e.g.
```
Microsoft.Office.Interop.Excel
```
. You say no OLE (which this isn't), but the interop classes are very easy to use. Check out the
C# Documentation here
(Interop for Excel starts on page 1072 of the C# PDF).
You might be impressed if you haven't tried them.
Please be warned of Microsoft's
stance
on this:
Microsoft does not currently recommend, and does not support,
  Automation of Microsoft Office applications from any unattended,
  non-interactive client application or component (including ASP,
  ASP.NET, DCOM, and NT Services), because Office may exhibit unstable
  behavior and/or deadlock when Office is run in this environment.


Question:
sqlite> DELETE FROM mails WHERE (`id` = 71);
SQL error: database is locked

How do I unlock the database so this will work?

Answer: the SQLite db files are just files, so the first step would be to make sure it isn't read-only.  The other thing to do is to make sure that you don't have some sort of GUI SQLite DB viewer with the DB open.  You could have the DB open in another shell, or your code may have the DB open.  Typically you would see this if a different thread, or application such as SQLite Database Browser has the DB open for writing.


Question:
When I load script/console, sometimes I want to play with the output of a controller or a view helper method.

Are there ways to:

simulate a request?

call methods from a controller instance on said request?

test helper methods, either via said controller instance or another way?

Answer:
Here's one way to do this through the console:
```
```
>> foo = ActionView::Base.new
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>

>> foo.extend YourHelperModule
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>

>> foo.your_helper_method(args)
=> "<html>created by your helper</html>"
```
```
Creating a new instance of
```
ActionView::Base
```
gives you access to the normal view methods that your helper likely uses.  Then extending
```
YourHelperModule
```
mixes its methods into your object letting you view their return values.


Question:
I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following:

for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
    bool last_iteration;
    // do something for all iterations
    if (!last_iteration) {
        // do something for all but the last iteration
    }
}

There seem to be several ways of doing this: random access iterators, the distance function, etc. What's the canonical method?

Edit: no random access iterators for maps!

Answer:
This seems like the simplest:
```
```
bool last_iteration = iter == (--someMap.end());
```
```


Question:
In .NET, under which circumstances should I use GC.SuppressFinalize()?

What advantage(s) does using this method give me?

Answer:
That method must be called on the
```
Dispose
```
method of objects that implements the
```
IDisposable
```
, in this way the GC wouldn't call the finalizer another time if someones calls the
```
Dispose
```
method.
See:
GC.SuppressFinalize(Object) Method - Microsoft Docs


Question:
Having this route:

map.foo 'foo/*path', :controller => 'foo', :action => 'index'

I have the following results for the link_to call

link_to "Foo", :controller => 'foo', :path => 'bar/baz'
# <a href="/foo/bar%2Fbaz">Foo</a>

Calling url_for or foo_url directly, even with :escape => false, give me the same url:

foo_url(:path => 'bar/baz', :escape => false, :only_path => true)
# /foo/bar%2Fbaz

I want the resulting url to be: /foo/bar/baz

Is there a way around this without patching rails?

Answer:
Instead of passing path a string, give it an array.
```
```
link_to "Foo", :controller => 'foo', :path => %w(bar baz)
# Foo
```
```
If you didn't have the route in your routes file, this same link_to would instead create this:
```
```
# Foo
```
```
The only place I could find this documented is in
this ticket
.


Question:
I have two tables that are joined together.

A has many B

Normally you would do:

select * from a,b where b.a_id = a.id

To get all of the records from a that has a record in b.

How do I get just the records in a that does not have anything in b?

Answer:
```
```
select * from a where id not in (select a_id from b)
```
```
Or like some other people on this thread says:
```
```
select a.* from a
left outer join b on a.id = b.a_id
where b.a_id is null
```
```


Question:
Which one should I use?

catch (_com_error e)

or

catch (_com_error& e)

Answer:
The second.  Here is my attempt at quoting Sutter
"Throw by value, catch by reference"
Learn to
```
catch
```
properly: Throw exceptions by value (not pointer) and
  catch them by reference (usually to
```
const
```
). This is the combination
  that meshes best with exception semantics. When rethrowing the same
  exception, prefer just
```
throw;
```
to
```
throw e;
```
.
Here's the full
Item 73. Throw by value, catch by reference.
The reason to avoid catching exceptions by value is that it implicitly makes a copy of the exception. If the exception is of a subclass, then information about it will be lost.
```
```
try { throw MyException ("error") }
catch (Exception e) {
    /* Implies: Exception e (MyException ("error")) */
    /* e is an instance of Exception, but not MyException */
}
```
```
Catching by reference avoids this issue by not copying the exception.
```
```
try { throw MyException ("error") }
catch (Exception& e) {
    /* Implies: Exception &e = MyException ("error"); */
    /* e is an instance of MyException */
}
```
```


Question:
I encountered the following ddl in a pl/sql script this morning:

create index genuser.idx$$_0bdd0011
...

My initial thought was that the index name was generated by a tool...but I'm also not a pl/sql superstar so I could very well be incorrect. Does the double dollar sign have any special significance in this statement?

Answer:
No special meaning or significance.
```
```
SQL> create table t (col number)
  2  /

Table created.

SQL> create index idx$$_0bdd0011 on t(col)
  2  /

Index created.
```
```
Note: CREATE INDEX is a DDL statement which is usually executed in a SQL script, not in PL/SQL.


Question:
I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date.

I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest are sorted by deadline date earliest to latest.

Any ideas on how to do this with SQL alone? (I can do it with PHP if needed, but an SQL-only solution would be great.)

Thanks!

Answer:
```
```
SELECT foo, bar, due_date FROM tablename
ORDER BY CASE ISNULL(due_date, 0)
WHEN 0 THEN 1 ELSE 0 END, due_date
```
```
So you have 2 order by clauses. The first puts all non-nulls in front, then sorts by due date after that


Question: If I have two dates (ex. '8/18/2008' and '9/26/2008'), what is the best way to get the number of days between these two dates?

Answer:
If you have two date objects, you can just subtract them, which computes a
```
timedelta
```
object.
```
```
from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)
```
```
The relevant section of the docs:
https://docs.python.org/library/datetime.html
.
See
this answer
for another example.


Question:
I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.

How can I accomplish this?

Answer:
In
How to get IP addresses in .NET with a host name
by John Spano, it says to add the
```
System.Net
```
namespace, and use the following code:
```
```
//To get the local IP address
string sHostName = Dns.GetHostName ();
IPHostEntry ipE = Dns.GetHostByName (sHostName);
IPAddress [] IpA = ipE.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
    Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ());
}
```
```


Question:
It seems that I've never got this to work in the past. Currently, I KNOW it doesn't work.

But we start up our Java process:

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=6002
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

I can telnet to the port, and "something is there" (that is, if I don't start the process, nothing answers, but if I do, it does), but I can not get JConsole to work filling in the IP and port.

Seems like it should be so simple, but no errors, no noise, no nothing. Just doesn't work.

Anyone know the hot tip for this?

Answer:
Are you running on Linux? Perhaps the management agent is binding to localhost:
http://java.sun.com/j2se/1.5.0/docs/guide/management/faq.html#linux1


Question:
movie id tt0438097 can be found at http://www.imdb.com/title/tt0438097/

What's the url for its poster image?

Answer:
The URL is a random string as far as I can tell.
It can still be easily retrieved. It is the only
```
img
```
inside the anchor named
```
poster
```
.
So, if you are reading the source, simply search for
```
<a name="poster"
```
and it will be the text following the first
```
src="
```
from there.
However, you will need to keep the screen scraping code updated because that will probably change.
You should also be aware that the images are copyrighted, so be careful to only use the image under a good "fair use" rationale.


Question: Is it possible to use system.currency. It says system.currency is inaccessible due to its protection level. what is the alternative of currency.

Answer:
You have to use
Decimal
data type..
The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.


Question:
I'm looking for a cross-browser method - I know IE has something (I've already forgotten what), and the way to do it in Mozilla may have to do with a focusNode thing I found, that seems related to getting text selections.

Methods involving jQuery or another common JS library are fine by me.

Thanks!

Answer:
OK then, so use jQuery.
There is no current, available way to just ask this. You need to track the focus events when they happen, so this sample (thanks to Karl Rudd
here
) does that across all elements. This is for inputs but you can adjust the selector to fit your needs, even across the entire DOM.
```
```
var currentFocus = null;
$(':input').focus( function() {
    currentFocus = this;
}).blur( function() {

    currentFocus = null;
});
```
```


Question:
How can I add an instance variable to a defined class at runtime, and later get and set its value from outside of the class?

I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class.  A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about.

Answer:
Ruby provides methods for this,
```
instance_variable_get
```
and
```
instance_variable_set
```
. (
docs
)
You can create and assign a new instance variables like this:
```
```
>> foo = Object.new
=> #<Object:0x2aaaaaacc400>

>> foo.instance_variable_set(:@bar, "baz")
=> "baz"

>> foo.inspect
=> #<Object:0x2aaaaaacc400 @bar=\"baz\">
```
```


Question: What are my options?  I tried MonoDevelop over a year ago but it was extremely buggy.  Is the latest version a stable development environment?

Answer:
Is the latest version stable a stable development environment?
Probably ... it hit 1.0 this past spring.


Question: Does anyone know any good tool that I can use to perform stress tests on a video streaming server? I need to test how well my server handles 5,000+ connections.

Answer: start downloading 5000+ files of the same type with different connections.  Don't really need to play them, because essentially the client video player, flash, windows media player, etc. will just be doing a download.  So if you server can handle 5000+ downloads you will be fine.  My bet is your bandwidth gives out before you server.


Question:
I have a function pointer defined by:

typedef void (*EventFunction)(int nEvent);

Is there a way to handle that function with a specific instance of a C++ object?

class A
{
private:
    EventFunction handler;

public:
    void SetEvent(EventFunction func) { handler = func; }

    void EventOne() { handler(1); }
};

class B
{
private:
    A a;
public:
    B() { a.SetEvent(EventFromA); }  // What do I do here?

    void EventFromA(int nEvent) { // do stuff }
};

Edit: Orion pointed out the options that Boost offers such as:

boost::function<int (int)> f;
X x;
f = std::bind1st(
      std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)

Unfortunately Boost is not an option for me.  Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?

Answer:
Unfortunately, the EventFunction type cannot point to a function of B, because it is not the correct type. You could make it the correct type, but that probably isn't really the solution you want:
```
typedef void (*B::EventFunction)(int nEvent);
```
... and then everything works once you call the callback with an obhect of B. But you probably want to be able to call functions outside of B, in other classes that do other things. That is sort of the point of a callback. But now this type points to something definitely in B. More attractive solutions are:
Make B a base class, then override a virtual function for each other class that might be called. A then stores a pointer to B instead of a function pointer. Much cleaner.
If you don't want to bind the function to a specific class type, even a base class (and I wouldn't blame you), then I suggest you make the function that gets called a static function: "
```
static void EventFrom A(int nEvent);
```
". Then you can call it directly, without an object of B. But you probably want it to call a specific instance of B (unless B is a singleton).
So if you want to be able to call a specific instance of B, but be able to call non-B's, too, then you need to pass something else to your callback function so that the callback function can call the right object. Make your function a static, as above, and add a void* parameter which you will make a pointer to B.
In practice you see two solutions to this problem: ad hoc systems where you pass a void* and the event, and hierarchies with virtual functions in a base class, like windowing systems


Question: I have a web service API. Some calls return objects containing text fields with information provided by the user. From both a design and a security standpoint, what are the downsides to returning null in those fields when no information has been provided? Is there a clear advantage to always returning an empty string instead, other then simplifying the API by not requiring the client code to check for nulls?

Answer:
I don't think there's a security issue involved with returning null vs. returning an empty string.
There's not any real downside to returning null for those fields for which there is no information - that's kind of what nulls are meant to indicate.
You can simplify your client code by using
```
```
string.IsNullOrEmpty()
```
```
(assuming this is .NET)


Question: In .NET, what is the difference between String.Empty and "", and are they interchangable, or is there some underlying reference or Localization issues around equality that String.Empty will ensure are not a problem?

Answer:
In .NET prior to version 2.0,
```
""
```
creates an object while
```
string.Empty
```
creates no object
ref
, which makes
```
string.Empty
```
more efficient.
In version 2.0 and later of .NET, all occurrences of
```
""
```
refer to the same string literal, which means
```
""
```
is equivalent to
```
.Empty
```
, but still not as fast as
```
.Length == 0
```
.
```
.Length == 0
```
is the fastest option, but
```
.Empty
```
makes for slightly cleaner code.
See the
.NET specification for more information
.


Question:
I am converting an excel sheet formula to java but I can't understand how excel manages to take the following: 0.22
Applies a formula: =TEXT(R5/14, "h:mm")
and somehow arrives at: 0.22

Again if I provide: 2.8
it arrives at 4.48
Can someone please explain to me how it does this. I have read a little regarding decimal and I understand the conversion but this hasn't yet helped to explain the above.

Answer:
Yeah it is a bit goofy.  Take the /14 out and that helps.  Basically 1=1 day so R5 is expressed in 14ths of a day.  You could probably do
```
```
int msInADay= 86400000;
Time value = new Time(R5/14 * msInADay);
```
```
but it is untested.


Question:
I came from Java, and now I am working more with Ruby.

One language feature I am not familiar with is the module. I am wondering what exactly is a module and when do you use one, and why use a module over a class?

Answer:
Basically, the module cannot be instantiated. When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.
A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance". OO purists will disagree with that statement, but don't let purity get in the way of getting the job done.
(This answer originally linked to
```
http://www.rubycentral.com/pickaxe/classes.html
```
, but that link and its domain are no longer active.)


Question: It is unclear to me from the MSDN documentation if I should provide a deep or a shallow clone when implementing ICloneable. What is the preferred option?

Answer:
Clones are deep by default, thats the naming convention
and copy constructors can be shallow if they want, for performance reasons.
Edit: This naming convention goes beyond boundaries, its the same for .Net, Java, C++, Javascript, etc... the actual source is beyond my knowledge but its part of the standard Object Oriented lexicon, just like objects, and classes. Thus MSDN doesn't specify implementation because its a given by the word itself (of course lots of newcomers to OO languages don't know this, and they SHOULD specify it, but then again their documentation is quite frugal anyways)


Question:
I'm looking for a cross-browser method of detecting that a client web browser is scrolled all the way to the bottom (or top) of the screen.

Really, the top is fairly easy, as

    scrY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop

is zero if you're at the top.  The problem is that scrY seems to return the top of the scroll bar, and not the bottom, so instead of getting something equivalent to the height of the document (in pixels) I what is presumably the height of the document less the size of the scroll bar.

Is there an easy, cross-browser way to find out if the user has scrolled down to the bottom of the document/window?  Most specifically, I understand general scroll bar manipulation (setting it, moving it, etc.) but how can I get the delta of the bottom of the scrollbar's position relative to the bottom of the window/document.

Answer:
http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
http://www.sitepoint.com/article/preserve-page-scroll-position/
http://codepunk.hardwar.org.uk/ajs02.htm
In order to ensure that an element is visible, you can use the
.scrollIntoView method


Question: I need to get the fully expanded hostname of the host that my Ruby script is running on.  In Perl I've used Sys::Hostname::Long with good results.  Google seems to suggest I should use Socket.hostname in ruby, but that's returning just the nodename, not the full hostname.

Answer:
This seems to work:
```
```
hostname = Socket.gethostbyname(Socket.gethostname).first
```
```


Question:
About a year ago, I picked up Scott Ambler's Refactoring Databases: Evolutionary Database Design. I was won over to the idea that just as you can develop your code with TDD, you probably should be covering your databases with unit tests (at least) or even writing database tests before you make a change to the schema so you do database work in a TDD style as well.

I really like the idea, and I have been doing this (OK, sometimes I do it) by hand for a while now, just writing regular unit tests that happen to connect to the database and check its structure against a given schema file. But I haven't found any good database change management tool-kits that might help automate this process. Does anyone know any?

Answer:
I only know of two unit testing frameworks:
DBUnit
TSQLUnit
As for change management, these are some recommended tools:
Redgate SQL Compare
ApexSQL
Toad
Although I am not sure if this is really what you're looking for.


Question:
I'm a huge fan of bzr and I'm glad they're working on tortoise for it, but currently it's WAY too slow to be useful.  The icons are almost always incorrect and when I load a directory in explorer with a lot of branches it locks up my entire system for anywhere from 10 seconds to 2 minutes.  I look forward to trying it again in the future, but for now I'd like to disable it.

Unfortunately I don't see it in add/remove programs and I can't find a way to disable it in the bazaar config directory.  When I right click the icon in the task panel (by the clock) and choose "Exit Program" it just restarts moments later.  I don't see it in the Services panel either.  Is there any way to disable it?

I'm running Windows XP on the system in question.

Answer:
According to the
TortoiseBZR readme
, you can disable it by running
```
```
python tortoise-bzr.py --unregister
```
```
from the install folder.  Not sure where it's installed by default, but it looks like that might be in your Python site-packages folder.


Question: How do you detect if Socket#close() has been called on a socket on the remote side?

Answer:
The
```
isConnected
```
method won't help, it will return
```
true
```
even if the remote side has closed the socket. Try this:
```
```
public class MyServer {
    public static final int PORT = 12345;
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
        Socket s = ss.accept();
        Thread.sleep(5000);
        ss.close();
        s.close();
    }
}

public class MyClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
        System.out.println(" connected: " + s.isConnected());
        Thread.sleep(10000);
        System.out.println(" connected: " + s.isConnected());
    }
}
```
```
Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
The only way to really find out is by reading (you'll get -1 as return value) or writing (an
```
IOException
```
(broken pipe) will be thrown) on the associated Input/OutputStreams.


Question: In PHP5, is the __destruct() method guaranteed to be called for each object instance? Can exceptions in the program prevent this from happening?

Answer:
The destructor will be called when the all references are freed, or when the script terminates.  I assume this means when the script terminates properly.  I would say that critical exceptions would not guarantee the destructor to be called.
The
PHP documentation
is a little bit thin, but it does say that Exceptions in the destructor will cause issues.


Question:
I'm looking for a tool that will, in bulk, add a license header to some source files, some of which already have the header.  Is there a tool out there that will insert a header, if it is not already present?

Edit: I am intentionally not marking an answer to this question, since answers are basically all environment-specific and subjective

Answer:
Python 2 solution, modify for your own need
Features:
handles UTF headers (important for most IDEs)
recursively updates all files in target directory passing given mask (modify the .endswith parameter for the filemask of your language (.c, .java, ..etc)
ability to overwrite previous copyright text (provide old copyright parameter to do this)
optionally omits directories given in the
```
excludedir
```
array
```
```
# updates the copyright information for all .cs files
# usage: call recursive_traversal, with the following parameters
# parent directory, old copyright text content, new copyright text content

import os

excludedir = ["..\\Lib"]

def update_source(filename, oldcopyright, copyright):
    utfstr = chr(0xef)+chr(0xbb)+chr(0xbf)
    fdata = file(filename,"r+").read()
    isUTF = False
    if (fdata.startswith(utfstr)):
        isUTF = True
        fdata = fdata[3:]
    if (oldcopyright != None):
        if (fdata.startswith(oldcopyright)):
            fdata = fdata[len(oldcopyright):]
    if not (fdata.startswith(copyright)):
        print "updating "+filename
        fdata = copyright + fdata
        if (isUTF):
            file(filename,"w").write(utfstr+fdata)
        else:
            file(filename,"w").write(fdata)

def recursive_traversal(dir,  oldcopyright, copyright):
    global excludedir
    fns = os.listdir(dir)
    print "listing "+dir
    for fn in fns:
        fullfn = os.path.join(dir,fn)
        if (fullfn in excludedir):
            continue
        if (os.path.isdir(fullfn)):
            recursive_traversal(fullfn, oldcopyright, copyright)
        else:
            if (fullfn.endswith(".cs")):
                update_source(fullfn, oldcopyright, copyright)

oldcright = file("oldcr.txt","r+").read()
cright = file("copyrightText.txt","r+").read()
recursive_traversal("..", oldcright, cright)
exit()
```
```


Question:
  <my:DataGridTemplateColumn
            CanUserResize="False"
            Width="150"
            Header="{Binding MeetingName, Source={StaticResource LocStrings}}"
            SortMemberPath="MeetingName">
  </my:DataGridTemplateColumn>

I have the above column in a Silverlight grid control. But it is giving me a XamlParser error because of how I am trying to set the Header property. Has anyone done this before? I want to do this for multiple languages.

Also my syntax for the binding to a resouce is correct because I tried it in a lable outside of the grid.

Answer:
You can't Bind to Header because it's not a FrameworkElement.  You can make the text dynamic by modifying the Header Template like this:
```
```
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"

<data:DataGridTemplateColumn>
   <data:DataGridTemplateColumn.HeaderStyle>
       <Style TargetType="dataprimitives:DataGridColumnHeader">
          <Setter Property="Template">
             <Setter.Value>
                <ControlTemplate>
                  <TextBlock Text="{Binding MeetingName, Source={StaticResource LocStrings}}" />
               </ControlTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </data:DataGridTemplateColumn.HeaderStyle>
</data:DataGridTemplateColumn>
```
```


Question:
I've been trying to submit a form with the FormPanel using the Action class Ext defaults to. However, I'd like it to consider the response as a script, not JSON-encoded.

Has anyone had any experience on this?

Answer:
The best plan would be to create a custom action by extending
```
Ext.form.Action
```
.
You can then
```
eval
```
the
```
response
```
object or the
```
result
```
object in the
```
success
```
callback of your custom action.
Your custom action can be called from
```
Ext.form.BasicForm
```
in the usual way.


Question:
The link over here lists ([http://www.yoda.arachsys.com/csharp/singleton.html][1]) some singleton patterns in C#. The article also describes the obvious that a singleton is not meant to accept parameters which “as otherwise a second request for an instance but with a different parameter could be problematic”. This means that any parameters you need to get the class working should be induced as a property.

I am curious to know if there are any parameterized singleton design patterns out there. Accepting values as a property does not enforce anything to the consumer.

Answer:
Based on your question, it seems you may be looking at an Abstract Factory pattern (creates an instance of several families of classes) that keeps an internal list/dictionary of classes that have already been instantiated, thus mimicking the singleton pattern functionality.
You would then use this factory class to request an object based on parameters you've passed in, and if it exists in its internal list it gets returned, and if not, a new instance is created and then added to the list and returned.


Question:
Is it possible for a web server to know which type of device request has been received from?

For example, can a create a website which shows different contents if request came from a computer (Firefox) and something different if it came from iPhone?

Answer:
Check the
```
User-Agent
```
in the Request Header
For full details on HTTP headers, see the specifications at
http://www.w3.org/Protocols/
.


Question:
Does Microsoft force an update down to all of its users of windows-update?  Is it for legal reasons?

EDIT(aku):

Question was reformulated. if you want to know which version of Windows comes with .NET see this topic:

https://stackoverflow.com/questions/71390/which-operating-systems-come-with-net

Answer:
Yes, Windows Vista shipped with .NET Framework 3.0. I'm sure future versions of Windows will ship with whichever is the most recent version of the framework.
Scott Hanselman recently blogged about the status of .NET 3.5 on Windows Update:
http://www.hanselman.com/blog/UpdateOnNETFramework35SP1AndWindowsUpdate.aspx


Question:
We have an old project written using Managed C++ syntax. I would like to propose to the team a reasonably pain-free (I don't mind some level of human interaction, I think I'm realistic in my expectations that we'll still have to do some work by hand) method of updating the existing code to C++/CLI syntax so that we can also add XML documentation (the project is a library into other projects and having documentation would be immensely useful).

So, are there any good tools out there to help with this? Or is it just a case of switching to the new C++/CLI syntax compiler and fixing errors as we go?

Answer:
Microsoft has a
tool
that will help a little.
Visual c++ blog post about it.
Here are a couple other resources I found useful when I made our switch
C++/CLI Migration Primer
Managed Extensions for C++ Syntax Upgrade Checklist
The Microsoft tool is just a start. there were many files that it could not convert.


Question:
Does it matter to developers that the current, and newer versions of .Net don't support windows 2000?

It scares me to think that several of my clients still use Windows 2000 and although I may decide to stop supporting Windows 2000 one day, I don't like that Microsoft is pushing it on people's products.

Could anyone see Microsoft doing this with XP in the future to spur sales of Vista and later?

Just to clarify, this is not a bashing of MS in any way, I love MS, but it is a genuine concern that I would like opinions on.

In contrast I can't see C++0x implementors saying "it won't work on windows 2000"

I'm really trying to convince myself that I should be switching to .Net but this is one of my concerns.

Answer:
Supporting older operating systems costs money. It's not necessarily a push to spur sales of new systems so much as avoiding the cost of trying to make things work on old systems that they've already ceased supporting. Just as Windows 2000 support has ended, so will Windows XP support, and Vista support, and Windows 7 support, etc etc. Continuing to support the .NET framework on operating systems that are no longer supported in any other way does not seem prudent.
EDIT: To address the notion that since the CLR is the same for .NET 2.0 and the newer framework versions, the restriction was artificial. Although it is still working on the same CLR, that doesn't mean that all the support they've added will effectively work on Windows 2000. There are performance and hardware considerations to be made and I think considering the age of Windows 2000 and some of the more intensive features added to 3.0 and 3.5 frameworks, it was a reasonable decision to abandon WIndows 2k.
Whenever we as developers consider supporting a particular user-base, there has to be a consideration of the resources needed to add that additional user-base over the benefits of supporting them. Testing, bug fixing, and support costs have to be factored in. As Windows 2000 is no longer given any security updates, they would need to resurrect an update mechanism just for .NET updates. I suspect that the benefits do not outweigh the costs in this scenario. It therefore makes sense to me that Microsoft should artificially prevent newer frameworks from running on Windows 2000 as they are then saving themselves these additional costs.


Question: just curious to know which CPU architectures support compare and swap atomic primitives?

Answer:
Sparc v9 has a cas instruction. The SPARC v9
architecture manual
discusses the use of the CAS instruction in Annex J, look specifically at examples J.11 and J.12.
I believe the name of the instruction is actually "casa", because it can access either the current address space or an alternate. "cas" is an assembler macro which accesses the current ASI.
There is also an article on
developers.sun.com
discussing the various atomic instructions which Sparc processors have implemented over the years, including cas.


Question:
Given a database field named "widget_ids", containing data like "67/797/124/" or "45/", where the numbers are slash separated widget_ids... how would you make an update statement with SQL that would say:
"if the widget_ids of the row with id X contains the text "somenumber/" do nothing, otherwise append "somenumber/" to it's current value"

Can you do something like that with SQL, or more specifically, sqlite? Is that something that is better done in the program for some reason or is there support for "if-then" like syntax in SQL?

Answer:
Updates are kind of like if-thens themselves, and there is also if-then support of some sort in most SQL implementations. A simple solution might be:
```
```
update <tablename>
  set widget_id = widget_id + "somenumber/"
  where row_id = X
    and widget_id not like "%/somenumber/%"
    and widget_id not like "somenumber/%";
```
```


Question:
I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives...

E.g., WIN32 on x86 has a family of functions _InterlockedCompareExchange in the <_intrin.h> header.

Answer:
I'll let others list the various platform-specific APIs, but for future reference in C++09 you'll get the
```
```
atomic_compare_exchange()
```
```
operation in the new "Atomic operations library".


Question:
Since Unicode lacks a series of zero width sorting characters, I need to determine equivalent characters that will allow me to force a certain order on a list that is automatically sorted by character values. Unfortunately the list items are not in an alphabetical order, nor is it acceptable to prefix them with visible characters to ensure the result of the sort matches the wanted outcome.

What Unicode characters can be thrown in front of regular Latin alphabet text, and will not appear, but still allow me to "spike" the sort in the way I require?

(BTW this is being done with Drupal 5 with a user profile list field. Don't bother suggesting changing that to a vocabulary/category.)

Answer:
Personally, I just prefer to use a primary/secondary sort key. It's less kludgy, and easy to implement in a typical sql query (ORDER BY column_a,column_b).
Edited to add
: In Php, you could use
```
usort(array, comparisonFunction)
```
with a custom comparison function to add additional logic for sorting, if you can't use SQL to do the trick.
However, if you only have one column to work with and that's unfixable, just prefix with a certain number of unlikely characters like underscores for sorting, then strip them just before you display them. (using regexp substitution or similar).
Unicode-based hacks will depend heavily on what fonts are used, what locale's collation/sorting order you're using, and may produce undesirable side effects on clients you don't have control over (different browsers, different oses, different client locales). Most "unprintable" characters yield the "unknown character" when displayed on systems without support for them, which usually looks like an empty square. There are some zero-width characters used for languages like Arabic, but they shouldn't affect sorting except in applications with very perverse Unicode support.


Question: This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them.  The purpose is to figure out that if every other window is fullscreen then I should start up like that too.  Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants.  Why make them waste time and energy resizing my window to match all the others they have?  I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.

Answer:
Check out the
```
win32gui
```
module
in the Windows extensions for Python. It may provide some of the functionality you're looking for.


Question:
In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:

if (var1 = var2) {
  ...
}

instead of:

var1 = var2;
if (var1) {
  ...
}

?

Answer:
It can be useful if you're calling a function that returns either data to work on or a flag to indicate an error (or that you're done).
Something like:
```
```
while ((c = getchar()) != EOF) {
    // process the character
}

// end of file reached...
```
```
Personally it's an idiom I'm not hugely fond of, but sometimes the alternative is uglier.


Question: I have renamed some excel files on my web server and after renaming the users cannot download those files. What could be the problem. They are all excel files.

Answer:
Some possibilities I can think of:
Make sure the extension on the files is still .xls (that's how it associates the mime type)
Check the file protections on the files in case it, or the ownership got changed when you renamed them
Make sure Excel didn't open them on the webserver (if a windows web server) as it will keep them locked until the EXCEL.EXE process is killed.
Might be one of those ...


Question:
I have a form where i have used Infragistics windows grid control to display the data.
In this, i have placed a button on one of the cell. I want to set its visibility either True or False based on the row condition.
I have handled the InitializeRow event of UltraWinGrid control and able to disable the button. But i am unable to set the button's visible to False.

Answer:
```
```
UltraGridRow row = ...

row.Cells[buttonCellIndex].Hidden = true;
```
```
(I'm using the
```
UltraGrid
```
in Infragistics NetAdvantage for Windows Forms 2008 Vol. 2 CLR 2.0.)


Question: What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)?

Answer:
A try/finally block is the closest thing that you can get to this behaviour:
```
```
Lock l = new Lock();
l.lock();  // Call the lock before calling try.
try {
    // Do some processing.
    // All code must go in here including break, return etc.
    return something;
} finally {
    l.unlock();
}
```
```


Question: Emacs puts backup files named foo~ everywhere and I don't like having to remember to delete them.  Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's confusing and awful.  How can I either eliminate these backup files, or have them go somewhere other than the same directory?

Answer:
If you've ever been saved by an Emacs backup file, you
probably want more of them, not less of them.  It is annoying
that they go in the same directory as the file you're editing,
but that is easy to change.  You can make all backup files go
into a directory by putting something like the following in your
```
.emacs
```
.
```
```
(setq backup-directory-alist `(("." . "~/.saves")))
```
```
There are a number of arcane details associated with how Emacs
might create your backup files.  Should it rename the original
and write out the edited buffer?  What if the original is linked?
In general, the safest but slowest bet is to always make backups
by copying.
```
```
(setq backup-by-copying t)
```
```
If that's too slow for some reason you might also have a look at
```
backup-by-copying-when-linked
```
.
Since your backups are all in their own place now, you might want
more of them, rather than less of them.  Have a look at the Emacs
documentation for these variables (with
```
C-h v
```
).
```
```
(setq delete-old-versions t
  kept-new-versions 6
  kept-old-versions 2
  version-control t)
```
```
Finally, if you absolutely must have no backup files:
```
```
(setq make-backup-files nil)
```
```
It makes me sick to think of it though.


Question: The Project's Web section (under project properties in VS2008) has a list of debuggers: ASP.NET, Native Code, SQL Server. What is Native Code?

Answer:
Native code is machine code executed directly by the CPU. This is in contrast to .NET bytecode, which is interpreted by the .NET virtual machine.
A nice MSDN hit:
Debugging Native Code


Question:
I am looking to store 2D arrays of 900x100 elements in a database.  Efficient recall and comparison of the arrays is important.  I could use a table with a schema like [A, x, y, A(x,y)] such that a single array would compromise 90,000 records.  This seems like an ~ok~ table design to store the array, and would provide for efficient recall of single elements, but inefficient recall of a whole array and would make for very inefficient array comparisons.

Should I leave the table design this way and build and compare my arrays in code?  Or is there a better way to structure the table such that I can get efficient array comparisons using database only operations?

thanks

Answer:
900 x 100 elements is actually very small (even if the elements are massive 1K things that'd only be 90 MB).  Can't you just compare in memory when needed and store on disk in some serialized format?
It doesn't make sense to store 2D arrays in the database, especially if it is immutable data.


Question:
In PHP 5, what is the difference between using self and $this?

When is each appropriate?

Answer:
According to
Static Keyword
, there isn't any
```
$self
```
. There is only
```
$this
```
, for referring to the current instance of the class (the object), and
```
self
```
, which can be used to refer to static members of a class. The difference between an object instance and a class comes into play here.


Question:
What is currying?

How can currying be done in C++?

Please Explain binders in STL container?

Answer:
In short, currying takes a function
```
f(x, y)
```
and given a fixed
```
Y
```
, gives a new function
```
g(x)
```
where
```
```
g(x) == f(x, Y)
```
```
This new function may be called in situations where only one argument is supplied, and passes the call on to the original
```
f
```
function with the fixed
```
Y
```
argument.
The binders in the STL allow you to do this for C++ functions. For example:
```
```
#include <functional>
#include <iostream>
#include <vector>

using namespace std;

// declare a binary function object
class adder: public binary_function<int, int, int> {
public:
    int operator()(int x, int y) const
    {
        return x + y;
    }
};

int main()
{
    // initialise some sample data
    vector<int> a, b;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    // here we declare a function object f and try it out
    adder f;
    cout << "f(2, 3) = " << f(2, 3) << endl;

    // transform() expects a function with one argument, so we use
    // bind2nd to make a new function based on f, that takes one
    // argument and adds 5 to it
    transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));

    // output b to see what we got
    cout << "b = [" << endl;
    for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {
        cout << "  " << *i << endl;
    }
    cout << "]" << endl;

    return 0;
}
```
```


Question:
I've got a php script. Most of the time the script returns html, which is working fine, but on one occasion (parameter ?Format=XML) the script returns XML instead of HTML.

Is there any way to change the returned mime type of the php output on the fly from text/html to text/xml or application/xml?

Answer:
```
```
header('Content-type: application/xml');
```
```
More information available at the PHP documentation for
```
header()
```


Question: I have a RDK-IDM from Luminary Micro. This board has a 32-bit ARM® Cortex™-M3 core. Has anybody tried to run a .NET Micro Framework application on such a device?

Answer:
It seems that the LM3S6918 (The chip on the RDK-IDM) has only 256KB Flash and 64Kb SRAM but .NET Micro Framework requires 256KB RAM and 512K Flash/ROM!
Read more
here


Question: .Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not?

Answer:
```
```
#region tuples

    public class Tuple<T>
    {
        public Tuple(T first)
        {
            First = first;
        }

        public T First { get; set; }
    }

    public class Tuple<T, T2> : Tuple<T>
    {
        public Tuple(T first, T2 second)
            : base(first)
        {
            Second = second;
        }

        public T2 Second { get; set; }
    }

    public class Tuple<T, T2, T3> : Tuple<T, T2>
    {
        public Tuple(T first, T2 second, T3 third)
            : base(first, second)
        {
            Third = third;
        }

        public T3 Third { get; set; }
    }

    public class Tuple<T, T2, T3, T4> : Tuple<T, T2, T3>
    {
        public Tuple(T first, T2 second, T3 third, T4 fourth)
            : base(first, second, third)
        {
            Fourth = fourth;
        }

        public T4 Fourth { get; set; }
    }

    #endregion
```
```
And to make declarations prettier:
```
```
public static class Tuple
{
    //Allows Tuple.New(1, "2") instead of new Tuple<int, string>(1, "2")
    public static Tuple<T1, T2> New<T1, T2>(T1 t1, T2 t2)
    {
        return new Tuple<T1, T2>(t1, t2);
    }
    //etc...
}
```
```


Question:
Any time I try to publish my Portal project on a Websphere Portal 6.1 Server, I get the following error message:

Portal project publishing is not supported on WebSphere Portal v6.1 Server

Is that really true or have I done something wrong?

I'm trying to deploy a portal project, with the underlying goal of publishing a new theme.

Unfortunately, any time I try to deploy, I get the error message listed above from the IDE and no errors in the console.

The RAD version is 7.0.0.7.

Answer:
Not sure this will help, but:
Limitation: Although the WebSphere
  Portal installer contains an advanced
  option to install an empty portal,
  Portal Designer relies on
  administration portlets for setting
  access control; therefore, publishing
  a portal project to an empty portal is
  not supported.
Are you trying to deploy a portlet or an entire portal project? What version of RAD are you using? Any other information in the error log? (Both within RAD & on WP server) Is the error message posted verbatim?


Question:
I have a submission table that is very simple: userId, submissionGuid

I want to select the username (simple inner join to get it) of all the users who have more than 10 submissions in the table.

I would do this with embedded queries and a group by to count submissions... but is there a better way of doing it (without embedded queries)?

Thanks!

Answer:
```
```
select userId, count(*)
from   submissions
having count(*) > 10
group by userId
```
```


Question:
I want to be able to compare an image taken from a webcam to an image stored on my computer.

The library doesn't need to be one hundred percent accurate as it won't be used in anything mission critical (e.g. police investigation), I just want something OK I can work with.

I have tried a demonstration project for Image Recognition from CodeProject, and it only works with small images / doesn't work at all when I compare an exact same image 120x90 pixels (this is not classified as OK :P ).

Has there been any success with image recognition before?

If so, would you be able to provide a link to a library I could use in either C# or VB.NET?

Answer:
You could try this:
http://code.google.com/p/aforge/
It includes a comparison analysis that will give you a score. There are many other great imaging features of all types included as well.
```
```
// The class also can be used to get similarity level between two image of the same size, which can be useful to get information about how different/similar are images:
// Create template matching algorithm's instance

// Use zero similarity to make sure algorithm will provide anything
ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0);

// Compare two images
TemplateMatch[] matchings = tm.ProcessImage( image1, image2 );

// Check similarity level
if (matchings[0].Similarity > 0.95)
{
    // Do something with quite similar images
}
```
```