Question:
Would this be right??

Black Box

1.1 Functional

    1.1.1 Equivalence
    1.1.2 BVA
    1.1.3 Use case
    1.1.4 Regression
    1.1.5 UAT

1.2 Non Functional

    1.2.1 Testing the System Design

White box

2.1. Functional

       2.1.1 Unit
       2.1.2 Integration
       2.1.3 System

Do the above fall under the right categories?

The reason I ask this is because as a part of a report I was trying to come up with a good reference that categorised Test Techniques well. This is what my analysis and research from various sources gave me. And I hope this is helpful for someone else who might be doing the same research, but if its incorrect it should be updated.

Answer:
You might also consider the case when several programs depending one on another are developed simultaneously. You have then to take into account the
applicative architecture
which groups all those applications into several
functional domains
So, for instance, a financial application having to process a large number of data would be
one
functional domain, in which you would have to develop a:
dispatcher module in order to process those data on several computers
GUI in order to see what is going on
launcher in order to initiate the right connections retrieve the correct data and format them
and so on
But that would only be
one
functional domain, as others would have to be developed in order to
exploit the results
of your programs (for instance, a "referential domain" would be there to store those results into various databases, and offer a communication bus for other programs to access them: that would be a second functional domain).
So I would add to your tests the following categories:
Assembly testing
: when you test within your own functional domain (on an assembly server when you deploy the different applications of your domain, with a set of testing data)
Integration testing
: when you test
all the applications from all the functional domains
, which is also called
front-to-end testing
.
Note: "integration testing" is not the same as "continuous integration testing", which basically can process the black and white tests you describe, for
one
program, on a very regular basis.
The tests I am referring to are executed a few times a week by an:
"
Project Operational Architecture
" team of your domain for assembly tests: usually some developers of your team which set up an assembly server, check if the data are up-to-date and deploy the various program you are in charge to develop.
"
Production Operational Architectural
" team, in charge of setting a "production-like" environment and who is the only one able to really
test
the all chain of application from font to back.
Note: an "Operation Architecture" team has the role to "make operational an execution environment", meaning to have:
the right logistic team contacts in order to have the right servers and networks,
the right application teams contacts in order to know about the various start/stop application processes and deployment procedures of
all
the application of your system!
In short: your categories are for
one program
, but when you are developing an IS (Information System), you are forced to acknowledge the fact that you are not talking about "
one
exe developed by
one
team deployed on
one
production machine"... and then, welcome to an all new world of testing ;)


Question:
I have the following character string:

"..1....10..20....30...40....50...80..."

and I need to extract all numbers from it into array.

What is the best way to do it in C?

Answer:
Perhaps the easiest way is to use the
```
strtok()
```
function (or
```
strtok_r()
```
if reentrancy is a concern):
```
```
char str[] = "..1...10...20";
char *p = strtok(str, ".");
while (p != NULL) {
    printf("%d\n", atoi(p));
    p = strtok(NULL, ".");
}
```
```
Once you have the results of calling
```
atoi()
```
, it should be a simple matter to save those integers into an array.


Question:
After having looked at each of these two projects, it seems that both are VERY similar. Both run on top of the CLI, both have python style syntax, both use .NET instead of the standard python libraries.

So, what are the differences between them and advantages of each?

Answer:
The main difference as I see it is that Boo is statically typed, meaning the type of a variable is inferred on its first assignment and is fixed from there - while IronPython has the "real" dynamic behaviour of normal Python code.
IronPython
is officially maintained by Microsoft now and
targets the new Dynamic Language Runtime in version 2.0. I suspect because of it's statically typed nature Boo might be faster. I don't have much "real" experience with that though ...
IronPython also reimplements lots of the python standard library so you can run lots of python software without change on IronPython (e.g.
Django
).


Question:
I'm trying to write a simple game/utility to calculate poker odds.  I know there's plenty of resources that talk about the formulas to do so, but I guess I'm having trouble translating that to code.  Particularly, I'm interested in Texas Hold-em ...

I understand that there are several different approaches, one being that you can calculate the odds that you will draw some hand based on the cards you can see.  The other approach is calculating the odds that you will win a certain hand.  The second approach seems much more complex as you'd have to enter more data (how many players, etc.)

I'm not asking that you write it for me, but some nudges in the right direction would help :-)

Answer:
Here are some links to articles, which could help as starting points:
Poker Logic in C#
and
Fast, Texas Holdem Hand Evaluation and Analysis
"This code snippet will let you calculate poker probabilities the hard way, using C# and .NET."
The theoretical fundamentals are given in this
Wikipedia article about Poker Probabilities
and in this excellent
statistical tutorial
.
An example of a complete project written in Objective-C, Java, C/C++ or Python is found at
SpecialKEval
. Further links and reading can be found therein.


Question:
I am a little confused by the multitude of ways in which you can import modules in Python.

import X
import X as Y
from A import B

I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why.  Should imports happen at a module level or a method/function level?  In the __init__.py or in the module code itself?

My question is not really answered by "Python packages - import by class, not file" although it is obviously related.

Answer:
I would normally use
```
import X
```
on module level. If you only need a single object from a module, use
```
from X import Y
```
.
Only use
```
import X as Y
```
in case you're otherwise confronted with a name clash.
I only use imports on function level to import stuff I need when the module is used as the main module, like:
```
```
def main():
  import sys
  if len(sys.argv) > 1:
     pass
```
```
HTH


Question: What is the difference between the CIL instructions "Call" and "Callvirt"?

Answer:
```
call
```
is for calling non-virtual, static, or superclass methods, i.e., the target of the call is not subject to overriding.
```
callvirt
```
is for calling virtual methods (so that if
```
this
```
is a subclass that overrides the method, the subclass version is called instead).


Question: How flexible should a programmer be if a client requests requirements that is not in the project scope?

Answer:
This question cannot be given a blanket answer. It depends project to project.
Examples:
Client has money to burn, long timeline, no other projects on the go, I am very flexible.
Client is tight with $$, short timeline, other projects on the go, I am hardly flexible at all.
Other factors come into play as well, such as the process that has been chosen for the project. For example, you will be more flexible in an agile process, less flexible in a waterfall approach.


Question:
Through some bungling in creating and removing publications, I was left with a lot of obsolete publications which for some reason still remains in the Replication Monitor.

How do you remove these publications? It doesn't seem to have a clear way to remove them.

Answer:
This is an old question of mine, but then again at least I found a way to resolve it.
I was able to remove the publications is by creating a new publication with the same name, then delete the publication again. This time the publication will no longer appear in the Replication Monitor. I did not remember if the publication has to be the same type as the obsoleted one, but it works.
UPDATE:
Okay, the publication type and database name is important, otherwise the newly created publication will be considered as a different publication. Kinda obvious, but now I'm sure of it.


Question:
Say I've got a string which contains a number. I want to check if this number is an integer.

Examples

IsInteger("sss") => false

IsInteger("123") => true

IsInterger("123.45") =>false

Answer:
You can use int.
TryParse
. It will return a bool if it can parse the string and set your out parameter to the value
```
```
int val;
if(int.TryParse(inputString, out val))
{
    //dosomething
}
```
```


Question:
I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to

enable "save" button only when something has changed

alert if the user wants to close the page and something is not saved

Ideas?

Answer:
Loop through all the input elements, and put an
```
onchange
```
handler on each. When that fires, set a flag which lets you know the form has changed. A basic version of that would be very easy to set up, but wouldn't be smart enough to recognize if someone changed an input from "a" to "b" and then back to "a". If it were important to catch that case, then it'd still be possible, but would take a bit more work.
Here's a basic example in jQuery:
```
```
$("#myForm")
    .on("input", function() {
        // do whatever you need to do when something's changed.
        // perhaps set up an onExit function on the window
        $('#saveButton').show();
    })
;
```
```


Question:
I am writing a script that powers on a system via network.  And then i need to run a few commands on the other host. How do I know whether the system has powered on?

My programming language is Perl and the target host is RHEL5.

Is there any kernel interrupt or network boot information that indicates the system has powered on and the os has loaded?

[In a different scenario] I was also wondering just in case if i just switch on my Machine manually. when is it exactly said to have powered on. and when is the OS is supposed to have booted completely for a network related operation such as executing a network command there. What if the system is on DHCP how would a remote system then search for this machine [i guess it is possible via mac address. but if i am wrong ].

If I have missed out any info please feel free to ask me. If you have any suggestions to make the task easier please surface them :)

thanx
imkin

Answer:
Well, I'd say the system is booted when it can perform the request you've made of it.  That is, the sshd daemon is running.  That's booted sufficiently for your purposes (I assume - substitute for whatever daemon you really need).
So, I'd send the power-on signal, and check back every 15-30 seconds to see if I could connect.  If I've failed to connect within whatever is a reasonable time for that machine (2 minutes or 5 minutes or whatever), then I'd send an alert to the IT support team.  Well, I'd send it to myself first, and only once I've investigated a few failures or so and found them to all be legitimate would I start sending it directly to IT.
DHCP is kind of a different question.  You'd have to start learning about broadcasting, or having a daemon on that machine "call home" during boot to register its current IP address.  And it would have to "call home" every time a DHCP renewal changed its IP address.  This is decidedly more convoluted.  Try to avoid DHCP on such server machines if at all possible.


Question:
At the team with which I work, we have an old codebase using PHP's ibase_* functions all over the code to communicate with database. We created a wrapper to it that would do something else beside just calling the original function and I did a mass search-replace in the entire code to make sure that wrapper is used instead.

Now, how do we prevent usage of ibase_* functions in the future?

Preferably, I'd like to still have them available, but make it throw a NOTICE or WARNING when it is used.

A solution in pure PHP (not needing to compile a custom version of PHP) is preferred.

Answer:
I haven't checked it by myself, but found this in my bookmarks:
http://wiki.php.net/rfc/e-user-deprecated-warning
Edit: Okay this doesn't work yet - so instead of E_USER_DEPRECATED just use something like E_USER_NOTICE:
```
```
<?php
class Foo
{
    public function __construct()
    {
        trigger_error('Use Bar instead', E_USER_NOTICE);
    }
}

$foo = new Foo()
```
```
This will end up with this:
```
```
Notice: Use Bar instead in /home/unexist/projects/ingame/svn/foo.php on line 6
```
```


Question: From my small amount of experience, I've only used Ant as a build tool. Are there any other projects which are better, and why?

Answer:
Maven
It is much better than ant because for most common tasks you don't have to write a complicated build.xml, maven has very good defaults and it's all convention over configuration.
It has also a big central repository of libraries and it's very easy to configure it to, like, "use latest stable commons-whatever". Maven will then download the latest stable version for you (no more checking in jars into VCS) and if a new upstream stable version is released, it will download it as well. Of course, it's just as easy to lock it to some specific version should you need that.
It is also well integrated both with Netbeans and Eclipse (m2eclipse plugin) so the IDE honors whatever settings (including dependencies) you declare in the pom.xml file.
There are also some downsides to maven: some plugins are rather poorly documented, integration with both IDEs is not really perfect, and that in different ways, some error messages may be hard to understand.


Question:
How to check reliably if a SoundChannel is still playing a sound?

For example,

[Embed(source="song.mp3")]
var Song: Class;

var s: Song = new Song();
var ch: SoundChannel = s.play();

// how to check if ch is playing?

Answer:
I've done a little research and I can't find a way to query any object to determine if a sound is playing. You'll have to write a wrapper class and manage it yourself it seems.
```
```
package
{
    import flash.events.Event;
    import flash.media.Sound;
    import flash.media.SoundChannel;

    public class SoundPlayer
    {
        [Embed(source="song.mp3")]
        private var Song:Class;

        private var s:Song;
        private var ch:SoundChannel;
        private var isSoundPlaying:Boolean;

        public function SoundPlayer()
        {
            s = new Song();
            play();
        }

        public function play():void
        {
            if(!isPlaying)
            {
                ch = s.play();
                ch.addEventListener(
                    Event.SOUND_COMPLETE,
                    handleSoundComplete);
                isSoundPlaying = true;
            }
        }

        public function stop():void
        {
            if(isPlaying)
            {
                ch.stop();
                isSoundPlaying = false;
            }
        }

        private function handleSoundComplete(ev:Event):void
        {
            isSoundPlaying = false;
        }
    }
}
```
```


Question:
With the popularity of the Apple iPhone, the potential of the Microsoft Surface, and the sheer fluidity and innovation of the interfaces pioneered by Jeff Han of Perceptive Pixel ...

What are good examples of Graphical User Interfaces which have evolved beyond the

Windows, Icons, ( Mouse / Menu ), and Pointer paradigm ?

Answer:
Are you only interested in GUIs?  A lot of research has been done and continues to be done on
tangible interfaces
for example, which fall outside of that category (although they can include computer graphics).  The
User Interface Wikipedia
page might be a good place to start.  You might also want to explore the
ACM CHI Conference
.  I used to know some of the people who worked on zooming interfaces; the
Human Computer Interaction Lab an the University of Maryland
also has a bunch of links which you may find interesting.
Lastly I will point out that a lot of innovative user interface ideas work better in demos than they do in real use.  I bring that up because your example, as a couple of commenters have pointed out, might, if applied inappropriately, be tiring to use for any extended period of time.  Note that light pens were, for the most part, replaced by mice.  Good design sometimes goes against naive intuition (mine anyway).  There is a nice
rant
on this topic with regard to 3d graphics on
useit.com
.


Question:
I'm using:

FileInfo(
    System.Environment.GetFolderPath(
        System.Environment.SpecialFolder.ProgramFiles)
    + @"\MyInstalledApp"

In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I couldn't think of another method).

On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?

Answer:
One way would be to look for the "ProgramFiles(x86)" environment variable:
```
```
String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
```
```


Question:
I asked before about pixel-pushing, and have now managed to get far enough to get noise to show up on the screen. Here's how I init:

CGDataProviderRef provider;
bitmap = malloc(320*480*4);
provider = CGDataProviderCreateWithData(NULL, bitmap, 320*480*4, NULL);
CGColorSpaceRef colorSpaceRef;
colorSpaceRef = CGColorSpaceCreateDeviceRGB();
ir = CGImageCreate(
320,
480,
8,
32,
4 * 320,
colorSpaceRef,
kCGImageAlphaNoneSkipLast,
provider,
NULL,
NO,
kCGRenderingIntentDefault
);

Here's how I render each frame:

for (int i=0; i<320*480*4; i++) {
bitmap[i] = rand()%256;
}
CGRect rect = CGRectMake(0, 0, 320, 480);
CGContextDrawImage(context, rect, ir);

Problem is this is awfully awfully slow, around 5fps. I think my path to publish the buffer must be wrong. Is it even possible to do full-screen pixel-based graphics that I could update at 30fps, without using the 3D chip?

Answer:
I suspect doing 614400 (
```
320*480*4
```
) memory writes, random number generation and making a new object each frame is slowing you down.
Have you tried just writing a static bitmap to screen and seeing how fast that is? Have you perhaps tried profiling the code? Do you also need to make a new CGRect each time?
If you just want to give the effect of randomness, there is probably no need to regenerate the entire bitmap each time.


Question:
I have a 2 dimensional array, like so:

char[,] str = new char[2,50];

Now, after I've stored contents in both str[0] and str[1], how do I store it in a

string[] s = new string[2];

?

I tried

s[0] = str[0].ToString();

but that seems to be an error: VC# expects 'two' indices within the braces, which means I can convert only a character from the array. Is there a way to convert the entire str[0] to a string? Or is changing it to a jagged array the only solution?

Answer:
Assuming the dimensions are fixed as 2x50:
```
```
char[,] str = new char[2,50];

// populate str somehow

// chose which of the strings we want (the 'row' index)
int strIndex = 0;
// create a temporary array (faster and less wasteful than using a StringBuilder)
char[] chars = new chars[50];
for (int i = 0; i < 50; i++)
  chars[i] = str[strIndex, i];
string s = new string[chars];
```
```
This would be easier and more performant if you used a jagged array:
```
```
char[][] str = new char[2][];
```
```
Then you could write:
```
```
string s = new string(characters[0]);
```
```


Question:
I am currently working on a rather large multi tiered app that will be deployed overseas.  Although I hope it won't fall over or blow up once depolyed I can't be 100% sure of this.  Therefore it would be nice to know that I could request the log file, to work out exactly what went wrong and why.

So basically as the title suggests I would like to know when and what to log?  I would like to know this to ensure I have comprehensive log files that can be examined easily to determine what has happened if my app falls over.

Answer:
1 - Make a single log, with a standardized format. Doesn't matter much what it is, but ensure that ever entry has the same basic fields. Just calling "printf" probably won't cut it ( substitute System.err.println or whatever as appropriate )
2 - Allow for at least one field to be an arbitrary string... the developer will know better then you what needs to be there.
3 - Include a high resolution time-stamp on each entry. You will need it eventually, trust me.
4 - If possible, include the file and line number of the origin of the error. That's easy in C, and a bit of a pain in Java. But it's
incredibly
useful later on, especially when people start to cut+paste code, including the error messages.
5 - Ensure the log is at a place that any level of the code can use it.
6 - I've often used "Primary" and "Secondary" error tags, where "Primary" means "I'm the guy who detected there is a problem", and "Secondary" means "I called a function which reported an error". That makes it easy to find the source of the problem ( "Primary: file not found" ) and still report the meaning of the error ( "Secondary: can't load calibration table" ).
7 - Include some capability to log non-errors as well as errors.
The hardest part I find is when an error isn't necessarily an error. If you call a function with a file, and the file doesn't exists, is that an error that should be logged or not? Sometimes it's a critical failure, and sometimes it's expected. It's pretty much up to the API of the function; if the function has a way to return an error,  I will usually have it do that without logging; then it's the job of the higher level code to decide if it needs to report that error or if it is expected.


Question:
I have a domain class containing a couple of fields. I can access them from my .gsps. I want to add a method to the domain class, which I can call from the .gsps (this method is a kind of virtual field; it's data is not coming directly from the database).

How do I add the method and how can I then call it from the .gsps?

Answer:
To add a method, just write it out like you would any other regular method. It will be available on the object when you display it in your GSP.
```
```
def someMethod() {
  return "Hello."
}
```
```
Then in your GSP.
```
```
${myObject.someMethod()}
```
```


Question: I have an HTML page (say welcome.html) which contains an iframe to a page I have no control over (say app.html).  The user performs some actions using the app within the iframe and clicks submit.  Once they do this, they are taken to a new page (say thanks.jsp), which loads within the iframe.  Is there a way in which I can force thanks.jsp to load in the full frame and not the iframe once submit is clicked?  Remember, I have no control over the logic behind that Submit button or app.html.  I do however have control over welcome.html and thanks.jsp.  If possible, I would like to stick with HTML and/or JavaScript.  Thank you in advance.

Answer:
You probably want to use a framebuster, with a base target in case it fails.
First:
If
```
thanks.jsp
```
is requested via a post request - redirect so it you present the page as the response to a get request.
Then:
Include framebuster JavaScript:
```
```
<script type="text/javascript">
   if (self != top) { top.location.replace(location); }
</script>
```
```
Finally:
In case the user doesn't have JavaScript enabled, make sure they don't stay in the frame any longer then they have to:
```
```
<base target="_top">
```
```


Question: Given a heapdump or a running VM, how do I discover what the contents of the permanent generation is ? I know about 'jmap -permstat' but that's not available on Windows.

Answer:
you can use JConsole or jvisualvm.exe(with jdk 1.6 7) to find what is where. If you want to know how all of your objects are related to each other and tree of objects, then you might want to try Eclipse Memory Analyzer --
http://www.eclipse.org/mat/
.
IN summary, you will get want you want from "
http://www.eclipse.org/mat/
".
Good luck,


Question: How can i release the memory that I used for a variable (e.g. a long string) in C?

Answer:
Assuming that you allocated the memory dynamically (using
```
malloc
```
or another memory allocator) you free it using
```
free
```
. If the memory was statically allocated, you can't free it.


Question:
Hoping that someone has some info on how to parse a xfa file. I can parse csv or xml files just fine, but an xfa one has come along and I'm not familar with the format. Looks like tab delimited body with column metadata at the top.

Anyone dealt with these before or can give me a steer on how to parse them?

I use vb.net but the language of any solution isn't too relevant.

Much appreciated.

Answer:
Mmm, looks like nobody has a clue. The problem is that .xfa doesn't look like a "standard" extension: after all, anybody can create its own extension names, from .xyz to .something...
I looked around a bit, found, unsurprisingly (the 'x') an XML format with this extension, not much more.
Indicating where this kind of file come from, what kind of data it holds, might help. Or not.
You describe the file as being a simple TSV (tab separated values) with a header. It is quite trivial to parse, with a tokenizer or some regex, so I am not sure where you are stuck.


Question:
Everyone (at least everyone who uses a compiled language) has faced compilation errors but how many times do you get to actually crash the compiler?

I've had my fair share of "internal compiler errors" but most went away just by re-compiling. Do you have a (minimal) piece of code that crashes the compiler?

Answer: Yes, especially when it's an old or undermaintained compiler (GCC 2.95, Tendra in C++ mode). I don't keep the pieces of code around, though.


Question:
In visual C++, I can do things like this:

template <class T>
class A{
protected:
    T i;
};

template <class T>
class B : public A<T>{
    T geti() {return i;}
};

If I try to compile this in g++, I get an error.  I have to do this:

template <class T>
class B : public A<T>{
    T geti() {return A<T>::i;}
};

Am I not supposed to do the former in standard C++?  Or is something misconfigured with gcc that's giving me errors?

Answer:
This used to be allowed, but changed in
gcc 3.4
.
In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example,
```
```
template <typename T> struct B {
      int m;
      int n;
      int f ();
      int g ();
    };
    int n;
    int g ();
    template <typename T> struct C : B<T> {
      void h ()
      {
        m = 0; // error
        f ();  // error
        n = 0; // ::n is modified
        g ();  // ::g is called
      }
    };
```
```
You must make the names dependent, e.g. by prefixing them with this->. Here is the corrected definition of C::h,
```
```
template <typename T> void C<T>::h ()
    {
      this->m = 0;
      this->f ();
      this->n = 0
      this->g ();
    }
```
```


Question:
I got a text file  with a couple of lines and I am looking for a string in this file. I need to pass following command line parameters to the program:

- file path

- the string I am looking for

- maximum number of processes the program is allowed to "fork" in order to complete this task.

How to such a program should be constructed?

Answer:
A couple of thoughts.
You will have to open the file separately from each process, otherwise they will share a single file descriptor and thus have a shared position in the file (or not, see the comments, as this may be system specific...).
You may not see the speed increase you are hoping for due to disk access and/or cache miss patterns.
You might be able to beat both issues by memory mapping the file (well you still risk an increased cache miss rate)...
How badly do you need this? It runs a real risk of being premature optimization. I would recommend against touching the problem without a compelling need. Really.


Question:
Is there an easy way to create standalone .exe files from Lua scripts? Basically this would involve linking the Lua interpreter and the scripts.

I believe it is possible (PLT Scheme allows the creation of standalone executables in the same way), but how, exactly?

Answer:
Since you say '.exe' I'll assume you're looking for a Windows solution. One idea is to just append scripts to a prebuilt interpreter executable. It may or may not qualify as 'easy' in your book.
The interpreter needs to be able to read itself, parse its header to determine where the regular .exe data ends (ie. where the script begins) and then hand off the remainder of the file to Lua.
Other solutions don't require the interpreter to work as hard but do require more involved linking, whereas with this method, exeifying a script can be as simple as
```
```
copy interpreter.exe+script.lua script.exe
```
```


Question:
In our legacy system, we wrote our own VM to execute our internal DSL at run time. The in-house VM was designed to run our internal DSL only. We are in the process of rewriting our legacy application. One of the idea we are considering is, to transform our internal DSL to external DSL (C# or Java) and take advantage of their VM.

There are no clear guide lines when to write our own VM for our intenral DSL vs. transforming to external DSL and running it that VM.

Answer:
The internal DSL/VM vs. external DSL/VM decision is the same as all build vs. buy vs. download decisions.  The guidelines are clear and the same for all software.
Why support your own VM, when someone else will support Java or Python for you?
Here's some clear guidelines.  Note that these are the same guidelines for all software.
Is it cheaper for you to continue to maintain your own software.  In this case,  DSL and VM?
Is your own DSL and VM better than Java or Python?  By "better", you must fill in any combination of quality factors: faster, smaller, more reliable, better features, less resource use, more auditable, more secure, etc.
Don't be confused by DSL and VM.  It's nothing special; it's just more software.


Question:
I've got a php page which handles requets for file downloads. I need to be able to detect when a file has been downloaded successfully. How can this be done? Perhaps there's some means of detecting this client-side then sending a confirmation down to the server.

Thanks.

Edit:
By handle, I mean that the page is doing something like this:

$file = '/var/www/html/file-to-download.xyz';
  header('Content-Type: application/octet-stream');
  header('Content-Length: ' . filesize($file));
  header('Content-Disposition: attachment; filename=' . basename($file));
  readfile($file);

Answer:
Handle the download in a seperate php script (better do a little more than just
```
readfile($file);
```
, you can also provide the ability to resume downloads like in this
question
).
Then in this script, when you
read
the last block and send it, you know that all the file was sent. This is not the same as knowing that all was received, but it should be enough for most scenarios.


Question:
i have robot and want to control it via internet using radio wave .. but still i dont know the best language to do that . with the need to build scure site to insure not any body can use it . i expect for site asp with c# but what is the language i'll need it to control from sender device to the recipt robot . also need to live video transfer to the site from robot camera............
soory for bothering .....i know it may wrong but i'm beginner

and thanks for all who read or try to help me

Answer:
I think it might be best to narrow down your choice of technologies before choosing a programming language. Robotics control can be a very complex topic, and there are many approaches to solving the same problem.
Having said that, with the components you've listed:
Secure internet interface
RF communication to an autonomous robot
Embedded robot control software
Video processing, compression and decompression
Display of video to internet visitors
I would guess that your complete solution would involve at least two or three different programming languages, depending on application and environment.


Question:
I have an application installed on my computer. How do I find out if it was compiled in DEBUG mode or not?

I've tried to use .NET Reflector, but it does not show anything specific. Here is what I see:

// Assembly APPLICATION_NAME, Version 8.0.0.15072
Location: C:\APPLICATION_FOLDER\APPLICATION_NAME.exe
Name: APPLICATION_NAME, Version=8.0.0.15072, Culture=neutral, PublicKeyToken=null
Type: Windows Application

Answer:
I
blogged
this a long time ago, and I don't know if it still valid or not, but the code is something like...
```
```
private void testfile(string file)
{
    if(isAssemblyDebugBuild(file))
    {
        MessageBox.Show(String.Format("{0} seems to be a debug build",file));
    }
    else
    {
        MessageBox.Show(String.Format("{0} seems to be a release build",file));
    }
}

private bool isAssemblyDebugBuild(string filename)
{
    return isAssemblyDebugBuild(System.Reflection.Assembly.LoadFile(filename));
}

private bool isAssemblyDebugBuild(System.Reflection.Assembly assemb)
{
    bool retVal = false;
    foreach(object att in assemb.GetCustomAttributes(false))
    {
        if(att.GetType() == System.Type.GetType("System.Diagnostics.DebuggableAttribute"))
        {
            retVal = ((System.Diagnostics.DebuggableAttribute)att).IsJITTrackingEnabled;
        }
    }
    return retVal;
}
```
```


Question:
IOKit and the DiskArbitration framework can tell me a lot of things about mounted volumes on a mac, but they don't seem to be able to differentiate between HFS+ and HFS Standard volumes.

The IOKit/DA keys Content, DAVolumeKind and DAMediaContent are always Apple_HFS and hfs for both HFS Standard and HFS+ volumes.

diskutil and DiskUtility.app can tell the difference, but I they don't seem to have been open sourced by Apple.

p.s. statfs (2) does not differentiate

Answer:
There are two ways to do this:
Use
```
getattrlist()
```
to retrieve the
```
ATTR_VOL_SIGNATURE
```
attribute for the mount path of the volume.
Use the Carbon call FSGetVolumeInfo() and look in the
```
signature
```
field of the returned struct.
The signature of a volume is a 16 bit value, usually interpreted as two ASCII characters.  The signature for HFS is 'BD', HFS+ is 'H+', and case sensitive HFS+ is 'HX'.
The man page for
```
getattrlist
```
says the field is a u_int32, but the equivalent field in the FSVolumeInfo struct is only 16 bits, so I'm not sure which 16 bits of the 32 are filled in with the signature when using
```
getattrlist
```
, you'll probably have to just experiment a bit if you want to go the non-Carbon route.
getattrlist man page
HFS Plus Volume Format reference
FSGetVolumeInfo


Question:
I have read several places that the difference between c_str() and data() (in STL and other implementations) is that c_str() is always null terminated while data() is not.
As far as I have seen in actual implementations, they either do the same or data() calls c_str().

What am I missing here?
Which one is more correct to use in which scenarios?

Answer:
The documentation is correct. Use
```
c_str()
```
if you want a null terminated string.
If the implementers happend to implement
```
data()
```
in terms of
```
c_str()
```
you don't have to worry, still use
```
data()
```
if you don't need the string to be null terminated, in some implementation it may turn out to perform better than c_str().
strings don't necessarily have to be composed of character data, they could be composed with elements of any type. In those cases
```
data()
```
is more meaningful.
```
c_str()
```
in my opinion is only really useful when the elements of your string are character based.
Extra
: In C++11 onwards, both functions are required to be the same. i.e.
```
data
```
is now required to be null-terminated.  According to
cppreference
: "The returned array is null-terminated, that is, data() and c_str() perform the same function."


Question:
Simply put, is there a way to create a 2D javascript array using similar syntax to this?

var newArray = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]
]

Answer:
Yes. This works fine:
```
```
<script>
var newArray = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]
]
alert(newArray[0][2]);
</script>
```
```


Question:
Is there a way to suppress warnings in Xcode?

For example I am calling an undocumented method and since the method is not in the header I get a warning on compile. I know I can add it to my header to stop the warning, but I am wondering if there is a way other than adding it to the header (so I can keep the headers clean and standard) to suppress the warning? A pragma or something?

Answer:
To disable warnings on a per-file basis, using Xcode 3 and llvm-gcc-4.2 you can use:
```
```
#pragma GCC diagnostic ignored "-Wwarning-flag"
```
```
Where warning name is some gcc warning flag.
This overrides any warning flags on the command line.  It doesn't work with all warnings though.  Add -fdiagnostics-show-option to your CFLAGS and you can see which flag you can use to disable that warning.


Question:
I was asked to build a java system that will have the ability to load new code (expansions) while running.
How do I re-load a jar file while my code is running? or how do I load a new jar?

Obviously, since constant up-time is important, I'd like to add the ability to re-load existing classes while at it (if it does not complicate things too much).

What are the things I should look out for?
(think of it as two different questions - one regarding reloading classes at runtime, the other regarding adding new classes).

Answer:
I googled a bit, and found this code
here
:
```
```
File file = getJarFileToLoadFrom();
String lcStr = getNameOfClassToLoad();
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
```
```
Can anyone share opinions/comments/answers regarding this approach?


Question:
I am a heavy command line user and use the find command extensively in my build system scripts. However on Mac OS X when I am not concentrating I often get output like this:

$ find -name \*.plist
find: illegal option -- n
find: illegal option -- a
find: illegal option -- m
find: illegal option -- e
find: *.plist: No such file or directory

Basically, I forgot to add the little dot:

$ find . -name \*.plist

Because BSD find requires the path and GNU find doesn't (it assumes the current directory if you don't specify one). I use Linux, Mac OS X and Cygwin often all at the same time, so it's of great benefit to me to have all my tools behave the same. I tried writing a bash find function that added "./" if I forgot, but I failed. Thanks for your help. :)

Answer:
```
```
find ./ -name "*.plist"
```
```
edit
: hmm, i may have misunderstood the question! if you were crazy, how about emulating it via a shell script? i routinely keep random utility scripts in ~/.bin, and that's the first thing in my PATH. if you had a similar setup perhaps you could do something like: (untested!)
```
```
#!/bin/sh
# remapping find!
CMD=`echo $1 | cut -c 1`
if [ $CMD = '-' ]
then
# pwd search
  /usr/bin/find ./ $*
else
# regular find
  /usr/bin/find $*
fi
```
```


Question:
If I have a method such as:

private function testMethod(param:string):void
{
  // Get the object that called this function
}

Inside the testMethod, can I work out what object called us? e.g.

class A
{
  doSomething()
  {
    var b:B = new B();
    b.fooBar();
  }
}

class B
{
  fooBar()
  {
    // Can I tell that the calling object is type of class A?
  }
}

Answer:
Sorry the answer is no (see edit below).  Functions received a special property called
```
arguments
```
and in AS2 it used to have the property
```
caller
```
that would do roughly what you want. Although the arguments object is still available in AS3 the caller property was removed from AS3 (and therefore Flex 3) so there is no direct way you can do what you want. It is also recommeded that you use the [...rest parameter](
http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter)
language feature instead of
arguments
.
Here is a
reference on the matter
(search for callee to find the relevant details).
Edit:
Further investigation has shown that it is possible to get a stack trace for the current executing function so if you are lucky you can do something with that. See
this blog entry
and
this forum post
for more details.
The basic idea from the blog post is you throw an Error and then catch it immediately and then parse the stack trace. Ugly, but it may work for you.
code from the blog post:
```
```
var stackTrace:String;

try { throw new Error(); }
catch (e:Error) { stackTrace = e.getStackTrace(); }

var lines:Array = stackTrace.split("\n");
var isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;

var path:String;
var line:int = -1;

if(isDebug)
{
    var regex:RegExp = /at\x20(.+?)\[(.+?)\]/i;
    var matches:Array = regex.exec(lines[2]);

    path = matches[1];

    //file:line = matches[2]
    //windows == 2 because of drive:\
    line = matches[2].split(':')[2];
}
else
{
    path = (lines[2] as String).substring(4);
}

trace(path + (line != -1 ? '[' + line.toString() + ']' : ''));
```
```


Question: What is the best way to determine whether there is an available Internet connection for a WinForms app. (Programatically of course) I want to disable/hide certain functions if the user is not connected to the Internet.

Answer:
I'm not a c# developer but in C++ you can use the Win32 API (specifically from Wininet.dll) like this:
```
```
bool IsInternetConnected( void )
{
    DWORD dwConnectionFlags = 0;

    if( !InternetGetConnectedState( &dwConnectionFlags, 0 ) )
        return false;

    if( InternetAttemptConnect( 0 ) != ERROR_SUCCESS )
        return false;

    return true;
}
```
```
I assume this is trivially turned into c#


Question:
Has anyone got to some good code to zoom into an image using javascript?

I know I could just resize it etc but was being lazy and looking for something clever to zoom to different levels, move around when zoomed etc

Answer:
This really depends on what quality you are after. If you need a hires hiquality image with detailed zoom levels and proper interpolation you will need to write a backend service to serve up zoomed portions of your images. If you have no care for quality or speed, you could download the entire image and fit it to display inside a div absolutely positioned, offset for the area you want to view and sized as determined by your zoom level.
I would say you are probably after the first option. There are some tools already made
for this
, I persoanlly havnt used any of the tools; I am sure othes will post links to others you can try; I have written my own service and client. I cant go into the exact details as its proprietary, but I can give you an overview of what I do.
I have an asp.net generic handler that takes a query string denoting which image (by an id) and the coordinates to zoom on and the target image size. I have the service load the image and crop and resize it (its more complicated than that as I have many optimizations and preparsing when the file is originally uploaded, such as multiple cross sections of the file for faster serving when zooming, but what I describing here is the basics).
That service simply returns type image/jpeg and sends the image.
On the client side I have written a marquee box control that allows the user to marquee an area on the image they want to zoom in on. they marquee the area and click zoom. This then calculates the offsets into the image of the selected coordinates based on the original image size and the viewable image size. I send hese coords to the handler previously mentioned.I load the the url with query string of the srvice into an Image object, and handle onload. If all went well i then swap that to the viewed image and updates all my client side variables for determining where on the image I am zoomed into and then it can be zoomed again or zoomed out or panned further from there.
Now i understand your lazy requirement, but i need to say that writing this is actually quite easy to do to get the basics going. the hardest part you will find is doing a select box. But then even that can be as simple as tracking two click. Top left of the zoom select marque and bottom right. Or not having a select box at all and have a zoom in and out only at predetermined intervals. I on my projects required a zoom box as its a fairly complex image analysis solution.
I hope this at least helpful and leads you to something useful.


Question: I downloaded Squeak, the Image file, and the Sources file, but I can't figure out how to write Smalltalk code. Is there something obvious I'm missing? Is Squeak even the right IDE for serious Smalltalk development?

Answer:
I don't think Squeak is really oriented towards "serious Smalltalk development". It's intended as a first programming environment for children. Which isn't to say that you can't do  useful stuff with it, it's just not aimed as much towards large-scale development.
Check out the
Wiki
for getting started tips. It's been a while since I last used Squeak, but I don't remember it being particularly hard to get started.


Question:
What is the most efficient way to go through and update every single node in a drupal site, to, for instance mechanically add tags? Drupal 6 has a shiny new batch API, but what to do in Drupal 5?

I started writing a script that keeps a pointer and then goes around all nodes on a cron, loads them and then saves them, but I wonder what else could be done.

Answer:
hmm i'm not familiar with drupal 5's database structure, but if it's similar enough to drupal 6, you could just modify this all pretty easily by just working off the
```
term_node
```
table. it's a mapper of node id's to term id's:
```
```
term_node
- nid
- vid
- tid
```
```
nid is the node id of course, vid is the revision id, if you use revisions, and tid is the term id. terms are all stored in
```
term_data
```
```
```
term_data
- tid
- name
```
```
are the more interesting columns. so if you already have existing terms, you can create a quick map of existing tid's, then add to whatever nodes you want in term_node. anyhow, being careless in this regard could possibly cause weird data issues, so i wouldn't suggest this approach unless you feel pretty comfortable with the raw database.


Question:
Is it possible to initialize an array of pointers to structs?
Something like:

struct country_t *countries[] = {
        {"United States of America", "America"},
        {"England", "Europe"},
        {"Ethiopia", "Africa"}
    }

I want to do that in order to get the entities in not-contiguous memory, and the pointers to them in contiguous memory... But I can't use dynamic memory, so I wonder if it is possible without it.

Answer:
Well, your code uses structures rather than pointers to structures.  There are ways to do what you seek, including:
```
```
static struct country_t us = { "United States of America", "America" };
static struct country_t uk = { "England",                  "Europe"  };
static struct country_t et = { "Ethiopia",                 "Africa"  };

struct country_t *countries[] = { &us, &uk, &et, };
```
```
There are other ways to do it with designated initializers and compound literals in C99.  Section 6.5.2.5 'Compound Literals' shows the way:
```
```
struct country_t *countries[] =
{
    &(struct country_t) { "United States of America", "America" },
    &(struct country_t) { "England",                  "Europe"  },
    &(struct country_t) { "Ethiopia",                 "Africa"  },
};
```
```
The standard illustrates pointers to structures with a function call.  Be aware that not all C compilers accept C99 syntax, and these compound literals were not present in C89 (aka C90).
Edit:
Upgraded to use 2-letter ISO 3166 country codes.  Also made the named structures into static variables - those symbols were not visible outside the file before (because they did not exist), and now they aren't visible outside the file after, either.  I debated whether to make anything const and decided not to - but using const when you can is generally a good idea.  Also, in the example, there are 3 countries in 3 continents.  Were you to have multiple countries in a single continent (the norm), you might want to be able to share the continent strings.  However, whether you can do that safely (or at all) depends on the details of the
```
struct country_t
```
(which were not given), and on whether the program is allowed to update the table (which comes back to the const-ness question).


Question:
What is the % code-coverage on your project?  I'm curious as to reasons why.

Is the dev team happy with it? If not, what stands in the way from increasing it?

Stuart Halloway is one whose projects aim for 100% (or else the build breaks!). Is anyone at that level?

We are at a painful 25% but aspire to 80-90% for new code.  We have legacy code that we have decided to leave alone as it evaporates (we are actively re-writing).

Answer: We run at 85% code coverage, but falling below it does not break the build.  I think using code coverage as an important metric is a dangerous practice.  Just because something is covered in a test does not mean the coverage is any good.  We try to use it as guidance for the areas we are weakly covered, not as a hard fact.


Question:
I have 2 classes for accessing the database:

MovieDAO - access database using "select" statements only; the purpose is for retrieving data for displaying in the web browser.

and

MovieExtendedDAO (extends MovieDAO) - which is more complete and allows for creating/updating/deleting a movie in addition to the inherited functionality. This class is intended to be used only in the site's administrative area.

I have been told it is overkill to separate it like this.

Is this is a normal way to do things or part of a design pattern? Or is there no real benefit to doing this? My main intention was to simplify things for the public side: a kind of optimization for how much stuff needs to get loaded up and also what kind of things can happen on the public (non-admin) side. Thank you for your comments!

Answer:
it's not a bad method, it's basically a
row data gateway
. in that sense i would think of your movieDAO as more of a finder, (same terminology fowler uses), and your movieextendeddao as a gateway (ie MovieFinder, and MovieGateway).
once you start getting more complex domain logic (ie calculating various things about movies) then you can look at some other data access patterns, but your approach seems reasonable for what you're doing.


Question:
Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,

set[obj] = true;

This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?

Answer:
JavaScript objects can only use strings as keys (anything else is converted to a string).
You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:
```
```
var ObjectReference = [];
ObjectReference.push(obj);

set['ObjectReference.' + ObjectReference.indexOf(obj)] = true;
```
```
Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.
Edit:
Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej
This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.


Question:
Where do the type/member/parameter descriptions that you see in the Intellisense bubble come from? Are they stored in type attributes?

EDIT: I'm specifically interested in the built-in types.

Answer:
I don't know about the built-in types, but when you're building your own classes you can use Xml comments to list out the intellisense information.  The comments are put into their own xml file when you build the project, and as long as that file is in the right place Visual Studio will be able to use it.  Not only that, but you'll get intellisense help to build the comments.  For C#, just add an extra / character to a comment line right above a class, property, or method: ///.  For VB, use two extra ' characters: '''
One caveat with this (and I'm sure there's an option somewhere to control it), but it's been my experience that once you put an xml comment
anywhere
in a project, you'll get a compile warning for
every
public item that isn't commented if you don't use them
everywhere
in the project.


Question:
I got one big question.

I got a linq query to put it simply looks like this:

from xx in table
where xx.uid.ToString().Contains(string[])
select xx

The values of the string[] array would be numbers like (1,45,20,10,etc...)

the Default for .Contains is .Contains(string).

I need it to do this instead:  .Contains(string[])...

EDIT : One user suggested writing an extension class for string[].  I would like to learn how, but any one willing to point me in the right direction?

EDIT : The uid would also be a number. That's why it is converted to a string.

Help anyone?

Answer:
How about:
```
```
from xx in table
where stringarray.Contains(xx.uid.ToString())
select xx
```
```


Question:
I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string.  I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?

Very specifically, what would the method "SomeMethod" have to be that would produce the output below?

string unformattedXml;
string formattedXml;

unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>"
formattedXml = SomeMethod(unformattedXml);

Console.WriteLine(formattedXml);

Output:

<?xml version="1.0"?>
  <book id="123">
    <author>Lewis, C.S.</author>
    <title>The Four Loves</title>
  </book>

Answer:
Is the string valid XML? Do you mean how can you convert an XML string into an XML document? If so, do this:
```
```
XmlDocument xml = new XmlDocument();

xml.LoadXml( YourString );
```
```


Question:
I thought the web page designer screen in 2005 was mediocre until I used the one in 2008 which I think is bad.  There is an interesting  white paper here:

http://www.west-wind.com/weblog/posts/484172.aspx

I've gotten very used to these WYSIWYG designers over the years, but I am looking now for a new way.

I make business web apps which call for data entry forms.  I don't need anything particularly artistic, but I do need to be able to line up text boxes etc on input forms so that they lkook orderly and are convenient for the user.  I use Telerik controls, and my skills with CSS are approaching passable.

People often mention that they don't use the designer, but they rarely state what approach they DO use.

What are some of the alternatives to using the VS designer?

Answer:
Is the string valid XML? Do you mean how can you convert an XML string into an XML document? If so, do this:
```
```
XmlDocument xml = new XmlDocument();

xml.LoadXml( YourString );
```
```


Question:
I have an array of 1000 or so entries, with examples below:

wickedweather
liquidweather
driveourtrucks
gocompact
slimprojector

I would like to be able to split these into their respective words, as:

wicked weather
liquid weather
drive our trucks
go compact
slim projector

I was hoping a regular expression my do the trick.  But, since there is no boundary to stop on, nor is there any sort of capitalization that I could possibly key on, I am thinking, that some sort of reference to a dictionary might be necessary?

I suppose it could be done by hand, but why - when it can be done with code! =)  But this has stumped me.  Any ideas?

Answer:
I think you're right in thinking that it's not really a job for a regular expression. I would approach this using the dictionary idea - look for the longest prefix that is a word in the dictionary. When you find that, chop it off and do the same with the remainder of the string.
The above method is subject to ambiguity, for example "drivereallyfast" would first find "driver" and then have trouble with "eallyfast". So you would also have to do some backtracking if you ran into this situation. Or, since you don't have that many strings to split, just do by hand the ones that fail the automated split.


Question: I've been researching PHP frameworks as of late for some personal projects, and it looks like most of them use a front controller to mimic a response. The controller gets the params from the request, and re-routes by sending the appropriate headers depending on the logic. This is the "response". Is this the best way to do this in PHP, or are there other theories about how to handle re-routing and responses?

Answer:
a front controller lends itself quite well to a web environment, allowing you to funnel all requests to your application. since HTTP is stateless, and a user can, in a sense, inadvertently stumble upon parts of your app by accident (ie, hitting random URL's), a front controller allows you to determine the entry point of your application, and respond appropriately.
edit
: in response to the comments, i think the confusion may be that java has a lot more structure to it than PHP, which might be overcomplicating the whole thing? ultimately PHP can provide for the very basic interaction from request to response:
```
```
switch($_GET['page']) {
  case "one";
      print "page one!";
      break;
  default:
      print "default page";
      break;
}
```
```
and from there you can layer in all sorts of things to front controllers passing request objects down a filter chain to a page controller which reroutes to the appropriate model which grabs data via your db abstraction layer, filters it, back up to the controller, and on to the view which constructs the appropriate response, all the while firing off random event hooks. ultimately it's up to you (as developer) to choose what level of complexity/separation you're looking for. this is both the beauty and evilness of PHP :)


Question:
Below is my $.ajax call, how do I put a selects (multiple) selected values in the data section?

$.ajax({
    type: "post",
    url: "http://myServer" ,
    dataType: "text",
    data: {
        'service' : 'myService',
        'program' : 'myProgram',
        'start' : start,
        'end' : end ,
        },
    success: function(request) {
      result.innerHTML = request ;
    }   // End success
  }); // End ajax method

EDIT I should have included that I understand how to loop through the selects selected options with this code:

$('#userid option').each(function(i) {
 if (this.selected == true) {

but how do I fit that into my data: section?

Answer:
how about using an array?
```
```
data: {
    ...
    'select' : ['value1', 'value2', 'value3'],
    ...
},
```
```
edit
: ah sorry, here's the code, a few caveats:
```
```
'select' : $('#myselectbox').serializeArray(),
```
```
in order for serializeArray() to work though, all form elements must have a name attribute. the value of
```
'select'
```
above will be an array of objects containing the name and values of the selected elements.
```
```
'select' : [
    { 'name' : 'box', 'value' : 1 },
    { 'name' : 'box', 'value' : 2 }
],
```
```
the select box to produce the above result would be:
```
```
<select multiple="true" name="box" id="myselectbox">
   <option value="1" name="option1" selected="selected">One</option>
   <option value="2" name="option2" selected="selected">Two</option>
   <option value="3" name="option3">Three</option>
</select>
```
```


Question:
I have some assembly that references NUnit and creates a single test class with a single test method. I am able to get the file system path to this assembly (e.g. "C:...\test.dll"). I would like to programmatically use NUnit to run against this assembly.

So far I have:

var runner = new SimpleTestRunner();
runner.Load(path);
var result = runner.Run(NullListener.NULL);

However, calling runner.Load(path) throws a FileNotFound exception. I can see through the stack trace that the problem is with NUnit calling Assembly.Load(path) down the stack. If I change path to be something like "Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" then I still get the same error.

I have added an event handler to AppDomain.Current.AssemblyResolve to see if I could manually resolve this type but my handler never gets called.

What is the secret to getting Assembly.Load(...) to work??

Answer:
"What is the secret to getting Assembly.Load to work?"
System.Reflection.Assembly.Load takes an string containing an assembly name, not a path to a file.
If you want to load an assembly from a file use:
```
```
Assembly a = System.Reflection.Assembly.LoadFrom(pathToFileOnDisk);
```
```
(LoadFrom actually uses Assembly.Load internally)
By the way, is there any reason why you can;t use the
NUnit-Console command line tool
and just pass it the path to your test assembly?  You could then just use the System.Diagnostics.Process to run this from within your client application, might be simpler?


Question:
I need to hide (make private) the -init method of my class in Objective-C.

How can I do that?

Answer:
That depends on what you mean by "make private".  In Objective-C, calling a method on an object might better be described as sending a message to that object.  There's nothing in the language that prohibits a client from calling any given method on an object; the best you can do is not declare the method in the header file.  If a client nevertheless calls the "private" method with the right signature, it will still execute at runtime.
That said, the most common way to create a private method in Objective-C is to create a
Category
in the implementation file, and declare all of the "hidden" methods in there.  Remember that this won't truly prevent calls to
```
init
```
from running, but the compiler will spit out warnings if anyone tries to do this.
MyClass.m
```
```
@interface MyClass (PrivateMethods)
- (NSString*) init;
@end

@implementation MyClass

- (NSString*) init
{
    // code...
}

@end
```
```
There's a decent
thread
on MacRumors.com about this topic.


Question:
Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista?

Some more clarification:

I have written a program that modifies the windows hosts file (c:\Windows\system32\drivers\etc\hosts) in Vista the program will not run and will fail with an exception unless you right-click and run as administrator even when the user has administrator privileges, unlike in XP where it will run if the user has administration rights, so I need a way to elevate it to the correct privileges programaticly.

Answer:
Do you mean that you want Windows to prompt for elevation when your program is run? This is controlled by adding a UAC manifest to the EXE's resources.
This blog entry
explains how to create the manifest and how to compile it into a .RES file.
I don't know what facilities py2exe has for embedding custom .RES files, so you might need to use the MT.EXE tool from the Platform SDK to embed the manifest in your program. MT.EXE doesn't need .RES files; it can merge the .manifest file directly.


Question:
How can I raise an event from a SWF file loaded into a Flex application (using SWFLoader)?

I want to be able to detect

a) when a button is pressed
b) when the animation ends

Answer:
You'll need to do 2 things:
Dispatch an event from the loaded swf. Make sure the event bubbles if you sent it from nested views. Bubbling can be set through the bubbles property of the event.
Listen to the event from your main application. I think you should be able to do that on the content property of the SWFLoader instance.
```
```
mySWFLoader.content.addEventListener("myEvent", myEventHandler);
```
```


Question: I am new to this community, but I am working on a site that requires implementation of a user/password/register check upon entry, which would check against a database, or write to the database, in the case of registration. I have experience with XHTML and CSS, and just discovered RoR. I honestly have very little insight into how to achieve my goal using just XHTML, so I decided to learn Ruby, taking a shot in the dark. I'm wondering if there's an easier language, or more direct fix that I should be implementing instead. Any thoughts?

Answer:
Are you looking for information on how to implement user authentication in Rails? You could try
```
acts_as_authenticated
```
.


Question: I have a Zimbra installation and I need to programmaticaly update contacts in it. It seems that its REST interface is only working to add new contacts, but I need to update existing ones. Is there a way, tool or something, open-source, to do that ?

Answer:
Well, I have an answer to my question : you may use the "zmmailbox" command. Under the Zimbra system user, it is possible to modify content in a mailbox. Since quite everything is stored in the Zimbra mailbox, contacts can be edited. I need now to find a way to use this :
```
```
box$ zmmailbox help contact

  autoComplete(ac)             [opts] {query}
    -v/--verbose                 verbose output

  autoCompleteGal(acg)         [opts] {query}
    -v/--verbose                 verbose output

  createContact(cct)           [opts] [attr1 value1 [attr2 value2...]]
    -i/--ignore                  ignore unknown contact attrs
    -f/--folder <arg>            folder-path-or-id
    -T/--tags <arg>              list of tag ids/names

  deleteContact(dct)           {contact-ids}

  flagContact(fct)             {contact-ids} [0|1*]

  getAllContacts(gact)         [opts] [attr1 [attr2...]]
    -f/--folder <arg>            folder-path-or-id
    -v/--verbose                 verbose output

  getContacts(gct)             [opts] {contact-ids} [attr1 [attr2...]]
    -v/--verbose                 verbose output

  modifyContactAttrs(mcta)     [opts] {contact-id} [attr1 value1 [attr2 value2...]]
    -i/--ignore                  ignore unknown contact attrs
    -r/--replace                 replace contact (default is to merge)

  moveContact(mct)             {contact-ids} {dest-folder-path}

  tagContact(tct)              {contact-ids} {tag-name} [0|1*]
```
```


Question:
Very simply put:

I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.

Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' constructor, I am getting an "unresolved external symbol" error at compilation.

class test
{
public:
    static unsigned char X;
    static unsigned char Y;

    ...

    test();
};

test::test()
{
    X = 1;
    Y = 2;
}

I'm new to C++ so go easy on me. Why can't I do this?

Answer:
If you are using
C++ 17
you can just use the
```
inline
```
specifier (see
https://stackoverflow.com/a/11711082/55721
)
If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y
```
```
unsigned char test::X;
unsigned char test::Y;
```
```
somewhere.  You might want to also initialize a static member
```
```
unsigned char test::X = 4;
```
```
and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)


Question:
I have the following template

<h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>

I would like to only display the headers (one,two,three) if there is at least one member of the corresponding template. How do I check for this?

Answer:
```
```
<xsl:if test="one">

one

  <xsl:apply-templates select="one"/>
</xsl:if>

```
```
Alternatively, you could create a named template,
```
```
<xsl:template name="WriteWithHeader">
   <xsl:param name="header"/>
   <xsl:param name="data"/>
   <xsl:if test="$data">

<xsl:value-of select="$header"/>

      <xsl:apply-templates select="$data"/>
   </xsl:if>
</xsl:template>
```
```
and then call as:
```
```
<xsl:call-template name="WriteWithHeader">
    <xsl:with-param name="header" select="'one'"/>
    <xsl:with-param name="data" select="one"/>
  </xsl:call-template>
```
```
But to be honest, that looks like more work to me... only useful if drawing a header is complex... for a simple
```
<h2>...</h2>
```
I'd be tempted to leave it inline.
If the header title is always the node name, you could simplifiy the template by removing the "$header" arg, and use instead:
```
```
<xsl:value-of select="name($header[1])"/>
```
```


Question:
I'm playing around with the <canvas> element, drawing lines and such.

I've noticed that my diagonal lines are antialiased. I'd prefer the jaggy look for what I'm doing - is there any way of turning this feature off?

Answer:
For images there's now
```
context.imageSmoothingEnabled
```
```
= false
```
.
However, there's nothing that explicitly controls line drawing. You may need to draw your own lines (
the hard way
) using
```
getImageData
```
and
```
putImageData
```
.


Question:
Are there any professional Combobox controls (dropdown list with autosuggestion) based on the jQuery library?

It should be able to handle large datasets and have some skinning options. A multi-column result list would be great too. I'm working with ASP.NET, but it's a not a problem if I had to write a wrapper for it.

I'm already using a third-party control, but I ran into some compatibilty issues between two vendor's controls. Well, I want to get rid of this kind of dependencies.

Answer:
Unfortunately, the best thing I have seen is the
jquery.combobox
, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.
I much prefer the
Combo Dropdown Box
, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.
Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.


Question:
I'd like to get all the permutations of swapped characters pairs of a string. For example:

Base string: abcd

Combinations:

bacd

acbd

abdc

etc.

Edit

I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.

What's the best way to do this?

Edit

Just for fun: there are three or four solutions, could somebody post a speed test of those so we could compare which is fastest?

Speed test

I made speed test of nickf's code and mine, and results are that mine is beating the nickf's at four letters (0.08 and 0.06 for 10K times) but nickf's is beating it at 10 letters (nick's 0.24 and mine 0.37)

Answer:
Edit: Markdown hates me today...
```
```
$input = "abcd";
$len = strlen($input);
$output = array();

for ($i = 0; $i < $len - 1; ++$i) {
    $output[] = substr($input, 0, $i)
              . substr($input, $i + 1, 1)
              . substr($input, $i, 1)
              . substr($input, $i + 2);
}
print_r($output);
```
```


Question:
I have an Arduino sending and receiving instructions with a Python script via a serial port.

The Arduino takes a button state and when it is pushed, it will send a message via the serial port to a Python script and await a response. (via Serial.available()). It works well enough.

However, if the Python script has crashed for whatever reason (ideally it will run in the background, so it can't be easily checked), the Arduino will wait forever and will be unavailable even on a script restart.

Is there a way for my Arduino to check if there is something listening on the serial port? (and alert me with flashing lights, etc. if not) or is this not how serial works? Worst case I guess I could use a timeout, although that is not ideal.

Answer:
You have a limited ability to detect if there is something listening on the other side by using the DSR/DTR pins.
When you open the serial port on the machine your scripts runs on, it should raise its DTR pin (or you should be able to convince it to do so: the documentation of the library you use to drive the COM port should tell you how).
Then, on your Arduino, you can check its DSR pin (assuming null-modem wiring with handshaking, where the PC DTR pin is wired to DSR+CD on the Arduino) at regular intervals, and handle the 'nobody connected' scenario in any way you see fit.
One problem with this approach is that your PC script may not close the serial port when it crashes/stops responding, leaving the DTR pin enabled as if everything is still OK. Also, your script may simply miss the message from the Arduino due to errors on the serial line.
For that reason, you should
always
implement a timeout in your receive routines: even if there is a party listening at the other end, there is no guarantee it has received your message (or that its response will reach you intact).
Re-sending the message at least once (assuming DSR is raised) if a timeout occurs makes your protocol more reliable.


Question:
Ryan Delucchi asked here in comment #3 to Tom Hawtin's answer:

why is Class.newInstance() "evil"?

this in response to the code sample:

// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();

so, why is it Evil?

Answer:
The Java API documentation explains why (
http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()
):
Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The
```
Constructor.newInstance
```
method avoids this problem by wrapping any exception thrown by the constructor in a (checked)
```
InvocationTargetException
```
.
In other words, it can defeat the checked exceptions system.


Question: I am trying to learn some programming related terms, and I often come over the word "handler". Can anyone please explain what it means and when to use it?

Answer:
A handler is a routine/function/method which is specialized in a certain type of data or focused on certain special tasks.
Examples:
Event handler - Receives and digests events and signals from the
surrounding system (e.g. OS or GUI).
Memory handler - Performs certain special tasks on memory.
File input handler - A function receiving file input and performing
special tasks on the data, all depending on context of course.


Question:
In IE when I insert text into a <pre> tag the newlines are ignored:

<pre id="putItHere"></pre>

<script>
function putText() {
   document.getElementById("putItHere").innerHTML = "first line\nsecond line";
}
</script>

Using \r\n instead of a plain \n does not work.

<br/> does work but inserts an extra blank line in FF, which is not acceptable for my purposes.

Answer:
```
<br/>
```
shoud only output one line in all browsers. Of course remove the \n as well, code should be:
```
```
document.getElementById("putItHere").innerHTML = "first line<br/>second line";
```
```


Question:
How is it possible for this to be true

XmlDocument d = BuildReportXML(schema);
DataSet ds = new DataSet();
ds.ReadXmlSchema(schema);
ds.ReadXml(new XmlNodeReader(d));

Schema is the schema location that I apply to the XmlDocument before I start setting data, assuring that all the columns are of the correct type. Then I set the schema to the DataSet, and read the document into it. When I do this it throws an "Input string was not in a correct format." I have a few decimal variables in the Xml, and I assume this is the error. All of the information is obviously of the correct format, else the XmlDocument would have had errors. What can I do?

Answer:
```
<br/>
```
shoud only output one line in all browsers. Of course remove the \n as well, code should be:
```
```
document.getElementById("putItHere").innerHTML = "first line<br/>second line";
```
```


Question:
I'm trying to debug an application (under PostgreSQL) and came across the following error:
"current transaction is aborted, commands ignored".

As far as I can understand a "transaction" is just a notion related to the underlying database connection.

If the connection has an auto commit "false", you can execute queries through the same Statement as long as it isn't failing. In which case you should rollback.

If auto commit is "true" then it doesn't matter as long as all your queries are considered atomic.

Using auto commit false, I get the aforementioned error by PostgreSQL even when a simple

select * from foo

fails, which makes me ask, under which SQLException(s) is a "transaction" considered invalid and should be rolled backed or not used for another query?

using MacOS 10.5, Java 1.5.0_16, PostgreSQL 8.3 with JDBC driver 8.1-407.jdbc3

Answer:
That error means that one of the queries sent in a transaction has failed, so the rest of the queries are ignored until the end of the current transaction (which will automatically be a rollback). To PostgreSQL the transaction has failed, and it will be rolled back in any case after the error with one exception. You have to take appropriate measures, one of
discard the statement and start anew.
use
SAVEPOINT
s in the transaction to be able to get back to that point in time and try another path. (This is the exception)
Enable
query logging
to see which query is the failing one and why.
In any case the exact answer to your question is that any SQLException should mean a rollback happened when the end of transaction command is sent, that is when a COMMIT or ROLLBACK (or END) is issued. This is how it works, if you use savepoints you'll still be bound by the same rules, you'll just be able to get back to where you saved and try something else.


Question:
I'm looking for a technique (javascript, CSS, whatever ???) that will let me control the amount of a string that is displayed. The string is the result of a search (and therefore not initially known). A simple Character count approach is trivial, but not acceptable, as it needs to handle proportional fonts. In otherwords if I want to limit to say 70 pixels then the examples below show different character counts (9 and 15) both measuring the same:-

Welcome M...

Hi Iain if I've ...

If you look at Yahoo search results they are able to limit the length of title strings and add ellipsis on the end of long strings to indicate more.
(try  site:loot.com wireless+keyboard+and+mouse to see an example of Yahoo achieving this)

Any Ideas?

Answer:
Perhaps the CSS property
```
overflow: hidden;
```
can help you, in conjuntion with
```
width
```
.


Question: I have read (or perhaps heard from a colleague) that in .NET, TransactionScope can hit its timeout and then VoteCommit (as opposed to VoteRollback).  Is this accurate or hearsay?  I couldn't track down information on the web that talked about this issue (if it IS an issue), so I wonder if anyone has any direct experience with it and can shed some light?

Answer:
If you mean in relation to SQL Server, then there is an issue that you can fix in the connection string; see my reply
here
, or the full details
here
.
The short version is: ensure you have
```
Transaction Binding=Explicit Unbind;
```
in the connection string.
It isn't actually doing a vote commit - the transaction (and any early operations) has rolled back, but any subsequent operations (still inside the
```
TransactionScope
```
) can get performed in the nul-transaction, i.e. auto-commit.


Question:
I know its possible to get the top terms within a Lucene Index, but is there a way to get the top terms based on a subset of a Lucene index?

I.e. What are the top terms in the Index for documents within a certain date range?

Answer:
Ideally there'd be a utility somewhere to do this, but I'm not aware of one.  However, it's not too hard to do this "by hand" in a reasonably efficient way.  I'll assume that you already have a
```
Query
```
and/or
```
Filter
```
object that you can use to define the subset of interest.
First, build a list in memory of all of the document IDs in your index subset.  You can use
```
IndexSearcher.search(Query, Filter, HitCollector)
```
to do this very quickly; the
```
HitCollector
```
documentation
includes an example that seems like it ought to work, or you can use some other container to store your doc IDs.
Next, initialize an empty HashMap (or whatever) to map terms to total frequency, and populate the map by invoking one of the
```
IndexReader.getTermFreqVector
```
methods for every document and field of interest.  The three-argument form seems simpler, but either should be just fine.  For the three-argument form, you'd make a
```
TermVectorMapper
```
whose
```
map
```
method checks if
```
term
```
is in the map, associates it with
```
frequency
```
if not, or adds
```
frequency
```
to the existing value if so.  Be sure to use the same
```
TermVectorMapper
```
object across all of the calls to
```
getTermFreqVector
```
in this pass, rather than instantiating a new one for each document in the loop.  You can also speed things up quite a bit by overriding
```
isIgnoringPositions()
```
and
```
isIgnoringOffsets()
```
; your object should return
```
true
```
for both of those.  It looks like your
```
TermVectorMapper
```
might also be forced to define a
```
setExpectations
```
method, but that one doesn't need to do anything.
Once you've built your map, just sort the map items by descending frequency and read off however many top terms you like.  If you know in advance how many terms you want, you might prefer to do some kind of fancy heap-based algorithm to find the top
k
items in linear time instead of using an O(
n
log
n
) sort.  I imagine the plain old sort will be plenty fast in practice.  But it's up to you.
If you prefer, you can combine the first two stages by having your
```
HitCollector
```
invoke
```
getTermFreqVector
```
directly.  This should certainly produce equally correct results, and intuitively seems like it would be simpler and better, but the docs seem to warn that doing so is likely to be quite a bit slower than the two-pass approach (on same page as the HitCollector example above).  Or I could be misinterpreting their warning.  If you're feeling ambitious you could try it both ways, compare, and let us know.


Question:
Would it be possible to execute a JSP page and capture its output outside of a web application?
Mode specifically, in my case there still exists a usual web application, but it loads JSP pages not from its classpath, but from an arbitrary source. It seems like I cannot simply  get RequestDispatcher and point it to a JSP file on disk.

Answer:
Correct me if I'm wrong, but I think you mean you want to capture the HTML... not the JSP.  A JSP is processed (into a JAVA file) on a servlet-engine (Web app Server) and after the HTML is formatted and served up to the requestor via a Web server (not the same as a web APP server).  You can't get the RequestDispatcher to work on a straight JSP from disk because it hasn't been processed yet by the web app server.
Now, to capture the output of a JSP (in HTML) should be possible, but I've never done that before.  There may be some slick APIs that those out there more knowledgable than I can address, but HTTP is typically done on port 80, so I guess one could read/write to port 80 on a TCPIP socket.  There's probably some more things to do on top of that, but at least that's some point to start looking into.
Sorry I can't provide more details, but hell... it's all theory to me at this point.


Question:
I use public boolean mouseDown(Event ev, int x, int y) to detect a click of the mouse.

I can distinguish between the right mouse button (ev.metaDown() is true) and the left and middle.

How can i differentiate the left from the middle button?
Or if it is impossible with mouseDown, what should i use?

Answer:
This might do it:
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/SwingUtilities.html#isMiddleMouseButton(java.awt.event.MouseEvent)
Haven't tried it myself.


Question:
Is there an easy way of programmatically checking if a serial COM port is already open/being used?

Normally I would use:

try
{
    // open port
}
catch (Exception ex)
{
    // handle the exception
}

However, I would like to programatically check so I can attempt to use another COM port or some such.

Answer:
I needed something similar some time ago, to search for a device.
I obtained a list of available COM ports and then simply iterated over them, if it didn't throw an exception i tried to communicate with the device. A bit rough but working.
```
```
var portNames = SerialPort.GetPortNames();

foreach(var port in portNames) {
    //Try for every portName and break on the first working
}
```
```


Question: Where does Internet Explorer store the history data, i.e. the list of URL that have been visited? I am using Windows XP SP3 and IE7. Basically I would like to read the list of URL and make some statistics on how often what pages are visited.

Answer:
Internet Explorer seems to keep its history in hidden directories under C:\Documents and Settings\USERNAME\Local Settings\History\History.IE5.  Note that some directories in this path are also marked hidden or system.  The history's format is opaque, but
there's code at CodeProject
that can decode the contents.  You can also find a list of typed URLs under HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs.
An easier alternative might be to setup an HTTP proxy between the IE and the internet, and then examine the proxy's log.


Question:
I accidentally coded SELECT $FOO.. and got the error "Invalid pseudocolumn "$FOO".

I can't find any documentation for them.   Is it something I should know?

Edit: this is a MS SQL Server specific question.

Answer:
A simple Google search brings up
this
from Oracle's reference:
A pseudocolumn behaves like a table
  column, but is not actually stored in
  the table. You can select from
  pseudocolumns, but you cannot insert,
  update, or delete their values.
I think that the error you got is simply because there is no column $FOO, so the query parser tests to see if there's a psuedocolumn named $FOO as a fallback. And since there is no pseudocolumn named "$FOO" (and there are no other fallback) you get the error "Invalid pseudocolumn $FOO". This is a guess, though. I'm no expert when it comes to databases.


Question:
What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi?

Which combination will need more memory and CPU time?

Which one is faster?

Which is known for being more stable than the other?

I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this?

Note: I didn't use any Python Web Framework, I just wrote the whole thing from scratch.

Note': Other suggestions are also welcome.

Answer:
One thing that CherryPy's webserver has going for it is that it's a pure python webserver (AFAIK), which may or may not make deployment easier for you.  Plus, I could see the benefits of using it if you're just using a server for WSGI and static content.
(shameless plug warning:  I wrote the WSGI code that I'm about to mention)
Kamaelia
will have WSGI support coming in the next release.  The cool thing is that you'll likely be able to either use the pre-made one or build your own using the existing HTTP and WSGI code.
(end shameless plug)
With that said, given the current options, I would personally probably go with CherryPy because it seems to be the simplest to configure and I can understand python code moreso than I can understand C code.
You may do best to try each of them out and see what the pros and cons of each one are for your specific application though.


Question: As the question states - is there a good tool out there which lists methods an unmanaged DLL exports? I would like it to list COM methods and interfaces too.

Answer:
Take a look at
Dependency Walker
to get a list of unmanaged functions exported from a DLL.
You can't easily get a l list of COM classes exported from a DLL. What you'd have to do is something like to through the registry and find all objects that reference the DLL in question. DLLs advertise their classes via registration in the registry...


Question:
I am taking my first steps programming in Lua and get this error when I run my script:

attempt to index upvalue 'base' (a function value)

It's probably due to something very basic that I haven't grasped yet, but I can't find any good information about it when googling. Could someone explain to me what it means?

Answer:
In this case it looks
```
base
```
is a function, but you're trying to index it like a table (eg.
```
base[5]
```
or
```
base.somefield
```
).
The 'upvalue' part is just telling you what kind of variable
```
base
```
is, in this case an upvalue (aka external local variable).


Question:
Does anybody know how to determine the location of a file that's in one of the folders specified by the PATH environmental variable other than doing a dir filename.exe /s from the root folder?

I know this is stretching the bounds of a programming question but this is useful for deployment-related issues, also I need to examine the dependencies of an executable. :-)

Answer:
You can use the
```
where.exe
```
utility in the
```
C:\Windows\System32
```
directory.


Question: I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity?

Answer:
```
Pop()
```
for the last element ought to be O(1) since you only need to return the element referred to by the last element in the array and update the index of the last element.  I would expect
```
pop()
```
for an arbitrary element to be O(N) and require on average N/2 operations since you would need to move any elements beyond the element you are removing one position up in the array of pointers.


Question:
I am trying to figure out Messagebox( ownerWindow, ... ).

Using reflector I see that the ownerWindow defaults to the ActiveWindow for the thread.

So the only time I need the ownerWindow parameter is to call Show from another thread.

However when I try this, I get a cross threading exception.

    private void button1_Click( object sender, EventArgs e ) {
        new Thread( () => MessageBox.Show( this, "Test" ) ).Start();
    }

So it looks like the only time I need the explicitly state the owner window, I cann't use it!

Answer:
You will have to do a BeginInvoke to marshal the call to the UI thread.
The code below is a simple example how you can do it. I haven't compiled it, so there might be errors in it, but it might give you some pointers.
```
```
private delegate void ThreadExecuteDelegate(object args);

public void StartThread
{
   Thread thread = new Thread(new ParameterizedThreadStart(ThreadExecute));
   thread.Start((IWin32Window)this);
}

private void ThreadExecute(object args)
{
    if(this.InvokeRequired)
    {
        this.BeginInvoke(new ThreadExecuteDelegate(ThreadExecute), args);
        return;
    }

    IWin32Window window = (IWin32Window)args;
    MessageBox.Show(window, "Hello world");
}
```
```


Question:
I have heard of desktop applications whose code has been open-sourced, but are there any websites whose code has been open-sourced? I don't think I have heard of any. If there are aren't any, are there any reasons why?

This will have the advantage of not having to wait for the web development team to include a new feature. Also, this would ensure that more eyes see the code, ensuring a lower bug count. Of course, hacking would be easy.

Answer:
Pastebin:
http://pastebin.com/
The wiki behind Wikipedia et al:
http://www.mediawiki.org/wiki/MediaWiki
GrailsCrowd:
http://grailscrowd.com/
Slashcode [slashdot engine]:
http://www.slashcode.com/
The reason that not as many people do it is because it would be easy for someone to set up a complete clone of your website without making any useful changes. OK, that's strictly allowed with true 'open source' code, but it's not quite within the spirit of the thing (IMO) and if the site became even moderately popular there would be a
lot
of useless clones. The site would become essentially worthless.
Those are -websites- that are open source. There is a huge amount of web application software that is open source [some of it shitty]
WordPress
InkType
Joomla
osCommerce
ZenCart
Drupal


Question:
Is it possible to copy a single file to multiple directories using the cp command ?

I tried the following , which did not work:

cp file1 /foo/ /bar/
cp file1 {/foo/,/bar}

I know it's possible using a for loop, or find. But is it possible using the gnu cp command?

Answer:
No,
```
cp
```
can copy multiple sources but will only copy to a single destination. You need to arrange to invoke
```
cp
```
multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.


Question:
I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).

Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.

Thanks

Answer:
I am not sure what your problem is, but perhaps your approach should be a little different. Try putting code into the iframe what would call functions of the parent. These functions would display the proper table:
```
```
<!-- in the main page --->
function showTable1() {}

<!-- in the iframe -->
window.onload = function () {
    parent.showTable1();
}
```
```
This would put a lot of control into your iframe, away from the main page.


Question:
Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction.  There's no reason for my mock class to actually create and close threads.  But, to mock a class, I have inherit from it.  When I create a new instance of my mock class, the base classes constructor is called, creating the thread.  When my mock object is destroyed, the base classes destructor is called, attempting to close the thread.

How does one mock an RAII class without having to deal with the actual resource?

Answer:
You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had:
```
```
class RAIIClass {
 public:
  RAIIClass(Foo* f);
  ~RAIIClass();
  bool DoOperation();

 private:
  ...
};
```
```
You would make an interface like:
```
```
class MockableInterface {
 public:
  MockableInterface(Foo* f);
  virtual ~MockableInterface();
  virtual bool DoOperation() = 0;
};
```
```
And go from there.


Question:
I have an XML file, which I open in F# like this:

let Bookmarks(xmlFile:string) =
    let xml = XDocument.Load(xmlFile)

Once I have the XDocument I need to navigate it using LINQ to XML and extract all specific tags. Part of my solution is:

let xname (tag:string) = XName.Get(tag)
let tagUrl (tag:XElement) = let attribute = tag.Attribute(xname "href")
                            attribute.Value
let Bookmarks(xmlFile:string) =
    let xml = XDocument.Load(xmlFile)
    xml.Elements <| xname "A" |> Seq.map(tagUrl)

How can I extract the specific tags from the XML file?

Answer:
Caveat: I've never done linq-to-xml before, but looking through other posts on the topic, this snippet has some F# code that compiles and does
something
, and thus it may help you get started:
```
```
open System.IO
open System.Xml
open System.Xml.Linq

let xmlStr = @"<?xml version='1.0' encoding='UTF-8'?>
<doc>
    <blah>Blah</blah>

    <yadda>
        <blah>Blah</blah>

    </yadda>
</doc>"

let xns = XNamespace.op_Implicit ""
let a = xns + "a"
let reader = new StringReader(xmlStr)
let xdoc = XDocument.Load(reader)
let aElements = [for x in xdoc.Root.Elements() do
                 if x.Name = a then
                     yield x]
let href = xns + "href"
aElements |> List.iter (fun e -> printfn "%A" (e.Attribute(href)))
```
```


Question: I'm writing a Rails application, but can't seem to find how to do relative time, i.e. if given a certain Time class, it can calculate "30 seconds ago" or "2 days ago" or if it's longer than a month "9/1/2008", etc.

Answer:
You can use the arithmetic operators to do relative time.
```
```
Time.now - 2.days
```
```
Will give you 2 days ago.