q: I need to resize PNG, JPEG and GIF files. How can I do this using Java?

[A]
After loading the image you can try:
```
```
BufferedImage createResizedCopy(Image originalImage,
            int scaledWidth, int scaledHeight,
            boolean preserveAlpha)
    {
        System.out.println("resizing...");
        int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
        BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
        Graphics2D g = scaledBI.createGraphics();
        if (preserveAlpha) {
            g.setComposite(AlphaComposite.Src);
        }
        g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
        g.dispose();
        return scaledBI;
    }
```
```


q:
I'm trying to use the VssGet task of the MSBuild Community Tasks, and the error message "File or project not found" is beating me with a stick.  I can't figure out what in particular the error message is referring to.  Here's the task:

<LocalFilePath Include="C:\Documents and Settings\michaelc\My Documents\Visual Studio 2005\Projects\Astronom\Astronom.sln" />

<VssGet DatabasePath="\\ofmapoly003\Individual\michaelc\VSS\Astronom_VSS\srcsafe.ini"
     Path="$/Astronom_VSS"
        LocalPath="@(LocalFilePath)"
        UserName="build" Password="build"
     Recursive="True" />

If I write a Streamreader to read to either the database path or the local path, it succeeds fine.  So the path to everything appears to be accessible.  Any ideas?

[A]
Two thoughts.  One, sometimes a type load exception manifests as a FNF - let's hope that's not it.  But if the code is actually being honest, you can track the problem using
Procmon
or
Filemon
.  Start one of those utilities and then run your task again.  You should be able to track down a record of a file that couldn't be located.

s: huggingface

c: devops

d: intermediate


q:
I'm working on a site which contains a whole bunch of mp3s and images, and I'd like to display a loading gif while all the content loads.

I have no idea how to achieve this, but I do have the animated gif I want to use.

Any suggestions?

[A]
Typically sites that do this by loading content via ajax and listening to the
```
readystatechanged
```
event to update the DOM with a loading GIF or the content.
How are you currently loading your content?
The code would be similar to this:
```
```
function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}
```
```
There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.


q: Is it possible to delete rows in an excel worksheet from SSIS?

[A]
From
forum
create a file system task in control flow, deleting the file.
create a sql task, excel connection type, i used my previous excel connection for this, then used a create table script as my sql statement
left my previous export object the same, then linked the flow of these in this order described.


q:
I have a pattern to match with the string:
string pattern = @"asc"
I am checking the SQL SELECT query for right syntax, semantics, ...
I need to say that in the end of the query string I can have "asc" or "desc".
How can it be written in C#?

[A]
You want the "alternation" operator, which is the pipe.
For instance, I believe this would be represented as:
```
```
asc|desc
```
```
If you want to make it a non-capturing group you can do it in the normal way. I'm not a regex expert, but that's the first thing to try.
EDIT: MSDN has a page about
regular expression language elements
which may help you.


q:
In c# (3.0 or 3.5, so we can use lambdas), is there an elegant way of sorting a list of dates in descending order? I know I can do a straight sort and then reverse the whole thing,

docs.Sort((x, y) => x.StoredDate.CompareTo(y.StoredDate));
docs.Reverse();

but is there a lambda expression to do it one step?

In the above example, StoredDate is a property typed as a DateTime.

[A]
```
```
docs.Sort((x, y) => y.StoredDate.CompareTo(x.StoredDate));
```
```
Should do what you're looking for.


q:
I'm trying to create a WPF Shape (PolyLine) editor, which is a control that I want to use to, edit shapes in a canvas.

What the editor needs to do is to be able to display the points and lines of the shape and to move those around.

Can anyone provide me with a idea of how I can accomplish this, or a starting point? I haven't found anything related to how I could do this, so far.

[A]
There is good series of texts about this on
CodeProject
WPF Diagram Designer - Part 1
WPF Diagram Designer - Part 2
WPF Diagram Designer - Part 3
WPF Diagram Designer - Part 4


q:
I ran into the problem that my primary key sequence is not in sync with my table rows.

That is, when I insert a new row I get a duplicate key error because the sequence implied in the serial datatype returns a number that already exists.

It seems to be caused by import/restores not maintaining the sequence properly.

[A]
Try
reindex
.
UPDATE: As pointed out in the comments, this was in reply to the original question.


q: I'm looking for a good reader/writer lock in C++. We have a use case of a single infrequent writer and many frequent readers and would like to optimize for this. Preferable I would like a cross-platform solution, however a Windows only one would be acceptable.

[A]
You could copy Sun's excellent
ReentrantReadWriteLock
.  It includes features such as optional fairness, lock downgrading, and of course reentrancy.
Yes it's in Java, but you can easily read and transpose it to C++, even if you don't know any Java.  The documentation I linked to contains all the behavioral properties of this implementation so you can make sure it does what you want.
If nothing else, it's a guide.


q:
It currently is 700MB but it's conceivable that it'll grow beyond the 1GB. Normally I just copy this file to another location (for the curious, it's the database of a Zope instance,
a ZODB file).

This file changes little from day to day, but I understand Bacula can't do inside-the-file subdivision for incremental backups. Anyway, it doesn't matter. What I want to do is a full backup daily and keep two of them and a full backup weekly and also keep two of them. So
at any given time I can get yesterday, the day before yesterday, a week
ago and two weeks ago. Would you think that's a good idea?

I suppose I should make two schedules, daily and weekly. But which numbers should I have on the volumes and the pools to achieve this? Two volumes of 1.5GB? Any hints or guidance is welcome, I'm not a sysadmin and my experience with Bacula is very limited.

[A]
In my experience with bacula and backup to disk, it is best to keep one volume per backup job.   That way there is no dead space in the files as jobs expire.  Bacula can reuse the whole volume and it cuts down on disk utilization.  Use the "Set Maximum Volume Jobs = 1" directive in the pool resource.
I would set up two pools, a daily and weekly.  Set the volume retention to two days in the daily and two weeks in the weekly. Schedule the daily on say, mon-sat, and the weekly on sunday.


q: I am getting a DC for a window handle of an object in another program using win32gui.GetDC which returns an int/long.  I need to blit this DC into a memory DC in python.  The only thing I can't figure out how to do is get a wxDC derived object from the int/long that win32gui returns.  None of the wxDC objects allow me to pass an actual DC handle to them from what I can tell.  This of course keeps me from doing my blit. Is there any way to do this?

[A]
From what I can tell, DCs in python are abstracted due to platform variation.  So a device context in python doesn't directly map to a device context in Windows even though many of the methods are direct Windows method calls.  To make this happen it appears you would need to make your own DelegateDC class or something similar that is intended just for Windows so that you could set the DC handle directly.
There might also be some way to attach a wxWindow to the window handle after which you could get a wxWindowDC from the wxWindow...can't figure this out though.


q:
I'm trying to run a shell command using the backtick operators, but the fact that the child process inherits php's open file descriptors is problematic.  Is there a way to keep this from happening?

I'm running PHP 5.1.2

[A]
The only way I really know of is to have the children open up their own resources after forking.
There is a fairly decent tutorial on pcntl here:
http://www.hackingwithphp.com/16/0/0/miscellaneous-topics
http://www.hackingwithphp.com/16/1/4/duplication-of-resources-when-forking


q:
Right now, I have

SELECT gp_id FROM gp.keywords
WHERE keyword_id = 15
AND (SELECT practice_link FROM gp.practices
     WHERE practice_link IS NOT NULL
     AND id = gp_id)

This does not provide a syntax error, however for values where it should return row(s), it just returns 0 rows.

What I'm trying to do is get the gp_id from gp.keywords where the the keywords table keyword_id column is a specific value and the practice_link is the practices table corresponds to the gp_id that I have, which is stored in the id column of that table.

[A]
```
```
select k.gp_id
from gp.keywords as k,
     gp.practices as p
where
keyword_id=15
and practice_link is not null
and p.id=k.gp_id
```
```


q:
Here's the quick and skinny of my issue:

$("a").toggle(function() { /*function A*/ }, function() { /*function B*/ });

Inside function A a form is displayed.  If the user successfully completes the form, the form is hidden again (returning to it's original state).

Inside function B the same form is hidden.

The theory behind this is that the user can choose to display the form and fill it out, or they can click again and have the form go back into hiding.

Now my question is this: currently, if the user fills out the form successfully--and it goes into hiding--the user would have to click on the link twice before returning to the toggle state that displays the form.

Is there anyway to programmatically reset the toggle switch to its initial state?

[A]
jQuery has two
```
.toggle()
```
methods:
```
.toggle()
```
Toggles each of the set of matched
  elements. If they are shown, toggle
  makes them hidden. If they are hidden,
  toggle makes them shown.
```
.toggle(even, odd)
```
Toggle between two function calls every other click.
In this case you want the first one. Something like this should do the trick:
```
```
$("a").click(function() {
    $("#theForm").toggle();
});
```
```


q:
In Windows Server 2003, how I can check if my program is running in local console ("on the screen of the server machine") instead of remote session?

I'm using Delphi Win32, so any Windows API based method should work..

[A]
Wouldn't the session number tell you this ?
ProcessIdToSessionId (GetCurrentProcessId(),&dwSessionNum)
You'd have to check the OS version as well, using GetVersionEx: for everything up to XP/Server 2003 session 0 is local (service or interactive console), anything higher is virtual. For Vista/2008 session 0 and 1 are both local (0 is service, 1 is console), everything else is virtual.
I'm guessing your Delphi units would declare the session number as var, so you wouldn't need the ampersand.


q:
I was playing a bit with Windows Vista (still using XP) and I liked how the standard Control Panel worked. Do you think this design is good also for normal applications?

I like the idea of showing main topics with large fonts + icons. Details within each main topic are displayed using a small font and are immediatelly accessible without the need to browse the menu. Probably everybody knows Vista, but anyway, here is the Control Panel layout.

Compared to a classic layout of icons for main topics and menu for minor topics, the Control Panel GUI seems to be good at first sight.

I haven't seen any app using this kind of GUI, so I don't know if I should rather use the common approach with icons and menu for a common application? Maybe this Control Panel GUI is suitable only for setting some options, other than working with any data?


q:
I've got two collections (generic Lists), let's call them ListA and ListB.

In ListA I've got a few items of type A. In ListB I've got some items of type B that have the SAME ID (but not same type) as the items in ListA, plus many more. I want to remove all the items from ListB that have the same ID as the ones in ListA. What's the best way of doing this? Is Linq to objects a nice fit? What algorithm would you use?

Example

ListA: ItemWithID1, ItemWithID2¨

ListB: ItemWithID1, ItemWithID2, ItemWithID3, ItemWithID4

EDIT: I forgot to mention in my original question that ListA and ListB doesn't contain the same types. So the only way to compare them is through the .Id property. Which invalidates the answers I've gotten so far.

[A]
simple loop:
```
```
for (item i: LISTA) {
    removeItem(i, LISTB);
}

method removeItem(Item, List) {
    for (Item i: List) {
        if (Item == i)
            List.removeItem(i);
    }
}
```
```


q:
Let's say you have several maintenance branches for existing releases of your software. Some developers are making direct changes in the maintenance branches, and merging periodically into the trunk. Now comes an extensive refactoring in the trunk codeline, scheduled for an upcoming major release. But this makes the maintenance branches fundamentally incompatible with the code in the trunk, as they might depend on code that does not exist anymore, for example.

How do you deal with this situation in practise?

[A] At the point that your maintenance branches are no longer compatible with the main trunk, it would be time to create new branches for that purpose. That is, at the start of the big project, you make sure all your developers are aware that new functionality is coming in the main trunk, so that they can make a better choice of where to implement fixes. Presumably, if the code changes occurring in the main trunk are so significant as to render the maintenance non-supportable, then the maintenance should be incorporated into the main trunk.


q:
I have a managed dll that calls into a native library.  This native library generally returns IntPtrs.  These can be passed in to other methods in the native library to do things, or to tell the library to free the instance associated with the IntPtr.  But only some of the instances need to freed in this way, others are managed by the library.  The problem is that the documentation is not always clear about which instances must be freed and which must not.

What I want to know is if there is a way that I can tell if my code has kept references to any of the pointers which must be freed, and so is causing memory to leak?

[A]
Sounds like a classloader hierarchy problem. I can't tell what type of environment your application is deployed in, but sometimes this problem can occur in a web environment - where the application server creates a hierarchy of classloaders, resembling something like:
javahome/lib - as root
appserver/lib - as child of root
webapp/WEB-INF/lib - as child of child of root
etc
Usually classloaders delegate loading to their parent classloader (this is known as "
```
parent-first
```
"), and if that classloader cannot find the class, then the child classloader attempts to. For example, if a class deployed as a JAR in webapp/WEB-INF/lib tries to load a class, first it asks the classloader corresponding to appserver/lib to load the class (which in turn asks the classloader corresponding to javahome/lib to load the class), and if this lookup fails, then WEB-INF/lib is searched for a match to this class.
In a web environment, you can run into problems with this hierarchy. For example, one mistake/problem I've run into before was when a class in WEB-INF/lib depended on a class deployed in appserver/lib, which in turn depended on a class deployed in WEB-INF/lib. This caused failures because while classloaders are able to delegate to the parent classloader, they cannot delegate back down the tree. So, the WEB-INF/lib classloader would ask appserver/lib classloader for a class, appserver/lib classloader would load that class and try to load the dependent class, and fail since it could not find that class in appserver/lib or javahome/lib.
So, while you may not be deploying your app in a web/app server environment, my too-long explanation might apply to you if your environment has a hierarchy of classloaders set up. Does it? Is JPF doing some sort of classloader magic to be able to implement it's plugin features?


q: Where is a reliable registry key to find install location of Excel 2007?


q:
I am writing a web application that will run in kiosk mode on a touch screen. I am currently only targeting it for running on Firefox 3. A few of the use cases I have need to visit external sites. I wish to do so with an embedded browser, which I'm tackling with the help of an <iframe>. I need back/forward buttons for the embedded home page.

I've managed to access the history object of the iframe with

var w = document.getElementById('embeddedBrowser').contentWindow;
w.history.back();

The history of the embedded window is the same as that of the parent window. Therefore for a newly loaded <iframe>, this call will go back to the previous page of the system.

Is there any way to avoid this or a more correct way of solving this?

[A]
You might want to take a look at
Adobe AIR
. It lets you write your application using all the same tools / languages (ajax, html, etc etc), but since it runs as a desktop app and not in a web browser, you have more control over things, such as embedding browser frames and knowing exactly what they are doing, what URL it's going to, controlling it's history, etc.
Look here
for a few pointers on getting started.


q:
I need to search a string and replace all occurrences of %FirstName% and %PolicyAmount% with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the String.Replace() method. I've seen web pages on the subject that suggest

Regex.Replace(strInput, strToken, strReplaceWith, RegexOptions.IgnoreCase);

However for some reason when I try and replace %PolicyAmount% with $0, the replacement never takes place. I assume that it has something to do with the dollar sign being a reserved character in regex.

Is there another method I can use that doesn't involve sanitizing the input to deal with regex special characters?

[A]
```
```
Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);
```
```


q:
I'm sure this is a relatively simple question, and there must be a good sensible rails way of doing it, but I'm not sure what it is.

Basically I'm adding books to a database, and I want to store the Author in a separate table. So I have a table called authors which is referenced by the table books.

I want to create a rails form for adding a book, and I'd like it to be just a simple form for Author, Title, Publisher etc, and if it finds the author already in the authors table then it should just reference that record, and if it isn't in the authors table then it should add a new record and reference it.

I'm sure there's an easy way of doing this in rails - but I can't seem to find it.

Cheers,

Robin

[A]
Assuming that your form passes an author_name and a book hash with the book attributes, you could do the following in your controller:
```
```
@author = Author.find_or_create_by_name(params[:author_name])
@book = Book.new(params[:book])
@book.author = @author
@book.save
```
```
This will find an author by that name, or create one, then assign that author to the book that's created.
Note: This also assumes that authors can be uniquely identified by their name, and this usually isn't the case.  There could be multiple guys namned "Steven King" out there, for instance, and only one of them wrote
The Shining


q:
This is baffling me, maybe somebody can shine the light of education on my ignorance.  This is in a C# windows app. I am  accessing the contents of a listbox from a thread.  When I try to access it like this
prgAll.Maximum = lbFolders.SelectedItems.Count;

I get the error.  However, here is the part I don't get.  If I comment out that line, the very next line
foreach (string dir in lbFolders.SelectedItems)

executes just fine.

Edit:
As usual, my communication skills are lacking.  Let me clarify.

I know that accessing GUI items from threads other than the ones they were created on causes problems.  I know the right way to access them is via delegate.

My question was mainly this:
Why can I access and iterate through the SelectedItems object just fine, but when I try to get (not set) the Count property of it, it blows up.

[A]
```
```
prgAll.Maximum = lbFolders.SelectedItems.Count;
```
```
On that line you perform an assignment (
set/add
), which by default is not thread-safe.
On the second line it's just a
get
operation, where thread-safety merely doesn't matter.
EDIT: I don't mean access to the prgAll element.
Accessing the Count property
changes the internal state
of the ListBox inner collection, that is why it throws the exception.


q: I've got several developers about to start working on the front end of a jquery-based web application. How can we structure the application so that multiple developers can work on the ui at the same time. The end result for the user will just be one web "page", but I don't all of the client development to occur in one file. There is already another team working on the back end.

[A]
If you're starting completely from scratch, you could break it up into the standard 3 tier architecture.
Have one person working on the database structure and creating the appropriate access libraries to the data.
Have one person working on the business/workflow tier, setting up all the interaction of data.
Have the third person doing all of the front end work with jQuery.
I'm sure following this there would be minimal collision, and each could work with some mock data/methods until the official stuff comes online.


q:
I'm looking for the equivalent in Qt to GetTickCount()

Something that will allow me to measure the time it takes for a segment of code to run as in:

uint start = GetTickCount();
// do something..
uint timeItTook = GetTickCount() - start;

any suggestions?

[A]
How about
```
QTime
```
?  Depending on your platform it should have 1 millisecond accuracy.  Code would look something like this:
```
```
QTime myTimer;
myTimer.start();
// do something..
int nMilliseconds = myTimer.elapsed();
```
```


q:
I know that tan(angle) gets me the tangent. But how do I do the "reverse tangent" so that I can get the angle given the length of both sides of the right triangle?

I'm assuming there is a method for this in math.h?

[A]
There should be an atan() function.
For example:
http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.7.html


q:
This is the css for setting the color for h1 text that is linked:

.nav-left h1 a,
a:visited {
  color: #055830;
}

<div class="nav-left">
  <h1><a href="/index.php/housing/">Housing</a></h1>
</div>

It does not look like it is working appropriately, any help is appreciated.

[A]
What about:
```
```
.nav-left h1 a:visited{
    color:#055830;
}
```
```


q:
I'm looking for an UPDATE statement where it will update a single duplicate row only and remain the rest (duplicate rows) intact
as is, using ROWID or something else or other elements to utilize in Oracle SQL or PL/SQL?

Here is an example duptest table to work with:

CREATE TABLE duptest (ID VARCHAR2(5), NONID VARCHAR2(5));

run one INSERT INTO duptest VALUES('1','a');

run four (4) times INSERT INTO duptest VALUES('2','b');

Also, the first duplicate row has to be updated (not deleted), always, whereas the other three (3) have to be remained as is!

Thanks a lot,
Val.

[A]
Will this work for you:
```
```
update duptest
set nonid = 'c'
WHERE ROWID IN (SELECT   MIN (ROWID)
                              FROM duptest
                          GROUP BY id, nonid)
```
```


q:
Can someone explain what this means?

int (*data[2])[2];

[A]
What are the parentheses for?
In C brackets [] have a higher precedence than the asterisk *
Good explanation from Wikipedia:
To declare a variable as being a
  pointer to an array, we must make use
  of parentheses. This is because in C
  brackets ([]) have higher precedence
  than the asterisk (*). So if we wish to declare a pointer to an array, we need to supply parentheses to override this:
```
```
double (*elephant)[20];
```
```
This declares that elephant is a
  pointer, and the type it points at is
  an array of 20 double values.
To declare a pointer to an array of
  pointers, simply combine the
  notations.
```
```
int *(*crocodile)[15];
```
```
Source
.
And your actual case:
```
```
int (*data[2])[5];
```
```
data is an array of 2 elements.  Each element contains a pointer to an array of 5 ints.
So you you could have in code using your 'data' type:
```
```
int (*data[2])[5];
int x1[5];
data[0] = &x1;
data[1] = &x1;

data[2] = &x1;//<--- out of bounds, crash data has no 3rd element
int y1[10];
data[0] = &y1;//<--- compiling error, each element of data must point to an int[5] not an int[10]
```
```


q:
Does YUI have selector methods like jQuery?

e.g. get me all div's that are children of <table> that have links in them?

[A]
Check the
YUI Selector Utility
, it gives you
CSS3
selector sintax, it still in beta but works quite well, check this example:
YAHOO.util.Selector.query


q:
I'm a confused newbie and hobbyist programmer trying to get a grip on this, so forgive me if my question is a little off or doesn't make much sense.

I see a lot of questions on SO revolving around the use of design patterns, and I'm wondering if anyone has a good resources for learning about, and implementing design patterns? I understand the general idea, and know how/when to use a couple of them(Singletons, Factory methods) but I know I'm missing out.

(Just in case it matters, my language of preference is C# but I could learn from examples in other languages)

[A]
Head First Design Patterns
and the
Design Pattern Wikipedia page
are the best resources for beginners.
FluffyCat
is another good, free online resource for design patterns in both
Java
and
PHP
.
The
Gang of Four book
is where to go afterward, but it's fairly advanced, so I'd wait until you have a pretty firm grasp from the other resources.


q:
I am currently publishing code behind .aspx in SharePoint. I can automatically publish the .dll to the bin folder of the virtual directory, but I cannot figure out how to push the .aspx pages and images to the server without manually using SharePoint Designer.

Where does the folder exist?

Or do I need to create a SharePoint feature for this?

[A]
Why not use
shell_exec
and
scp
?
```
```
<?php
    $output = shell_exec('scp file1.txt dvader@deathstar.com:somedir');
    echo "<pre>$output</pre>";
?>
```
```


q:
So this might be really simple, but I haven't been able to find any examples to learn off of yet, so please bear with me. ;)

Here's basically what I want to do:

<div>Lots of content! Lots of content! Lots of content! ...</div>

....

$("div").html("Itsy-bitsy bit of content!");

I want to smoothly animate between the dimensions of the div with lots of content to the dimensions of the div with very little when the new content is injected.

Thoughts?

[A]
maybe something like this?
```
```
$(".testLink").click(function(event) {
    event.preventDefault();
    $(".testDiv").hide(400,function(event) {
        $(this).html("Itsy-bitsy bit of content!").show(400);
    });
});
```
```
Close to what I think you wanted, also try slideIn/slideOut or look at the UI/Effects plugin.


q:
I have the following before_filter:

  def find_current_membership
    respond_to do |wants|
      wants.html { @current_membership = @group.memberships.for(@current_user) }
      wants.rss  {}
      wants.js   { @current_membership = @group.memberships.for(@current_user) }
    end
  end

I would like to share the code for the HTML and JS blocks.  Is there a better way than just throwing the code into a method?  I was hoping this would work:

  def find_current_membership
    respond_to do |wants|
      wants.rss  {}
      wants.all  { @current_membership = @group.memberships.for(@current_user) }
    end
  end

But alas, it did not.

[A]
In this case you could probably do something like:
```
```
before_filter :only => :find_current_membership do |c|
    load_current_membership if not request.format.rss?
end
```
```
Alternatively you could use the request.format.rss? in your controller method to conditionally load the memberships.
Either way your first step should be to refactor that into a method.


q:
I have a c# site which makes use of a lot of images with embedded english text.

How can I use a standard resource file to swap out images depending on the language?

I have a resx file in my App_GlobalResources directory, but I can't seem to get it plugged into an asp:image control for the imageurl correctly.

Ideas?

UPDATE:

For some further information, here is the image tag code:

<asp:image runat="server" ID="img2" ImageUrl="<%$Resources: Resource, cs_logo %>" />

The result on the client side is:

<img id="img2" src="System.Drawing.Bitmap" style="border-width:0px;" />

Note that the source is obviously not what I expected...

[A]
you can store the url of the image in your resource file and use the following inline code in the control
```
```
<asp:Image ImageUrl="<%$resources:Image1 %>" />
```
```
Update
this
link
could be helpful on what you are trying to accomplish
or
you can also try to stored the resource as string and set the value to the url location instead of storing the image in the resouce file.


q:
Simple question really - how do I use text_field_with_auto_complete inside a form_for block?

I've tried doing f.text_field_with_auto_complete but that gives an error, and just using text_field_with_auto_complete by itself doesn't seem to do anything.

Am I missing something here?

[A]
If your intent is to set a id field, you must:
render the results in LI items, each li having it DOM id set up to the id of the returned record, like this:
```
```

Item 1

Item 2

```
```
Your text field would be something like:
```
```
<%= text_field_with_auto_complete :model, :method, {}, :after_update_element => ‘getSelectionId’ % >
```
```
and a javascript method called getSelectionId like this
```
```
function getSelectionId(text, li) {

alert (li.id);

}
```
```
note that you can do anything via javascript since you have the text and the li element available.
Another option is
this plugin


q:
For my web service component, I need to generate a relatively large XML (~500 lines) according to many factors. I am facing a few different choices here:
1. StringBuilder
2. XmlWriter class
3. C# object with serialization???

Which one should I use. Is there any other ways that I am not aware of?

[A]
I generate an RSS feed very simply using LINQ to XML. It's the nicest XML API I know of, to be honest.
I have a a couple of extension methods which I use to make it even easier - it converts from an anonymous type to either elements or attributes:
```
```
public static IEnumerable<XElement> AsXElements(this object source)
  {
      foreach (PropertyInfo prop in source.GetType().GetProperties())
      {
          object value = prop.GetValue(source, null);
          yield return new XElement(prop.Name.Replace("_", "-"), value);
      }
  }

  public static IEnumerable<XAttribute> AsXAttributes(this object source)
  {
      foreach (PropertyInfo prop in source.GetType().GetProperties())
      {
          object value = prop.GetValue(source, null);
          yield return new XAttribute(prop.Name.Replace("_", "-"), value ?? "");
      }
  }
```
```
That may not be at all appropriate for you, but I find it really handy. Of course, this assumes you're using .NET 3.5...


q:
I'm having some problems with the ranking used by fulltext search in SQL Server.

Suppose a user searches for two words, "foo bar".  We assume the user intends to do an OR search, so we pass "foo OR bar" to our CONTAINSTABLE call.  What we're finding is that an row that contains "foo" 10 times but does not contain "bar" will have a much higher rank then an row that that has both "foo" and "bar".
  We would want the row that has both terms to be preferred over a row that only has one term multiple times.  Any advice on how to achieve this?

I have found documentation related to a RANKMETHOD modifier, but that seems to be for SQL Enterprise search only, and not available on regular SQL Server 2005 installs.  We could also switch to Lucene.Net, but I would hope to verify it has the better ranking available.  We might also do multiple searches and merge the results, but that seems undesireable as the number of words searched for increases.

[A]
I did a short discussion on Inverted Indexes and Cosine Ranking (the core algorithms and data structures of full-text retrieval systems)
Here.
On a pure cosine ranking, foo (1), bar (1) should be closer to the vector occupied by foo, bar than foo (10), bar (0).  One can fiddle the cosine value post-hoc, which is essentially what
Pagerank
does.  If the full-text search is fiddling the cosine ranking after calculating the dot product rather than weighting the axes, this would explain the disproportionate significance of foo.


q: We are re-platforming for a client, and they are concerned about SEO. Their current site supports SEO friendly URLs, and so does the new platform. So for those, we are just going to create the same URL mapping. However, they have a large number of other URLs that are not SEO friendly that they want to permanently redirect. These do not follow a similar pattern, so one regex in an .htaccess won't cut it. What is the best way to handle this on a LAMP stack? The application has a front controller too, so I need to make sure that works along with the hard redirects.

[A]
One approach (the one
I chose
) was to create a simple table of old urls and new ones, and then use
mod_rewrite
to read the table and perform redirects.  The table can live in a file external to the Apache config.
Alternatively, you could write a script to query a database if you wanted the table to live in a database.
This means you either need to manually create the mapping, or write some script to output this mapping file.


q:
I'm really stumped on this one. I want to output a list and have the tag file take care of commas, singular versus plural, etc. but when I display the list it completely ignores whitespace so everythingrunstogetherlikethis. I tried using the HTML entities "thinsp", "ensp" and "emsp" (I can't use "nbsp", these have to be breaking), but they're all hideously wide on IE except thinsp which is way too skinny on everything else.

Edit:
 won't work. The output from the tag has no spaces at all. Although any content in the JSP has normal spacing. Obviously I could just put everything in the JSP but this is code that goes on multiple JSPs, so tag files would make a lot of sense.

[A]
Maybe put the jsp content in an html
```
<pre>
```
tag?
This seems to me to be the right thing to do as the list is pre-formatted content.


q:
Consider the following code:

Public Class Animal

Public Overridable Function Speak() As String
    Return "Hello"
End Function

End Class

Public Class Dog
    Inherits Animal

    Public Overrides Function Speak() As String
        Return "Ruff"
    End Function

End Class

Dim dog As New Dog
Dim animal As Animal
animal = CType(dog, Animal)
// Want "Hello", getting "Ruff"
animal.Speak()

How can I convert/ctype the instance of Dog to Animal and have Animal.Speak get called?

[A]
You don't; the subclass's method overrides the superclass's method, by definition of inheritance.
If you want the overridden method to be available, expose it in the subclass, e.g.
```
```
Public Class Dog
    Inherits Animal
    Public Overrides Function Speak() As String
        Return "Ruff"
    End Function
    Public Function SpeakAsAnimal() As String
        Return MyBase.Speak()
    End Function
End Class
```
```


q:
I have a protected Excel worksheet, without a password.
What I'd like to do is trap the event that a user unprotects the worksheet, so that I can generate a message (and nag 'em!). I can setup event checking for the application, for when new workbooks are opened, etc., but not for Unprotect.

Does anyone have an idea?

[A]
It is possible to modify the menu using Tools->Customize. Protect/Unprotect can be set to run a macro, for example:
```
```
Sub UnprotectTrap()
If ActiveSheet.ProtectContents = True Then
    MsgBox "Tut,tut!"
    ActiveSheet.Unprotect
Else
    ActiveSheet.Protect

End If
End Sub
```
```


q:
Is it possible via code to programmatically (from .NET for example via SQL query) to ask an Access database if it is corrupt or have tables with corrupt rows in it?

//Andy

[A]
Here is some VBA that can be used to check for an error in previous releases of Access. It may also suit 2007.
```
```
Sub CheckForErr(tablename)
Dim rs As dao.Recordset
Dim db As Database

Set db = CurrentDb

Set rs = db.OpenRecordset(tname)

With rs
   Do While Not .EOF
        For Each fld In rs.Fields
            If IsError(rs(fld.Name)) Then
               Debug.Print "Error"
            End If
        Next
        .MoveNext
    Loop
End With

rs.Close
Set rs = Nothing

End Sub
```
```


q:
I need to match a string like "one. two.    three. four. five.  six. seven. eight. nine. ten. eleven" into groups of four sentences.  I need a regular expression to break the string into a group after every fourth period. Something like:

  string regex = @"(.*.\s){4}";

  System.Text.RegularExpressions.Regex exp = new System.Text.RegularExpressions.Regex(regex);

  string result = exp.Replace(toTest, ".\n");

doesn't work because it will replace the text before the periods, not just the periods themselves.  How can I count just the periods and replace them with a period and new line character?

[A]
Try defining the method
```
```
private string AppendNewLineToMatch(Match match) {
    return match.Value + Environment.NewLine;
}
```
```
and using
```
```
string result = exp.Replace(toTest, AppendNewLineToMatch);
```
```
This should call the method for each match, and replace it with that method's result. The method's result would be the matching text and a newline.
EDIT: Also, I agree with Oliver. The correct regex definition should be:
```
```
string regex = @"([^.]*[.]\s*){4}";
```
```
Another edit: Fixed the regex, hopefully I got it right this time.


q: I'm using a the TreeView control and it scrolls automatically to left-align TreeViewItem when one of them is clicked.  I've gone looking at my Styles and ControlTemplates, but I haven't found anything.  Is there a default ControlTemplate that causes this? I want to disable it.

[A]
It looks like I found a good clue on
MSDN
:
Sounds like this is an interaction
  with the scrollviewer and the focus
  system.
When an element is focused within a
  ScrollViewer (which is part of the
  TreeView template), the ScrollViewer
  is instructed to make the element
  visible. It automatically responds by
  scrolling to the requested element.
The methods inside of ScrollViewer
  that handle these focus requests are
  all private and / or internal so you
  really can't get to them. I don't
  think there's too much you can do in
  this case; it's just how focus works.
So, is that it? Surely there's a way to modify the TreeView template so that the ScrollViewer won't have this behavior...


q:
I am creating a small web page using PHP that will be accessed as an IFRAME from a couple of sites.  I'm wanting to restrict access to this site to work ONLY within the "approved" sites, and not other sites or accessed directly.  Does anyone have any suggestions?  Is this even possible?  The PHP site will be Apache, and the sites iframing the content will probably be .NET.

Just to clarify, any site can view the page, as long as it's iframe'd within an approved site.  I want to block people from accessing it directly.  I'm thinking cookies might be a solution, but I'm not sure.

[A]
Unfortunately this isn't going to be possible.
Using Javascript you can check to see if your page is embedded in another frame, but this won't be foolproof as Javascript can be turned off in some people's browsers.
For example, you can run the following javascript to reparent your page if that's the intention:
```
```
if (top.location != location) {
  top.location.href = document.location.href ;
}
```
```


q:
By default Windows (XP) shows the underlined hotkeys only, when ALT is pressed. This can be changed in display-properties in the subdialog "Effects" so, that the hotkeys are always underlined

How can it be changed programmatically? Which API-call or registry-setting can be used to change this setting?

[A]
Do you mean you want to change this system-wide setting, or that you want to be able to override the behavior only in your program?
If it's the latter and you're using the Win32 API, it looks like you might be able to catch the WM_CHANGEUISTATE notification:
http://blogs.msdn.com/oldnewthing/archive/2005/05/03/414317.aspx
I've not tried it myself but it seems feasible.
If it's the former you're aiming for, I've not yet been able to discover a method.


q:
Has anybody else had trouble with getting the .Net Framework source code?  Google doesn't have anything to say about this error message, and neither does the CodePlex issue tracker.

Here is the command I'm using to get the source code for the modules that make up mscorlib.dll.  Am I doing something obviously wrong?

NetMassDownloader.exe -o source -f "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll"


q: I'm looking for a way to add a close button to a .NET ToolTip object similar to the one the NotifyIcon has. I'm using the tooltip as a message balloon called programatically with the Show() method. That works fine but there is no onclick event or easy way to close the tooltip. You have to call the Hide() method somewhere else in your code and I would rather have the tooltip be able to close itself.  I know there are several balloon tooltips around the net that use manage and unmanaged code to perform this with the windows API, but I would rather stay in my comfy .NET world. I have a thrid party application that calls my .NET application and it has crashes when trying to display unmanaged tooltips.

[A]
You could try an implement your own tool tip window by overriding the existing one and customizing the onDraw function. I never tried adding a button, but have done other customizations with the tooltip before.
```
```
1    class MyToolTip : ToolTip
    2     {
    3         public MyToolTip()
    4         {
    5             this.OwnerDraw = true;
    6             this.Draw += new DrawToolTipEventHandler(OnDraw);
    7
    8         }
    9
   10         public MyToolTip(System.ComponentModel.IContainer Cont)
   11         {
   12             this.OwnerDraw = true;
   13             this.Draw += new DrawToolTipEventHandler(OnDraw);
   14         }
   15
   16         private void OnDraw(object sender, DrawToolTipEventArgs e)
   17         {
                      ...Code Stuff...
   24         }
   25     }
```
```


q:
So what I have right now is something like this:

PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public);

where obj is some object.

The problem is some of the properties I want aren't in obj.GetType() they're in one of the base classes further up.  If I stop the debugger and look at obj, the I have to dig through a few "base" entries to see the properties I want to get at.  Is there some binding flag I can set to have it return those or do I have to recursively dig through the Type.BaseType hierarchy and do GetProperties on all of them?

[A]
If you access
```
Type.BaseType
```
, you can get the base type. You can recursively access each base type and you'll know when you've hit the bottom when your type is
```
System.Object
```
.
```
```
Type type = obj.GetType();
PropertyInfo[] info = type.GetProperties(BindingFlags.Public);
PropertyInfo[] baseProps = type.BaseType.GetProperties(BindingFlags.Public);
```
```


q:
I have an ASP.NET web site dedicated to reporting on PBX extension stats.  It comprises many report pages, with HTML generated almost purely by code-behind (setting a Label control's Text property instead of using Response.Write), using un-parameterised string literal SQL queries that populate By Reference DataTable parameters.

Maintenance pages at least comprise DataGrids and detail forms, but use the same DAL, on e thing for which can be said is that it supports multiple DB servers, with sub-classes each overriding these access methods with their own string literal queries.

What do I need to consider cleaning up this mess?  I've already made an almost obvious decision to use a third party reporting solution, and move the queries to stored procs in their respective DB languages, narrowing the diversity of the different DAL classes, and to separate CSS out to shared files, as lots of it is very hidden in C# files!

[A]
For your back-end design, I suggest having a class to represent each main table of your database (i.e. a Report class and a User class, for example). Anything that's not an event handler should go in the back-end class files / namespace.
For your GUI, looks like you're on the right track using ASP.NET controls instead of just streaming your data out to the user. However, you may consider objectifying the areas of the page. For example, one of my favorite tricks is to open semitransparent "popup" panels when requiring user input or a something like the Information Bar when displaying a short message.
Consider AJAX and the AJAX Control Toolkit. It's easy to implement (especially in the case of a rewrite) and provides great flexibility. Specifically, I've found Accordions - sometimes even nested within other Accordions - are excellent at organizing overabundances of information.
Edit:
Note that if you were to use AJAX, you basically can't even consider using response.write anymore.
As far as having too much content on the screen, remember Panels have a "Scrollbar" property and DIVs don't without some heavy changes.
Also, I tend to separate my code files by Namespace; but the popular trend is to do so by Class.  This is a better option if you have many Developers or if it's likely several classes within a namespace will be checked out or simultaneously modified by different people.


q:
How do I properly convert two columns from SQL (2008) using Linq into a Dictionary (for caching)?

I currently loop through the IQueryable b/c I can't get the ToDictionary method to work. Any ideas?
This works:

var query = from p in db.Table
            select p;

Dictionary<string, string> dic = new Dictionary<string, string>();

foreach (var p in query)
{
    dic.Add(sub.Key, sub.Value);
}

What I'd really like to do is something like this, which doesn't seem to work:

var dic = (from p in db.Table
             select new {p.Key, p.Value })
            .ToDictionary<string, string>(p => p.Key);

But I get this error:

Cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to
'System.Collections.Generic.IEnumerable'

[A]
```
```
var dictionary = db
    .Table
    .Select(p => new { p.Key, p.Value })
    .AsEnumerable()
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
;
```
```


q:
I read some properties from an xml file, amongst which is a string that refers to an llblgen object for example 'article'. For now I have set up a rather long

Select Case myString
  Case "article"
    return New ArticleEntity()

Etc. which is getting rather ugly as it gets longer and longer ;). Is there a better way to do this ?

(the above is vb.net, but c# examples are fine as well)

[A]
You could store the type names in the file and use:
```
```
return Activator.CreateInstance(Type.GetType("Some.Type.String"));
```
```
(that would work as long as
```
Some.Type.String
```
has a default parameterless constructor.)


q:
I am writing a stored procedure where I have an input parameter called my_size that is an INTEGER. I want to be able to use it in a LIMIT clause in a SELECT statement. Apparently this is not supported, is there a way to work around this?

# I want something like:
SELECT * FROM some_table LIMIT my_size;

# Instead of hardcoding a permanent limit:
SELECT * FROM some_table LIMIT 100;

[A]
A search turned up
this article
.  I've pasted the relevant text below.
Here's a forum post showing an example of prepared statements letting
  you assign a variable value to the limit clause:
http://forums.mysql.com/read.php?98,126379,133966#msg-133966
However, I think this bug should get some attention because I can't
  imagine that prepared statements within a procedure will allow for any
  procedure-compile-time optimizations.  I have a feeling that prepared
  statements are compiled and executed at the runtime of the procedure,
  which probaby has a negative impact on efficiency.  If the limit
  clause could accept normal procedure variables (say, a procedure
  argument), then the database could still perform compile-time
  optimizations on the rest of the query, within the procedure.  This
  would likely yield faster execution of the procedure.  I'm no expert
  though.


q:
How do you go about verifying the type of an uploaded file reliably without using the extension? I'm guessing that you have to examine the header / read some of the bytes, but I really have no idea how to go about it. Im using c# and asp.net.

Thanks for any advice.

ok, so from the above links I now know that I am looking for 'ff d8 ff e0' to positively identify a .jpg file for example.

In my code I can read the first twenty bytes no problem:

                FileStream fs = File.Open(filePath, FileMode.Open);
                Byte[] b = new byte[20];
                fs.Read(b, 0, 20);

so (and please excuse my total inexperience here) but how do I check whether the byte array contains 'ff d8 ff e0'?

[A]
The first few bytes of a file will often tell you the file type.  See, for example,
http://www.garykessler.net/library/file_sigs.html
http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html
Use System.IO to read the byes as binary after the upload.
I'm curious, though, why you can't rely on on the ContentType header?


q:
When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not?

When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"?

[A]
In short, it means there are no restrictions on the object's use. It's the same as
any other object.
A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have.
Depending on the language, this can
  imply:
being expressible as an anonymous literal value
being storable in variables
being storable in data structures
having an intrinsic identity (independent of any given name)
being comparable for equality with other entities
being passable as a parameter to a procedure/function
being returnable as the result of a procedure/function
being constructible at runtime
being printable
being readable
being transmissible among distributed processes
being storable outside running processes
Source
.
In C++ functions themselves are not first class objects, however:
You can override the '()' operator making it possible to have an object function, which is first class.
Function pointers are first class.
boost bind, lambda and function do offer first class functions
In C++, classes are not first class objects but instances of those classes are.  In Python both the classes
and
the objects are first class objects.  (See
this answer
for more details about classes as objects).
Here is an example of Javascript first class functions:
```
```
// f: function that takes a number and returns a number
// deltaX: small positive number
// returns a function that is an approximate derivative of f
function makeDerivative( f, deltaX )
{
    var deriv = function(x)
    {
       return ( f(x + deltaX) - f(x) )/ deltaX;
    }
    return deriv;
}
var cos = makeDerivative( Math.sin, 0.000001);
// cos(0)     ~> 1
// cos(pi/2)  ~> 0
```
```
Source
.
Entities that are not first class objects are referred to as second-class objects.  Functions in C++ are second class because they can't be dynamically created.
Regarding the edit:
EDIT. When one says "everything is
  an object" (like in Python), does he
  indeed mean that "everything is
  first-class"?
The term object can be used loosely and doesn't imply being first class.  And it would probably make more sense to call the whole concept 'first class entities'.  But in Python they do aim to make everything first class.  I believe the intent of the person who made your statement meant first class.


q:
I'd like to check ancestry using two jQuery objects. They don't have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called get()). jQuery's  is() only works with expressions, so this code would be ideal but will not work:

var someDiv = $('#div');

$('a').click(function() {
    if ($(this).parents().is(someDiv)) {
        alert('boo');
    }
}

Just want to see if one element is a child of another and I'd like to avoid stepping back into DOM land if possible.

[A]
You can use the index() method to check if an element exists in a list, so would the following work?
```
```
var someDiv = $('#div');

$('a').click(function() {
    if ($(this).parents().index(someDiv) >= 0) {
        alert('boo');
    }
}
```
```
From
#index reference
.


q:
I feel like I should know this, but I haven't been able to figure it out...

I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text.  I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.

[A]
I think the
```
traceback
```
module might have what you're looking for. In particular, the
```
extract_stack
```
function looks like it will do the job.


q:
This one has me scratching my head.

I'm running Subversion 1.3.1 (r19032) on Ubuntu. All was well until recently when I tried to run svnadmin verify prior to a dump. This is the error message:

svnadmin: Invalid diff stream: insn 0
  cannot be decoded

I have looked around for an explanation and fix but can't seem to find one. Subversion experts, I need your help.

[A]
You should ensure that you are using the correct version of
```
svnadmin
```
for your repository version. It's possible to get errors like this by using the wrong version.
Having said that, version 1.3.x is pretty old now and you should consider upgrading to the latest 1.5.x.
I also found through google that
some versions of SVNKit
can cause this problem.


q:
Has anyone else had any problems using google's Domain Tracking API, I am specifically talking about the _link() method.

The documentation is here

The example provided shows that the _link() method should be used in the onclick event like this:

<a href="http://www.newsite.com" onclick="pageTracker._link('http://www.newsite.com');return false;">Go to our sister site</a>

However, this essentially just makes the link...do nothing (most probably because of the 'return false').

My understanding is that the pageTracker._link() method is 'supposed' to add additional parameters to the url and do it's own document.location style redirect.

Any ideas / catches / previous posts??


q: After reading many of the replies to this thread, I see that many of those who dislike it cite the potential for abuse of the new keyword. My question is, what sort of abuse? How could this be abused so badly as to make people vehemently dislike it? Is it just about purism? Or is there a real pitfall that I'm just not seeing?

[A]
Some see it as a tool that will be abused.  Like "Option Strict Off" and "On Error Resume Next" in VB which "pure" languages like C# and Java have never had.
Many said the same about the "var" keyword, yet I don't see it being abused, once it became understood that it wasn't the same as VB's "Variant"
It could be abused in places that lazy developers don't want type checking on classes and just try catch dynamic calls instead of writing "if blah is Blah ...".
I personally feel it could be used properly in situations like
this
recent question that I answered.
I think the ones really understanding it's power are those heavily into the dynamic .NET languages.


q:
I'm using tortoise svn in Windows.

How can I branch in SVN and have it branch my svn:external folders as well?

[A]
When you create a branch within Subversion you are simply creating a cheap copy of the trunk, branch, or tag that you are branching from. This cheap copy will contain all of the same files and properties as the trunk, branch, or tag that you branched from until you begin to modify the properties or files of the new branch.
However, you may be able to modify one of the 'commit' hooks to modify settings automatically once you commit your branch.
http://svnbook.red-bean.com/en/1.1/ch05s02.html
Otherwise if you want your externals to be modified on the branch you will need to do so manually.


q:
I've been working on a SharePoint project and I have gone the route of loading User Controls through a custom web part.

I have several web controls where I need to dynamically generate hyperlinks (in a loop from a database) that will call certain functions of the User Control when clicked.

When I'm building my own ASP.NET sites, I just add parameters to the hyperlink and check on the page load to see if I need to run any other code when a hyperlink is click.

I'm starting to realize that this probably won't be very reliable inside the SharePoint environment because I don't control the way web page URLs are formed.

I would prefer to have it post back when the hyperlink is clicked and pass some values, but I'm not sure the best way to approach this.

Could someone point me in the right direction?

Thanks.


q:
Does anybody know how to call the import data built-in dialog excel from a macro (vba)?

I've tried Application.Dialogs.Item(...).Show but I can´t find the right dialog.
Please help.

Thanks in advance.

[A]
If you choose the Object Browser and search for say, xlDialogImportTextFile, you will get a list of possible dialogs.
EDIT:
Perhaps something on these lines would suit:
```
```
'Allow user to select text file
sf = Application _
    .GetOpenFilename("Text Files (*.txt), *.txt")
If sf <> False Then
    'Open text file
    Workbooks.OpenText sf
End If
```
```


q:
I'd like to show an image in an iPhone app, but the image I'm using is too big.
I'd like to scale it to fit the iPhone screen, I can't find any class to handle it.

[A]
```
```
UIImageView* view = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"your_image.png"]];
view.frame = CGRectMake(0, 0, width, height);
```
```
To get the frame of the iPhone screen you can use
```
```
CGRect frame = [[UIScreen mainScreen] bounds];
```
```


q:
I have the following intentionally trivial function:

void ReplaceSome(ref string text)
{
    StringBuilder sb = new StringBuilder(text);
    sb[5] = 'a';
    text = sb.ToString();
}

It appears to be inefficient to convert this to a StringBuilder to index into and replace some of the characters only to copy it back to the ref'd param. Is it possible to index directly into the text param as an L-Value?

Or how else can I improve this?

[A]
I don't know if this is more efficient, but it works. Either way you'll have to recreate the string after each change since they're immutable.
```
```
string test = "hello world";
    Console.WriteLine(test);

    test = test.Remove(5, 1);
    test = test.Insert(5, "z");

    Console.WriteLine(test);
```
```
Or if you want it more concise:
```
```
string test = "hello world".Remove(5, 1).Insert(5, "z");
```
```


q:
I'm fairly new to Castle Windsor and am looking into the in's and out's of the logging facility. It seems fairly impressive but the only thing i can't work out is where Windsor sets the Logger property on my classes. As in the following code will set Logger to the nullLogger if the class hasn't been setup yet but when Resolve is finished running the Logger property is set.

private ILogger logger;

public ILogger Logger
{
    get
    {
        if (logger == null)
            logger = NullLogger.Instance;
        return logger;
    }
    set { logger = value; }
}

So what I am wondering is how and where windsor sets my Logger property.

Cheers
Anthony

[A]
The logger is setup by the logging facility, which is in the
```
<facilities>
```
section of the configuration.  For example to use log4net your app or web.config would look something like this:
```
```
<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
    </configSections>
<Configuration>

<castle>

    <facilities>
        <facility id="loggingfacility"
             type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging"
             loggingApi="log4net"
             configFile="logging.config" />
    </facilities>

</castle>
</configuration>
```
```


q:
I have an application where I have a main.m that returns NSApplicationMain(argc,  (const char **) argv);.

I want to run code on -applicationDidFinishLaunching:, but I just dont see how to do it.

Can anyone help or have an example?

Thanks!
-Jason

[A]
The applicationDidFinishLaunching: method of the NSApplication delegate will be called when the app has finished loading. Many of the project templates setup a delegate. If you are using one just add the appropriate method to it.
If your project does not have an app delegate set up you will need to do that yourself. First, make a new class to act as your delegate (you can use an exiting one if there is something logically appropriate). Now make sure that class is instantiated in your MainMenu.nib. Finally, hook the delegate property of the "File's Owner" object to the instantiate delegate in IB.


q:
What are some of the lesser know, but important and useful features of Windows batch files?

Guidelines:

One feature per answer

Give both a short description of the feature and an example, not just a link to documentation

Limit answers to native funtionality, i.e., does not require additional software, like the Windows Resource Kit

Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants.

(See also: Windows batch files: .bat vs .cmd?)

[A]
I have always found it difficult to read comments that are marked by a keyword on each line:
```
```
REM blah blah blah
```
```
Easier to read:
```
```
:: blah blah blah
```
```


q:
I have done this:

$ z() { echo 'hello world'; }

How do I get rid of it?

[A]
```
```
unset -f z
```
```
Will unset the function named z.  A couple people have answered with:
```
```
unset z
```
```
but if you have a function and a variable named z only the variable will be unset, not the function.


q:
Here's the situation - I've got a shell that loads an external .swf. Now, that .swf is 800x600, but it's an animation piece, and there are elements that extends off the stage. When I load the .swf into the shell and call its width attribute, it returns 1200 - because it's including the elements that break out of the stage.

This isn't what I want - ideally, there would be two properties, one to return the 'calculated width' and one to return the 'default width'. Do these properties exist, and if not, what's the best workaround?

[A]
The width and height of the loaded SWF as defined by the FLA it was created with can be found in the
```
Loader
```
object in which you've loaded the SWF into.
```
```
swfLoader.contentLoaderInfo.width
swfLoader.contentLoaderInfo.height
```
```
This will always show you the dimensions as defined in the FLA properties. It makes no difference if any images, MovieClips, or what have you extend off the stage.
The
```
stage.stageWidth
```
and
```
stage.stageHeight
```
properties will always return the width of the stage, the stage is always the top most SWF. In other words, it will always represent the dimensions of the shell's stage. There is only ever one stage in a Flash application.


q:
Using Python I want to be able to draw text at different angles using PIL.

For example, imagine you were drawing the number around the face of a clock.  The number 3 would appear as expected whereas 12 would we drawn rotated counter-clockwise 90 degrees.

Therefore, I need to be able to draw many different strings at many different angles.

[A]
I'm not saying this is going to be easy, or that this solution will necessarily be perfect for you, but look at the documentation here:
http://effbot.org/imagingbook/pil-index.htm
and especially pay attention to the Image, ImageDraw, and ImageFont modules.
Here's an example to help you out:
```
```
import Image
im = Image.new("RGB", (100, 100))
import ImageDraw
draw = ImageDraw.Draw(im)
draw.text((50, 50), "hey")
im.rotate(45).show()
```
```
To do what you really want you may need to make a bunch of separate correctly rotated text images and then compose them all together with some more fancy manipulation.  And after all that it still may not look great.  I'm not sure how antialiasing and such is handled for instance, but it might not be good.  Good luck, and if anyone has an easier way, I'd be interested to know as well.


q:
How do you connect to a remote server via IP address in the manner that TOAD, SqlDeveloper, are able to connect to databases with just the ip address, username, SID and password?

Whenever I try to specify and IP address, it seems to be taking it locally.

In other words, how should the string for cx_Oracle.connect() be formatted to a non local database?

There was a previous post which listed as an answer connecting to Oracle via cx_Oracle module with the following code:

#!/usr/bin/python

import cx_Oracle
connstr='scott/tiger'
conn = cx_Oracle.connect(connstr)
curs = conn.cursor()

curs.execute('select * from emp')
print curs.description
for row in curs:
    print row
conn.close()

[A]
You can specify the server in the connection string, e.g.:
```
```
import cx_Oracle
connstr = 'scott/tiger@server:1521/orcl'
conn = cx_Oracle.connect(connstr)
```
```
"server" is the server, or the IP address if you want.
"1521" is the port that the database is listening on.
"orcl" is the name of the instance (or database service).


q:
Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector.

void buttonVectorCleanup(vector<Button *> dVector){
    Button* tmpClass;
    for(int i = 0; i < (int)dVector.size(); i++){
        tmpClass = dVector[i];

        delete tmpClass;
    }
}

This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.

[A]
The best thing to do is use smart pointers, such as from
Boost
.  Then the objects will be deleted automatically.
Or you can make a template function
```
```
template <class T>
void vectorCleanup(vector<T *>& dVector){
    T* tmpClass;
    for(vector<T*>::size_type i = 0; i < dVector.size(); i++){
        tmpClass = dVector[i];

        delete tmpClass;
    }
```
```
}


q:
I have form area in my view. If I click button A, I want to submit to /Books/1 and if I click button B, I want to submit to /Books/2

How do I achieve this with MVC?

[A]
MVC Views can have multiple forms on a 'page', so just create separate  sections and give each one their own form action.
```
```
<form id="form1" name="form1" action="/Books/1" method="get">
<!--...form fields-->
</form>

<form id="form2" name="form2" action="/Books/2" method="get">
<!--...form fields-->
</form>
```
```


q:
What's the best algorithm for comparing two arrays to see if they have the same members?

Assume there are no duplicates, the members can be in any order, and that neither is sorted.

compare(
    [a, b, c, d],
    [b, a, d, c]
) ==> true

compare(
    [a, b, e],
    [a, b, c]
) ==> false

compare(
    [a, b, c],
    [a, b]
) ==> false

[A]
The best I can think of is O(n^2), I guess.
```
```
function compare($foo, $bar) {
    if (count($foo) != count($bar)) return false;

    foreach ($foo as $f) {
        foreach ($bar as $b) {
            if ($f == $b) {
                // $f exists in $bar, skip to the next $foo
                continue 2;
            }
        }
        return false;
    }
    return true;
}
```
```


q:
Let's say I have two arrays:

int ArrayA[] = {5, 17, 150, 230, 285};

int ArrayB[] = {7, 11, 57, 110, 230, 250};

Both arrays are sorted and can be any size. I am looking for an efficient algorithm to find if the arrays contain any duplicated elements between them. I just want a true/false answer, I don't care which element is shared or how many.

The naive solution is to loop through each item in ArrayA, and do a binary search for it in ArrayB. I believe this complexity is O(m * log n).

Because both arrays are sorted, it seems like there should be a more efficient algorithm.

I would also like a generic solution that doesn't assume that the arrays hold numbers (i.e. the solution should also work for strings). However, the comparison operators are well defined and both arrays are sorted from least to greatest.

[A]
Pretend that you are doing a mergesort, but don't send the results anywhere.  If you get to the end of either source, there is no intersection.  Each time you compare the next element of each, if they are equal, there is an intersection.
For example:
```
```
counterA = 0;
counterB = 0;
for(;;) {
    if(counterA == ArrayA.length || counterB == ArrayB.length)
        return false;
    else if(ArrayA[counterA] == ArrayB[counterB])
        return true;
    else if(ArrayA[counterA] < ArrayB[counterB])
        counterA++;
    else if(ArrayA[counterA] > ArrayB[counterB])
        counterB++;
    else
        halt_and_catch_fire();
}
```
```


q: Most developers understand the concept of wicked problems. What's a good analogy to use when explaining this concept to project managers?

[A]
Every changing requirements lead to an impossible to manage design. Just send him here:
Winchester Mystery House
. The house is filled with staircases to nowhere and doors that open to brick walls. It was built exactly as spec'd, but isn't really what you'd call usable.
Of course up here in New England a "wicked problem" is one that requires a wicked good engineer to come up with a wicked clever solution :)


q:
Will their be a new release of the compact framework with VS2010 and .net 4.0 and if so what new features will it include?
WPF?
linq to SQL?
etc

[A]
I'm not sure about 4.0 for compact devices (although it seems likely),
and I don't know about WPF either, but I can tell you they are going to provide Silverlight for mobile devices giving you access to a subset of WPF.
Haven't found any other references yet...


q:
In DB2, you can name a column ORDER and write SQL like

SELECT ORDER FROM tblWHATEVER ORDER BY ORDER

without even needing to put any special characters around the column name.  This is causing me pain that I won't get into, but my question is:  why do databases allow the use of SQL keywords for object names?  Surely it would make more sense to just not allow this?

[A]
Many SQL parsers (expecially DB2/z, which I use) are smarter than some of the regular parsers which sometimes separate lexical and semantic analysis totally (this separation is mostly a good thing).
The SQL parsers can figure out based on context whether a keyword is valid or should be treated as an identifier.
Hence you can get columns called ORDER or GROUP or DATE (that's a particularly common one).
It does annoy me with some of the syntax coloring editors when they brand an identifier with the keyword color. Their parsers aren't as 'smart' as the ones in DB2.


q:
In an information security lab I'm working on, I've been tasked with executing multiple commands with a single call to "system()" (written in C, running on Fedora).  What is the syntax that will allow me to execute more than command through system()?  (The idea being you could execute arbitrary commands through a program running on a remote computer, if the program interacts with the OS through the system() call.)

I.e.:

char command[] = "????? \r\n";
system(command);

[A]
That depends on the shell being invoked to execute the commands, but in general most shells use
```
;
```
to separate commands so something like this should work:
```
```
command1; command2; command3
```
```
[EDIT]
As @dicroce mentioned, you can use
```
&&
```
instead of
```
;
```
which will stop execution at the first command that returns a non-zero value.  This may or may not be desired (and some commands may return non-zero on success) but if you are trying to handle commands that can fail you should probably not string multiple commands together in a system() call as you don't have any way of determining where the failure occured.  In this case your best bet would either be to execute one command at a time or create a shell script that performs the appropriate error handling and call that instead.


q:
I didn't attend PDC 2008, but I heard some news that C# 4.0 is announced to support Generic covariance and contra-variance. That is, List<string> can be assigned to List<object>. How could that be?

In Jon Skeet's book C# in Depth, it is explained why C# generics doesn't support covariance and contra-variance. It is mainly for writing secure code. Now, C# 4.0 changed to support them. Would it bring chaos?

Anybody know the details about C# 4.0 can give some explanation?

[A]
Variance will only be supported in a
safe
way - in fact, using the abilities that the CLR already has. So the examples I give in the book of trying to use a
```
List<Banana>
```
as a
```
List<Fruit>
```
(or whatever it was) still won't work - but a few other scenarios will.
Firstly, it will only be supported for interfaces and delegates.
Secondly, it requires the author of the interface/delegate to decorate the type parameters as
```
in
```
(for contravariance) or
```
out
```
(for covariance). The most obvious example is
```
IEnumerable<T>
```
which only ever lets you take values "out" of it - it doesn't let you add new ones. That will become
```
IEnumerable<out T>
```
. That doesn't hurt type safety at all, but lets you return an
```
IEnumerable<string>
```
from a method declared to return
```
IEnumerable<object>
```
for instance.
Contravariance is harder to give concrete examples for using interfaces, but it's easy with a delegate. Consider
```
Action<T>
```
- that just represents a method which takes a
```
T
```
parameter. It would be nice to be able to convert seamlessly use an
```
Action<object>
```
as an
```
Action<string>
```
- any method which takes an
```
object
```
parameter is going to be fine when it's presented with a
```
string
```
instead. Of course, C# 2 already has covariance and contravariance of delegates to some extent, but via an actual conversion from one delegate type to another (creating a new instance) - see P141-144 for examples. C# 4 will make this more generic, and (I believe) will avoid creating a new instance for the conversion. (It'll be a reference conversion instead.)
Hope this clears it up a bit - please let me know if it doesn't make sense!


q:
Are there any 'standard' plugins for detecting the CPU architecture in scons?

BTW, this question was asked already here in a more general form... just wondering if anyone has already taken the time to incorporate this information into scons.

[A]
Something like this?
```
```
env = Environment()
conf = Configure(env)
if conf.CheckDeclaration("__i386__"):
    conf.Define("MY_ARCH", "blahblablah")
env = conf.Finish()
```
```


q:
My database consists of 3 tables (one for storing all items, one for the tags, and one for the relation between the two):

Table: Post
Columns: PostID, Name, Desc

Table: Tag
Columns: TagID, Name

Table: PostTag
Columns: PostID, TagID

What is the best way to save a space separated string (e.g. "smart funny wonderful") into the 3 database tables shown above?

Ultimately I would also need to retrieve the tags and display it as a string again.    Thanks!

[A]
If you have a Tag Table, wouldn't you have a row for each Tag?
```
```
tag.id = 1; tag.name = 'smart'
tag.id = 2; tag.name = 'funny'
tag.id = 3; tag.name = 'wonderful'
```
```
In Groovy/Grails, you'd retrieve them as a list, possibly concatenating them into a space separated list for display.
Unless I'm really misunderstanding the question, Groovy/Grails/GORM will handle this with little or no code with the default scaffolding, no real coding required.


q: Many examples of macros seem to be about hiding lambdas, e.g. with-open-file in CL. I'm looking for some more exotic uses of macros, particularly in PLT Scheme. I'd like to get a feel for when to consider using a macro vs. using functions.

[A]
I'll start answering the last question. When to use a macro instead of a function. The macros do things the functions can't, and the functions do thing the macros can't, so it'll be hard to mix them, but let's go deeper.
You use functions when you want the arguments evaluated and macros when you want the arguments un-evaluated. That's not very useful, is it? You use macros when you want to write something in a different way, when you see a pattern and you want to abstract. For example: I define three functions called foo-create, foo-process and foo-destroy for different values of foo and with similar bodies where the only change is foo. There's a pattern but a too-high level for a function, so you create a macro.
In my humble experience, macros in Scheme are to used as much as in other Lisps, like Common Lisp or
Clojure
. I suppose it's proof that maybe hygienic macros are not such a good idea, and here I would disagree with Paul Graham about why. It's not because sometimes you want to be dirty (un-hygienic) but because hygienic macros end up being complex or convoluted.


q:
This is similar to this question, but I want to include the path relative to the current directory in unix. If I do the following:

ls -LR | grep .txt

It doesn't include the full paths. For example, I have the following directory structure:

test1/file.txt
test2/file1.txt
test2/file2.txt

The code above will return:

file.txt
file1.txt
file2.txt

How can I get it to include the paths relative to the current directory using standard Unix commands?

[A]
Try
```
find
```
. You can look it up exactly in the man page, but it's sorta like this:
```
find [start directory] -name [what to find]
```
so for your example
```
find . -name "*.txt"
```
should give you what you want.


q:
When running PHP in CLI mode, most of the time (not always), the script will hang at the end of execution for about 5 seconds and then output this:

Error in my_thread_global_end(): 1 threads didn't exit

It doesn't seem to actually have any effect on the script itself.

Some web searches turned up blogs which suggest replacing the php_mysql.dll with a different version, however this has not solved the issue for me, and I suspect the info from those blogs is now out of date.

My setup:

PHP Version 5.2.4

Apache/2.2.4 (Win32)

Windows Vista Home Premium SP1

[A]
Did you take a look at
this resource
? You may want to double check that you got a specific libmysql.dll (5.2.1) that is unaffected by this, and also to double check that you don't have any stray mysql libraries lying around that PHP could be picking up instead. Or, switch from FastCGI if that's an option for you.
For interests sake, the bug appears to be best detailed
here
. The general idea of the problem (from the mysql bug link) appears to be:
```
```
Whenever a new thread is created libmysql is told about that by Windows. It then
increases a thread counter and initializes some data. When libmysql is being unloaded
it checks whether all threads have finished, if not it tries to tell them "close now"
and gives them 5 seconds for that. In general this works in a nice way.
```
```


q:
Is it possible for the .NET CLR to support Objective-C? Are there any reasons (either from a legal or implementational) standpoint why this wouldn't be possible?

In the spirit of cross-platform application development, it would be nice to be able to write and run Objective-C applications on Windows machines. At least I think it would.

[A]
No, there really aren't.  .NET compiles to
IL
(or CIL or MSIL) which is basically machine code for a virtual machine.  You can program in IL like you do in assembly (not that I've seen anyone do it).  If you had the experience, knowledge, and gumption there would be no problem writing an Objective-C to IL compiler.  Hell, there are even
functional programming languages (F#)
for .NET.  Besides the messaging capabilities and the libraries, it's not too different from C#, VB.NET, etc.
What an awesome idea!  Objective-C# or some such.
Here's where you might start:
Wikipedia on Microsoft's IL


q:
For example, when I'm dividing two ints and want a float returned, I superstitiously write something like this:

int a = 2, b = 3;
float c = (float)a / (float)b;

If I do not cast a and b to floats, it'll do integer division and return an int.

Similarly, if I want to multiply a signed 8-bit number with an unsigned 8-bit number, I will cast them to signed 16-bit numbers before multiplying for fear of overflow:

u8 a = 255;
s8 b = -127;
s16 = (s16)a * (s16)b;

How exactly does the compiler behave in these situations when not casting at all or when only casting one of the variables? Do I really need to explicitly cast all of the variables, or just the one on the left, or the one on the right?

[A]
Division of integers:  cast any one of the operands, no need to cast them both.  If both operands are integers the division operation is an integer division, otherwise it is a floating-point division.
As for the overflow question, there is no need to explicitly cast, as the compiler implicitly does that for you:
```
```
#include <iostream>
#include <limits>

using namespace std;
int main()
{
    signed int a = numeric_limits<signed int>::max();
    unsigned int b = a + 1; // implicit cast, no overflow here
    cout << a << ' ' <<  b << endl;
    return 0;
}
```
```


q:
In SQL Server given a Table/View how can you generate a definition of the Table/View in the form:

C1 int,

  C2 varchar(20),

  C3 double

The information required to do it is contained in the meta-tables of SQL Server but is there a standard script / IDE faciltity to output the data contained there in the form described above ?.

For the curious I want this as I have to maintain a number of SP's which contain Table objects (that is a form of temporary table used by SQL Server). The Table objects need to match the definition of Tables or Views already in the database - it would make life a lot easier if these definitions could be generated automatically.

[A]
If you want to duplpicate a table definition you could use:
```
```
select top 0
  *
into
  newtable
from
  mytable
```
```
Edit: Sorry, just re-read your question, and realised this might not answer it. Could you be clear on what you are after, do you want an exact duplicate of the table definition, or a table that contains information about the tables definition?


q:
For example, using the answer for this question:

How to select all users who made more than 10 submissions
"How to select all users who made more than 10 submissions."

select userId
from submission
group by userId
having count(submissionGuid) > 10

Let's say now I want to know many rows this sql statement outputted. How scalable is the solution for counting the rows of counting the rows?

[A]
In SQL Server you could do
```
```
select @@ROWCOUNT
```
```
immediately following the query you posted.


q:
What I want to do is scroll down the window when I expand elements in my page.

The effect I am trying to achieve is like the Stack Overflow comments. If it expands beyond the page, it scrolls down to fit all the comments in the window.

What is the best way of doing this?

Edit: I am using JQuery.

[A]
If you have the advantage of using Prototype, you can use
```
$(element).scrollTo()
```
.
Otherwise, the general idea is to calculate the cumulative offset of the element, then set
```
window.scrollTop
```
(and
```
window.scrollLeft
```
) accordingly.


q:
Like, let's say I had a tree structure, then I would use, naturally a tree control, since that GUI element maps perfectly to the structure.

But what I have is a graph, potentially too wide to fit in one web page.  I can't think of examples of GUIs that really match the structure.  Some ideas I have that don't quite fit are, the web itself, with hyperlinks, the browser back button, and the forward button.   But that just shows you one node at a time.  I would like to display as many nodes as I can, and allow navigation to a new area of the graph.   Something like Google maps might be a good model, in that you have full freedom to scroll in any direction.

[A]
Facebook used to do this,
way
back in the day, to visualize your friends. They drew nodes as little boxes, with lines connecting them, as expected. They drew the graphs into an SVG image, so you could easily zoom in and out.
Another option might be to draw into a
```
<canvas>
```
tag and scale that somehow. I imagine that's possible, but I don't know much about
```
<canvas>
```
Another option would be to draw it into an inline frame or other box that allows the user to scroll horizontally and vertically.


q:
I use screen to persist my work session and connect to the same session from multiple machines. How can I setup SSH and screen such that the XDISPLAY variable inside my persistent screen session is always set to the machine I am currently connecting from?

ie. I start the screen session at work and use gvim, which uses the X server running on my work machine. Later, I connect to the same session from home and also want to use gvim. But this time, I want gvim to use the X server on my home machine. I realize I could manually update XDISPLAY every time I connect from a different machine but I'd rather have an automated system.

Bonus points if I can actually move gvim from my work machine to my home machine while it is running. I tried xmove but could never get it to play nice.

[A]
There is no "trivial" way to change environment variables in foreign processes.
A straightforward solution might be to persist your
```
XDISPLAY
```
into a file on login and use a
```
PROMPT_COMMAND
```
to read this file before printing the next prompt.
For moving X applications around look at something like
```
X11vnc
```
or
```
Xvnc
```
.


q:
As a second interview I get people to sit down and write code...I try to make the problem really technology independent.

My programming problems that I have don't really exercise peoples OO abilities.  I tend to try and keep the coding problem solvable within 2 hours ish.  So, I've struggled to find a problem small enough and involved enough that it exposes peoples OO design skills.

Any suggestions?

[A]
These aren't specifically OO Questions, but check out the other questions tagged
interview-questions
Edit: What about implementing some
design patterns
? I don't have the best knowledge in the area but it seems as if you would be getting two questions for the price of one. You can test for both OO and Design pattens in the one question.


q:
I have recently discovered the incredibly useful Eclipse Memory Analysis Tool, which makes quick work of finding memory leaks in Java applications.  Unfortunately, after switching my JDK to 1.6 (under Mac OS 10.5), the JVM terminates immediately upon startup.  All that appears is a dialog stating "JVM terminated" with "Exit code = -1".

Anyone else encounter this one? Perhaps there is a way to configure it to use a different JDK?  (such as 1.5: which it was shown to be compatible with)

[A]
The official Java 6 for the Mac only has a 64 bit data model. Unfortunately, Eclipse uses Carbon on the Mac which is only available in 32 bits. In short, it is impossible to run Eclipse with the official Java 6 distribution.
The classical solution to this is to set the default VM to Java 5, and then choose Java 6 as the JRE/JDK within Eclipse.
If you really need to run Eclipse with Java 6, then you could take a look at
SoyLatte
which is a build of OpenJDK which both supports 32 and 64 bit modes.


q:
What does InitializeComponent() do, and how does it work in WPF?

In general first, but I would especially be interested to know the gory details of order of construction, and what happens when there are Attached Properties.

[A]
The call to
```
InitializeComponent()
```
(which is usually called in the default constructor of at least
```
Window
```
and
```
UserControl
```
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the
```
Window
```
/
```
UserControl
```
that is loading, and passes it to the
```
System.Windows.Application.LoadComponent()
```
static method.
```
LoadComponent()
```
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail,
```
LoadComponent
```
creates an instance of the
```
XamlParser
```
, and builds a tree of the XAML. Each node is parsed by the
```
XamlParser.ProcessXamlNode()
```
. This gets passed to the
```
BamlRecordWriter
```
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the
```
InitializeComponent
```
is a method on the
```
System.Windows.Markup.IComponentConnector
```
interface, of which
```
Window
```
/
```
UserControl
```
implement in the partial generated class.
Hope this helps!


q: I have a legacy app where it reads message from a client program from file descriptor 3. This is an external app so I cannot change this. The client is written in C#. How can we open a connection to a specific file descriptor in C#? Can we use something like AnonymousPipeClientStream()? But how do we specify the file descriptor to connect to?

[A]
Unfortunately, you won't be able to do that without P/Invoking to the native Windows API first.
First, you will need to open your file descriptor with a native P/Invoke call. This is done by the OpenFileById WINAPI function.
Here's how to use it
on MSDN,
here's an other link
explaining it in detail on the MSDN forums, and
here's some help (pinvoke.net)
on how to construct your P/Invoke call.
Once you got the file handle, you need to wrap it in a SafeFileHandle, this time in safe, managed C#:
```
```
// nativeHandle is the WINAPI handle you have acquired with the P/Invoke call
SafeFileHandle safeHandle = new SafeFileHandle(nativeHandle, true);
```
```
Now you can open the file stream directly:
```
```
Stream stream = new FileStream(safeHandle, FileAccess.ReadWrite);
```
```
And from this point you can use it as any other file or stream in C#. Don't forget to dispose your objects once you're done.


q:
I have a site behind basic authentication (IIS6).

Part of this site calls a web service that is also part of the site and thus behind basic authentication as well.

However, when this happens the calling code receives a 401 Authentication Error.

I've tried a couple of things, with the general recommendation being code like this:

Service.ServiceName s = new Service.ServiceName();
s.PreAuthenticate = true;
s.Credentials = System.Net.CredentialCache.DefaultCredentials;
s.Method("Test");

However, this does not seem to resolve my problem.

Any advice?

Edit

This seems to be a not uncommon issue but so far I have found no solutions.
Here is one thread on the topic.

[A]
The Line:
```
```
s.Credentials = System.Net.CredentialCache.DefaultCredentials();
```
```
Maybe you should try :
```
```
s.Credentials = HttpContext.Current.User.Identity;
```
```


q: For general code, do I really need to dispose an object?  Can I just ignore it for the most part or is it a good idea to always dispose an object when your 100% sure you don't need it anymore?

[A]
If the object implements IDisposable, you should dispose of it as soon as you are done with it. The easiest way is to surround it with a
using
block:
```
```
using (SqlCommand cmd = new SqlCommand(conn)) {
    cmd.ExecuteNonQuery();
}
```
```


q:
I have a vba macro which runs a loop for about 200 iterations, using up the ram page file as it runs.

I need some kind of quick fix to clear the page file after every iteration. I know the best fix would be to clean up the code, but time is a constraint here.

[A]
At the end of each loop iteration set any objects that will be re-created to
```
Nothing
```
.
This
article
explains it in detail.


q:
If I were to include .Net Framework setup file along with my apps (installation process is done by our own technician), to be install on a clean Windows (XP SP2/SP3 or Vista SP1) without prior installation of any framework, which of the .Net Framework setup do I need to install in sequence, to get to 3.5 SP1?
Currently I have the setup file for:

.Net 2.0

.Net 2.0 SP1

.Net 3.0

.Net 3.5

.Net 3.5 SP1

All redistributable version.

EDIT : I need the full installation, client profile won't work as our client's machine might not have internet access. Basically I need a install-and-forget-it procedure, so when we decided to use anything new within 3.5 SP1 later, we can rest assure that we can just simple apply update our apps without having to install another pre-requisite

[A]
NET 3.5 SP1 introduces a new setup package option for developers building .NET client applications called the "
.NET Framework Client Profile
".This provides a new setup installer that enables a smaller, faster, and simpler installation experience for .NET client applications on machines that do not already have the .NET Framework installed.
The .NET Framework Client Profile setup contains just those assemblies and files in the .NET Framework that are typically used for client application scenarios.  For example: it includes Windows Forms, WPF, and WCF.  It does not include ASP.NET and those libraries and components used primarily for server scenarios.  We expect this setup package to be about
26MB
in size, and it can be downloaded and installed much quicker than the full .NET Framework setup package.


q:
What is the best way to extract the MAC address from ifconfig's output?

Sample output:

bash-3.00# ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 1F:2E:19:10:3B:52
          inet addr:127.0.0.66  Bcast:127.255.255.255  Mask:255.0.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          ....
          ....

Should I use cut, AWK or anything else, and what are the merits and demerits of one method over the other.

[A]
Not sure whether there really are any advantages, but you can simply use awk:
```
```
ifconfig eth0 | awk '/HWaddr/ {print $5}'
```
```


q:
i would like to release a snapshot project 'foo-1.0-SNAPSHOT' using the maven release plugin. The project depends on a 3rd party module 'bar-1.0-SNAPSHOT' which is not released yet.
I use the option 'allowTimestampedSnapshots' in my project's pom.xml to allow timestamped snapshots but i assume that the 3rd party module (bar) is not timestamped unless i build it myself as maven still complains about unresolved SNAPSHOT dependencies.

Is there a way to release the project foo regardless of dependent SNAPSHOT projects and if not how could i add a timestamp to the 3rd party project?

[A]
The short answer is see the
following answer
.... the long answer is you can work around it.
The only way I have coped in the past is to effectively fork the 3rd party library and cut a release myself. This of course is easier said than done and is just plain difficult if the library is large and complex and impossible if the 3rd party library is closed source. An easier route maybe to approach the 3rd party and ask them to cut a release.
Another option may be to copy their pom (ensure that it has no snapshots) change the version information and manually install the pom and artifact in your repository.


q: How do you go about finding unused icons, images, strings in .resx files that may have become 'orphaned' and are no longer required?

[A]
This is no information an algorithm can reliably compute. The inspected program could fetch a list of all resources and do something with them, like letting the user choose from several icons.
Your best bet is probably to search for all references to your resource-access API of choice and inspect those manually. Using
```
grep
```
/
```
sed
```
you might be able to reduce the sites you have to inspect manually by handling all "easy" ones where a simple string is used.