q:
I've got a problem similar to,but subtly different from, that described here (Loading assemblies and their dependencies).

I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL?

Say now our customer has a .NET app that can be either 32 or 64bit, and that it being a pure .NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time?

Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?

[A]
I encountered a similar scenario a while back. A toolkit I was using did not behave well in a 64-bit environment and I wasn't able to find a way to dynamically force the assemblies to bind as 32 bit.
It is possible to force your assemblies to work in 32 bit mode, but this requires patching the CLR header, (there is a tool that does that in the Framework) and if your assemblies are strongly-named, this does not work out.
I'm afraid you'll need to build and publish two sets of binaries for 32 and 64 bit platforms.


q:
I am trying to replace the current selection in Word (2003/2007) by some RTF string stored in a variable.

Here is the current code:

Clipboard.SetText(strRTFString, TextDataFormat.Rtf)
oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0)

Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?

[A]
You can use a RichTextbox to convert RTF to text or vice versa.
```
```
RichTextBox r = new RichTextBox();
r.Rtf = strRTFString;
Console.WriteLine(r.Text);
```
```

s: huggingface

c: devops

d: intermediate


q:
I flatter myself that I'm a good programmer, and can get away with graphic design. But something I'm incapable of doing is coming up with good names - and it seems neither are the people I work with. We're now in the slightly ludicrous situation that the product we've been working on for a couple of years is being installed to customers, is well received and is making money - but doesn't yet have a name.

We're too small a company to have anything like a proper marketing division to do this thing. So how have people tended to choose names, logos and branding?

[A]
You should try
BustaName
.  It basically combines words to create available domain names.  You are able to choose similar words for the words that you previously entered.
Also try these links out:
Naming a company
77 ways to come up with an idea
Igor Naming Guide
(PDF)


q:
I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread.  I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.

Based on the community suggestions, I've used this:

// earlier in the code
mCoolObject.CoolEvent+=
           new CoolObjectEventHandler(mCoolObject_CoolEvent);
// then
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    if (InvokeRequired)
    {
        CoolObjectEventHandler cb =
            new CoolObjectEventHandler(
                mCoolObject_CoolEvent);
        Invoke(cb, new object[] { sender, args });
        return;
    }
    // do the dirty work of my method here
}

[A]
I shun redundant delegate declarations.
```
```
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    if (InvokeRequired)
    {
        Invoke(new Action<object, CoolObjectEventArgs>(mCoolObject_CoolEvent), sender, args);
        return;
    }
    // do the dirty work of my method here
}
```
```
For non-events, you can use the
```
System.Windows.Forms.MethodInvoker
```
delegate or
```
System.Action
```
.
EDIT: Additionally, every event has a corresponding
```
EventHandler
```
delegate so there's no need at all to redeclare one.


q:
Is there any way to tinker with the iPhone SDK on a Windows machine? Are there plans for an iPhone SDK version for Windows?

The only other way I can think of doing this is to run a Mac VM image on a VMWare server running on Windows, although I'm not too sure how legal this is.

[A]
It's certainly possible to develop on a Windows machine, in fact, my first application was exclusively developed on the old Dell Precision I had at the time :)
There are three routes;
Install
OSx86
(aka iATKOS / Kalyway) on a second partition/disk and dual boot.
Run Mac OS X Server under VMWare (Mac OS X 10.7 (Lion) onwards, read the update below).
Use a framework and/or toolset, which allows developing on Windows, like Delphi XE4 with the mac-in-cloud service, which can build without MacOS device need. This is a commercial toolset, but the component and lib support is growing.
Other honorable mentions are
Flutter
,
Xamarin
and similar; which may at end need actual MacOS device for final build (but you can test on Android till then, as they're cross-platform).
The first route requires modifying (or using a pre-modified) image of Leopard that can be installed on a regular PC. This is not as hard as you would think, although your success/effort ratio will depend upon how closely the hardware in your PC matches that in Mac hardware - e.g. if you're running a Core 2 Duo on an Intel Motherboard, with an NVidia graphics card you are laughing. If you're running an AMD machine or something without SSE3 it gets a little more involved.
If you purchase (or already own) a version of Leopard then this is a gray area since the Leopard EULA states you may only run it on an "Apple Labeled" machine. As many point out if you stick an Apple sticker on your PC you're probably covered.
The second option is more costly. The EULA for the workstation version of Leopard prevents it from being run under emulation and as a result, there's no support in VMWare for this. Leopard server, however, CAN be run under emulation and can be used for desktop purposes. Leopard server and VMWare are expensive, however.
If you're interested in option 1) I would suggest starting at
Insanelymac
and reading the OSx86 sections.
I do think you should consider whether the time you will invest is going to be worth the money you will save though. It was for me because I enjoy tinkering with this type of stuff and I started during the early iPhone betas, months before their App Store became available.
Alternatively, you could pick up a low-spec Mac Mini from eBay. You don't need much horsepower to run the SDK and you can always sell it on later if you decide to stop development or buy a better Mac.
Update: You cannot create a Mac OS X Client virtual machine for OS X 10.6 and earlier. Apple does not allow these Client OSes to be virtualized. With Mac OS X 10.7 (Lion) onwards, Apple has changed its licensing agreement in regards to virtualization. Source:
VMWare KnowledgeBase


q: I'm wondering how you can implement a program similar to tail -f in C/C++, a program that watches for and processes new lines added to a log file?

[A]
See here
You could either call out to tail and retrieve the stream back into your app, or as it's open source, maybe try to pull it into your own code.
Also, it is possible in C++ iostream to open a file for viewing only and just read to the end, while buffering the last 10-20 lines, then output that.


q: I'm looking at the PHP Manual, and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?

[A]
PHP has arrays, which are actually associative arrays and can also be used as sets. Like many interpreted languages, PHP offers all this under one hood instead of providing different explicit data types.
E.g.
```
```
$lst = array(1, 2, 3);
$hsh = array(1 => "This", 2 => "is a", 3 => "test");
```
```
Also, take a look
in the manual
.


q:
I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done...

With the release of ColdFusion 8, we got the CFImage tag, but it doesn't support this conversion; and nor does Image.cfc, or Alagad's Image Component.

However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process:

<cfset jthread = createObject("java", "java.lang.Thread")/>
<cfset jthread.sleep(5000)/>

I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here?

[A]
A very simple formula for converting from CMYK to RGB ignoring all color profiles is:
```
R = ( (255-C)*(255-K) ) / 255;
    G = ( (255-M)*(255-K) ) / 255;
    B = ( (255-Y)*(255-K) ) / 255;
```
This code requires CMYK values to be in rage of 0-255. If you have 0 to 100 or 0.0 to 1.0 you'll have to convert the values.
Hope this will get you started.
As for the java and ColdFusion interfacing, I'm sorry, but I have no idea how to do that.


q:
I am looking for information on handling search in different ORMs.

Currently I am redeveloping some old application in PHP and one of requirements is: make everything or almost everything searchable, so user just types "punkrock live" and the app finds videos clips, music tracks, reviews, upcoming events or even user comments labeled that way.

In environment where everything is searchable ORM need to support this feature in two ways:

providing some indexing API on "O" side of ORM

providing means for bulk database retrieval on "R" side

Ideal solution would return ready made objects based on searched string.
Do you know any good end-to-end solutions that does the job, not necessarily in PHP?
If you dealt with similar problem it would be nice to listen what your experience is. Something more than Use Lucene or semantic web is the way oneliners, tho ;-)*

[A]
I have recently integrated the
Compass
search engine into a Java EE 5 application. It is based on
Lucene Java
and supports different ORM frameworks as well as other types of models like XML or no real model at all ;)
In the case of an object model managed by an ORM framework you can annotate your classes with special annotations (e.g. @Searchable), register your classes and let Compass index them on application startup and listen to changes to the model automatically.
When it comes to searching, you have the power of Lucene at hand. Compass then gives you instances of your model objects as search result.
It's not PHP, but you said it didn't have to be PHP necessarily ;) Don't know if this helps, though...


q:
I have this gigantic ugly string:

J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM
J0000010: Project name: E:\foo.pf
J0000011: Job name: MBiek Direct Mail Test
J0000020: Document 1 - Completed successfully

I'm trying to extract pieces from it using regex. In this case, I want to grab everything after Project Name up to the part where it says J0000011: (the 11 is going to be a different number every time).

Here's the regex I've been playing with:

Project name:\s+(.*)\s+J[0-9]{7}:

The problem is that it doesn't stop until it hits the J0000020: at the end.

How do I make the regex stop at the first occurrence of J[0-9]{7}?


q:
I'm going to be working on some iPhone apps so I've been given a golden ticket to buy a Mac. However the golden ticket isn't worth that much, and I'm thinking iMac. Now, Macs are great, I love 'em and use 'em at home, but I know that the iMac is geared more towards the average consumer than the professional. Is an iMac going to be powerful enough to do iPhone development on?

If it helps any, the only thing I envision doing on the Mac is running XCode and maybe a web browser.

Is there anybody out there doing iPhone development and having trouble running the required tools on their machine? If so, what do you have?

[A] I run XCode on a 17" iMac (2 yrs old) with 2GB of RAM and haven't had any trouble.


q: How do I select all records that contain "LCS" within the title column in sql.

[A]
```
```
SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%';
```
```
% is the wild card matcher.


q:
I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines.

I tried this but it just barfs.

preg_match(
    '^J[0-9]{7}:\s+
    (.*?)             #Extract the Transaction Start Date msg
    \s+J[0-9]{7}:\s+Project\sname:\s+
    (.*?)             #Extract the Project Name
    \s+J[0-9]{7}:\s+Job\sname:\s+
    (.*?)             #Extract the Job Name
    \s+J[0-9]{7}:\s+',
    $this->getResultVar('FullMessage'),
    $atmp
);

Is there are way to pass a regex in the above form to preg_match?

[A]
You can use the extended syntax:
```
```
preg_match("/
    test
/x", $foo, $bar);
```
```


q:
I need to find out how to format numbers as strings. My code is here:

return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm

Hours and minutes are integers, and seconds is a float.  the str() function will convert all of these numbers to the tenths (0.1) place.  So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".

Bottom line, what library / function do I need to do this for me?

[A]
Starting with Python 3.6, formatting in Python can be done using
formatted string literals
or
f-strings
:
```
```
hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
```
```
or the
```
str.format
```
function starting with 2.7:
```
```
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
```
```
or the
string formatting
```
%
```
operator
for even older versions of Python, but see the note in the docs:
```
```
"%02d:%02d:%02d" % (hours, minutes, seconds)
```
```
And for your specific case of formatting time, there’s
```
time.strftime
```
:
```
```
import time

t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
```
```


q:
What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?

try
{
    //some code
}
catch (Exception ex)
{
    throw ex;
}

Vs:

try
{
    //some code
}
catch
{
    throw;
}

[A]
The way to preserve the stack trace is through the use of the
```
throw;
```
This is valid as well
```
```
try {
  // something that bombs here
} catch (Exception ex)
{
    throw;
}
```
```
```
throw ex;
```
is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the
```
throw ex;
```
statement.
Mike
is also correct, assuming the exception allows you to pass an exception (which is recommended).
Karl Seguin
has a
great write up on exception handling
in his
foundations of programming e-book
as well, which is a great read.
Edit: Working link to
Foundations of Programming
pdf. Just search the text for "exception".


q: From a desktop application developer point of view, is there any difference between developing for Windows XP and developing for Windows Vista?

[A]
Do not
ever
assume your user has access to certain key areas of the disc (i.e. program files, windows directory etc). Instead the default user account will only be able to write to a small section of their application data. Also, they won't be able to write to global areas of the registry - only the current user section.
You can of course elevate their privileges, but that in itself is a task.
Generally programming for Vista is the same as XP, it's just the new account restrictions you have to be wary of.
Have a look at this page with regards to making your application "UAC aware"
http://www.codeproject.com/KB/vista-security/MakingAppsUACAware.aspx


q:
I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.

The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows .bat file to download the actual MP3 file. I would prefer to have the entire utility written in Python.

I struggled to find a way to actually download the file in Python, thus why I resorted to using wget.

So, how do I download the file using Python?

[A]
Use
```
urllib.request.urlopen()
```
:
```
```
import urllib.request
with urllib.request.urlopen('http://www.example.com/') as f:
    html = f.read().decode('utf-8')
```
```
This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers.
On Python 2, the method is in
```
urllib2
```
:
```
```
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
```
```


q:
How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel?

Edit: A language-agnostic algorithm to determine this is the main goal here.

[A]
I once wrote this function to perform that exact task:
```
```
public static string Column(int column)
{
    column--;
    if (column >= 0 && column < 26)
        return ((char)('A' + column)).ToString();
    else if (column > 25)
        return Column(column / 26) + Column(column % 26 + 1);
    else
        throw new Exception("Invalid Column #" + (column + 1).ToString());
}
```
```


q:
I have a listening port on my server that I'm connecting to using a Java class and the Socket interface, i.e.

Socket mySocket = new Socket(host,port);

I then grab an OutputStream, decorate with a PrintWriter in autoflush mode and I'm laughing - except if the listening port closes. Then I get

tcp4       0      0  *.9999                 *.*                    LISTEN
tcp        0      0  127.0.0.1.45737        127.0.0.1.9999         CLOSE_WAIT

and I can't seem to detect the problem in the program - I've tried using the isConnected() method on the socket but it doesn't seem to know that the connection is closed.

I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.

Any advice please?

Thanks all

[A]
Set a short timeout?
Does
```
isOutputShutdown()
```
not get you what you want?
You could always build a
```
SocketWatcher
```
class that spins up in its own
```
Thread
```
and repeatedly tries to write empty strings to the
```
Socket
```
until that raises a
```
SocketClosedException
```
.


q: Has anyone got a working solution without some Java/COM-bridge? E.g. process the Email as a file (.msg) rather than locating the data that is referenced in the Clipboard?

[A]
I did make some headway on this sort of thing a few years back using
Apache POI
to extract the contents of an email from .msg files.  I'm pretty sure they have a simple swing explorer / viewer that you can use to examine the structure within the compound document format, but I can't find it right now.
I was able to extract most information that I was interested in but was ultimately wanting to create a mime format version of the message and couldn't extract all the information I needed in a format I could use.


q:
Wondering if there is a better why in  the WHERE clause of choosing records when you need to look at effective start and end dates?

Currently this how I've done it in the past on MS SQL Server. Just worried about the date and not the time. I'm using SQL Server 2005.

AND Convert(datetime, Convert(char(10), ep.EffectiveStartDate, 101))
   <= Convert(datetime, Convert(char(10), GetDate(), 101))
AND Convert(datetime, Convert(char(10), ep.EffectiveEndDate, 101))
   >= Convert(datetime, Convert(char(10), GetDate(), 101))

[A]
try
```
```
ep.EffectiveStartDate BETWEEN @date1 AND @date2
```
```
where you would do something like
```
```
declare @date1 datetime, @date2 datetime;
set @date1 = cast('10/1/2000' as datetime)
set @date2 = cast('10/1/2020' as datetime)
```
```


q:
In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original?

I usually just copy the string to a new variable then bind it to the s/// regex that does the replacement on the new string, but I was wondering if there is a better way to do this?

$newstring = $oldstring;
$newstring =~ s/foo/bar/g;

[A]
This is the idiom I've always used to get a modified copy of a string without changing the original:
```
```
(my $newstring = $oldstring) =~ s/foo/bar/g;
```
```
In perl 5.14.0 or later, you can use the new
```
/r
```
non-destructive substitution modifier
:
```
```
my $newstring = $oldstring =~ s/foo/bar/gr;
```
```
NOTE:
The above solutions work without
```
g
```
too. They also work with any other modifiers.
SEE ALSO:
```
perldoc perlrequick
```
: Perl regular expressions quick start


q:
I want to show HTML content inside Flash. Is there some way to do this?
I am talking about full blown HTML (with JavaScript if possible).

[A]
How complex HTML are we talking about? Simple HTML, like <b> and <i> is supported in text fields if you use the
```
htmlText
```
property. You can also attach a CSS style sheet to the text field for more styling. Have a look at TextField in the Flash API documentation (I'm sure you can just google it).


q:
Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a .xls) file?

I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement...

[A]
In SQL server it is as easy as
```
```
SELECT * INTO NewTablenNmeHere
FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')
```
```


q:
I've got a JavaScript "object", built this way:

function foo()
{
    this.length = 0;
}

foo.prototype.getLength = function()
{
    return this.length;
}

...

I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced?

I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced.

Thanks
rp

[A]
Shouldn't be much different:
```
```
namespace.foo = function foo() {...}
namespace.foo.prototype.getLength = function() { ... }
```
```
or you could use
```
```
(function() {
  function foo() { ... }
  foo.prototype...
  namespace.foo = foo;
})();
```
```
to save some typing.


q:
I'm creating an application that will store a hierarchical collection of items in an XML file and I'm wondering about the industry standard for storing collections in XML. Which of the following two formats is preferred? (If there is another option I'm not seeing, please advise.)

Option A

<School>
    <Student Name="Jack" />
    <Student Name="Jill" />
    <Class Name="English 101" />
    <Class Name="Math 101" />
</School>

Option B

<School>
    <Students>
        <Student Name="Jack" />
        <Student Name="Jill" />
    </Students>
    <Classes>
        <Class Name="English 101" />
        <Class Name="Math 101" />
    </Classes>
</School>

[A]
I'm no XML expert, but I find Option B to be more human readable, and I think it's just as machine readable as Option A. I believe that XML is designed to be both human and machine readable, so I would go for Option B myself.
I just realized something else after Ryan Farley's post. If the Students or Classes section becomes too big and must be moved to another XML file, it seems like it would be easier to copy the node and create a new XML file out of that node with Option B.


q:
Did you ever have to choose between WISA or LAMP at the beginning of a web project?

While pros and cons are littered around the net, it would be helpful to know about your real experience in coming up w/ criteria, evaluating, deciding, and reflecting upon your decision to go w/ either platform.

[A]
@Thomas WISA is:
W=Windows
I=IIS
S=SQL (Microsoft SQL Server)
A=ASP (or ASP .NET)
As for choosing between them, I would think that the available resources and talent would be the deciding factor. If you can get great ASP .NET and MS SQL devs, go that route. If you've got a bunch of PHP/MySQL gurus on hand, go LAMP.
The reality is, regardless of the pros and cons of the platform, you'll struggle to get a great system on WISA out of a primarily PHP dev team, and vice versa.


q: In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask).  When we create a window, our normal practice is to put this in the window's user data area via SetWindowLong(hwnd, GWL_USERDATA, this), which allows us to have an MFC-like callback or a tightly integrated WndProc, depending.  The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide.  What's a better solution to this problem that works on both 32- and 64-bit systems?

[A]
SetWindowLongPtr
was created to replace
SetWindowLong
in these instances.  It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations.
```
```
LONG_PTR SetWindowLongPtr(
    HWND hWnd,
    int nIndex,
    LONG_PTR dwNewLong
);
```
```
Remember that the constants have changed too, so usage now looks like:
```
```
SetWindowLongPtr(hWnd, GWLP_USERDATA, this);
```
```
Also don't forget that now to retrieve the pointer, you must use
GetWindowLongPtr
:
```
```
LONG_PTR GetWindowLongPtr(
    HWND hWnd,
    int nIndex
);
```
```
And usage would look like (again, with changed constants):
```
```
LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);
MyObject* pMyObject = (MyObject*)lpUserData;
```
```


q: What's the best way to handle a user going back to a page that had cached items in an asp.net app?  Is there a good way to capture the back button (event?) and handle the cache that way?

[A]
The best way to deal with it is to probably put a no-cache directive in your ASP.NET pages (or a master page if you're using one). I don't think there's a way to deal with this directly in your ASP.NET code (since the cache decision is happening on the client).
As for MVC, don't know how you would accomplish that (assuming it's different from Web Forms-based ASP.NET); I haven't used it.


q: I'm pretty green still when it comes to web programming, I've spent most of my time on client applications.  So I'm curious about the common exploits I should fear/test for in my site.

[A]
These three are the most important:
Cross Site Request Forgery
Cross Site Scripting
SQL injection


q: What is the best method to parse multiple, discrete, custom XML documents with Java?

[A]
You will want to use
```
org.xml.sax.XMLReader
```
(
http://docs.oracle.com/javase/7/docs/api/org/xml/sax/XMLReader.html
).


q: As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?

[A]
You could always run a server-side script that keeps running for a period of time.
For example:
```
```
<?php
   sleep(10); //sleep for 10 seconds.
   print "This script has finished.";
>
```
```


q:
When using Groovy MarkupBuilder, I have places where I need to output text into the document, or call a function which outputs text into the document. Currently, I'm using the undefined tag "text" to do the output.  Is there a better way to write this code?

li {
  text("${type.getAlias()} blah blah ")
  function1(type.getXYZ())
  if (type instanceof Class1) {
    text(" implements ")
    ft.getList().each {
      if (it == '') return
      text(it)
      if (!function2(type, it)) text(", ")
    }
  }
}

[A]
Include a method:
```
```
void text(n){
    builder.yield n
}
```
```
Most likely you (I) copied this code from somewhere that had a text method, but you didn't also copy the text method.  Since MarkupBuilder accepts any name for the name of a tag and browsers ignore unknown markup, it just happened to work.


q:
This is mostly geared toward desktop application developers.
How do I design a caching block which plays nicely with the GC?
How do I tell the GC that I have just done a cache sweep and it is time to do a GC?
How do I get an accurate measure of when it is time to do a cache sweep?

Are there any prebuilt caching schemes which I could borrow some ideas from?


q: Is there a .NET variable that returns the "All Users" directory?

[A]
You'll want to use the
```
system.environment
```
variables.
Most of the predefined ones are
shown here
.
For the "
All Users
" you would use:
```
```
System.Environment.GetEnvironmentVariable("ALLUSERSPROFILE")
```
```
I know I got a lot of upmods and a correct answer for my other stuff, but this actually works. where as the other
environment variables
I linked to previously don't seem to work with that function call.


q:
I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the javascript: prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between:

onchange="javascript: myFunction(this)"

and

onchange="myFunction(this)"

?

[A]
Probably nothing in your example. My understanding is that
```
javascript:
```
is for anchor tags (in place of an actual
```
href
```
). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank
```
href
```
coupled with an
```
onclick
```
will do).
For example:
```
```
Blah
```
```
Rather than:
```
```
Blah
```
```


q: Where can I get some decent looking free ASP.Net or CSS themes?

[A]
I wouldn't bother looking for ASP.NET stuff specifically (probably won't find any anyways). Finding a good CSS theme easily can be used in ASP.NET.
Here's some sites that I love for CSS goodness:
http://www.freecsstemplates.org/
http://www.oswd.org/
http://www.openwebdesign.org/
http://www.styleshout.com/
http://www.freelayouts.com/


q: Anything thats as good and as stable and as feature-rich as gigaspaces?

[A] Gigaspaces is top notch as far as a Javaspaces implementation goes for scalability and performance. Are you restricted to a Javaspaces implementation? Blitz Javaspaces is top notch for a free product.


q:
Have just started using Visual Studio Professional's built-in unit testing features, which as I understand, uses MS Test to run the tests.

The .trx file that the tests produce is xml, but was wondering if there was an easy way to convert this file into a more "manager-friendly" format?

My ultimate goal is to be able to automate the unit-testing and be able to produce a nice looking document that shows the tests run and how 100% of them passed  :)

[A]
Since this file is XML you could and should use xsl to transform it to another format. The
IAmUnkown
- blog has an entry about
decoding/transforming the trx file into html
.
You can also use
.NetSpecExporter from Bekk
to create nice reports. Their product also uses XSL, so you could probably
steal
it from the downloaded file and apply it with whatever xsl-application you want.


q:
Has anyone worked with DSLs (Domain Specific Languages) in the finance domain? I am planning to introduce some kind of DSL support in the application that I am working on and would like to share some ideas.

I am in a stage of identifying which are the most stable domain elements and selecting the features which would be better implemented with the DSL. I have not yet defined the syntax for this first feature.

[A]
Jay Fields and Obie Fernandez have written and talked extensively on the subject.
Jay Fields intro on
Domain Specific Languages
Jay Fields' series on
Business Natural Language
Obie Fernandez
Expressing Contract Terms in a DSL
A very good
presentation
on infoQ by Jay Fields
You'll also find general stuff on implementing DSL in Martin Fowler's writings (but not specific to finance).
DSL


q:
Can anyone recommend some good resources that highlight the differences between Oracle and the AS/400 database?

I am trying to help someone with a lot of AS/400 experience implement an Oracle installation, and they need some guidance.

A book or online resource would be ideal.

[A]
I've done this a fair few times and the solutions out there really depend on the environment (enterprise / mission critical or development).  The BEST way would be the
Oracle AS/400 Gateway
.  Here are some important links in that area:
Allow AS/400 apps to access oracle with the Oracle Access Manager:
Installation Guide for the AS/400 Oracle Access Manager
Allow your Oracle apps to access AS/400 tables and be queried using Oracle:
Oracle Transparent Gateway for DB/2
^^^Those products are fairly expensive but super powerful.^^^
Alternately, here are some more academic approaches to the situation:
Here's a technical comparison of the two technologies... It's a little propagandaish*.
Technical comparisons of Oracle and DB/2
Here's a document written from the opposite point of view - Someone moving from Oracle to DB2.  I still find it's useful information:
Leverage your Oracle 10g skills to learn DB2...
And another IBM link that has some really great information all around:
IBM Developer Network Search Results
Hope this helps!
*Yes, I know propagandaish is not a real word.


q:
I'm working with Subversion based on Windows and would like to write an easy utility in .NET for working with the Apache password file.  I understand that it uses a function referred to as MD5Crypt, but I can't seem to find a description of the algorithm beyond that at some point it uses MD5 to create a hash.

Can someone describe the MD5Crypt algorithm and password line format?

[A]
You can find an implementation of md5crypt in the
tcllib package.
Download is available from
sourceforge
.
You can also find an example of an apache-compatible md5crypt in the
source code for the CAS Generic Handler


q: And on top of that, are there cases where one has to use the global assembly cache or where one cannot use it?

[A] In all my life, I have had maybe one application where I had to put an assembly in the GAC, simply because these assemblies were part of a framework that a number of applications would use it, and it seemed right to put them into the GAC.


q:
I'm looking for a way to find a the windows login associated with a specific group. I'm trying to add permissions to a tool that only allows names formatted like:

DOMAIN\USER
DOMAIN\GROUP

I have a list of users in active directory format that I need to add:

ou=group1;ou=group2;ou=group3

I have tried adding DOMAIN\Group1, but I get a 'user not found' error.

P.S.  should also be noted that I'm not a Lan admin

[A]
OU is an Organizational Unit (sort of like a Subfolder in Explorer), not a Group, Hence group1, 2 and 3 are not actually groups.
You are looking for the DN Attribute, also called "distinguishedName". You can simply use DOMAIN\DN once you have that.
Edit: For groups, the CN (Common Name) could also work.
The full string from Active Directory normally looks like this:
cn=Username,cn=Users,dc=DomainName,dc=com
(Can be longer or shorter, but the important bit is that the "ou" part is worthless for what you're trying to achieve.


q: What are the best open source (open source and commercial) reporting tools for ASP.NET similar to Crystal Reports for ASP.NET?

[A]
As much as I despise Crystal Reports (we describe digging deep into it the seven layers of Crystal hell) -- it seems to be the best/most-flexible tool for the job. I hope someone comes along and knocks them off the block though.
Microsoft Reporting Services is an alternative, but didn't have the features we needed.


q:
I am looking for open source or free data collaboration software. Specifically this is for a non-profit organization that wants to teach remote students how a foreign language.  The idea is that an instructor would teach a class and there would be up to 10 students in the class at a time.  The instructor would be able to post slides or other teaching material and the students would be able to see it on their computers remotely.  Video is not required but audio is a must.  Any recommendations?

Also if there have been any reviews or feature comparison amongst these products, I would be interested in hearing about them.

[A]
I know a few of the developers on the Carleton University developed
Blindside Project
.  They are actively developing an open-source web conferencing and presentation tool for e-learning, with the intent of eventually offering university courses online.
It's pretty fully featured software, and is meant to be installed as a server that can host many conference rooms at a time.  It has voice, video, text, and a whiteboard/slideshow (
Edit:
supports PDF at the moment) capability.  One feature I think it neat is that students can 'raise their hands' in the class to ask the instructor a question, where they can take the floor for a moment.
Check out the demo on the site (if it's not working anymore I'll nudge the developers).  Another pro is that the clients only need to have flash installed.
I just logged onto the online demo and created this preview:
This project is now called BigBlueButton :
http://code.google.com/p/bigbluebutton/
Here is the demo:
http://demo.bigbluebutton.org/


q:
Does anyone know of a .NET date/time parser similar to Chronic for Ruby (handles stuff like "tomorrow" or "3pm next thursday")?

Note: I do write Ruby (which is how I know about Chronic) but this project must use .NET.

[A]
I'm not aware of one, but it sounded like a cool problem, so here's my whack at it (VB.NET):
```
```
Private Function ConvertDateTimeToStringRelativeToNow(ByVal d As DateTime) As String
    Dim diff As TimeSpan = DateTime.Now().Subtract(d)
    If diff.Duration.TotalMinutes < 1 Then Return "Now"

    Dim str As String
    If diff.Duration.TotalDays > 365 Then
        str = CInt(diff.Duration.TotalDays / 365).ToString() & " years"
    ElseIf diff.Duration.TotalDays > 30 Then
        str = CInt(diff.TotalDays / 30).ToString() & " months"
    ElseIf diff.Duration.TotalHours > 24 Then
        str = CInt(diff.Duration.TotalHours / 24) & " days"
    ElseIf diff.Duration.TotalMinutes > 60 Then
        str = CInt(diff.Duration.TotalMinutes / 60) & " minutes"
    Else
        str = CInt(diff.Duration.TotalMinutes).ToString() & " minutes"
    End If
    If str.StartsWith("1") Then str = str.SubString(0, str.Length - 1)
    If diff.TotalDays > 0 Then
        str &= " ago"
    Else
        str &= " from now"
    End If
    Return str
End Function
```
```
It's really not as sophisticated as ones that already exist, but it works alright I guess.  Could be a nice extension method.


q:
Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine?  I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running.  You could say that this isn't so much a specific-software question as it is a general networking question.

I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the same port (ie, they both run on port 80)?

The web servers would not be serving files from the same domains.  For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com.

I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole.  :)

[A]
Your best bet would be putting Apache httpd in front of port 80 and relay requests meant for other servers through Apache by using modules. Most popular scenario would be Tomcat behind Apache where you'll be able to run both php and jsp applications.
I'm not familiar with CherryPy, so I can only suggest you look for an Apache module for CherryPy.
Edit: This looks promising:
http://tools.cherrypy.org/wiki/BehindApache


q:
When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives:

1. needle.find(haystack)

2. haystack.find(needle)

3. searcher.find(needle, haystack)

Which do you prefer, and why?

I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world".

In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided?

[A]
This entirely depends on what varies and what stays the same.
For example, I am working on a (non-OOP)
framework
where the find algorithm is different depending both on the type of the needle and the haystack. Apart from the fact that this would require double-dispatch in an object-oriented environment, it also means that it isn't meaningful to write either
```
needle.find(haystack)
```
or to write
```
haystack.find(needle)
```
.
On the other hand, your application could happily delegate finding to either of both classes, or stick with one algorithm altogether in which case the decision is arbitrary. In that case, I would prefer the
```
haystack.find(needle)
```
way because it seems more logical to apply the finding to the haystack.


q: I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.

[A]
Let
```
Y = 0.3*R + 0.59*G + 0.11*B
```
for each pixel in the image, then set them to be
```
((R1+Y)/2,(G1+Y)/2,(B1+Y)/2)
```
if
```
(R1,G1,B1)
```
is what you are colorizing with.


q:
What are some strategies that people have had success with for maintaining a change history for data in a fairly complex database. One of the applications that I frequently use and develop for could really benefit from a more comprehensive way of tracking how records have changed over time. For instance, right now records can have a number of timestamp and modified user fields, but we currently don't have a scheme for logging multiple change, for instance if an operation is rolled back. In a perfect world, it would be possible to reconstruct the record as it was after each save, etc.

Some info on the DB:

Needs to have the capacity to grow by thousands of records per week

50-60 Tables

Main revisioned tables may have several million records each

Reasonable amount of foreign keys and indexes set

Using PostgreSQL 8.x

[A]
In the past I have used triggers to construct db update/insert/delete logging.
You could insert a record each time one of the above actions is done on a specific table into a logging table that keeps track of the action, what db user did it, timestamp, table it was performed on, and previous value.
There is probably a better answer though as this would require you to cache the value before the actual delete or update was performed I think. But you could use this to do rollbacks.


q:
What is the best way to find something in a list?  I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0.  Lets get the best refactorings for this common code pattern.

Currently I use code like this:

// mObjList is a List<MyObject>
MyObject match = null;
foreach (MyObject mo in mObjList)
{
    if (Criteria(mo))
    {
        match = mo;
        break;
    }
}

or

// mObjList is a List<MyObject>
bool foundIt = false;
foreach (MyObject mo in mObjList)
{
    if (Criteria(mo))
    {
        foundIt = true;
        break;
    }
}

[A]
Put the code in a method and you save a temporary and a
```
break
```
(and you recycle code, as a bonus):
```
```
T Find<T>(IEnumerable<T> items, Predicate<T> p) {
    foreach (T item in items)
        if (p(item))
            return item;

    return null;
}
```
```
… but of course this method already exists anyway for Lists, even in .NET 2.0.


q:
I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example:

Name: Fernando

Age: {person.age}

Sex: Male

I would like to know how to hide it!

[A]
You can mark variables as "
silent
" like this:
```
```
$!variable
```
```
If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would.


q: The Close method on an ICommunicationObject can throw two types of exceptions as MSDN outlines here. I understand why the Close method can throw those exceptions, but what I don't understand is why the Dispose method on a service proxy calls the Close method without a try around it. Isn't your Dispose method the one place where you want make sure you don't throw any exceptions?


q:
I'm trying to do a simple rotation in OpenGL but must be missing the point.
I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally.

At the moment I have code like this:

glPushMatrix();
  glRotatef(90.0, 0.0, 1.0, 0.0);
  glBegin(GL_TRIANGLES);
    glVertex3f( 1.0, 1.0, 0.0 );
    glVertex3f( 3.0, 2.0, 0.0 );
    glVertex3f( 3.0, 1.0, 0.0 );
  glEnd();
glPopMatrix();

But the result is not a triangle rotated 90 degrees.

Edit
Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho.  I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result.

[A]
Ensure that you're modifying the modelview matrix by putting the following before the glRotatef call:
```
```
glMatrixMode(GL_MODELVIEW);
```
```
Otherwise, you may be modifying either the projection or a texture matrix instead.


q:
Given two different image files (in whatever format I choose), I need to write a program to predict the chance if one being the illegal copy of another. The author of the copy may do stuff like rotating, making negative, or adding trivial details (as well as changing the dimension of the image).

Do you know any algorithm to do this kind of job?

[A]
Read the paper:
Porikli, Fatih, Oncel Tuzel, and Peter Meer. “Covariance Tracking Using Model Update Based
on Means on Riemannian Manifolds”. (2006) IEEE Computer Vision and Pattern Recognition.
I was successfully able to detect overlapping regions in images captured from adjacent webcams using the technique presented in this paper.  My covariance matrix was composed of Sobel, canny and SUSAN aspect/edge detection outputs, as well as the original greyscale pixels.


q:
I currently use AnkhSVN to integrate subversion into Visual Studio. Is there any reason I should switch to VisualSVN?

AnkhSVN is free (in more than one sense of the word) while VisualSVN costs $50. So right there unless I'm missing some great feature of VisualSVN I don't see any reason to switch.

[A] I used VisualSVN until Ankh hit 2.0, and ever since, I've abandoned VisualSVN. Ankh has surpassed VisualSVN in functionality, in my mind, and all the 1.x perf and integration issues are gone.


q:
When writing database queries in something like TSQL or PLSQL, we often have a choice of iterating over rows with a cursor to accomplish the task, or crafting a single SQL statement that does the same job all at once.

Also, we have the choice of simply pulling a large set of data back into our application and then processing it row by row, with C# or Java or PHP or whatever.

Why is it better to use set-based queries?  What is the theory behind this choice?  What is a good example of a cursor-based solution and its relational equivalent?

[A]
The main reason that I'm aware of is that set-based operations can be optimised by the engine by running them across multiple threads. For example, think of a quicksort - you can separate the list you're sorting into multiple "chunks" and sort each separately in their own thread. SQL engines can do similar things with huge amounts of data in one set-based query.
When you perform cursor-based operations, the engine can only run sequentially and the operation has to be single threaded.


q: I'm interested in finding out how the recently-released (http://mirror.facebook.com/facebook/hive/hadoop-0.17/) Hive compares to HBase in terms of performance. The SQL-like interface used by Hive is very much preferable to the HBase API we have implemented.

[A]
It's hard to find much about Hive, but I found this
snippet
on the Hive site that leans heavily in favor of HBase (bold added):
Hive is based on Hadoop which is a batch processing system. Accordingly, this system does not and
cannot promise low latencies on queries
. The paradigm here is strictly of submitting jobs and being notified when the jobs are completed as opposed to real time queries. As a result it should not be compared with systems like Oracle where analysis is done on a significantly smaller amount of data but the analysis proceeds much more iteratively with the response times between iterations being less than a few minutes.
For Hive queries response times for even the smallest jobs can be of the order of 5-10 minutes and for larger jobs this may even run into hours.
Since HBase and HyperTable are all about performance (being modeled on Google's BigTable), they sound like they would certainly be much faster than Hive, at the cost of functionality and a higher learning curve (e.g., they don't have joins or the SQL-like syntax).


q:
What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time?

What are their typical usages?

Are they unique to Java? Is there a C++ equivalent?

[A]
Also, are they unique to Java, is there a C++ equivalent?
No, but VB and C# have
attributes
which are the same thing.
Their use is quite diverse. One typical Java example,
```
@Override
```
has no effect on the code but it can be used by the compiler to generate a warning (or error) if the decorated method doesn't actually override another method. Similarly, methods can be marked obsolete.
Then there's reflection. When you reflect a type of a class in your code, you can access the attributes and act according to the information found there. I don't know any examples in Java but in .NET this is used by the compiler to generate
(de)serialization
information for classes, determine the
memory layout
of structures and
declare function imports
from legacy libraries (among others). They also control how the IDE form designer works.
/EDIT: Attributes on classes are comparable to tag interfaces (like
Serializable
in Java). However, the .NET coding guidelines say not to use tag interfaces. Also, they only work on class level, not on method level.


q: Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this?

[A]
Kevin,
it is possible. You can create library with window hook proc using managed C++. All you need to do is to inject this hook into some application using standard WinAPI (SetWindowsHookEx etc.). Inside this hook you can call System::AppDomain::CurrentDomain->Load method to load your assembly into target application's AppDomain. Then you can call methods defined in your assembly using reflection. For example,
Snoop
uses this method.


q:
In my second year of University we were "taught" Haskell, I know almost nothing about it and even less about functional programming.

What is functional programming, why and/xor where would I want to use it instead of non-functional programming and am I correct in thinking that C is a non-functional programming language?

[A]
May be worth checking out this article on
F# "101"
on CoDe Mag recently posted.
Also,
Dustin Campbell has a great blog
where he has posted many articles on his adventures on getting up to speed with F#..
I hope you find these useful :)
EDIT:
Also, just to add, my understanding of functional programming is that
everything
is a function, or parameters to a function, rather than instances/stateful objects.. But I could be wrong F# is something I am dying to get in to but just dont have the time! :)


q:
In C# I can use the FileSystemWatcher object to watch for a specific file and raise an event when it is created, modified, etc.

The problem I have with this class is that it raises the event the moment the file becomes created, even if the process which created the file is still in the process of writing. I have found this to be very problematic, especially if I'm trying to read something like an XML document where the file must have some structure to it which won't exist until it is completed being written.

Does .NET (preferably 2.0) have any way to raise an event after the file becomes accessible, or do I have to constantly try reading the file until it doesn't throw an exception to know it is available?

[A]
Not sure if there is a way of an event actually being raised by the standard class, but I eas experiencing similar problems on some recent work I was doing.
In short, I was trying to write to a file that was locked at the time. I ended up wrapping the write method up so it would automatically try the write again in a few ms after..
Thinking out loud, Can you probe the file for a ReadOnly status? May be worth then having a wrapper for file IO which can stack up delegates for pending file operations or something.. Thoughts?


q:
Trying to find some simple SQL Server PIVOT examples.  Most of the examples that I have found involve counting or summing up numbers.  I just want to pivot some string data.  For example, I have a query returning the following.

Action1 VIEW
Action1 EDIT
Action2 VIEW
Action3 VIEW
Action3 EDIT

I would like to use PIVOT (if even possible) to make the results like so:

Action1 VIEW EDIT
Action2 VIEW NULL
Action3 VIEW EDIT

Is this even possible with the PIVOT functionality?

[A]
Well, for your sample and any with a limited number of unique columns, this should do it.
```
```
select
    distinct a,
    (select distinct t2.b  from t t2  where t1.a=t2.a and t2.b='VIEW'),
    (select distinct t2.b from t t2  where t1.a=t2.a and t2.b='EDIT')
from t t1
```
```


q:
What is the "best" way to store international addresses in a database? Answer in the form of a schema and an explanation of the reasons why you chose to normalize (or not) the way you did. Also explain why you chose the type and length of each field.

Note: You decide what fields you think are necessary.

[A]
You need to provide a bit more details about how you are planning to use the data. For example, fields like City, State, Country can either be text in the single table, or be codes which are linked to a separate table with a Foreign Key.
Simplest would be
Address_Line_01 (Required, Non blank)
Address_Line_02
Address_Line_03
Landmark
City (Required)
Pin (Required)
Province_District
State (Required)
Country (Required)
All the above can be Text/Unicode with appropriate field lengths.
Phone Numbers as applicable.


q:
I have a Struts + Velocity structure like for example, a Person class, whose one property is a Car object (with its own getter/setter methods) and it is mapped to a Velocity form that submits to an Action, using ModelDriven and getModel structure.

I what to put a button on the form that shows "View Car" if car property is not null or car.id != 0 or show another button "Choose Car" if car is null or car.id = 0.

How do I code this. I tried something like that in the template file:

#if($car != null)
  #ssubmit("name=view" "value=View Car")
#else
  #ssubmit("name=new" "value=Choose Car")
#end

But I keep getting error about Null value in the #if line.

I also created a boolean method hasCar() in Person to try, but I can't access it and I don't know why.

And Velocity + Struts tutorials are difficult to find or have good information.

Thanks

[A]
You should change the #if line to:
```
```
#if($car)
```
```


q: While going through university and from following the development of SO, I've heard a lot about the Model-View-Controller architectural design pattern. I inadvertently used the MVC pattern even before I knew what it was, and still use it in my everyday job. From what I've seen, it's probably the most popular pattern used today. What I haven't heard much about though, are the alternative patterns you can use instead of MVC. What options are there, and for what reasons would you decide to use them over MVC? I'm also interested in knowing the types of systems they are typical of being used for. Finally, what are the pros and cons that come along with using them?

[A]
Passive View -
http://martinfowler.com/eaaDev/PassiveScreen.html
Supervising Controller -
http://martinfowler.com/eaaDev/SupervisingPresenter.html
Model-View-Presenter -
http://martinfowler.com/eaaDev/ModelViewPresenter.html
My personal favorite is the
Passive View
. More testable than others I've seen including MVC.


q:
Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I found this one, and it's a start, but nothing more.

Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-)

The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do.

Thanks for any help.

[A]
Beware of
clbuttic mistakes
.
"Apple made the clbuttic mistake of forcing out their visionary - I mean, look at what NeXT has been up to!"
Hmm. "clbuttic".
Google "clbuttic" - thousands of hits!
There's someone who call his car 'clbuttic'.
There are "Clbuttic Steam Engine" message boards.
Webster's dictionary - no help.
Hmm. What can this be?
HINT: People who make buttumptions about their regex scripts, will be
  embarbutted when they repeat this mbuttive mistake.


q:
I'm trying to fetch Wikipedia pages using LWP::Simple, but they're not coming back. This code:

#!/usr/bin/perl
use strict;
use LWP::Simple;

print get("http://en.wikipedia.org/wiki/Stack_overflow");

doesn't print anything. But if I use some other webpage, say http://www.google.com, it works fine.

Is there some other name that I should be using to refer to Wikipedia pages?

What could be going on here?

[A]
Apparently Wikipedia blocks LWP::Simple requests:
http://www.perlmonks.org/?node_id=695886
The following works instead:
```
```
#!/usr/bin/perl
use strict;
use LWP::UserAgent;

my $url = "http://en.wikipedia.org/wiki/Stack_overflow";

my $ua = LWP::UserAgent->new();
my $res = $ua->get($url);

print $res->content;
```
```


q:
I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.

Should I do it at declaration?:

public class Dice
{
    private int topFace = 1;
    private Random myRand = new Random();

    public void Roll()
    {
       // ......
    }
}

or in a constructor?:

public class Dice
{
    private int topFace;
    private Random myRand;

    public Dice()
    {
        topFace = 1;
        myRand = new Random();
    }

    public void Roll()
    {
        // .....
    }
}

I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.

[A]
My rules:
Don't initialize with the default values in declaration (
```
null
```
,
```
false
```
,
```
0
```
,
```
0.0
```
…).
Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
If the value of the field changes because of a constructor parameter put the initialization in the constructors.
Be consistent in your practice (the most important rule).


q:
In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it?

A little context if it helps...

I have this code in my global.asax as a helper method.  Normally, between requests, this isn't a problem.  But right after signing in, this is getting called more than once, and the second time I end up trying to attach the Member object in the same unit of work where it was created.

private void CheckCurrentUser()
{
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
    {
        AppHelper.CurrentMember = null;
        return;
    }

    IUserService userService = new UserService();

    if (AppHelper.CurrentMember != null)
        userService.AttachExisting(AppHelper.CurrentMember);
    else
        AppHelper.CurrentMember = userService.GetMember(
            HttpContext.Current.User.Identity.Name,
            AppHelper.CurrentLocation);
}


q: Is there a good ruby gem for a WYSIWYG editor that will easily work with a rails app?

[A] Though it's certainly not a direct answer, in the past I've found I prefer to use RedCloth (or a Markdown parser if you don't enjoy Textile) and use a simple textarea with an AJAXy preview. Generally speaking, WYSIWYG editors have a long history of creating redundant tags and similar, leading to potentially broken pieces of HTML.


q: How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line?

[A]
Look into  build tool
NAnt
or
MSBuild
. I believe MSBuild is the build tool for Visual Studio 2005 and later. I am, however, a fan of NAnt...


q:
I am considering creating my own website using Java and am trying to decide what framework to use. However, doing a quick search for Java frameworks returns more than 50 to choose from!

My website is just going to be for my own enjoyment of building it in the beginning, but if it becomes popular, it would be good for it to have some scalability, or to at least be able to redesign for that.

What are the main differences between the more popular frameworks? Are there instances where one significantly outperforms the others? For example, high-traffic enterprise applications versus low-traffic small applications. I'm also wondering if some are much easier to learn and use than others.

Is there anyone who has experience with some of these frameworks and can make a recommendation? Does the sheer number of choices just serve as an early warning to avoid Java-based web development where possible?

[A]
Disclamer: I work at Vaadin (previously IT Mill)
If you are doing something RIAish, you might want to take look at
Vaadin
. It's an open source UI-oriented AJAX framework that, to me, is nice to use (I come from a PHP background myself).
There's a
case study
that compares doing the same application (i.e. two applications with the same set of features) in Icefaces and Vaadin. In a nutshell, it states that the UI development was considerably faster.
Even though the study is hosted at the company's wiki, I can assure that it's objective, genuine and truthful, although I can't force you in believing me.


q:
What can be reasons to prevent a class from being inherited? (e.g. using sealed on a c# class)
Right now I can't think of any.

[A]
How about if you are not sure about the interface yet and don't want any other code depending on the present interface? [That's off the top of my head, but I'd be interested in other reasons as well!]
Edit:
A bit of googling gave the following:
http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx
Quoting:
There are three reasons why a sealed class is better than an unsealed class:
Versioning
: When a class is originally sealed, it can change to unsealed in the future without breaking compatibility. (…)
Performance
: (…) if the JIT compiler sees a call to a virtual method using a sealed types, the JIT compiler can produce more efficient code by calling the method non-virtually.(…)
Security and Predictability
: A class must protect its own state and not allow itself to ever become corrupted. When a class is unsealed, a derived class can access and manipulate the base class’s state if any data fields or methods that internally manipulate fields are accessible and not private.(…)


q:
I can set the PHP include path in the php.ini:

include_path = /path/to/site/includes/

But then other websites are affected so that is no good.

I can set the PHP include in the start of every file:

$path = '/path/to/site/includes/';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

But that seems like bad practice and clutters things up.

So I can make an include of that and then include it into every file:

include 'includes/config.php';

or

include '../includes/config.php';

This is what I'm doing right now, but the include path of config.php will change depending on what is including it.

Is there a better way? Does it matter?

[A]
If you're using apache as a webserver you can override (if you allow it) settings using
.htaccess
files. See
the PHP manual
for details.
Basically you put a file called
.htaccess
in your website root, which contains some PHP
```
ini
```
values. Provided you configured Apache to allow overrides, this site will use all values in your PHP config, + the values you specify in the
.htaccess
file.
Can be used only with
```
PHP_INI_ALL
```
and
```
PHP_INI_PERDIR
```
type directives
as stated in the page I linked. If you click through to the full listing, you see that the include path is a
```
PHP_INI_ALL
```
directive.


q:
Can you tell me what is the difference between abstraction and information hiding in software development?

I am confused. Abstraction hides detail implementation and
information hiding abstracts whole details of something.

Update: I found a good answer for these three concepts. See the separate answer below for several citations taken from there.

[A]
The meaning of abstraction given by the Oxford English Dictionary (OED) closest to the meaning intended here is 'The act of separating in thought'. A better definition might be 'Representing the essential features of something without including background or inessential detail.'
Information hiding is the principle that users of a software component (such as a class) need to know only the essential details of how to initialize and access the component, and do not need to know the details of the implementation.
Edit
: I seems to me that abstraction is the
process
of deciding which parts of the implementation that should be
hidden
.
So its not abstraction VERSUS information hiding. It's information hiding VIA abstraction.


q:
Jeff actually posted about this in Sanitize HTML. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java?

[Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is!

(*) In fact, I think it was still in closed beta

[A]
The biggest problem by using jeffs code is the @ which currently isnt available.
I would probably just take the "raw" regexp from jeffs code if i needed it and paste it into
http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html
and see the things needing escape get escaped and then use it.
Taking the usage of this regex in mind I would personally make sure I understood exactly what I was doing, why and what consequences would be if I didnt succeed, before copy/pasting anything, like the other answers try to help you with.
(Thats propbably pretty sound advice for any copy/paste)


q: What are some resources for getting started writing a Firefox Addon?  Is there an API guide somewhere?  Is there a getting started tutorial somewhere?  Is there a developer discussion board somewhere?

[A]
This is a great resource to start learning how to build a FireFox extension:
How to create Firefox extensions
This is an awesome tutorial and will covers most type of extensions.
Edit: Updated link to use archived copy since original page no longer exists


q: Does anyone know of an easy way to escape HTML from strings in jQuery?  I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks).  I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.

[A]
If you're escaping for HTML, there are only three that I can think of that would be really necessary:
```
```
html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
```
```
Depending on your use case, you might also need to do things like
```
"
```
to
```
"
```
.  If the list got big enough, I'd just use an array:
```
```
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]]
for(var item in findReplace)
    escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);
```
```
```
encodeURIComponent()
```
will only escape it for URLs, not for HTML.


q: Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)?

[A]
You need to use
setTimeout
and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!


q: In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?

[A]
```
++i
```
increments the value, then returns it.
```
i++
```
returns the value, and then increments it.
It's a subtle difference.
For a for loop, use
```
++i
```
, as it's slightly faster.
```
i++
```
will create an extra copy that just gets thrown away.


q:
I'm trying to solve the 3n+1 problem and I have a for loop that looks like this:

for(int i = low; i <= high; ++i)
        {
                res = runalg(i);
                if (res > highestres)
                {
                        highestres = res;
                }

        }

Unfortunately I'm getting this error when I try to compile with GCC:

3np1.c:15: error: 'for' loop initial
  declaration used outside C99 mode

I don't know what C99 mode is. Any ideas?

[A]
I'd try to declare
```
i
```
outside of the loop!
Good luck on solving 3n+1 :-)
Here's an example:
```
```
#include <stdio.h>

int main() {

   int i;

   /* for loop execution */
   for (i = 10; i < 20; i++) {
       printf("i: %d\n", i);
   }

   return 0;
}
```
```
Read more on for loops in C
here
.


q: Is there a performance difference between i++ and ++i if the resulting value is not used?

[A]
Executive summary:  No.
```
i++
```
could potentially be slower than
```
++i
```
, since the old value of
```
i
```
might need to be saved for later use, but in practice all modern
compilers will optimize this away.
We can demonstrate this by looking at the code for this function,
both with
```
++i
```
and
```
i++
```
.
```
```
$ cat i++.c
extern void g(int i);
void f()
{
    int i;

    for (i = 0; i < 100; i++)
        g(i);

}
```
```
The files are the same, except for
```
++i
```
and
```
i++
```
:
```
```
$ diff i++.c ++i.c
6c6
<     for (i = 0; i < 100; i++)
---
>     for (i = 0; i < 100; ++i)
```
```
We'll compile them, and also get the generated assembler:
```
```
$ gcc -c i++.c ++i.c
$ gcc -S i++.c ++i.c
```
```
And we can see that both the generated object and assembler files are the same.
```
```
$ md5 i++.s ++i.s
MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e
MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e

$ md5 *.o
MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22
MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22
```
```


q:
I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case.

Can someone show me (with code examples) an example of when you would have to do some "memory management" ?

[A]
You have to do "memory management" when you want to use memory on the heap rather than the stack. If you don't know how large to make an array until runtime, then you have to use the heap. For example, you might want to store something in a string, but don't know how large its contents will be until the program is run. In that case you'd write something like this:
```
```
char *string = malloc(stringlength); // stringlength is the number of bytes to allocate

 // Do something with the string...

 free(string); // Free the allocated memory
```
```


q:
We have the question is there a performance difference between i++ and ++i in C?

What's the answer for C++?

[A]
[Executive Summary: Use
```
++i
```
if you don't have a specific reason to use
```
i++
```
.]
For C++, the answer is a bit more complicated.
If
```
i
```
is a simple type (not an instance of a C++ class),
then the answer given for C ("No there is no performance difference")
holds, since the compiler is generating the code.
However, if
```
i
```
is an instance of a C++ class, then
```
i++
```
and
```
++i
```
are making calls to one of the
```
operator++
```
functions. Here's a standard pair of these functions:
```
```
Foo& Foo::operator++()   // called for ++i
{
    this->data += 1;
    return *this;
}

Foo Foo::operator++(int ignored_dummy_value)   // called for i++
{
    Foo tmp(*this);   // variable "tmp" cannot be optimized away by the compiler
    ++(*this);
    return tmp;
}
```
```
Since the compiler isn't generating code, but just calling an
```
operator++
```
function, there is no way to optimize away the
```
tmp
```
variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact.


q:
What is the difference between the EXISTS and IN clause in SQL?

When should we use EXISTS, and when should we use IN?

[A]
I'm assuming you know what they do, and thus are used differently, so I'm going to understand your question as: When would it be a good idea to rewrite the SQL to use IN instead of EXISTS, or vice versa.
Is that a fair assumption?
Edit
: The reason I'm asking is that in many cases you can rewrite an SQL based on IN to use an EXISTS instead, and vice versa, and for some database engines, the query optimizer will treat the two differently.
For instance:
```
```
SELECT *
FROM Customers
WHERE EXISTS (
    SELECT *
    FROM Orders
    WHERE Orders.CustomerID = Customers.ID
)
```
```
can be rewritten to:
```
```
SELECT *
FROM Customers
WHERE ID IN (
    SELECT CustomerID
    FROM Orders
)
```
```
or with a join:
```
```
SELECT Customers.*
FROM Customers
    INNER JOIN Orders ON Customers.ID = Orders.CustomerID
```
```
So my question still stands, is the original poster wondering about what IN and EXISTS does, and thus how to use it, or does he ask wether rewriting an SQL using IN to use EXISTS instead, or vice versa, will be a good idea?


q:
Is it possible to capture Python interpreter's output from a Python script?

Is it possible to capture Windows CMD's output from a Python script?

If so, which librar(y|ies) should I look into?

[A]
In which context are you asking?
Are you trying to capture the output from a program you start on the command line?
if so, then this is how to execute it:
```
```
somescript.py | your-capture-program-here
```
```
and to read the output, just read from standard input.
If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.


q:
I am using Simpletest as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter.

I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself.

Are there any good extended HTML reporters or GUI's out there for Simpletest?

Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried Cool PHPUnit Test Runner, but was not convinced.


q:
How to determine the applications associated with a particular extension (e.g. .JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...).

I already know how to read and write to the registry.  It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located.

[A]
The file type associations are stored in the Windows registry, so you should be able to use the
Microsoft.Win32.Registry class
to read which application is registered for which file format.
Here are two articles that might be helpful:
Reading and Writing the Registry in .NET
Windows Registry Using C#


q:
I am currently learning OLAP & MDX after many years of relational database development.

Any tips on getting started in MDX? What are the best books and resources to learn MDX?

[A]
A classic, albeit a bit dated, book is
Fast Track to MDX
. It's a great overview and a quick read, though it doesn't cover the new MDX features of SQL Server 2005.
The Spofford book
MDX Solutions
is more up date and a little deeper, but a bit harder to get through.
I also highly recommend the blogs of
Mosha Pasumansky
,
Chris Webb
, and
Darren Gosbell
.


q:
I have defined a Java function:

static <T> List<T> createEmptyList() {
    return new ArrayList<T>();
}

One way to call it is like so:

List<Integer> myList = createEmptyList(); // Compiles

Why can't I call it by explicitly passing the generic type argument? :

Object myObject = createEmtpyList<Integer>(); // Doesn't compile. Why?

I get the error Illegal start of expression from the compiler.

[A]
You can, if you pass in the type as a method parameter.
```
```
static <T> List<T> createEmptyList( Class<T> type ) {
  return new ArrayList<T>();
}

@Test
public void createStringList() {
  List<String> stringList = createEmptyList( String.class );
}
```
```
Methods cannot be genericised in the same way that a type can, so the only option for a method with a dynamically-typed generic return type -- phew that's a mouthful :-) -- is to pass in the type as an argument.
For a truly excellent FAQ on Java generics,
see Angelika Langer's generics FAQ
.
.
.
Follow-up:
It wouldn't make sense in this context to use the array argument as in
```
Collection.toArray( T[] )
```
. The only reason an array is used there is because the same (pre-allocated) array is used to contain the results (if the array is large enough to fit them all in). This saves on allocating a new array at run-time all the time.
However, for the purposes of education, if you did want to use the array typing, the syntax is very similar:
```
```
static <T> List<T> createEmptyList( T[] array ) {
  return new ArrayList<T>();
}

@Test
public void testThing() {
  List<Integer> integerList = createEmptyList( new Integer[ 1 ] );
}
```
```


q:
I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message:

Could not find default endpoint element that references contract
  'MyServiceReference.IMyService' in the ServiceModel client
  configuration section. This might be because no configuration file was
  found for your application, or because no endpoint element matching
  this contract could be found in the client element.

The code I am using to create the instance is:

myServiceClient = new MyServiceClient();

where MyServiceClient inherits from

System.ServiceModel.ClientBase

How do I solve this?

Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems.

[A]
It would probably help if you posted your app.config file, since this kind of error tends to point to a problem in the
```
<endpoint>
```
block.  Make sure the contract attribute seems right to you.
Edit: Try fully qualifying your contract value; use the full namespace.  I think that is needed.


q:
What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?

I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.

Based on Marius and Andy's answers I'm using the following solution:

double red = (percent < 50) ? 255 : 256 - (percent - 50) * 5.12;
double green = (percent > 50) ? 255 : percent * 5.12;
var color = Color.FromArgb(255, (byte)red, (byte)green, 0);

Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ...

[A]
As yellow is a mix of red and green, you can probably start with
```
#F00
```
and then slide green up until you hit
```
#FF0
```
, then slide red down to
```
#0F0
```
:
```
```
for (int i = 0; i < 100; i++) {
    var red = i < 50
        ? 255
        : 255 - (256.0 / 100 * ((i - 50) * 2));
    var green = i < 50
        ? 256.0 / 100 * (i * 2)
        : 255;
    var col = Color.FromArgb((int) red, (int) green, 0);
}
```
```


q:
Does anyone have any suggestions on how to mentor a junior programmer ? If you have mentored someone did you follow any process or was it quite informal ?

If you've been mentored in the past what kind of things did you find most helpful ?

[A]
Try to set aside between 30-60 minutes a day to review their code together. If you can't do this, then try to get together to review their code whenever they make a code commit, unless it was very basic. Have them explain why they chose the approach they took in lieu of others. A process like this helps to establish a great relationship, as well as really stimulate the student to think on their own and be able to defend their decisions. Not only does the student end up with someone approachable whom they can trust, but you'll notice an improvement in their quality of code and logic almost immediately.
Edit
: Also, If you are unable to commit this much time to co-review with your junior, then you probably shouldn't be mentoring them and instead see if anyone else has a schedule that would allow it. The whole point of mentoring is to actively aid in the professional development of the student, and they're not going to learn much if proper attention and guidance is not given to them.


q:
In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream?

The use-case I have is I want to create a ZIP file in memory, and ZipFile requires a file-like object.

[A]
Look at the struct package:
https://docs.python.org/library/struct.html
, it allows you to interpret strings as packed binary data.
Not sure if this will completely answer your question but you can use struct.unpack() to convert binary data to python objects.
```
```
import struct
f = open(filename, "rb")
s = f.read(8)
x, y = struct.unpack(">hl", s)
```
```
int this example, the ">" tells to read big-endian the "h" reads a 2-byte short, and the "l" is for a 4-byte long. you can obviously change these to whatever you need to read out of the binary data...


q: Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?

[A]
Yes this is possible. I believe there are multiple libraries to accomplish this. The most widely used is probably
ImageMagick
which is actually not PHP specific but comes with appropriate bindings.
See also in the
PHP documentation
.


q:
What types of applications have you used model checking for?

What model checking tool did you use?

How would you summarize your experience w/ the technique, specifically in evaluating its effectiveness in delivering higher quality software?

In the course of my studies, I had a chance to use Spin, and it aroused my curiosity as to how much actual model checking is going on and how much value are organizations getting out of it. In my work experience, I've worked on business applications, where there is (naturally) no consideration of applying formal verification to the logic. I'd really like to learn about SO folks model checking experience and thoughts on the subject. Will model checking ever become a more widely used developing practice that we should have in our toolkit?

[A]
I just finished a class on model checking and the big tools we used were
Spin
and
SMV
. We ended up using them to check properties on common synchronization problems, and I found SMV just a little bit easier to use.
Although these tools were fun to use, I think they really shine when you combine them with something that dynamically enforces constraints on your program (so that it's a bit easier to verify 'useful' things about your program). We ended up taking the
Spring WebFlow framework
, which uses XML to write a state-machine like file that specifies which web pages can transition to which other ones, and using SMV to be able to perform verification on said applications (
shameless plug here
).
To answer your last question, I think model checking is definitely useful to have, but I lean more towards using unit testing as a technique that makes me feel comfortable about delivering my final product.


q:
I have two arrays of animals (for example).

$array = array(
    array(
        'id' => 1,
        'name' => 'Cat',
    ),
    array(
        'id' => 2,
        'name' => 'Mouse',
    )
);

$array2 = array(
    array(
        'id' => 2,
        'age' => 321,
    ),
    array(
        'id' => 1,
        'age' => 123,
    )
);

How can I merge the two arrays into one by the ID?

[A]
First off, why don't you use the ID as the index (or key, in the mapping-style array that php arrays are imo)?
```
```
$array = array(
    1 => array(
        'name' => 'Cat',
    ),
    2 => array(
        'name' => 'Mouse',
    )
);
```
```
after that you'll have to foreach through one array, performing array_merge on the items of the other:
```
```
foreach($array2 as $key=>$value) {
  if(!is_array($array[$key])) $array[$key] = $value;
  else $array[$key] = array_merge($array[key], $value);
}
```
```
Something like that at least. Perhaps there's a better solution?


q:
I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).

The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.

What is the best practice to switch between the views?
From start to running?
Between the running views?

Ideas:

Use one form and hide and show controls

Use one start form and then a form with a TabControl

Use six separate forms

[A]
Tabbed forms are usually good... but only if you want the user to be able to see any view at any time... and it sounds like you might not.
Separate forms definitely works, but you need to make sure that the switch is seemless...if you make sure the new form appears the same exact size and location of the old form, it will look like it thew same for with changing controls.
The method I often use is actually to pre-setup all my controls on individual "Panel" controls and then show and hide these panels as I need them.  The "Panel" control is basically a control container... you can move the panel and all controls on it move relative.  And if you show or hide the panel, the controls on it do the same.  They are great for situations like this.


q:
I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo.

Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?

[A]
A single image alone doesn't give the browser the semantic information on the logos within. You could use an
image map
to supply the coordinates. To achieve tooltips, just apply a
```
title
```
attribute to each link. For more sophisticated tooltips (such as with styling, multiple lines, etc.), you'll need something non-standard, such as
UniTip
.


q:
I've used the PHP MVC framework Symfony to build an on-demand web app.

It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as this one did not help me.

I intend not to migrate to Symfony 1.1 (which fixes this bug) in the foreseeable future.

Has anyone been there and solved it? I would be most grateful for a hint or two!

[A]
The company I work for has been using Symfony and the workaround that we've used is to trigger a warning with javascript before the user gets logged out. I suspect that there is a a way to make 'heartbeat' ajax calls to the server to trigger the timer to reset, but that may be a lot of trouble. I think that there may not be a full fix that's suitable for you though, except maybe re-writing the session handler.
Sorry I couldn't be more specific, if I get the chance, I'll ask our Symfony devs if they know of a better solution.


q:
I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata:

15, 'QHS', '20', '2008-08-24 13:36:33.465567-04'
15, 'QHE', '8', '2008-08-24 12:07:08.660519-04'
15, 'QHS', '21', '2008-08-24 09:44:44.39354-04'
15, 'QHE', '10', '2008-08-24 08:47:57.672058-04'

I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code.

[A]
I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here goes...
One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the 'deprecation date' instead. Another way is to expand the table with an 'active' column, but that would introduce some redundancy.
The classic solution would be to have both 'Valid-From' and 'Valid-To' fields where the 'Valid-To' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity.
Common to these is that there is a single way of determining the set of current fields. You'd simply select all entries with the active user and a NULL 'Valid-To' or 'deprecation date' or a true 'active'.
You might be interested in taking a look at the Wikipedia entry on
temporal databases
and the article
A consensus glossary of temporal database concepts
.


q:
I have a couple of files containing a value in each line.

EDIT :

I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state.

I was trying to do:

paste -d ',' file1 file2 file 3 file 4 > file5.csv

and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things.

[A]
you probably need to clarify or retag your question but as it stands the answer is below.
joining two files under Linux
```
```
cat filetwo >> fileone
```
```


q:
What's the best way to make an element of 100% minimum height across a
  wide range of browsers ?

In particular if you have a layout with a header and footer of fixed height,

how do you make the middle content part fill 100% of the space in between with the footer fixed to the bottom ?

[A]
I am using the following one:
CSS Layout - 100 % height
Min-height
The #container element of this page has a min-height of 100%. That
  way, if the content requires more height than the viewport provides,
  the height of #content forces #container to become longer as well.
  Possible columns in #content can then be visualised with a background
  image on #container; divs are not table cells, and you don't need (or
  want) the physical elements to create such a visual effect. If you're
  not yet convinced; think wobbly lines and gradients instead of
  straight lines and simple color schemes.
Relative positioning
Because #container has a relative position, #footer will always remain
  at its bottom; since the min-height mentioned above does not prevent
  #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer.
Padding-bottom
Since it is no longer in the normal flow, padding-bottom of #content
  now provides the space for the absolute #footer. This padding is
  included in the scrolled height by default, so that the footer will
  never overlap the above content.
Scale the text size a bit or resize your browser window to test this
  layout.
```
```
html,body {
    margin:0;
    padding:0;
    height:100%; /* needed for container min-height */
    background:gray;

    font-family:arial,sans-serif;
    font-size:small;
    color:#666;
}

h1 {
    font:1.5em georgia,serif;
    margin:0.5em 0;
}

h2 {
    font:1.25em georgia,serif;
    margin:0 0 0.5em;
}
    h1, h2, a {
        color:orange;
    }

p {
    line-height:1.5;
    margin:0 0 1em;
}

div#container {
    position:relative; /* needed for footer positioning*/
    margin:0 auto; /* center, not in IE5 */
    width:750px;
    background:#f0f0f0;

    height:auto !important; /* real browsers */
    height:100%; /* IE6: treaded as min-height*/

    min-height:100%; /* real browsers */
}

div#header {
    padding:1em;
    background:#ddd url("../csslayout.gif") 98% 10px no-repeat;
    border-bottom:6px double gray;
}
    div#header p {
        font-style:italic;
        font-size:1.1em;
        margin:0;
    }

div#content {
    padding:1em 1em 5em; /* bottom padding for footer */
}
    div#content p {
        text-align:justify;
        padding:0 1em;
    }

div#footer {
    position:absolute;
    width:100%;
    bottom:0; /* stick to bottom */
    background:#ddd;
    border-top:6px double gray;
}
div#footer p {
    padding:1em;
    margin:0;
}
```
```
Works fine for me.


q: How do you unit test a HttpModule in asp.net given that HttpApplication and HttpContext do no implement an interface ?

[A]
In the past before moving to ASP.NET MVC, I used
this library
Phil Haack created for Unit Testing anything that used the HttpApplication and HttpContext.  It in turned used a
Duck Typing library
.
Unfortunately, this was the best way to do it.  ASP.NET was not made to be easily testable.  When they worked on ASP.NET MVC, one of the goals is to get rid of these headaches by making the framework more testable.


q:
Has anybody out there used the SWIG library with C#?  If you have, what pitfalls did you find and what is the best way to use the library?  I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my .NET application.

Edit:  Some clarification on target OS's.

I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG.  P/Invoke is not an option.

[A]
I did attempt to use SWIG to wrap a project C++ for using in .NET a few years ago.
I didn't get very far as it was a massive giant pain to produce the configuration that SWIG required. At the time I just wanted a solution, not to learn another language/api/etc. SWIG may be easier to use these days, I couldn't tell you.
We ended up using Managed C++ to wrap the C++ project. It worked really well.
If you're just invoking functions straight out of a dll, I'd suggest not worrying about either of the above, and just using
P/Invoke


q:
There is a request to make the SO search default to an AND style functionality over the current OR when multiple terms are used.

The official response was:

not as simple as it sounds; we use SQL Server 2005's FREETEXT() function, and I can't find a way to specify AND vs. OR -- can you?

So, is there a way?

There are a number of resources on it I can find, but I am not an expert.

[A]
As far as I've seen, it is
not
possible to do AND when using FREETEXT() under SQL 2005 (nor 2008, afaik).
A FREETEXT query ignores Boolean, proximity, and wildcard operators by design. However you could do this:
```
```
WHERE FREETEXT('You gotta love MS-SQL') > 0
 AND FREETEXT('You gotta love MySQL too...') >  0
```
```
Or that's what I think :)
-- The idea is make it evaluate to Boolean, so you can use boolean operators. Don't know if this would give an error or not. I think it
should
work. But reference material is pointing to the fact that this is not possible by design.
The use of CONTAINS() instead of FREETEXT() could help.