Question:
In JavaScript, using the Prototype library, the following functional construction is possible:

var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"];
words.pluck('length');
//-> [7, 8, 5, 16, 4]

Note that this example code is equivalent to

words.map( function(word) { return word.length; } );

I wondered if something similar is possible in F#:

let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"]
//val words: string list
List.pluck 'Length' words
//int list = [7; 8; 5; 16; 4]

without having to write:

List.map (fun (s:string) -> s.Length) words

This would seem quite useful to me because then you don't have to write functions for every property to access them.

Answer:
Prototype's
```
pluck
```
takes advantage of that in Javascript
```
object.method()
```
is the same as
```
object[method]
```
.
Unfortunately you can't call
```
String.Length
```
either because it's not a static method. You can however use:
```
```
#r "FSharp.PowerPack.dll"
open Microsoft.FSharp.Compatibility
words |> List.map String.length
```
```
http://research.microsoft.com/fsharp/manual/FSharp.PowerPack/Microsoft.FSharp.Compatibility.String.html
However, using
```
Compatibility
```
will probably make things more confusing to people looking at your code.


Question:
There's an MSDN article here, but I'm not getting very far:

p = 139;
g = 5;

CRYPT_DATA_BLOB pblob;
pblob.cbData = sizeof( ULONG );
pblob.pbData = ( LPBYTE ) &p;

CRYPT_DATA_BLOB gblob;
gblob.cbData = sizeof( ULONG );
gblob.pbData = ( LPBYTE ) &g;

HCRYPTKEY hKey;
if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF,
                    CRYPT_PREGEN, &hKey ) )
{
    ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &pblob, 0 );

Fails here with NTE_BAD_DATA.  I'm using MS_DEF_DSS_DH_PROV.   What gives?

Answer:
It looks to me that
```
KP_P
```
,
```
KP_G
```
,
```
KP_Q
```
are for DSS keys (Digital Signature Standard?). For Diffie-Hellman it looks like you're supposed to use
```
KP_PUB_PARAMS
```
and pass a
```
DATA_BLOB
```
that points to a
```
DHPUBKEY_VER3
```
structure.
Note that the article you're pointing to is from the Windows Mobile/Windows CE SDK. It wouldn't be the first time that CE worked differently from the desktop/server.
EDIT: CE does not implement
```
KP_PUB_PARAMS
```
. To use this structure on the desktop, see
Diffie-Hellman Version 3 Public Key BLOBs
.


Question:
I'm trying to load test data into a test DB during a maven build for integration testing. persistence.xml is being copied to target/test-classes/META-INF/ correctly, but I get this exception when the test is run.

javax.persistence.PersistenceException:
  No Persistence provider for
  EntityManager named aimDatabase

It looks like it's not finding or loading persistence.xml.

Answer:
If this is on windows, you can use sysinternal's procmon to find out if it's checking the right path.
Just filter by path -> contains -> persistence.xml.  Procmon will pick up any attempts to open a file named persistenc.xml, and you can check to see the path or paths that get tried.
See here for more detail on procmon:
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx


Question:
Is there a way to have a 64 bit enum in C++?  Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.

For some reason I thought the following might work:

enum MY_ENUM : unsigned __int64
{
    LARGE_VALUE = 0x1000000000000000,
};

Answer:
An enum in C++ can be any integral type. You can, for example, have an enum of chars. IE:
```
```
enum MY_ENUM
{
   CHAR_VALUE = 'c',
};
```
```
I would
assume
this includes __int64. Try just
```
```
enum MY_ENUM
{
   LARGE_VALUE = 0x1000000000000000,
};
```
```
According to my commenter, sixlettervariables, in C the base type will be an int always, while in C++ the base type is whatever is large enough to fit the largest included value. So both enums above should work.


Question: I would like to call my unmanaged C++ libraries from my C# code. What are the potential pitfalls and precautions that need to be taken? Thank you for your time.

Answer:
There are a couple routes you can go with this - one, you can update your unmanaged C++ libraries to have a managed C++ extensions wrapper around them and have C# utilize those classes directly.  This is a bit time-consuming, but it provides a nice bridge to legacy unmanaged code.  But be aware that managed C++ extensions are sometimes a bit hard to navigate themselves as the syntax is similar to unmanaged C++, but close enough that a very trained eye will be able to see the differences.
The other route to go is have your umnanaged C++ implement COM classes and have C# utilize it via an autogenerated interop assembly.  This way is easier if you know your way around COM well enough.
Hope this helps.


Question: Where may one find references on implementing an algorithm for calculating a "dirty rectangle" for minimizing frame buffer updates?  A display model that permits arbitrary edits and computes the minimal set of "bit blit" operations required to update the display.

Answer:
To build the smallest rectangle that contains all the areas that need to be repainted:
Start with a blank area (perhaps a rectangle set to 0,0,0,0 - something you can detect as 'no update required')
For each dirty area added:
Normalize the new area (i.e. ensure that left is less than right, top less than bottom)
If the dirty rectangle is currently empty, set it to the supplied area
Otherwise, set the left and top co-ordinates of the dirty rectangle to the smallest of {dirty,new}, and the right and bottom co-ordinates to the largest of {dirty,new}.
Windows, at least, maintains an
update region
of the changes that it's been informed of, and any repainting that needs to be done due to the window being obscured and revealed. A
region
is an object that is made up of many possibly discontinuous rectangles, polygons and ellipses. You tell Windows about a part of the screen that needs to be repainted by calling InvalidateRect - there is also an InvalidateRgn function for more complicated areas. If you choose to do some painting before the next WM_PAINT message arrives, and you want to exclude that from the dirty area, there are ValidateRect and ValidateRgn functions.
When you start painting with BeginPaint, you supply a PAINTSTRUCT that Windows fills with information about what needs to be painted. One of the members is the smallest rectangle that contains the invalid region. You can get the region itself using GetUpdateRgn (you must call this before BeginPaint, because BeginPaint marks the whole window as valid) if you want to minimize drawing when there are multiple small invalid areas.
I would assume that, as minimizing drawing was important on the Mac and on X when those environments were originally written, there are equivalent mechanisms for maintaining an update region.


Question:
I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; messages (id, body) and messages_read (user_id, message_id).

Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this?

Thanks!

Answer:
Well, you could use
```
```
SELECT id FROM messages m WHERE m.id NOT IN(
    SELECT message_id FROM messages_read WHERE user_id = ?)
```
```
Where ? is passed in by your app.


Question: I need to return a list of record id's from a table that may/may not have multiple entries with that record id on the same date. The same date criteria is key - if a record has three entries on 09/10/2008, then I need all three returned. If the record only has one entry on 09/12/2008, then I don't need it.

Answer:
```
```
SELECT id, datefield, count(*) FROM tablename GROUP BY datefield
  HAVING count(*) > 1
```
```


Question:
How cheap can MySQL be compared to MS SQL when you have tons of data (and joins/search)? Consider a site like  stackoverflow full of Q&As already and after getting dugg.

My ASP.NET sites are currently on SQL Server Express so I don't have any idea how cost compares in the long run. Although after a quick research, I'm starting to envy the savings MySQL folks get.

Answer:
I know that stackoverflow has had problems with deadlocks from reads/writes coming at odd intervals but they're claiming their architecture (MSSQL) is holding up fine.  This was before the public beta of course and according to Jeff's twitter earlier today:
the range of top 32 newest/modified
  questions was about 20 minutes in the
  private beta; now it's about 2
  minutes.
That the site hasn't crashed yet is a testament to the database (as well as good coding and testing).
But why not post some specific numbers about your site?


Question: What factors determine which approach is more appropriate?

Answer: Not nearly enough information here. It depends if your language even supports the construct "Thing.something" or equivalent (ie. it's an OO language). If so, it's far more appropriate because that's the OO paradigm (members should be associated with the object they act on). In a procedural style, of course, DoSomethingtoThing() is your only choice... or ThingDoSomething()


Question: What's the best library to use to generate RSS for a webserver written in Common Lisp?

Answer:
xml-emitter
says it has an RSS 2.0 emitter built in.


Question: How can I set the protected DoubleBuffered property of the controls on a form that are suffering from flicker?

Answer:
```
```
public void EnableDoubleBuffering()
{
   this.SetStyle(ControlStyles.DoubleBuffer |
      ControlStyles.UserPaint |
      ControlStyles.AllPaintingInWmPaint,
      true);
   this.UpdateStyles();
}
```
```


Question:
I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.

My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using gcc).

I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?

Answer:
```
```
ulimit -c unlimited
```
```
is a system variable, wich will allow to create a core dump after your application crashes. In this case an unlimited amount. Look for a file called core in the very same directory. Make sure you compiled your code with debugging informations enabled!
regards


Question: I would like to display multiple colors (and potentially shapes and sizes) of data points in a Google Chart scatter chart. Does anyone have an example of how to do so?

Answer:
You can only use one dataset in a scatter plot, thus only one color.
http://code.google.com/apis/chart/#scatter_plot
From the API description:
Scatter plots use multiple data sets differently than other chart types. You can only show one data set in a scatter plot.


Question:
I've used the MIT Continuous testing plugin in the past, but it has long since passed out of date and is no longer compatible with anything approaching a modern release of Eclipse.

Does anyone have a good replacement? Free, naturally, is preferred.

Answer:
There is a list in this Ben Rady article at Object Mentor:
Continuous Testing Explained
.  Unfortunately the only Eclipse tool appears to be
CT-Eclipse
which is not currently maintained either.
There is also
Fireworks
for IntelliJ and
Infinitest
which is not IDE specific but also has some IntelliJ integration.


Question:
I will be moving our production SQL2005 application to SQL2008 soon. Any things to lookout for before/after the move? Any warnings, advices?

Thank you!

Answer:
The upgrade adviser can also help.
Look at the execution plans with production data in the database.
Though my best advice is to test, test, test.
When people started moving from 2000 to 2005 it wasn't the breaking features that were show stoppers it was the change in how queries performed with the new optimizer.
Queries that were heavily optimized for 2000 now performed poorly or even worse erratically leading people to chase down non-problems and generally lowering the confidence of the end users.


Question: What is the easiest way to capitalize the first letter in each word of a string?

Answer:
Take a look at the
ucfirst
function.
```
```
$line = join " ", map {ucfirst} split " ", $line;
```
```


Question:
Can I persuade operator>> in C++ to read both a hex value AND and a decimal value?  The following program demonstrates how reading hex goes wrong.  I'd like the same istringstream to be able to read both hex and decimal.

#include <iostream>
#include <sstream>

int main(int argc, char** argv)
{
    int result = 0;
    // std::istringstream is("5"); // this works
    std::istringstream is("0x5"); // this fails

    while ( is.good() ) {
        if ( is.peek() != EOF )
            is >> result;
        else
            break;
    }

    if ( is.fail() )
        std::cout << "failed to read string" << std::endl;
    else
        std::cout << "successfully read string" << std::endl;

    std::cout << "result: " << result << std::endl;
}

Answer:
You need to tell C++ what your base is going to be.
Want to parse a hex number?  Change your "is >> result" line to:
```
```
is >> std::hex >> result;
```
```
Putting a std::dec indicates decimal numbers, std::oct indicates octal.


Question:
I would like to keep the overhead at a minimum. Right now I have:

// Launch a Message Box with advice to the user
DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation);

// The test will only be launched if the user has selected Yes on the Message Box
if(result == DialogResult::Yes)
{
    // Execute code
}

Unfortunately my client would prefer "Continue" and "Cancel" in place of the default "Yes" and "No" button text. It seems like there should be an easy way to do this.

Answer:
You can use "OK" and "Cancel"
By substituting
```
MessageBoxButtons::YesNo
```
with
```
MessageBoxButtons::OKCancel
```
MessageBoxButtons Enum
Short of that you would have to create a new form, as I don't believe the Enum can be extended.


Question:
In the Java collections framework, the Collection interface declares the following method:

<T> T[] toArray(T[] a)

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

If you wanted to implement this method, how would you create an array of the type of a, known only at runtime?

Answer:
```
```
Array.newInstance(Class componentType, int length)
```
```


Question:
Suppose I have a vector that is nested in a dataframe one or two levels.  Is there a quick and dirty way to access the last value, without using the length() function?  Something ala PERL's $# special var?

So I would like something like:

dat$vec1$vec2[$#]

instead of

dat$vec1$vec2[length(dat$vec1$vec2)]

Answer:
If you're looking for something as nice as Python's x[-1] notation, I think you're out of luck.  The standard idiom is
```
```
x[length(x)]
```
```
but it's easy enough to write a function to do this:
```
```
last <- function(x) { return( x[length(x)] ) }
```
```
This missing feature in R annoys me too!


Question:
GDB has severe issues when debugging with multiple threads (pthreads).
Are there any other good multi-threaded debuggers for C/C++ on *nix?

Answer: From my search, I have not found any good multi-thread debuggers for *nix. GDB seems to be getting better, and the last time I had to debug a multi-threaded application on FreeBSD (7.0-RELEASE) it behaved fairly well, letting me find where the error was.


Question:
I want to write a raw byte/byte stream to a position in a file.
This is what I have currently:

$fpr = fopen($out, 'r+');
fseek($fpr, 1); //seek to second byte
fwrite($fpr, 0x63);
fclose($fpr);

This currently writes the actually string value of "99" starting at byte offset 1.  IE, it writes bytes "9" and "9".  I just want to write the actual one byte value 0x63 which happens to represent number 99.

Thanks for your time.

Answer:
```
fwrite()
```
takes strings. Try
```
chr(0x63)
```
if you want to write a
```
0x63
```
byte to the file.


Question:
I have an application written in java, and I want to add a flash front end to it. The flash front end will run on the same computer as the java app in the stand alone flash player. I need two way communication between the two parts, and have no idea how to even start going about this. I suppose I could open a  socket between the two programs, but I feel that there must be an easier way. Is there a nice part of the api in actionscript 3.0 that will allow me to access java methods directly, or will I have to resort to sockets? I am relatively new to flash, by the way, so any good guides would be much appreciated!

Thanks

Answer:
AMF
is a messaging protocol commonly used to talk between flash and a backend system. There're several Java implementations, but I haven't used any of them so can't tell you which is best.
Blaze DS
Red5
Granite DS
Flash can also talk plain old XML, SOAP or REST to the backend, so depending on your codebase that might be easier.


Question:
I am trying to run a SeleniumTestCase with phpunit but I cannot get it to run with the phpunit.bat script.

My goal is to use phpunit with Selenium RC in CruiseControl & phpUnderControl. This is what the test looks like:

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class WebTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser('*firefox');
        $this->setBrowserUrl('http://www.example.com/');
    }

    public function testTitle()
    {
        $this->open('http://www.example.com/');
        $this->assertTitleEquals('Example Web Page');
    }
}

I also got PEAR in the include_path and PHPUnit installed with the Selenium extension. I installed these with the pear installer so I guess that's not the problem.

Any help would be very much appreciated.

Thanks, Remy

Answer:
Have a look at one of the comments in the require_once entry in the php manual..
http://ie.php.net/manual/en/function.require-once.php#62838
"require_once (and include_once for that matters) is slow
Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class."


Question:
This is not "exactly" a programming question, but it's highly related.  We are writing an app that sends out email invitations for a client (no, it's not spam).  Their designer gave us an HTML and CSS template to use which is fine.  The problem is that it looks like crap in Outlook 2007 because Microsoft decided to use Word (of all things!) as the rendering engine for HTML in Outlook 2007.  I want the client to understand that they should design a "compatible" look and would love to be able to show some kind of statistics about what email clients are being used out there, namely that Outlook 2007 is growing in use.

Has anyone run across any white papers, web sites, studies that even come close to providing a view on this?  I don't expect census level accuracy, but something fairly credible would be good.  Thanks for any help.

Answer:
you should look at
ReturnPath
- they somewhat specialize in that.
Clients you likely need to consider (aside from Outlook):
AOL
Gmail
(Google)
Yahoo Mail
(Yahoo)
Hotmail
/
Live
/
MSN
/
Outlook
(Microsoft)
Lotus Notes (IBM)
Thunderbird
(Mozilla)


Question: I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?

Answer:
Tk does not natively support windows bitmap files. However, the "Img" extension does and is freely available on just about every platform. You do not need to read the data in, you can create the image straight from the file on disk. In plain tcl/tk your code might look something like this:
```
```
package require Img
set image [image create photo -file /path/to/image.bmp]
label .l -image $image
pack .l
```
```
a little more information can be found at
http://wiki.tcl.tk/6165


Question: How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that use strict; isn't sufficient for this purpose.

Answer:
Include this:
```
```
use Carp ();
```
```
Then include
one
of these lines at the top of your source file:
```
```
local $SIG{__WARN__} = \&Carp::confess;
local $SIG{__WARN__} = \&Carp::cluck;
```
```
The
```
confess
```
line will give a stack trace, and the
```
cluck
```
line is much more terse.


Question:
I recently came across a ASP 1.1 web application that put a whole heap of stuff in the session variable - including all the DB data objects and even the DB connection object. It ends up being huge. When the web session times out (four hours after the user has finished using the application) sometimes their database transactions get rolled back. I'm assuming this is because the DB connection is not being closed properly when IIS kills the session.

Anyway, my question is what should be in the session variable? Clearly some things need to be in there. The user selects which plan they want to edit on the main screen, so the plan id goes into the session variable. Is it better to try and reduce the load on the DB by storing all the details about the user (and their manager etc.) and the plan they are editing in the session variable or should I try to minimise the stuff in the session variable and query the DB for everything I need in the Page_Load event?

Answer:
This is pretty hard to answer because it's so application-specific, but here are a few guidelines I use:
Put as little as possible in the session.
User-specific selections that should only last during a given visit are a good choice
often, variables that need to be accessible to multiple pages throughout the user's visit to your site (to avoid passing them from page to page) are also good to put in the session.
From what little you've said about your application, I'd probably select your data from the db and try to find ways to minimize the impact of those queries instead of loading down the session.


Question: How can I dismiss dialog in Cocoa application when user presses Esc or Enter key? I have OK button, is it possible to make it default button?

Answer:
If you present the alert panel using the
```
NSAlert
```
class or,
```
NSRunAlertPanel
```
family of functions, or the
```
NSBeginAlertSheet
```
family of functions, you will get support for default and cancel buttons automatically.
If you're presenting a sheet that needs OK/Cancel buttons, and you're not using any of the above, you should be able to assign your buttons appropriate keyboard equivalents in Interface Builder using the attributes inspector.  (Just highlight the
Key Equiv.
area and press the key you want to be equivalent to pressing that button.)
If you're presenting a dialog that's not either an alert or a document/window-modal sheet — don't. :)  Document-modal alerts aren't Mac-like, and shouldn't be used for things like preferences windows.


Question: Is it possible to create custom events in C++?  For example, say I have the variable X, and the variable Y.  Whenever X changes, I would like to execute a function that sets Y equal to 3X.  Is there a way to create such a trigger/event?  (triggers are common in some databases)

Answer:
Think you should read a little about
Design Patterns
, specifically the
Observer Pattern
.
Qt from
Trolltech
have implemented a nice solutions they call
Signals and Slots
.


Question: I do work in theoretical chemistry on a high performance cluster, often involving molecular dynamics simulations.  One of the problems my work addresses involves a static field of N-dimensional (typically N = 2-5) hyper-spheres, that a test particle may collide with.  I'm looking to optimize (read: overhaul) the the data structure I use for representing the field of spheres so I can do rapid collision detection.  Currently I use a dead simple array of pointers to an N-membered struct (doubles for each coordinate of the center) and a nearest-neighbor list.  I've heard of oct- and quad- trees but haven't found a clear explanation of how they work, how to efficiently implement one, or how to then do fast collision detection with one.  Given the size of my simulations, memory is (almost) no object, but cycles are.

Answer:
A Quad tree is a 2 dimensional tree, in which at each level a node has 4 children, each of which covers 1/4 of the area of the parent node.
An Oct tree is a 3 dimensional tree, in which at each level a node has 8 children, each of which contains 1/8th of the volume of the parent node.  Here is picture to help you visualize it:
http://en.wikipedia.org/wiki/Octree
If you're doing N dimensional intersection tests, you could generalize this to an N tree.
Intersection algorithms work by starting at the top of the tree and recursively traversing into any child nodes that intersect the object being tested, at some point you get to leaf nodes, which contain the actual objects.


Question: I would like to have some suggestions about which third-part controls can we use in our Visual C++ MFC application?

Answer:
If you don't mind paying, there's FarPoint Spread:
http://www.componentsource.com/selec/products/farpoint-spread/summary.html


Question: What is the best/fastest way to sort Alphanumeric fields?

Answer:
You will find that most development libraries ship with an implementation of the quicksort algorithm, which is often the fastest sorting algorithm.  Check out the
Wikipedia link here
.


Question:
In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that they might be protected by a lock or not (barriers perhaps).

Does the pthread POSIX standard have any say about this, is this compiler-dependent or neither?

Edit to add: Thanks for the great answers. But what if you're not using locks; what if you're using barriers for example? Or code that uses primitives such as compare-and-swap to directly and atomically modify a shared variable...

Answer:
Volatile means that we have to go to memory to get or set this value. If you don't set volatile, the compiled code might store the data in a register for a long time.
What this means is that you should mark variables that you share between threads as volatile so that you don't have situations where one thread starts modifying the value but doesn't write its result before a second thread comes along and tries to read the value.
Volatile is a compiler hint that disables certain optimizations. The output assembly of the compiler might have been safe without it but you should always use it for shared values.
This is especially important if you are NOT using the expensive thread sync objects provided by your system - you might for example have a data structure where you can keep it valid with a series of atomic changes. Many stacks that do not allocate memory are examples of such data structures, because you can add a value to the stack then move the end pointer or remove a value from the stack after moving the end pointer. When implementing such a structure, volatile becomes crucial to ensure that your atomic instructions are actually atomic.


Question: If I am given a MemoryStream that I know has been populated with a String, how do I get a String back out?

Answer:
use a
StreamReader
, then you can use the
ReadToEnd
method that returns a string.


Question:
My employer just asked me to run a timed batch process in a Java EE WebSphere application they have running. It's supposed to run a certain class at 11:30 pm everyday.

I'm not very familiar with Java EE nor WebSphere server (or tomcat, in the development environment), and I've been digging around but all I've found is about the java timer class but not how to set it or invoke it.

It seems that editing the web.xml file is required as well.

Any help will be appreciated!

Answer:
You should look at the open-source
Quartz library
from OpenSymphony. Very easy to use and perfect for this kind of thing.
TimerTasks are best suited for running something in a short time in the future. But for a repeated execution in a large timeframe such as this, Quartz excels. You can even keep your list of upcoming tasks in persistent storage such as a file or database, so upcoming timed jobs are not lost if your application is restarted.
Also, there's a fantastic abstraction for Quartz in the Spring framework.


Question: I am just getting started with flex and am using the SDK (not Flex Builder). I was wondering what's the best way to compile a mxml file from an ant build script.

Answer:
The Flex SDK ships with a set of ant tasks. More info at:
http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html
Here is an example of compiling Flex SWCs with ant:
http://www.mikechambers.com/blog/2006/05/19/example-using-ant-with-compc-to-compile-swcs/
mike chambers


Question: The two connection limit can be particularly troublesome when you have multiple tabs open simultaneously.  Besides "ignore the problem," what coping mechanisms have you seen used to get multiple tabs both doing heavily interactive Ajax despite the two connection limit?

Answer:
The two connection limit is a "suggestion" and this
article
describes how to get around it where possible.  Other Firefox configuration is discussed on this about the
about:config
capability in Firefox.
Also, if you own the website, you can tweak the performance of the site using suggestions form this
book
from the Chief Performance Yahoo.


Question:
I installed both the Delphi 2009 trial and actual release via the web installer when I received them and experienced the same errors when installing both.

Both times it appears that the core web installer failed when it went to spawn the additional install packages for boost, documentation and dbtools.  (It brought up a findfile dialog asking for a setup.msi that didn't exist on my machine).  When cancelling out of this, the installer reported a fatal error.

The uninstaller did not appear in my program list, and would did not launch from the installation folder.

Future attempts to bring up the installer had it in a state where it thought Delphi 2009 was already installed and it wouldn't correct or repair or uninstall it.

Answer:
The problems seem to originate with the web installer not having all the files needed.
Download the 2009 ISO:
http://cc.codegear.com/item/26049
Mounted it using this free tool from Microsoft:
http://download.microsoft.com/download/7/b/6/7b6abd84-7841-4978-96f5-bd58df02efa2/winxpvirtualcdcontrolpanel_21.exe
(You can burn it to a DVD too)
Then reran the installer.  At this point, both the repair and uninstall worked.


Question: How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.

Answer:
Use sub references, and closures. A good perlish example of this
```
```
sort { lc($a) cmp lc($b) } @items
```
```


Question:
What are some reasons why PHP would force errors to show, no matter what you tell it to disable?

I have tried

error_reporting(0);
ini_set('display_errors', 0);

with no luck.

Answer:
Note the caveat in the manual at
http://uk.php.net/error_reporting
:
Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).
If your underlying system is configured to report E_STRICT errors, these may be output before your code is even considered. Don't forget, error_reporting/ini_set are runtime evaluations, and anything performed in a "before-run" phase will not see their effects.
Based on your comment that your error is...
Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in /usr/home/REDACTED/public_html/dev.php on line 11
Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a ';'). Therefore, your change of error reporting is never encountered.
Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place...
php_value error_reporting 0
in a .htaccess file to suppress them all, but this is system configuration dependent.
Pragmatically, don't write files with syntax errors :)


Question:
I'm toying with my first remoting project and I need to create a RemotableType DLL. I know I can compile it by hand with csc, but I wonder if there are some facilities in place on Visual Studio to handle the Remoting case, or, more specificly, to tell it that a specific file should be compiled as a .dll without having to add another project to a solution exclusively to compile a class or two into DLLs.

NOTE: I know I should toy with my first WCF project, but this has to run on 2.0.

Answer:
Note the caveat in the manual at
http://uk.php.net/error_reporting
:
Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).
If your underlying system is configured to report E_STRICT errors, these may be output before your code is even considered. Don't forget, error_reporting/ini_set are runtime evaluations, and anything performed in a "before-run" phase will not see their effects.
Based on your comment that your error is...
Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in /usr/home/REDACTED/public_html/dev.php on line 11
Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a ';'). Therefore, your change of error reporting is never encountered.
Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place...
php_value error_reporting 0
in a .htaccess file to suppress them all, but this is system configuration dependent.
Pragmatically, don't write files with syntax errors :)


Question:
I've been running into a peculiar issue with certain Java applications in the HP-UX environment.

The heap is set to -mx512, yet, looking at the memory regions for this java process using gpm, it shows it using upwards of 1.6GBs of RSS memory, with 1.1GB allocated to the DATA region.  Grows quite rapidly over a 24-48hour period and then slows down substantially, still growing 2MB every few hours. However, the Java heap shows no sign of leakage.

Curious how this was possible I researched a bit and found this HP write-up on memory leaks in java heap and c heap: http://docs.hp.com/en/JAVAPERFTUNE/Memory-Management.pdf

My question is what determines what is ran in the C heap vs the java heap, and for things that do not run through the java heap, how would you identify those objects being run on the C heap? Additionally does the java heap sit inside the C heap?

Answer:
My only guess with the figures you have given is a memory leak in the Java VM.  You might want to try one of the other VMs they listed in the paper you referred.  Another (much more difficult) alternative might be to compile the open java on the HP platform.
Sun's Java isn't 100% open yet, they are working on it, but I believe that there is one in sourceforge that is.
Java also thrashes memory by the way.  Sometimes it confuses OS memory management a little (you see it when windows runs out of memory and asks Java to free some up, Java touches all it's objects causing them to be loaded in from the swapfile, windows screams in agony and dies), but I don't think that's what you are seeing.


Question:
Our application commonly used an ActiveX control to download and install our client on IE (XP and prior), however as our user base has drifted towards more Vista boxes with "Protected Mode" on, we are required to investigate.

So going forward, is it worth the headache of trying to use the protected mode API?  Is this going to result in a deluge of dialog boxes and admin rights to do the things our app needs to do (write to some local file places, access some other applications, etc)?

I'm half bent on just adding a non-browser based installer app that will do the dirty work of downloading and installing the client, if need be... this would only need to be installed once and in large corporate structures it could be pushed out by IT.

Are there some other ideas I'm missing?

Answer:
Have you checked out Microsoft's
ClickOnce Deployment
?
If I remember correctly you can embed a manifests which would help with dealing with protected modes automatically, saving you those headaches with the APIs.
I believe ClickOnce is geared for the same thing your ActiveX installer was designed to do.
Since you say your IT dept could push this out, I assume you could use this kind of technology as well.
Even though you might not be writing applications on the .NET CLR, you can use Visual Studio to generate those manifest and installers for you.


Question:
I would like to replicate this in python:

gvimdiff <(hg cat file.txt) file.txt

(hg cat file.txt outputs the most recently committed version of file.txt)

I know how to pipe the file to gvimdiff, but it won't accept another file:

$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"

Getting to the python part...

# hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])

When subprocess is called it merely passes <(hg cat file) onto gvimdiff as a filename.

So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:

diff <(cat file.txt) file.txt

Answer:
There is also the commands module:
```
```
import commands

status, output = commands.getstatusoutput("gvimdiff <(hg cat file.txt) file.txt")
```
```
There is also the popen set of functions, if you want to actually grok the data from a command as it is running.


Question: How to create a DOM from a User's input in PHP5?

Answer:
I would use the DOM API that has been part of the core since 5. For an XML string $xml, you can build a DOM object with
```
```
$dom = new DOMDocument();
$dom->loadXML($xml);
```
```
Manipulate it with the rest of the DOM API, defined at
http://uk.php.net/DOM


Question:
What are the steps to estimating using function points?

Is there a quick-reference guide of some sort out there?

Answer:
I took a conference session on Function Point Analysis a few years back.  There is a lot too it.  You can check out the
Free Function Point Training Manual
online, the
Fundamentals of Function Points
, or I suspect you can get a book on it at a computer store.
You might also check out the
International Function Point Users Group
and see if they have some resources or a local meeting for you.


Question:
How can I find out the date a MS SQL Server 2000 object was last modified?

I need to get a list of all the views, procs, functions etc that were modified since Aug 15th.  In sysObjects I can see the date objects were created but I need to know when they were last altered.

NB: this is an SQL 2000 database.

Answer:
Note that SQL Server actually does
not
record the last modification date. It does not exist in any system tables.
The Schema Changes History report is actually constructed from the
Default Trace
. Since many admins (and web hosts) turn that off, it may not work for you.
Buck Woody had a good explanation of how this report works
here
. The data is also temporary.
For this reason, you should never RELY on the Schema Changes History report. Alternatives:
Use
DDL Triggers
to log all schema modification to a table of your choosing.
Enforce a protocol where views and procs are never altered, they are only dropped and recreated. This means the created date will also be the last updated date (this does not work with tables obviously).
Vigilantly version your SQL objects and schema in source control.
--
Edit: saw that this is SQL 2000. That rules out Default Trace and DDL Triggers. You're left with one of the more tedious options I listed above.


Question: Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?

Answer:
I suppose you could step through the string and check if there are any
```
.
```
characters in it.  That's just the first thing that popped into my head though, so I'm sure there are other (better) ways to be more certain.


Question:
I'd like to be able to open a TDataSet asynchronously in its own thread so that the main VCL thread can continue until that's done, and then have the main VCL thread read from that TDataSet afterwards. I've done some experimenting and have gotten into some very weird situations, so I'm wondering if anyone has done this before.

I've seen some sample apps where a TDataSet is created in a separate thread, it's opened and then data is read from it, but that's all done in the separate thread. I'm wondering if it's safe to read from the TDataSet from the main VCL thread after the other thread opens the data source.

I'm doing Win32 programming in Delphi 7, using TmySQLQuery from DAC for MySQL as my TDataSet descendant.

Answer:
I have seen it done with other implementations of TDataSet, namely in the
Asta
components.  These would contact the server, return immediately, and then fire an event once the data had been loaded.
However, I believe it depends very much on the component.  For example, those same Asta components could not be opened in a synchronous manner from anything other than the main VCL thread.
So in short, I don't believe it is a limitation of TDataSet per se, but rather something that is implementation specific, and I don't have access to the components you've mentioned.


Question: How can I get a ASP.NET (inc MVC) application talking to a Flex UI over AMF.  I am wanting to push approx 100+ records around at a time and AMF would appear to be the way forward, but there doesn't appear to be anything obvious.

Answer:
If you're pressed for time, you can just use the RemoteObject to hit a compiled DLL  (like WebORB - its free for .NET, but you need a VS copy above Express to compile your classes that you want to expose to Flex)
and Retrieve the object that way...
Obviously your objects should have a DAL in place or be generated so you can communicate with your database.
But i suggest using Cairngorm for any data intensive Flex application. It isn't simple and development won't feel as fast, but once you understand it, things go alot smoother and it just feels right. I could go into the details, but there are people that are much smarter than I am that have already explained it, in depth. Someone like yourself should be able to grasp the concepts pretty quickly.
here are the links to learning WebORB and Cairngorm:
weborb :
http://www.themidnightcoders.com/weborb/
cairngorm :
http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm
learning Cairngorm :
http://www.adobe.com/devnet/flex/articles/cairngorm_pt1.html


Question:
I'm looking for a good 3D Mesh library

Should be able to read popular formats (OFF, OBJ...)

Should support both half-edge structure and a triangle soup

Should be tolerant to faults and illegal meshes.

Basic geometric operations - intersections, normal calculation, etc'

Most importantly - Should not be convoluted with endless template and inheritance hierarchies.

I've tried both CGAL and OpenMesh but both fail miserably in the last point.

Specifically CGAL which is impossible to follow even with the most advanced code analysis tools.

So far I'm seriously considering to pull my own.

My preference is C++ but I'm open to other options.

Answer:
May I ask why the last point is a requirement?
Libraries written for public consumption are designed to be as generic as possible so that it is usable by the widest possible audience.  In C++, this is often best done using templates.  It would suck tremendously if found a good library, only to discover it was useless for your purposes because it used floats instead of doubles.
CGAL, for example, appears to have adopted the well-known and well-tested STL paradigm of writing generic and extensible C++ libraries.  This does indeed make it difficult to follow with code analysis tools; I doubt they're much good at following STL headers either.
But are you trying to use the library or modify it?  Either way, they seem to have some extremely high-quality documentation (e.g.
Kernel Manual
) that should make it relatively simple to figure out what you need to do, without having to resort to reading their code.
Disclaimer:  I know this isn't what you're asking for.  But I don't think what you're looking for exists.  It is
extraordinarily
rare to find open source code with documentation as good as what I've seen scanning through CGAL.  I would strongly suggest that you take another look at it.


Question:
I'm using KVM to run a Windows virtual machine on my Linux box. Networking is accomplished through a tap device, hooked into a bridged Ethernet device, which allows the Windows VM to basically appear like a separate physical computer on my network. This is pretty nice.

However, my understanding is that most, if not all, wireless drivers can't support bridging. I'd really like to be able to roam a little more freely while I'm working -- does anyone know of an effective workaround?

User-mode networking won't work, as I have to use some Windows VPN software that wants lower-level networking access.

Answer:
I assume that you could configure your Windows guest to use the host as its default gateway, and set up NAT via the wireless interface on the host. So the signal flow would look like this:
Windows software opens connections to a host on the internets.
Windows routes the packet via the default gateway, i.e. the host Linux system.
Linux does NAT magic and routes the packet via its normal routing table (which should use a default gateway via the wireless interface).
I have never tried this in combination with bridging though.


Question: Does any know of a good calendar (not datepicker, but a BIG browsable calendar) plugin for one of the major javascript frameworks.  I'd prefer jQuery.

Answer:
You might want to send the guys at
jCalendar
a note. They were working on a Google Calendar-like jQuery plugin.  Project seems to have moved on, but they may be able to point you in the right direction.
From their site:
Coming soon will be v1.0, which will allow for not only visually selecting dates but also for displaying them in both mini and full page calendar views, similar to that of Google Calendar.


Question: How can I programmatically make a query in MS Access default to landscape when printed, specifically when viewing it as a PivotChart? I'm currently attempting this in MS Access 2003, but would like to see a solution for any version.

Answer:
The following function should do the trick:
```
```
Function SetLandscape()
   Application.Printer.Orientation = acPRORLandscape
End Function
```
```
Should be able to call this from the autoexec function to ensure it always runs.


Question:
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?

I have code that looks something like this:

class DownloadThread:
    def foo(self):
        pass

class DownloadManager():
    def __init__(self):
        dwld_threads = []
    def create_new_thread():
        dwld_threads.append(DownloadThread())

But now I'm wondering if there's a situation where nesting would be better. Something like:

class DownloadManager():
    class DownloadThread:
        def foo(self):
            pass
    def __init__(self):
        dwld_threads = []
    def create_new_thread():
        dwld_threads.append(DownloadManager.DownloadThread())

Answer:
You might want to do this when the "inner" class is a one-off, which will never be used outside the
definition
of the outer class. For example to use a metaclass, it's sometimes handy to do
```
```
class Foo(object):
    class __metaclass__(type):
        ....
```
```
instead of defining a metaclass separately, if you're only using it once.
The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together:
```
```
class Group(object):
    class cls1(object):
       ...

    class cls2(object):
       ...
```
```
Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.


Question: Is there an effective tool to convert C# code to Java code?

Answer:
They don't convert directly, but it allows for interoperability between .NET and J2EE.
http://www.mainsoft.com/products/index.aspx


Question: How do you use gen_udp in Erlang to do multicasting? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.

Answer:
Multicast is specified by IP Address
It's the same in erlang as for all languages.  The IP addresses 224.0.0.0 through 239.255.255.255 are multicast addresses.
Pick an address in that range, check that you're not overlapping an already assigned address, and you are good to go.
http://www.iana.org/assignments/multicast-addresses


Question:
In SQL Server 2005, a snapshot of a database can be created that allows read-only access to a database, even when the database is in "recovery pending" mode.   One use case for this capability is in creating a reporting database that references a copy of a production database, which is kept current through log-shipping.

In this scenario, how can I implement security on the "snapshot" database that is different from the "production" source database?

For example, in the production database, all access to data is through stored procedures, while in the snapshot database users are allowed to select from table in the database for reporting purposes.    The problem the I see is that security for the snapshot database is inherited from the source database, and can not be changed because snapshots are strictly read-only.

Answer:
Are you able to manage permissions on this database?  Would adding a separate user who only has read access to a database be sufficient for this type of scenario?  This could be a read-only user on the main database, but is only effectively used on the snapshot db.
i.e. Add a new user, readerMan5000 who is only given select access, to the database in question.  Then require users to authenticate through that new credential.
Note to future commenters, you may want to read:
http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/
or
http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx
before you open your big mouth like me. :)


Question:
ASP.NET 1.1 - I have a DataGrid on an ASPX page that is databound and displays a value within a textbox. The user is able to change this value, then click on a button where the code behind basically iterates through each DataGridItem in the grid, does a FindControl for the ID of the textbox then assigns the .Text value to a variable which is then used to update the database. The DataGrid is rebound with the new values.

The issue I'm having is that when assigning the .Text value to the variable, the value being retrieved is the original databound value and not the newly entered user value. Any ideas as to what may be causing this behaviour?

Code sample:

foreach(DataGridItem dgi in exGrid.Items)
{
    TextBox Text1 = (TextBox)dgi.FindControl("TextID");
    string exValue = Text1.Text; //This is retrieving the original bound value not the newly entered value
    // do stuff with the new value
}

Answer:
Are you able to manage permissions on this database?  Would adding a separate user who only has read access to a database be sufficient for this type of scenario?  This could be a read-only user on the main database, but is only effectively used on the snapshot db.
i.e. Add a new user, readerMan5000 who is only given select access, to the database in question.  Then require users to authenticate through that new credential.
Note to future commenters, you may want to read:
http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/
or
http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx
before you open your big mouth like me. :)


Question:
I have an image (mx) and i want to get the uint of the pixel that was clicked.

Any ideas?

Answer:
A few minutes on the
BitmapData LiveDoc Page
will take you where you need to go.  Once you have your image loaded into a Bitmap variable, you can access its BitmapData property.  Add a
Mouse Click Event
Listener to the image and then use
BitmapData::getPixel
.  The example for getPixel shows how to convert the uint response to an rgb hex code.
Here's a modification of the Example given on the BitmapData page that worked for me (using mxmlc - YMMV):
```
```
package {
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.net.URLRequest;

    public class BitmapDataExample extends Sprite {
        private var url:String = "santa-drunk1.jpg";
        private var size:uint = 200;
        private var image:Bitmap;

        public function BitmapDataExample() {
            configureAssets();
        }

        private function configureAssets():void {
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);

            var request:URLRequest = new URLRequest(url);
            loader.load(request);
            addChild(loader);
        }

        private function completeHandler(event:Event):void {
            var loader:Loader = Loader(event.target.loader);
            this.image = Bitmap(loader.content);

            this.addEventListener(MouseEvent.CLICK, this.clickListener);
        }

        private function clickListener(event:MouseEvent):void {
            var pixelValue:uint = this.image.bitmapData.getPixel(event.localX, event.localY)
            trace(pixelValue.toString(16));
        }
    }
}
```
```


Question: What is the difference between publishing a website with visual studio and just copying the files over to the server?  Is the only difference that the publish files are pre-compiled?

Answer:
I believe you are correct in your assumption. It has been my experience that the only difference is that published files are compiled.
Visual Studio® 2008 Web Deployment Projects
is a nice enhancement for customizing your build scripts for both your Websites and Web Applications.


Question:
I have an xslt sheet with some text similar to below:

<xsl:text>I am some text, and I want to be bold</xsl:text>

I would like some text to be bold, but this doesn't work.

<xsl:text>I am some text, and I want to be <strong>bold<strong></xsl:text>

The deprecated b tag doesn't work either. How do I format text within an xsl:text tag?

Answer:
Try this:
```
```
<fo:inline font-weight="bold"><xsl:text>Bold text</xsl:text></fo:inline>
```
```
XSL-FO Tutoria: Inline Text
Formatting
XSL-FO inline Object


Question:
More specifically I am trying to make the mailto component show within my template; the same way as an article does.

By default the mailto component opens in a new window. So far I changed the code so it opens on the same window, but that way the whole template is gone.

Any suggestions?

Answer:
I'm afraid I can't entirely follow your question - do you want to have a sign up form for membership or email notifications shown as an article? If so, then the easiest way is to install 'm2c' - the 'module to component' component. Then you can put any module (ie the sign up box) in the centre content area.
The m2c component can be found here:
http://joomla.focalizaisso.com.br/en/componentes/index.php


Question:
What is the single most effective practice to prevent arithmetic overflow and underflow?

Some examples that come to mind are:

testing based on valid input ranges

validation using formal methods

use of invariants

detection at runtime using language features or libraries (this does not prevent it)

Answer:
One possibility is to use a language that has arbitrarily sized integers that never overflow / underflow.
Otherwise, if this is something you're really concerned about, and if your language allows it, write a wrapper class that acts like an integer, but checks every operation for overflow.  You could even have it do the check on debug builds, and leave things optimized for release builds.  In a language like C++, you could do this, and it would behave almost exactly like an integer for release builds, but for debug builds you'd get full run-time checking.
```
```
class CheckedInt
{
private:
    int Value;

public:
    // Constructor
    CheckedInt(int src) : Value(src) {}

    // Conversions back to int
    operator int&() { return Value; }
    operator const int &() const { return Value; }

    // Operators
    CheckedInt operator+(CheckedInt rhs) const
    {
        if (rhs.Value < 0 && rhs.Value + Value > Value)
            throw OverflowException();
        if (rhs.Value > 0 && rhs.Value + Value < Value)
            throw OverflowException();
        return CheckedInt(rhs.Value + Value);
    }

    // Lots more operators...
};
```
```
Edit:
Turns out someone is
doing this already for C++
- the current implementation is focused for Visual Studio, but it looks like they're getting support for gcc as well.


Question:
I have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email.

It is working for me, except sometimes the rule fails and Outlook deactivates it.

Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day.

I would love to fix this once and for all.

Answer:
have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email. It is working for me, except sometimes the rule fails and Outlook deactivates it. Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day. I would love to fix this once and for all.
Here is the code stripped of the functionality, but giving you an idea of how it looks:
```
```
Public WithEvents myOlItems As Outlook.Items

   Public Sub Application_Startup()
       ' Reference the items in the Inbox. Because myOlItems is declared
       ' "WithEvents" the ItemAdd event will fire below.
       ' Set myOlItems = Outlook.Session.GetDefaultFolder(olFolderInbox).Items
       Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
   End Sub

   Private Sub myOlItems_ItemAdd(ByVal Item As Object)
       On Error Resume Next
       If TypeName(Item) = "MailItem" Then
           MyMessageHandler Item
       End If
   End Sub

   Public Sub MyMessageHandler(ByRef Item As MailItem)
       Dim strSender As String
       Dim strSubject As String

       If TypeName(Item) <> "MailItem" Then
           Exit Sub
       End If

       strSender = LCase(Item.SenderEmailAddress)
       strSubject = Item.Subject

       rem do stuff
       rem do stuff
       rem do stuff
   End Sub
```
```
One error I get is "Type Mismatch" calling MyMessageHandler where VB complains that Item is not a MailItem. Okay, but TypeName(Item) returns "MailItem", so how come Item is not a MailItem?
Another one I get is where an email with an empty subject comes along. The line
```
```
strSubject = Item.Subject
```
```
gives me an error. I know Item.Subject should be blank, but why is that an error?
Thanks.


Question:
I have the following HTML <select> element:

<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?

Answer:
You can use this function:
```
```
function selectElement(id, valueToSelect) {
    let element = document.getElementById(id);
    element.value = valueToSelect;
}

selectElement('leaveCode', '11');
```
```
```
```
<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>
```
```
Optionally if you want to trigger onchange event also, you can use :
```
```
element.dispatchEvent(new Event('change'))
```
```


Question:
I've written a control that inherits from the System.Web.UI.WebControls.DropDownList and so I don't have any code in front for this control, but I still want to set the OutputCache directive.  I there any way to set this in the C# code, say with an attribute or something like that?

I'm particularly hoping to be able to replicate the VaryByParam property

Answer:
```
```
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetValidUntilExpires(true);
```
```


Question:
I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic).

So for these records (id-parent_id pairs):

0-7 0-4 4-9 4-14 4-16 9-6

I have this tree:

0
├ 7
└ 4
  ├ 9
  | └ 6
  ├ 14
  └ 16

I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.

I'm confused... does this fits into the classical tree problems? or is it a graph one?

How can I compose this structure and solve this problem using php?

Answer:
This is the perfect chance to use recursion!
Pseudo-code:
```
```
nodeList = {}
enumerateNodes(rootNode, nodeList);

function enumerateNodes(node, nodeList) {
   nodeList += node;
   foreach ( childnode in node.children ) {
       enumerateNodes(childnode, nodeList);
   }
}
```
```
Edit: Didn't notice that your tree is in the adjacent list format. I would probably just build that into an actual tree datastructure before I started working with it. Just loop through all pairs (creating nodes the first time you see them) and linking them. I
think
it should be easy...


Question: Why does Leopard mangle some symbols with $non_lazy_ptr?  More importantly what is the best method to fix undefined symbol errors because a symbol has been mangled with $non_lazy_ptr?

Answer:
From:
Developer Connection - Indirect Addressing
Indirect addressing is the name of the code generation technique that allows symbols defined in one file to be referenced from another file, without requiring the referencing file to have explicit knowledge of the layout of the file that defines the symbol. Therefore, the defining file can be modified independently of the referencing file. Indirect addressing minimizes the number of locations that must be modified by the dynamic linker, which facilitates code sharing and improves performance.
When a file uses data that is defined in another file, it creates symbol references. A symbol reference identifies the file from which a symbol is imported and the referenced symbol. There are two types of symbol references: nonlazy and lazy.
Nonlazy symbol references are resolved (bound to their definitions) by the dynamic linker when a module is loaded.
A nonlazy symbol reference is essentially a symbol pointer—a pointer-sized piece of data. The compiler generates nonlazy symbol references for data symbols or function addresses.
Lazy symbol references are resolved by the dynamic linker the first time they are used (not at load time). Subsequent calls to the referenced symbol jump directly to the symbol’s definition.
Lazy symbol references are made up of a symbol pointer and a symbol stub, a small amount of code that directly dereferences and jumps through the symbol pointer. The compiler generates lazy symbol references when it encounters a call to a function defined in another file.


Question:
I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like:

SVN repository in: svn://myserver/path/to/svn/repos

Git repository in: git://myserver/path/to/git/repos

git-do-the-magic-svn-import-with-history \
svn://myserver/path/to/svn/repos \
git://myserver/path/to/git/repos

I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example.

Answer:
Magic:
```
```
$ git svn clone http://svn/repo/here/trunk
```
```
Git and SVN operate very differently.  You need to learn Git, and if you want to track changes from SVN upstream, you need to learn
```
git-svn
```
.  The
```
git-svn
```
main page has a good examples section
:
```
```
$ git svn --help
```
```


Question:
For example, if I have a page located in Views/Home/Index.aspx and a JavaScript file located in Views/Home/Index.js, how do you reference this on the aspx page?

The example below doesn't work even though the compiler says the path is correct

<script src="Index.js" type="text/javascript"></script>

The exact same issue has been posted here in more detail:
http://forums.asp.net/p/1319380/2619991.aspx

If this is not currently possible, will it be in the future? If not, how is everyone managing their javascript resources for large Asp.net MVC projects? Do you just create a folder structure in the Content folder that mirrors your View folder structure? YUCK!

Answer:
You can use the VirtualPathUtility.ToAbsolute method like below to convert the app relative url of the .js file to an absolute one that can be written to the page:
```
```
<script type="text/javascript" src="<%=VirtualPathUtility.ToAbsolute("~/Views/Home/Index.js") %>"></script>
```
```


Question: In your experience, how often should Oracle database statistics be run? Our team of developers recently discovered that statistics hadn't been run our production box in over 2 1/2 months. That sounds like a long time to me, but I'm not a DBA.

Answer:
Whenever the data changes "significantly".
If a table goes from 1 row to 200 rows, that's a significant change.  When a table goes from 100,000 rows to 150,000 rows, that's not a terribly significant change.  When a table goes from 1000 rows all with identical values in commonly-queried column X to 1000 rows with nearly unique values in column X, that's a significant change.
Statistics store information about item counts and relative frequencies -- things that will let it "guess" at how many rows will match a given criteria.  When it guesses wrong, the optimizer can pick a
very
suboptimal query plan.


Question: When working with tables in Oracle, how do you know when you are setting up a good index versus a bad index?

Answer:
Here's a great SQL Server article:
http://www.sql-server-performance.com/tips/optimizing_indexes_general_p1.aspx
Although the mechanics won't work on Oracle, the tips are very apropos (minus the thing on clustered indexes, which don't quite work the same way in Oracle).


Question:
What are the characteristics of a multitasking operating system?

What makes it multitasking?

Are there non-multitasking operating systems?

Answer:
A multi tasking operating systems is:
An operating system that gives you the perception of 2 or more tasks/jobs/processes running at the same time.  It does this by dividing system resources amongst these tasks/jobs/processes.  And switching between the tasks/jobs/processes while they are executing very fast over and over again.
Yes there are non multi tasking operating systems, example: commodore 64's OS (Commodore BASIC 2.0).  Probably some custom made software for some companies.  Perhaps like an ATM machine, or movie theater stub ticket system.


Question:
Can databases (MySQL in particular, any SQL--MS, Oracle, Postgres--in general) do mass updates, and figure out on their own what the new value should be? Say for example I've got a database with information about a bunch of computers, and all of these computers have drives of various sizes--anywhere from 20 to 250 GB. Then one day we upgrade every single computer by adding a 120 GB hard drive. Is there a way to say something like

update computers set total_disk_space = (whatever that row's current total_disk_space is plus 120)

Answer:
Yeah:
```
```
update computers set total_disk_space = total_disk_space + 120;
```
```


Question: The documentation with the module itself is pretty thin, and just tends to point to MOP.

Answer:
First you should read through the
Manual
if you haven't already. Then you can go on to read the
Cookbook
.
I think the docs are actually pretty good these days, as long as you read the right ones. You
really
shouldn't bother looking at most of the docs for any class name starting with "
```
Moose::Meta
```
" unless you're interested in Moose's introspection features. I've tried to make this more obvious in the Moose.pm docs, which as of 0.57 tell you to read the
Manual
and
Cookbook
first.
If you're coming from a background of doing Perl 5 OO "the old school way", I'd also suggest taking a look at the
```
Moose::Manual::Unsweetened
```
document, which compares Moose to equivalent Perl 5 "by hand" code.


Question:
I have a method that can return either a single object or a collection of objects. I want to be able to run object.collect on the result of that method whether or not it is a single object or a collection already. How can i do this?

profiles = ProfileResource.search(params)
output = profiles.collect do | profile |
    profile.to_hash
end

If profiles is a single object, I get a NoMethodError exception when I try to execute collect on that object.

Answer:
```
```
profiles = [ProfileResource.search(params)].flatten
output = profiles.collect do |profile|
    profile.to_hash
end
```
```


Question:
In a multitasking operating system context, sometimes you hear the term round-robin scheduling. What does it refer to?

What other kind of scheduling is there?

Answer:
Round Robin Scheduling
If you are a host in a party of 100 guests, round-robin scheduling would mean that you spend 1 minute (a fixed amount) per guest. You go through each guest one-by-one, and after 100 minutes, you would have spent 1 minute with each guest. More on
Wikipedia
.
There are many other types of scheduling, such as priority-based (i.e. most important people first), first-come-first-serve, earliest-deadline-first (i.e. person leaving earliest first), etc. You can start off by googling for scheduling algorithms or check out
scheduling at Wikipedia


Question:
What, at a minimum, should an application health-monitoring system do for you (the developer) and/or your boss (the IT Manager) and/or the operations (on-call) staff?

What else should it do above the minimum requirements?

Is monitoring the 'infrastructure' applications (ms-exchange, apache, etc.) sufficient or do individual user applications, web sites, and databases also need to be monitored?

if the latter, what do you need to know about them?

ADDENDUM: thanks for the input, i was really looking for application-level monitoring not infrastructure monitoring, but it is good to know about both

Answer:
Minimum: make sure it is running :)
However, some other stuff would be very useful. For example, the CPU load, RAM usage and (in multiuser systems) which user is running what. Also, for applications that access network, a list of network connections for each app. And (if you have access to client computer(s)) it would be cool to be able to see the 'window title' of the app - maybe check each 2-3 minutes  if it changed and save it. Also, a list of files open by the application could be very useful, but it is not a must.


Question:
I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute.

I've seen this gamedev article, and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working.

I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself.

Answer:
This is by no means an easy problem. I'll try to give you an overview only.
What you could do is something like the following:
Compute the average (root-mean-square) loudness of the signal over blocks of, say, 5 milliseconds. (Having never done this before, I don't know what a good block size would be.)
Take the Fourier transform of the "blocked" signal, using the FFT algorithm.
Find the component in the transformed signal that has the largest magnitude.
A Fourier transform is basically a way of computing the strength of all frequencies present in the signal. If you do that over the "blocked" signal, the frequency of the beat will hopefully be the strongest one.
Maybe you need to apply a filter first, to focus on specific frequencies (like the bass) that usually contain the most information about the BPM.


Question:
I have a div with two images and an h1. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be absolute positioned within the div.

What is the CSS needed for this to work on all common browsers?

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</div>

Answer:
```
```
<div id="header" style="display: table-cell; vertical-align:middle;">
```
```
...
or CSS
```
```
.someClass
{
   display: table-cell;
   vertical-align:middle;
}
```
```
Browser Coverage


Question:
(sorry I should have been clearer with the code the first time I posted this. Hope this makes sense)

File "size_specification.rb"

class SizeSpecification
  def fits?
  end
end

File "some_module.rb"

require 'size_specification'

module SomeModule
  def self.sizes
    YAML.load_file(File.dirname(__FILE__) + '/size_specification_data.yml')
  end
end

File "size_specification_data.yml

---
- !ruby/object:SizeSpecification
  height: 250
  width: 300

Then when I call

SomeModule.sizes.first.fits?

I get an exception because "sizes" are Object's not SizeSpecification's so they don't have a "fits" function.

Answer:
On second reading I'm a little confused, you seem to want to mix the class into module, which is porbably not so advisable.  Also is the YAML supposed to load an array of the SizeSpecifications?
It appears to be that you're not mixing the Module into your class.  If I run the test in irb then the require throws a LoadError. So I assume you've put two files together, if not dump it.
Normally you'd write the functionality in the module, then mix that into the class.  so you may modify your code like this:
```
```
class SizeSpecification
  include SomeModule
  def fits?
  end
end
```
```
Which will allow you to then say:
```
```
SizeSpecification::SomeModule.sizes
```
```
I think you should also be able to say:
```
```
SizeSpecification.sizes
```
```
However that requires you to take the self off the prefix of the sizes method definition.
Does that help?


Question: What is the best method to transfer data from sales table to sales history table in sql server 2005. sales history table will be used for reporting.

Answer:
Bulkcopy is fast and it will not use the transaction log. One batch run at the end of the day.
Deleting the copied records from your production server is a different situation that needs to be planed on that server's maintenance approach/plans. Your reporting server solution should not interfere with or affect the production server.
Keep in mind that your reporting server is not meant to be a backup of the data but rather a copy made exclusively for reporting purposes.
Also check on the server settings of your reporting server to be on
Simple recovery model
.


Question: I've set up Passenger in development (Mac OS X) and it works flawlessly. The only problem came later: now I have a custom GEM_HOME path and ImageMagick binaries installed in "/usr/local". I can put them in one of the shell rc files that get sourced and this solves the environment variables for processes spawned from the console; but what about Passenger? The same application cannot find my gems when run this way.

Answer:
I've run into this issue as well.  It
appears
that Passenger doesn't passthrough values set using the
```
SetEnv
```
apache directive - which is unfortunate.
Perhaps it might be possible to set environment variables in your environment.rb or boot.rb (assuming you're talking about a Rails app; I'm not familiar with Rack but presumably it has similar functionality)


Question:
I'm trying to replace some bespoke message queues with ActiveMQ, and I need to talk to them (a lot) from Perl.  ActiveMQ provides a Stomp interface and Perl has Net::Stomp, so this seems like it should be fine, but it's not.

Even if I send a BEGIN command over Stomp, messages sent with SEND are immediately published, and if I ABORT the transaction, nothing happens.

I can't find any clear answers suggesting that suggest it's not possible, that is is possible, or that there's a relevant bit of configuration.  Also, Stomp doesn't seem to be a great protocol for checking for error responses from the server.

Am I out of luck?

Answer:
BTW the best place to ask Perl/ActiveMQ/Stomp questions is the
ActiveMQ user forum
as lots of Perl-Stomp folks hang out there.
The trick with STOMP transactions is to make sure each message you send or each acknowledgement you make includes the transaction ID header. See the
transaction handling section of the STOMP protocol
.
The reason for this is that with STOMP you could have many transactions taking place at the same time if your client is multi threaded - along with some non-transacted operations.


Question: I want to use Apple's or RedHat's built-in Apache but I want to use Perl 5.10 and mod_perl.  What's the least intrusive way to accomplish this?  I want the advantage of free security patching for the vendor's Apache, dav, php, etc., but I care a lot about which version of Perl I use and what's in my @INC path.  I don't mind compiling my own mod_perl.

Answer:
You'll want to look into
mod_so


Question:
I have determined that my JSON, coming from the server, is valid (making the ajax call manually), but I would really like to use JQuery. I have also determined that the "post" URL, being sent to the server, is correct, using firebug. However, the error callback is still being triggered (parse error). I also tried datatype: text.

Are there other options that I should include?

$(function() {
    $("#submit").bind("click", function() {
        $.ajax({
            type: "post",
            url: "http://myServer/cgi-bin/broker" ,
            datatype: "json",
            data: {'start' : start,'end' : end},
            error: function(request,error){
                alert(error);
            },
            success: function(request) {
                alert(request.length);
            }
        }); // End ajax
    }); // End bind
}); // End eventlistener

Answer:
Here are a few suggestions I would try:
1) the 'datatype' option you have specified should be 'dataType' (case-sensitive I believe)
2) try using the 'contentType' option as so:
```
```
contentType: "application/json; charset=utf-8"
```
```
I'm not sure how much that will help as it's used in the request to your post url, not in the response.
See this article for more info:
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax
(It's written for asp.net, but may be applicable)
3) Triple check the output of your post url and run the output through a JSON validator just to be absolutely sure it's valid and can be parsed into a JSON object.
http://www.jsonlint.com
Hope some of this helps!


Question:
I'm considering Altova MapForce (or something similar) to produce either XSLT and/or a Java or C# class to do the translation. Today, we pull data right out of the database and manually build an XML string that we post to a webservice.

Should it be db -> (internal)XML -> XSLT -> (External)XML? What do you folks do out there in the wide world?

Answer:
I would use one of the out-of-the-box XML serialization classes to do your internal XML generation, and then use XSLT to transform to the external XML.  You might generate a schema as well to enforce that the translation code (whatever will drive your XSLT translation) continues to get the XML it is expecting for translation in case of changes to the object breaks things.
There are a number of XSLT editors on the market that will help you do the mappings, but I prefer to just use a regular XML editor.


Question: I am writing a web application that requires user interaction via email.  I'm curious if there is a best practice or recommended source for learning about processing email.  I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing.  I'm also looking for guidance on processing bouncebacks.

Answer:
There are some pretty serious concerns here for how to send email automatically, and here are a few:
Use an email library. Python includes one called 'email'. This is your friend, it will stop you from doing anything tragically wrong. Read an example from
the Python Manual
.
Some points that will stop you from getting blocked by spam filters:
Always send from a valid email address. You must be able to send email to this address and have it received (it can go into /dev/null after it's received, but it must be possible to /deliver/ there). This will stop spam filters that do Sender Address Verification from blocking your mail.
The email address you send from on the server.sendmail(fromaddr, [toaddr]) line will be where bounces go. The From: line in the email is a totally different address, and that's where mail will go when the user hits 'Reply:'. Use this to your advantage, bounces can go to one place, while reply goes to another.
Send email to a local mail server, I recommend postfix. This local server will receive your mail and be responsible for sending it to your upstream server. Once it has been delivered to the local server, treat it as 'sent' from a programmatic point of view.
If you have a site that is on a static ip in a datacenter of good reputation, don't be afraid to simply relay the mail directly to the internet. If you're in a datacenter full of script kiddies and spammers, you will need to relay this mail via a public MTA of good reputation, hopefully you will be able to work this out without a hassle.
Don't send an email in only HTML. Always send it in Plain and HTML, or just Plain. Be nice, I use a text only email client, and you don't want to annoy me.
Verify that you're not running SPF on your email domain, or get it configured to allow your server to send the mail. Do this by doing a TXT lookup on your domain.
```
```
$ dig google.com txt
...snip...
;; ANSWER SECTION:
google.com.     300 IN  TXT "v=spf1 include:_netblocks.google.com ~all"
```
```
As you can see from that result, there's an SPF record there. If you don't have SPF, there won't be a TXT record. Read more about
SPF on wikipedia
.
Hope that helps.


Question:
I have a two tables joined with a join table - this is just pseudo code:

Library
Book
LibraryBooks

What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.

So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?

I was thinking:

l = Library.find(1)
allLibraries = l.books.libraries

But that doesn't seem to work. Suggestions?

Answer:
Perhaps:
```
```
l.books.map {|b| b.libraries}
```
```
or
```
```
l.books.map {|b| b.libraries}.flatten.uniq
```
```
if you want it all in a flat array.
Of course, you should really define this as a method on Library, so as to uphold the noble cause of encapsulation.


Question: How do you get all the classes in a namespace through reflection in C#?

Answer:
```
```
using System.Reflection;
using System.Collections.Generic;
//...

static List<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();

    List<string> namespacelist = new List<string>();
    List<string> classlist = new List<string>();

    foreach (Type type in asm.GetTypes())
    {
        if (type.Namespace == nameSpace)
            namespacelist.Add(type.Name);
    }

    foreach (string classname in namespacelist)
        classlist.Add(classname);

    return classlist;
}
```
```
NB: The above code illustrates what's going on.  Were you to implement it, a simplified version can be used:
```
```
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...

static IEnumerable<string> GetClasses(string nameSpace)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    return asm.GetTypes()
        .Where(type => type.Namespace == nameSpace)
        .Select(type => type.Name);
}
```
```


Question:
In the vxWorks RTOS, there is a shell that allows you to issue command to your embedded system.

The documentation refers to kernel shell, host shell and target shell. What is the difference between the three?

Answer:
The target shell and kernel shell are the same.  They refer to a shell that runs on the target. You can connect to the shell using either a serial port, or a telnet session.
A task runs on the target and parses all the commands received and acts on them, outputting data back to the port.
The host shell is a process that runs on the development station. It communicates with the debug agent on the target.  All the commands are actually parsed on the host and only simplified requests are sent to the target agent:
Read/Write Memory
Set/Remove Breakpoints
Create/Delete/Suspend/Resume Tasks
Invoke a function
This results in less real-time impact to the target.
Both shells allow the user to perform low level debugging (dissassembly, breakpoints, etc..) and invoke functions on the target.


Question:
This is my first real question of need for any of those Gridview experts out there in the .NET world.

I an creating a Gridview from codebehind and I am holding a bunch of numerical data in the columns.  Although, I do add the comma in the number fields from codebehind.  When I load it to the Gridview, I have the sorting ability turned on, BUT the gridview chooses to ALPHA sort rather than sorting numerically because I add in those commas.

So I need help.  Anyone willing to give this one a shot?  I need to change some of my columns in the gridview to numerical sort rather than the alpha sort it is using.

Answer:
If you do end up implementing your own comparer and sorting them as strings, the algorithm for treating numbers 'properly' is called Natural Sorting. Jeff wrote a pretty good entry on it here:
Sorting for Humans : Natural Sort Order
You can find a pretty good implementation in C# here:
http://www.codeproject.com/KB/string/NaturalSortComparer.aspx


Question:
This question may be too product specifc but I'd like to know if anyone is exporting bug track data from HP Quality Center.

HP Quality Center (QC) has an old school COM API but I'd rather use a web service or maybe even screen scraper to export the data into an excel spreadsheet.

In any case, what's the best way to export bug tracking data from hosted HP Quality Center?

Answer:
You can use this QC API Code to modify bugs/requirements.
```
```
TDAPIOLELib.TDConnection connection = new TDAPIOLELib.TDConnection();
connection.InitConnectionEx("http://SERVER:8080/qcbin");
connection.Login("USERNAME", "PASSWORD");
connection.Connect("QCDOMAIN", "QCPROJECT");
TDAPIOLELib.BugFactory bugFactory = connection.BugFactory as TDAPIOLELib.BugFactory;
TDAPIOLELib.List bugList = bugFactory.NewList("");
foreach (TDAPIOLELib.Bug bug in bugList)
{
  // View / Modify the properties
  // bug.ID, bug.Name, etc.
  // Save them when done
  // bug.Post();
}
```
```


Question: We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available.

Answer: According to the DirectX 9.0 SDK (summer 2004) documentation, see the GetDXVer SDK sample at \Samples\Multimedia\DXMisc\GetDXVer.


Question:
I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day.

For example, if Alice worked a job from 15:30 to 19:30 and Bob worked from 12:15 to 17:00, the chart would look like this:

I have a WTFey solution right now that involves a spreadsheet going out to column DY or something like that. The needed resolution is 15-minute intervals.

I'm assuming this is something best done in the database then exported for chart creation. Let me know if I'm missing any details. Thanks.

Answer:
I came up with a pseudocode solution, hope it helps.
```
```
create an array named timetable with 24 entries
initialise timetable to zero

for each user in SQLtable
  firsthour = user.firsthour
  lasthour = user.lasthour

  firstminutes = 4 - (rounded down integer(user.firstminutes/15))
  lastminutes = rounded down integer(user.lastminutes/15)

  timetable(firsthour) = timetable(firsthour) + firstminutes
  timetable(lasthour) = timetable(lasthour) + lastminutes

  for index=firsthour+1 to lasthour-1
    timetable(index) = timetable(index) + 4
  next index

next user
```
```
Now the timetable array holds the values you desire in 15 minute granularity, ie. a value of 4 = 1 hour, 5 = 1 hour 15 minutes, 14 = 3 hours 30 minutes.


Question:
How do I convert a datetime string in local time to a string in UTC time?

I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.

Clarification:  For example, if I have 2008-09-17 14:02:00 in my local timezone (+10), I'd like to generate a string with the equivalent UTC time: 2008-09-17 04:02:00.

Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.

Answer:
```
```
def local_to_utc(t):
    secs = time.mktime(t)
    return time.gmtime(secs)

def utc_to_local(t):
    secs = calendar.timegm(t)
    return time.localtime(secs)
```
```
Source:
http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html
Example usage from
bd808
: If your source is a
```
datetime.datetime
```
object
```
t
```
, call as:
```
```
local_to_utc(t.timetuple())
```
```


Question:
The situation is this:

You have a Hibernate context with an
object graph that has some lazy
loading defined.

You want to use
the Hibernate objects in your UI as
is without having to copy the data
somewhere.

There are different UI
contexts that require different
amounts of data.

The data is too
big to just eager load the whole
graph each time.

What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?

Any help.

Answer:
Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orders.
Then I would define a Repository with a fluent interface that will allow me to say something like :
```
```
new ClientRepo().LoadClientBy(id)
                .WithOrders()
                .WithBonus()
                .OrderByName();
```
```
And there you have the client with everything you need. It's preferably that you know in advance what you will need for the current operation. This way you can avoid unwanted trips to the database.(new devs in your team will usually do this - call a property and not be aware of the fact that it's actually a call to the DB)


Question: Since the Google App Engine Datastore is based on Bigtable and we know that's not a relational database, how do you design a database schema/data model for applications that use this type of database system?

Answer:
As GAE builds on how data is managed in Django there is a lot of info on how to address similar questions in the Django documentation (for example see
here
, scroll down to 'Your first model').
In short you design you db model as a regular object model and let GAE sort out all of the object-relational mappings.


Question:
We have two tasks (T1 and T2) in our vxWorks embedded system that have the same priority (110).

How does the regular vxWorks scheduler deal with this if both tasks are ready to run?

Which task executes first?

Answer:
The task that will run first is the task that is spawned first as realized by the VxWorks scheduler task. VxWorks uses
priority-based scheduling
by default. So in your case, since T1 and T2 have the same priority, whichever one gets the CPU first will continue to run indefinitely until it is explicitly blocked (using
taskSuspend
or
taskDelay
), at which time the other READY task will execute until it is blocked, and so on. This ought to be controlled by semaphores or mutexes (mutices?)
The main problem with priority-based scheduling is illuminated by this exact problem. How do we determine how long to let these tasks run? The fact that they have the same priority complicates things. Another concern is that VxWorks tasks that have high priority (lower number means higher priority) can preempt your application which you must be prepared for in your code. These problems can be solved by using
round-robin scheduling
. The additional problems posed by round-robin scheduling and the solutions are all described
here
.


Question:
What are the stack and heap?

Where are they located physically in a computer's memory?

To what extent are they controlled by the OS or language run-time?

What is their scope?

What determines their sizes?

What makes one faster?

Answer:
Stack:
Stored in computer RAM just like the heap.
Variables created on the stack will go out of scope and are automatically deallocated.
Much faster to allocate in comparison to variables on the heap.
Implemented with an actual stack data structure.
Stores local data, return addresses, used for parameter passing.
Can have a stack overflow when too much of the stack is used (mostly from infinite or too deep recursion, very large allocations).
Data created on the stack can be used without pointers.
You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.
Usually has a maximum size already determined when your program starts.
Heap:
Stored in computer RAM just like the stack.
In C++, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with
```
delete
```
,
```
delete[]
```
, or
```
free
```
.
Slower to allocate in comparison to variables on the stack.
Used on demand to allocate a block of data for use by the program.
Can have fragmentation when there are a lot of allocations and deallocations.
In C++ or C, data created on the heap will be pointed to by pointers and allocated with
```
new
```
or
```
malloc
```
respectively.
Can have allocation failures if too big of a buffer is requested to be allocated.
You would use the heap if you don't know exactly how much data you will need at run time or if you need to allocate a lot of data.
Responsible for memory leaks.
Example:
```
```
int foo()
{
  char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
  bool b = true; // Allocated on the stack.
  if(b)
  {
    //Create 500 bytes on the stack
    char buffer[500];

    //Create 500 bytes on the heap
    pBuffer = new char[500];

   }//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete[] pBuffer;
```
```


Question: I want to run text through a filter to ensure it is all UTF-8 encoded.  What is the recommended way to do this with PHP?

Answer:
Your question is unclear, are you trying to encode something?  If so
utf8_encode
is your friend.  Are you trying to determine if it doesn't need to be encoded?  If so,
utf8_encode
is still your friend, because you can check that the result is the same as the input!


Question:
I'm sure there were several, but the one I was thinking of would display a nice text screen when you crashed the computer thoroughly.

The Text was "Well smoke me a kipper."

Answer:
No one else has answered this, so I'll answer the part I can: the original Macintosh debugger was
MacsBug
.
So far as the kipper quote goes, the only thing that comes to mind is the
Pathogen
computer virus.