q: When I started programming I was using Ruby and the colorful little notepad that came with it. Since I started learning Java I've been using Eclipse, which is apparently an IDE. Now I've read a bit about this Mono on Reddit, but I don't think I understand exactly what it is. The website says it is a development framework: is that just another word for IDE? I'm a true beginner who wants to work in a number of languages, from Java and Ruby to z80 and ARM9... is there an IDE or development framework that might be best for little me?

[A]
a framework is a set of classes and supporting code to be used to build applications. this can be as simple as the C standard library or as complex as the Smalltalk environment, or may even include the infrastructure for complex application like Dynamic or ERP systems - but essentially a framework is just a class library
an IDE (Integrated Development Environment) is a tool for writing programs; this tool is essentially a just a program that contains a text-editor that supports compilation and debugging et al
[mono is a linux-based implementation of the .NET framework, by the way]


q:
I have a website with a mix of ASP (classic) and ASP.NET pages.

For some reason Visual Studio (specifically 2008 Pro) keeps trying to compile the ASP classic pages.

How do I prevent it from trying to compile the .asp pages?

Reason: I'm getting a ton of errors on a specific .asp file that includes a Class. I believe it's trying to compile it as a Visual Basic class instead of seeing it as a vBScript class. It should be skipping over .asp files anyway, correct?

Here is the error:

Property Get/Let/Set are no longer
  supported; use the new Property
  declaration syntax.

[A]
What is in the @Page directive on those classic ASP pages? Have you tried inserting
```
<% @Page language="vbscript" %>
```
Maybe this does it already?

s: huggingface

c: devops

d: intermediate


q:
I would like to intercept any URL which the user enters in their browser and perform some tasks before allowing the navigation to continue (any way could be good - i.e. via plug in, via proxy or any other creative suggestion).
To clarify - I am not referring to a specific application that needs to catch this, but rather - any navigation that the user does on his browser needs to be caught (i.e. the user is not opening my application, it should be running in the background or something like that...)
Thanks in advance...

[A]
If you're using Javascript, there's an event which fires when the user exists a page called
```
onunload
```
.
```
```
window.onunload = function() {
    alert("You're leaving this page.");
};
```
```


q:
Given a bitmap image with some blots of solid color on it, what algorithm would you employ to construct polygons in the same shape as the blots?

This can be done in multiple steps: a high-resolution polygon could be later cut down by a best fit algorithm.  Bonus points if you can tell me how to cut the resulting polygons into convex components so that they can be rendered in OpenGL without problems.

[A]
Reverse rasterizing is referred to as
vectorizing
.  The algorithms are generally quite complex, here's a
googlet
of a few of them.  Check out sparse pixel tracking and sparse pixel vectorization for some good examples.
For good algorithms for polygon partitioning, check out Joespeh O'Rourkes 'Computational Geometry in C', ISBN 0-521-44034-3, or search for
concave polygon partitioning
algorithms, such as
this


q:
I am a bit confused why this code compiles.  I leave out the "necessary" #include <OpenGL/gl.h> and still the program can compile.  How is this possible when my program is calling functions from the GL library, without including them.

int main(int argc, char** argv)
{

    glClearColor(1.0,1.0,1.0,1.0);
    return 0;
}

I use this compilation command:

 gcc -framework GLUT -framework OpenGL test.c

I was under the assumption that adding -framework just specifies to the linker where the library is, but I thought I still need the headers?

[A]
glClearColor isn't a macro so you don't
need
the headers to define it. If you add warnings:
```
```
gcc -o test -Wall -W test.c -framework GLUT -framework OpenGL
```
```
Then you'll get a warning about the implicit declaration of glClearColor. You also won't be able to use any macros as the compiler will give you an error that they are undefined. Since the glClearColor symbol gets properly resolved by the linker, you never get an error.
It also occurs to me that you might have been wondering this because you thought you were compiling for C++. The example you gave actually compiles C code where it is not an error to fail to declare function prototypes. If you meant to compile this as C++ code, you would need the following command line:
g++ -o test test.cpp -framework OpenGL
In that case you most certainly would get an error for not including gl.h and your code would fail to compile. When executing GCC from the command line, g++ is the C++ compiler while gcc is the general C compiler.


q:
I am storing all my passwords in the form hashed. I need to retrieve these passwords
Eg

My password is "123456" I save this as hashed "3453474852dfdsfdsfdf" value.

I need to retrieve the original password from the hashed value. (Get Password).

How can I do that?. I am doing SHA1 hashing algorithm.

[A]
This is not possible. SHA1 is, very carefully and deliberately, a
one-way function
.
Why are you trying to recover the original password? It is not needed for authentication, because you simply hash the input password and compare the hash values.
If it is because the user forgot their password, then standard practice appears to be generating a randomized reset link and emailing it to the user.


q:
I want to check whether the user is viewing my site from a mobile device or PC. If it's a mobile device, I want to redirect my site URL like Google does...

If possible I would like to implement this in JavaScript. How can I do this?

[A]
You typically use the User-Agent header to detect the browser.
Here's JavaScript code that does basically that (only for mainstream browsers though, you'd have to add the Mobile User-Agents)
http://www.quirksmode.org/js/detect.html
And here's a list of mobile browser identifiers
http://www.zytrax.com/tech/web/mobile_ids.html
The list is not complete and will never be, given the rate new mobiles appear on the market, but what I did back when I did it is to store all received user agents in a database, and then look for them to classify them as mobile and which brand/model.
What you can't rely on though is JavaScript, it's better done in server code (not all mobile browsers execute JavaScript).
There is a related question here on SO but I couldn't find it.


q:
How do I add a certain number of days to the current date in PHP?

I already got the current date with:

$today = date('y:m:d');

Just need to add x number of days to it


q: Let's say I have a source file with many preprocessor directives. Is it possible to see how it looks after the preprocessor is done with it?

[A]
Most compilers have an option to just run the preprocessor.
e.g.
, gcc provides -E:
```
```
-E  Stop after the preprocessing stage; do not run the compiler proper.
       The output is in the form of preprocessed source code, which is sent
       to the standard output.
```
```
So you can just run:
```
```
gcc -E foo.c
```
```
If you can't find such an option, you can also just find the C preprocessor on your machine.  It's usually called cpp and is probably already in your path.  Invoke it like this:
```
```
cpp foo.c
```
```
If there are headers you need to include from other directories , you can pass -I/path/to/include/dir to either of these, just as you would with a regular compile.
For Windows, I'll leave it to other posters to provide answers as I'm no expert there.


q:
I want to be able to compare Dates and Times in Rails without always having to call the to_time or to_date method. So I wrote the following code:

class Date
  def ==(other)
    if other.kind_of?(Time)
      self.to_time == other
    else
      super(other)
    end
  end
end

I know there's an easy way to write this so that I can make this work for >, <, >=, <= and <=>. But I forgot how :P Any ideas?

[A]
Your example looks okay, but I wouldn't use
```
kind_of?
```
- if
```
other
```
doesn't implement
```
to_time
```
you get an exception anyway!
Update: What you are looking for is probably the
```
<=>
```
operator!


q:
What is a mathematical way of of saying 1 - 1 = 12 for a month calculation?  Adding is easy, 12 + 1 % 12 = 1, but subtraction introduces 0, stuffing things up.

My actual requirement is x = x + d, where x must always be between 1 and 12 before and after the summing, and d any unsigned integer.


q:
I've been reading through the details of the System libraries set and get methods yet the parameters are usually Strings.

Would you consider the use of String as parameters bad practise since the inclusion of enum?

A better alternative at minimum might be public final String, No?

[A]
I would consider Enums to be a better approach than Strings. They are type safe and comparing them is faster than comparing Strings.
As a pre Java 1.5 alternative you could use the type-safe enum pattern suggested by Joshua Bloch in his book Effective Java. For type-safe enums see also
http://www.javacamp.org/designPattern/enum.html


q:
I need to read the user's fingerprint from my application.

What I really want is a simple SDK that works with a lot of inexpensive fingerprint readers but I can deal with something that works only with one specific model if that model is cheap and available worldwide.

And it has to be royalty-free, I can pay for a development license but if I have to pay for each installation I just can't use it.

What I'm doing has no relation to login or encryption, so the software included with the reader will probably be useless to me.

[A] There is no standard API for reading fingerprint data as far as I'm aware since it is a fairly new field and there's no standard way of doing it. Each manufacturer will provide their own API for reading the hardware. The API could just be IO specification to the hardware and there's no library whatsoever, which makes things a bit trickier. This is down to two factors. The first is that finger print readers are used in many applications - custom hardware, embedded systems through to PC authentication and beyond. Providing software for all those different systems would not be viable from the manufacturers point of view. Secondly, each manufacturer uses a different approach to reading and processing the captured images which would make a common API problematic.


q:
Most programming houses / managers i know of can only define quality in terms of the no of bugs made / resolved in retrospect.

However most good programmers can innately sense quality once they start meddling with the code.(right?)

Has any programming houses that you know of, successfully translated this information into metrics that organizations can measure and track to ensure quality?

I ask since i very often hear rantings from dis-gruntled managers who just cannot put their finger on what quality really is. But some organizations like HoneyWell i hear has lots of numbers to track programmer performance, all of which translates to numbers and can be ticked off during appraisals. Hence my question to the community at large to bring out the stats they know of.

Suggestions about tools that can do a good job of measuring messy codes will help too.


q:
I have an existing standalone application which is going to be extended by a 3rd-party, using a network protocol. The capabilities are already implemented, all I need is to expose them to the outside.

Assuming the transport protocol is already chosen (UDP), are there any resources that will help me to design my application protocol?

There seems to be a lot of information about software design, but not on protocol design.
I've already looked at Application Protocol Design.

[A]
First off, UDP is primarily a one-way broadcast transport method. Also, it is
potentially lossy
, so you need to be able handle missing packets and out-of-order packets. If you need any level of reliability from UDP, or require two-way connections, you will end up needing just about everything from TCP, so you might as well go with that to start with and let the network stack take care of it.
Next up, if your data is potentially larger than a single IP packet then you will need some way of identifying the start and end of each packet, and a means of handling illegal or corrupt packets. I would recommend some kind of header with packet length, some kind of footer, and maybe a checksum.
Then you need some way of encoding the messages and responses. There are many RPC protocols around. You could look at SOAP, or design a custom XML-based protocol, or a binary one.


q:
I want to store a list of the following tuples in a compressed format and I was wondering which algorithm gives me

smallest compressed size

fastest de/compression

tradeoff optimum ("knee" of the tradeoff curve)

My data looks like this:

(<int>, <int>, <double>),
(<int>, <int>, <double>),
...
(<int>, <int>, <double>)

One of the two ints refers to a point in time and it's very likely that the numbers ending up in one list are close to each other. The other int represents an abstract id and the values are less likely to be close, although they aren't going to be completely random, either. The double is representing a sensor reading and while there is some correlation between the values, it's probably not of much use.

[A]
Since the "time" ints can be close to each other, try to only store the first and after that save the difference to the int before (delta-coding). You can try the same for the second int, too.
Another thing you can try is to reorganize the data from [int1, int2, double], [int1, int2, double]... to [int1, int1...], [int2, int2...], [double, double...].
To find out the compression range your result will be in, you can write your data into a file and download the compressor CCM from Christian Martelock
here
. I found out that it performs very well for such data collections. It uses a quite fast
context mixing
algorithm. You can also compare it to other compressors like WinZIP or use a compression library like zLib to see if it is worth the effort.


q:
I know Flex pretty good but also started to use Java FX. I am a little bit confused. Java FX seems to focus more on low level drawing operations and animations. Less on creating standard UIs like Flex.

So is JavaFX more like Flash than Flex?

On the other side JavaFX also supports Swing components as well as data binding, which makes it appear more like Flex.

[A]
I think JavaFX is more like Flex, because JavaFX is more about building applications than animations (which is, I gather, one of the sensitive distinctions between Flex and Flash).
I think of JavaFX and Flex as the future heirs to Rich Internet Application programming.  They're both intended to stretch the realm of what's possible with RIA.
One of the biggest benefits of JavaFX that I see is that
you can use your existing Java business logic by simply importing it
.
Some of the language features, such as
binding
and
duration as a data type
, are paradigm-shifting, because they make certain functionality possible and readily available:
Binding: Connecting two values together, so you can automatically update one value when the other updates.  Example: "name: bind textfield.getValue".  Much easier than setting up Observer patterns to watch for changes to variables.
Duration can be used as a data type: "var frameDelay = 5ms".  Having Duration as an integral part of the language seems like a no-brainer when dealing with animations.


q: Does anybody know how I can see the actual machine code that v8 generates from Javascript? I've gotten as far as Script::Compile() in src/api.cc but I can't figure out where to go from there.

[A]
You're on the right track, I think.
It looks like you need to get from Script::Compile to Compiler::Compile, which will lead you to the code generators (codegen*.cc and .h).
All of this to say that, looking at codegen-ia32.cc, if you define ENABLE_DISASSEMBLER
when you build, your disassembly should get printed, I think.
Of course, all of this is just from a quick browse of an old copy of the source I have here, so YMMV, but I think this should work.
(Looking at your post again, I see you're looking for the machine language, not the assembler -- I'm not sure, but you might have to modify the logic if you want the assembled code output rather than its disassembly)


q: I have huge number of Word files I need to merge (join) into one file, and will be time consuming to use the Word merger (one by one). Have you experienced any tool that can handle this job?

[A]
Have you tried using the Word COM api? You can automate lots of things - maybe you can automate a merge.
Do you really need to do an actual merge, or do you want to join the files together. The two things are quite different.
Merging is used when you have two versions of an original file with (potentially conflicting) changes. I can't really see how you would have a "huge number" of files that you needed to merge all together. This would be an absolute nightmare of conflicts. Do you mean to merge sets of them into individual files?
Joining would be when you want to concatenate them one after the other. This would be a lot easier to do. This is quite possible using the COM api.


q: What are the differences between MyISAM and Inno DB types in MySql?

[A]
The major difference is that InnoDB supports
transactions
, whereas MyISAM doesn't.


q: Does anyone know how function indexes work in databases?


q:
In Python, if I do this:

print "4" * 4

I get

> "4444"

In Perl, I'd get

> 16

Is there an easy way to do the former in Perl?

[A]
```
```
$ perl -e 'print "4" x 4; print "\n"'
4444
```
```
The x operator is documented in perldoc
perlop
. Here binary means an operator taking two arguments, not composed of bits, by the way.
Binary "x" is the repetition operator. In scalar context or if the
left operand is not enclosed in parentheses, it returns a string consisting
of the left operand repeated the number of times specified by the right
operand. In list context, if the left operand is enclosed in parentheses
or is a list formed by "
```
qw/STRING/
```
", it repeats the list. If the right
operand is zero or negative, it returns an empty string or an empty
list, depending on the context.
```
```
print '-' x 80;             # Print row of dashes

       print "\t" x ($tab/8), ' ' x ($tab%8);      # Tab over

       @ones = (1) x 80;           # A list of 80 1’s
       @ones = (5) x @ones;        # Set all elements to 5
```
```
```
perl -e
```
is meant to execute Perl code from the command line:
```
$ perl --help
Usage: perl [switches] [--] [programfile] [arguments]

  -e program     one line of program (several -e's allowed, omit programfile)
```


q:
In a database, I have a string that contains "default" written in it. I just want to replace that default with 0. I have something like:

select * from tblname where test = 'default'

I do not want quotes in the replacement for "default".

I want

select * from tblname where test = 0

is there any way to do this?

[A]
I think you would be better using format strings
```
```
string myVar = "0";
string sql = String.Format(@"select * from tblname where test = \"{0}\"", myVar);
```
```
You should also ask yourself why you are generating inline SQL on the fly and not using stored procedures as this is how SQL injection attacks can occur unless you sanitize the input.


q:
I am trying to let a piece of runtime state decide WHICH implementation of an interface to use, preferably solely by autowiring.

I have tried making an object factory for the interface thet uses dynamic proxies, and I used qualifiers to coerce the @Autowired injections to use the factory. The qualifiers are necessary because both the factory and the implementations respond to the same interface.

The problem with this is that I end up annotating every @Autowired reference with the @Qualifier. What I'd really want to do is annotate the non-factory implementations with something like @NotCandidateForAutowiringByInterface (my fantasy annotation), or even better make spring prefer the single un-qualified bean when injecting to an un-qualified field

I may thinking along the totally wrong lines here, so alternate suggestions are welcome.
Anyone know how to make this happen ?


q: How do you identify the file content as being in ASCII or binary using C++?

[A]
Well, this depends on your definition of ASCII. You can either check for values with ASCII code <128 or for some charset you define (e.g. 'a'-'z','A'-'Z','0'-'9'...) and treat the file as binary if it contains some other characters.
You could also check for regular linebreaks (0x10 or 0x13,0x10) to detect text files.


q:
I’m currently using the OpenNETCF.Desktop.Communication.dll to copy files from my desktop to a CE device, but I keep getting an error:

‘Could not create remote file’

My development environment is VS2005 (VB.NET)

My code:

ObjRapi.Connect()
ObjRapi.CopyFileToDevice("C:\results.txt", "\results.txt")
ObjRapi.Dispose()
ObjRapi.Disconnect()

Has anyone run into this and did you manage to get around it.

Thanks

[A]
I have run into this once before but I can't really remember what was causing it.
The only thing I can think of from looking at your code is this line:
```
```
ObjRapi.CopyFileToDevice("C:\results.txt", "\ \results.txt")
```
```
I'm not sure but you could try and change the destination path to something different. Something like this:
```
```
ObjRapi.CopyFileToDevice("C:\results.txt", "\My Documents\results.txt")
```
```
I can't really test this at the moment but I really don't see why it wouldn't work.
EDIT: I just had a look at some code that I have writen using the RAPI,when I do any copying my line looks like this:
```
```
ObjRapi.CopyFileToDevice("C:\results.txt", "\My Documents\results.txt",True)
```
```
The boolean on the end is an overwrite switch, setting that to true may work.


q:
On our build server, we've installed the .NET Framework 2.0 SDK in order to kick off MSBuild and run our builds. Now we are upgrading to the .NET Framework 3.5. We do not want to install the complete Visual Studio, but we cannot find a .NET Framework 3.5 SDK on the internet either?

The question: What do we need ot download and install to get the equivalent of a .NET Framework 3.5 SDK installation?

[A] .net 3.5 comes with compiler and msbuild bundled with it. just download the normal .net 3.5 framework (not the client profile) and you'll be fine.


q:
Just say I have a file: "HelloWorld.pm" in multiple subdirectories within a Git repository.

I would like to issue a command to find the full paths of all the files matching "HelloWorld.pm":

For example:

/path/to/repository/HelloWorld.pm
/path/to/repository/but/much/deeper/down/HelloWorld.pm
/path/to/repository/please/dont/make/me/search/through/the/lot/HelloWorld.pm

How can I use Git to efficiently find all the full paths that match a given filename?

I realise I can do this with the Linux/Unix find command but I was hoping to avoid scanning all subdirectories looking for instances of the filename.

[A]
Try:
```
```
git ls-tree -r HEAD | grep HelloWorld.pm
```
```


q:
It looks like all the methods for loading SQLite involve loading from a named file using a string.  I would like to load SQlite database from memory.

The database is already loaded into memory.

[A]
Use a special file name,
```
:memory:
```
```
```
sqlite3_open(":memory:", &db);
```
```
```
libsqlite
```
must have been compiled
without
```
SQLITE_OMIT_MEMORYDB
```
defined, as pointed out in
SQLite documentation
:
```
SQLITE_OMIT_MEMORYDB
```
When this is defined, the library does not respect the special database name
```
":memory:"
```
(normally used to create an in-memory database). If
```
":memory:"
```
is passed to
```
sqlite3_open()
```
,
```
sqlite3_open16()
```
, or
```
sqlite3_open_v2()
```
, a file with this name will be opened or created.
If you want to read the database that is
already
fully loaded into memory however, it will be more work. You will have to implement a custom VFS layer to operate on memory files and register it with your SQLite context.
See:
```
sqlite3_vfs
```
```
sqlite3_io_methods
```
I have not implemented it myself, so I can't reliably tell whether you have to implement the entire new VFS layer, or you can get away with substituting some functions in the default one (latter is unlikely).


q:
Outlook 2007 shows pictures of contacts on the right hand side of the mail form. This only works for your personal contacts and if you have photos.

Is there a way to hook that picture up to the GAL or AD for the company so that all employees photos show automatically?  Hopefully without having to write and deploy a new msg form.

[A]
To store a photo in AD, you can use the
```
jpegPhoto
```
attribute (see
formal description in MSDN
). Here is
a way to do it using VBScript
, and here's one to
do it using VB.NET
.
I'm not sure Outlook 2007 makes use of this value (my guess is - it does not), but it's worth a try. My guess is even that Outlook does not care about the
```
jpegPhoto
```
if you put someone from the GAL to your personal address book. Anyway, this should be easy enough to test.
If all else fails, you are stuck with either making clear that it doesn't work or building a custom form that reads the value.


q:
I'm looking for a Windows tool that is able to log every action (read & write) that were made to a specific path inside the local Filesystem in order to debug a program (find out why it is sometimes slow and sometimes not).
In theory it could work like a virus scanner that is recognizing every file that any of the running programs do read or write and logs every thing that it sees.


q: How to perform validation for a radio button group (one radio button should be selected) using jQuery validation plugin?

[A]
use the following rule for validating radio button group selection
```
```
myRadioGroupName : {required :true}
```
```
myRadioGroupName is the value you have given to name attribute


q:
Now I know that bigint is 2^64; that is, more atoms than there are in the known universe.  I shouldn't be worried, as my mere human brain simply can't get around the enormity of that number.

However, let's say that I record every change to every category, product and order in my system, from launch until the end of time.  Should I be concerned about the performance of table writes before I worry about running out of primary key values?  Should I record events of different priorities to different event tables?  Will I run out of atoms on a hard drive before I run out of bigints?  How big should I let an event log table get before I start archiving / clearing it out?

[A] Even if every of your entries only had 1 byte, 2^64 entries would occupy around 18000000 TB on your hard drive, so I guess you shouldn't worry about this.


q:
What exactly is a learning curve?

And why is it wrong to use the term "steep learning curve" for something which has high entry barriers and takes quite some time to get into?

As to the why-ness of this question:

The terms are used often and inconsistently on Stack Overflow

I myself have been confused by it

Mostly the newbies are confronted with these terms when they for example ask questions like "what's the best php development framework"

[A]
from Widipedia:
The term learning curve refers to the
  graphical relation between the amount
  of learning and the time it takes to
  learn.
The term "steep learning curve" is often
wrongly
used for things which need some time to wrap ones mind around. Also here on Stack Overflow I've seen it used wrongly many times and hence this Question and my own answer to it.
In fact a steep learning curve is given, when it is relatively easy to start of with a new skill/technique/...
it means that the relationship between "learning progress (y)" and "time invested (x)" is greater than 1.


q:
I am working on a database that usually uses GUIDs as primary keys.

By default SQL Server places a clustered index on primary key columns. I understand that this is a silly idea for GUID columns, and that non-clustered indexes are better.

What do you think - should I get rid of all the clustered indexes and replace them with non-clustered indexes?

Why wouldn't SQL's performance tuner offer this as a recommendation?

[A]
The problem with clustered indexes in a GUID field are that the GUIDs are random, so when a new record is inserted, a significant portion of the data on disk has to be moved to insert the records into the middle of the table.
However, with integer-based clustered indexes, the integers are normally sequential (like with an
```
IDENTITY
```
spec), so they just get added to the end an no data needs to be moved around.
On the other hand, clustered indexes are not always bad on GUIDs... it all depends upon the needs of your application.  If you need to be able to
```
SELECT
```
records quickly, then use a clustered index... the
```
INSERT
```
speed will suffer, but the
```
SELECT
```
speed will be improved.


q: While calculating the hash table bucket index from the hash code of a key, why do we avoid use of remainder after division (modulo) when the size of the array of buckets is a power of 2?

[A]
When calculating the hash, you want as much information as you can cheaply munge things into with good distribution across the entire range of bits: e.g. 32-bit unsigned integers are usually good, unless you have a lot (>3 billion) of items to store in the hash table.
It's converting the hash code into a bucket index that you're really interested in. When the number of buckets n is a power of two, all you need to do is do an AND operation between hash code h and (n-1), and the result is equal to h mod n.
A reason this may be bad is that the AND operation is simply discarding bits - the high-level bits - from the hash code. This may be good or bad, depending on other things. On one hand, it will be very fast, since AND is a lot faster than division (and is the usual reason why you would choose to use a power of 2 number of buckets), but on the other hand, poor hash functions may have poor entropy in the lower bits: that is, the lower bits don't change much when the data being hashed changes.


q:
I am having a number of panels in my page in which I am collecting user information and saving the page details. The page panel has textbox, dropdown list, listbox.

When I need to come to this page. I need to show the Page if these controls have any values. How to do this?

[A]
It boils down to enumerating all the controls in the control hierarchy:
```
```
IEnumerable<Control> EnumerateControlsRecursive(Control parent)
    {
        foreach (Control child in parent.Controls)
        {
            yield return child;
            foreach (Control descendant in EnumerateControlsRecursive(child))
                yield return descendant;
        }
    }
```
```
You can use it like this:
```
```
foreach (Control c in EnumerateControlsRecursive(Page))
        {
            if(c is TextBox)
            {
                // do something useful
            }
        }
```
```


q:
I've always wondered why the C++ Standard library has instantiated basic_[io]stream and all its variants using the char type instead of the unsigned char type. char means (depending on whether it is signed or not) you can have overflow and underflow for operations like get(), which will lead to implementation-defined value of the variables involved. Another example is when you want to output a byte, unformatted, to an ostream using its put function.

Any ideas?

Note: I'm still not really convinced. So if you know the definitive answer, you can still post it indeed.

[A]
Possibly I've misunderstood the question, but conversion from unsigned char to char isn't unspecified, it's implementation-dependent (4.7-3 in the C++ standard).
The type of a 1-byte character in C++ is "char", not "unsigned char". This gives implementations a bit more freedom to do the best thing on the platform (for example, the standards body may have believed that there exist CPUs where signed byte arithmetic is faster than unsigned byte arithmetic, although that's speculation on my part). Also for compatibility with C. The result of removing this kind of existential uncertainty from C++ is C# ;-)
Given that the "char" type exists, I think it makes sense for the usual streams to use it even though its signedness isn't defined. So maybe your question is answered by the answer to, "why didn't C++ just define char to be unsigned?"


q:
3/10/2008 = 1822556159

2/10/2008 = 1822523391

1/10/2008 = 1822490623

30/09/2008 = 1822392319

29/09/2008 = 1822359551

This is all the information that I know at the current time.

Dates increment by 32768 except when changing month when the increment is 32768 x 2 (65536).

Has anyone seen this binary date format and how can I extract the correct date?

It is possible that the remaining portion of the date is for time (hours, minutes, seconds)

[A]
September 30th 2008
```
```
1822392319 = 0x6c9f7fff
0x6c = 108 = 2008 (based on 1900 start date)
0x9 = 9 = September
0xf7fff - take top 5 bits = 0x1e = 30
```
```
October 1st 2008
```
```
1822490623 = 0x6ca0ffff
0x6c = 108 = 2008
0xa = 10  = October
0x0ffff  - take top 5 bits = 0x01 = 1
```
```
It's anyone's guess what the remaining 15 one-bits are for, if anything.
EDIT:  by take top 5 bits I mean:
```
```
day_of_month = (value >> 15) & 0x1f
```
```
Similarly:
```
```
year = (value >> 24) & 0xff + 1900
month = (value >> 20) & 0x0f
```
```


q:
I'm passing small (2-10 KB)XML documents as input to a WCF service. now I've two option to read data values from incoming XML

Deserialize to a strongly typed object and use object properties to access values

use XPath to access values

which approach is faster? some statistics to support your answer would be great.

[A]
There's a third option of sticking with XML, but query with whatever XML API you're using - e.g. LINQ to XML makes queries relatively straightforward in code.
Have you already parsed the text into an XML document?
Are you convinced that this is actually a significant performance bottleneck in your code? (e.g. if you're then talking to a database, then don't worry about this to start with - just get it to work in the simplest way first)
Are the queries always the same, or are they dynamic in some way?
Do you have a test rig with realistic messages and queries? If not, you need one in order to evaluate any answers given here with
your
data. If you do, I would expect it to be reasonably easy to try it yourself :)


q:
i tried the following

svnadmin create svn_repos

svn import my_first_proj file:///c:/svn_repos -m "initial import"

svn checkout file:///c:/svn_repos

and the command returned

A    svn_repos\trunk
A    svn_repos\trunk\Sample.txt.txt
A    svn_repos\branches
A    svn_repos\branches\my_pers_branch
Checked out revision 1.

Yet the .svn folder was not created in the checked out folders.
Because of which [I guess], I'm not able to do svn  copy or svn merge.

Why does this occur?
what is the problem?
is there anything wrong in my commands

[A]
Are you sure it's not just hidden (they are by default)?
Try running
```
dir /AH
```


q:
I am trying to use the Recurring payment API offered by PayPal.
I have a scenario which I am not able to address directly. It goes like this.

We have a website where we sell some services. Now the services are charged per user license. A user can buy/cancel user license in between. We want to offer the customer a recurring billing option. We have to notice here that the amount may vary each billing cycle based on the number of user licenses the customer uses during that cycle.

Is there any way I can achieve this using PayPal recurring Payment API's.

[A]
The recurring payment option is a fixed amount that the customer pre-agrees to pay each month (or period).  To do what you're trying to do, a customer would have to pre-agree to pay whatever amount you decide to charge at a later time.  This means pre-authorizing an unknown payment amount, which will not be allowed by any payment service.
Your only options are:
Bill the variable amount each month (i.e. no subscription).
Set up a subscription where the monthly amount is the maximum that could potentially be billed, and then refund the difference each month.
Good luck with #2 - I would never agree to such a thing as a customer, personally.


q: In particular what strengths does it have over caching features of Asp.net

[A]
memcached is a distributed cache -- the whole cache can be spread into multiple boxes. so for example you can use memcached to store session data in cluster environment, so this data is available to any box of the cluster.
memcached can be compared to Microsoft's Velocity (
http://blogs.msdn.com/velocity/
).


q: How do I create, execute and control a winform from within a console application?

[A]
The easiest option is to start a windows forms project, then change the output-type to Console Application. Alternatively, just add a reference to System.Windows.Forms.dll, and start coding:
```
```
using System.Windows.Forms;

[STAThread]
static void Main() {
    Application.EnableVisualStyles();
    Application.Run(new Form()); // or whatever
}
```
```
The important bit is the
```
[STAThread]
```
on your
```
Main()
```
method, required for full COM support.


q:
I'm using Java's Transformer class to process an XML Document object.

This is the code that creates the Transformer:

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

transformer.transform(source, result);

Currently, my output looks like this: <svg ... />. I'd like it to include the namespace of each element, as in <svg:svg ... />

How can I do that ?

[A]
The package description for
javax.xml.transform
has a section
Qualified Name Representation
which seems to imply that it is possible to get the namespace represented in both input and output.
It isn't really clear to me what the result would look like, other than the namespace URI would be included.
Give it a try - hopefully someone else will have more concrete experience.


q:
Is there a catch or hidden problem in using a DisposableBase base class instead of recoding the Dispose pattern on every class?

Why aren't everyone using such a relevant class?

Edits:

I naturally only meant classes that implement IDisposable

I know it uses up the option for inheritance, but I'm willing to pay the price (at least when I can and it doesn't hurt me otherwise).

When I can seal the class, I do - but I have some cases where I want the base of an inheritance hierarchy to be Disposable.

[A]
You don't need to implement Dispose() on
every
class - just those with something that needs deterministic cleanup. Re a Disposable base-class, I'm not entirely sure it provides a whole lot -
```
IDisposable
```
isn't a complex interface. The main time it might be useful is if you are handling unmanaged resources and want a finalizer, but even then it isn't much code.
Personally, I wouldn't bother with such a base class. In particular, inheritance (in a single-inheritance world) gets restrictive very quickly. But more to the point, overriding a method isn't much different to simply providing a public Dispose() method.
Again: you only need a finalizer etc if you are handling unmanaged objects.
If I had a lot of these (unmanaged resouces), I might see whether I could get
PostSharp
to do the work for me. I don't know if one already exists, but it
might
be possible to create an aspect that handles (in particular) the finalizer etc. Who knows...


q:
I have a DAV server (Oracle Portal in this case). If I open word and then enter the DAV URL of a document, I'm correctly prompted for username/password and the document is checked out. I can edit it and just click Save to save it back to the server. So far, so good.

What I need is a link on a web page that will open the document for editing in Word. If I just use the same URL as I use in the File Open dialog in Word, I get a read-only copy, and the File Save dialog suggests to save it locally.

Is there a way to open a document for DAV editing directly from a hyperlink?

[A]
No. The dav protocol uses standard HTTP transactions, and unless the client is aware of the support for DAV, it won't know to use it.
Word is likely not DAV aware, and you're relying on people mounting DAV devices as a mounted network drive.
IE: As far as words concerned, its just like any other URL.
( Unless there is a way to tell word its specifically on a DAVFS system, via a url with a different protocol specifier, for example  davfs://www.google.com/  if davfs happened to be a registered protocol that your client recognised, this of course makes too much sense, and for that reason alone, you are unlikely to find it supported in windows )


q:
I need to check the RequestType of an HttpRequest in ASP.NET (or WebRequest.Method). I know that I can just use the string values "POST" or "GET" for the request type, but I could have sworn there was a constant somewhere in some class in .NET that contained the values.

Out of curiosity I was wondering if anyone knew what class these string constants for GET and POST were in. I've tried searching online but I've had no luck, so I thought I'd ask here.

[A]
```
```
System.Net.WebRequestMethods.Http
    .Connect = "CONNECT"
    .Get = "GET"
    .Head = "HEAD"
    .MkCol = "MKCOL"
    .Post = "POST"
    .Put = "PUT"
```
```
Ultimately, though; since
```
const
```
expressions are burned into the caller, this is identical to using "GET" etc, just without the risk of a typo.


q:
Is it alright to do this?

$author = strtolower($_SESSION['valid_username']);

I want to enter all authors into the table as lower case.

[A]
Yes, that's fine as long as
```
$_SESSION['valid_username']
```
is set, otherwise you'll get a notice (if your error reporting is set that low).
You can check if it exists with
```
if (isset($_SESSION['valid_username']))
```


q:
How can we find the junit tests in our suite that take the longest amount of time to run?  The default output of the junitreport ant task is helpful, but our suite has thousands of tests organized into many smaller suites, so it gets tedious, and the worst offenders are always changing.

We use luntbuild but ideally it would be something we could just run from ant.

[A]
Use
TeamCity
. They have great reports, and version 4.0 even orders your tests so the most flaky tests run first.


q:
I'm trying to expand navigation options of the context menu on certain elements (specifically, h1 and h2 tags)
I want to prevent the browser's default action when right-clicking on those elements.

I found nice information at this page.

However, I couldn't find how to disable the context menu for certain elements. Does someone know how to do it?

I'm using prototype as my javascript API.

[A]
This will prevent the context menu from appearing on a particular element
```
```
$(it).observe("contextmenu", function(e){
    e.stop();
});
```
```
So, for example stop all H1/H2 tags from showing a context menu
```
```
$$('h1, h2').each(function(it){
    $(it).observe("contextmenu", function(e){
        e.stop();
    });
})
```
```


q: My huge 32-bit web services LLBLGen-based data access application is running alone on a dedicated 64-bit machine. Its physical memory consumption steadily grows up to approximately 2GB when the process releases almost all of the allocated space (up to 1,5GB) and continues to grow from that point again. There is no observable increase in Page Input values or other page file usage parameters so it looks like the memory is released rather than being swapped out to page file. I am thinking what kind of profile is this? There is nothing to actually prevent the process from grabbing all memory it can, on the other hand there are unacceptable http internal errors around the memory release - probably the clean-up blocks useful work. What would be a good strategy to make the cleanup less obtrusive, given the above is an acceptable behaviour in the first place.

[A]
The Garbage Collector doesn't automatically free memory when it releases objects, it holds on to that memory to help minimise the expense of future mallocs.
When a low memory condition is triggered that memory will be returned to the OS and you will see more available memory when looking through task manager.  This will normally happen about the 2GB mark, or 3GB if you use the
relevant switch
.
```
<contentious>
```
By setting objects to null when they are dead you can encourage the GC to reuse the memory consumed by those objects, this limiting the growing consumption of memory.
But which objects should you set to null?  Big objects, large collections, frequently created objects.
```
</contentious>
```
EDIT
: There is evidence to support the value of setting objects to null.  See
this
for detail.  Of course there is no
need
to set objects to null, the point is does it help memory management in any way?
EDIT
: We need a recent benchmark if such a thing exists rather than continuing to opine.


q: What is the functional equivalent of Windows Communication Foundation in Java 6?

[A]
I don't know what all WCF contains, but
JAX-WS
(and its reference implementation
Metro
) might be a good starting point.
Some of the other
technologies in J2EE
may apply as well.


q:
I would like to hear opinions or peoples experiences regarding Rel.  Is it destined for the dustbin, or is it the next big thing in programming?  I haven't tried doing anything with it yet (and it looks like you really can't at this point), but I'm intrigued by a few of the concepts discussed in it.  Notably:

Removal of nulls completely from the data handling part of the language.

No need for mapping types between the language and the data storage.

Nesting tables

Complete separation of design and implementation.

Thoughts?

[A]
I think it is intended as an aid to
teaching
the pure relational model, not as a competitor to SQL DBMSs for "real work" in the short or medium term.  However, Date and Darwen make a compelling case for the proper implementation of the relational model in their book
The Third Manifesto
.  Maybe one day someone will produce a successful product based on it.  After all, Oracle was a very small, niche company once!


q:
I have a table of events with a recorded start and end time as a MySQL DATETIME object (in the format YYYY-MM-DD HH:MM:SS. I want to find all events that occur in a specific date range. However, events can span multiple days (and go outside of my date range, but I want to return them if they even overlap by 1 second or more with my date range).

Suggestions?

[A]
```
```
SELECT *
FROM table
WHERE startdate >= 'starting date' AND startdate < 'ending date'
    OR enddate >= 'starting date' AND enddate < 'ending date'
```
```
should work for you.
Make sure you specify 'starting date' and 'ending date' with the time included.
```
```
'2008-01-01 00:00:00'' AND '2008-01-31 23:59:59'
```
```
This will help to avoid errors where dates are the same, but your time falls within the interval by a few hours, minutes, or seconds.


q:
Do you know of a JAXB setting to prevent standalone="yes" from being generated in the resulting XML?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

[A]
This property:
```
```
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false);
```
```
...can be used to have no:
```
```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
```
```
However, I wouldn't consider this best practice.


q:
I know that to find all the .h files I need to use:

find . -name "*.h"

but how to find all the .h AND .cpp files?

[A]
```
```
find . -name \*.h -print -o -name \*.cpp -print
```
```
or
```
```
find . \( -name \*.h -o -name \*.cpp \) -print
```
```


q:
I have an authentication script (CheckLogin.aspx), and if any of the credentials do not match my application will redirect (via Server.Transfer) to the access denied page (forbidden.aspx).  Each time my script runs,it gets an InvalidOperationException: Failed to map the path '/forbidden.aspx'.  Here is a mockup of my applications file structure:

<root>
..default.aspx
..forbidden.aspx
..<inc>
....scripts.js
..<auth>
....CheckLogin.aspx

As you can see, the CheckLogin.aspx page is in a folder inside the root, and the forbidden.aspx page is inside the root itself.  The path I am telling my application to redirect to is /forbidden.aspx.

[A]
Sometimes you have to precede the page path with a tilde to indicate the root directory:
```
```
'~/forbidden.aspx'
```
```


q:
I'm working with a third party to integrate some of our systems with theirs and they provide us with a SOAP interface to make certain requests and changes in their connected systems. The problem for me is that they do not supply a WSDL-file for me to work against. If I had a WSDL-file it would be a simple matter just to run the supplied .NET command (wsdl.exe) and generate a proxy class to interact with the service.

Is there an "easy" way to do this without a WSDL-file? I have all the functions that we can access and what parameters I need to send and what I should expect in return.

Is it common to have a SOAP-service without WSDL-files? (I'm asking this since we're going to add more external systems into the mix in the future)

Has anyone done a proxy-class or any other form of client against a WDSL-less service and have any good pointers on how to do it?

[A]
I haven't built a SOAP interface without access to a WSDL file, but the format is
fairly well-documented
.  Your best bet might be to create a simplified WSDL file of your own that reflects what you know of the service you're subscribing to....
If you decide to go this route, an
existing stackoverflow question
points at some tools for validating your WSDL.


q:
I want to get the overall total CPU usage for an application in C#. I've found many ways to dig into the properties of processes, but I only want the CPU usage of the processes, and the total CPU like you get in the TaskManager.

How do I do that?

[A]
You can use the
PerformanceCounter
class from
System.Diagnostics
.
Initialize like this:
```
```
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;

cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
```
```
Consume like this:
```
```
public string getCurrentCpuUsage(){
            return cpuCounter.NextValue()+"%";
}

public string getAvailableRAM(){
            return ramCounter.NextValue()+"MB";
}
```
```


q:
I've been using Git on Windows (msysgit) to track changes for some design work I've been doing.

Today I've been working on a different PC (with remote repo brian) and I'm now trying to merge the edits done today back into my regular local version on my laptop.

On my laptop, I've used git pull brian master to pull the changes into my local version. Everything was fine apart from the main InDesign document - this shows as a conflict.

The version on the PC (brian) is the latest one that I want to keep but I don't know what commands tells the repo to use this one.

I tried directly copying the file across onto my laptop but this seems to break the whole merge process.

Can anyone point me in the right direction?

[A]
You have to resolve the conflict manually (copying the file over) and then commit the file (no matter if you copied it over or used the local version) like this
```
```
git commit -a -m "Fix merge conflict in test.foo"
```
```
Git normally autocommits after merging, but when it detects conflicts it cannot solve by itself, it applies all patches it figured out and leaves the rest for you to resolve and commit manually. The
Git Merge Man Page
, the
Git-SVN Crash Course
or
this
blog entry might shed some light on how it's supposed to work.
Edit:
See the post below, you don't actually have to copy the files yourself, but can use
```
```
git checkout --ours -- path/to/file.txt
git checkout --theirs -- path/to/file.txt
```
```
to select the version of the file you want. Copying / editing the file will only be necessary if you want a mix of both versions.
Please mark mipadis answer as the correct one.


q: What is a good way to create and read an OpenOffice spreadsheet in Perl?

[A]
OpenOffice supports a number of formats, if you are looking for something that can read/write Excel-compatible spreadsheets check out
Spreadsheet::ParseExcel
for reading, and
Spreadsheet::WriteExcel
for writing.  I have used them both, they are pretty mature and work well.


q: and to spice things a bit , what is the best approach for globalization in Asp.net Mvc App

[A]
From the
W3C I18n FAQ
:
Localization refers to the adaptation of a product, application or document content to meet the language, cultural and other requirements of a specific target market (a "locale").
Internationalization (or globalization) is the design and development of a product, application or document content that enables easy localization for target audiences that vary in culture, region, or language.
I've never globalized an ASP.NET MVC application, so sorry if I can't help you there.


q:
I am using some custom controls one of which is a tooltip controller that can display images, so I am using th ebelow code to instantiate it:

Image newImage = Image.FromFile(imagePath);
e.ToolTipImage = newImage;

obviously could inline it but just testing at the moment. The trouble is the image is sometimes the wrong size, is there a way to set the display size. The only way I can currently see is editing the image using GDI+ or something like that. Seems like a lot of extra processing when I am only wanting to adjust display size not affect the actual image.

[A]
Once you have an image object loaded from its source, the Height and Width (and Size, and all ancillary properties) are read-only. Therefore, you are stuck with GDI+ methods for resizing it in RAM and then displaying it accordingly.
There are a lot of approaches you can take, but if you were to encapsulate that out to a library which you could reuse should this problem occur again, you'll be set to go. This isn't exactly optimized (IE, may have some bugs), but should give you an idea of how to approach it:
```
```
Image newImage = Image.FromFile(myFilePath);
Size outputSize = new Size(200, 200);
Bitmap backgroundBitmap = new Bitmap(outputSize.Width, outputSize.Height);
using (Bitmap tempBitmap = new Bitmap(newImage))
{
    using (Graphics g = Graphics.FromImage(backgroundBitmap))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        // Get the set of points that determine our rectangle for resizing.
        Point[] corners = {
            new Point(0, 0),
            new Point(backgroundBitmap.Width, 0),
            new Point(0, backgroundBitmap.Height)
        };
        g.DrawImage(tempBitmap, corners);
    }
}
this.BackgroundImage = backgroundBitmap;
```
```
I did test this, and it worked. (It created a 200x200 resized version of one of my desktop wallpapers, then set that as the background image of the main form in a scratch WinForms project. You'll need
```
using
```
statements for
```
System.Drawing
```
and
```
System.Drawing.Drawing2D
```
.


q:
What is the string concatenation operator in Oracle SQL?

Are there any "interesting" features I should be careful of?

(This seems obvious, but I couldn't find a previous question asking it).

[A]
It is
```
||
```
, for example:
```
```
select 'Mr ' || ename from emp;
```
```
The only "interesting" feature I can think of is that
```
'x' || null
```
returns
```
'x'
```
, not
```
null
```
as you might perhaps expect.


q:
I realize that this would be COMPLETELY bad practice in normal situations, but this is just for a test app that needs to be taking input from a bar code scanner (emulating a keyboard).  The problem is that I need to start up some scripts while scanning, so I need the window to regain focus directly after I click the script to run it.  I've tried using Activate(), BringToFront(), Focus() as well as some Win32 calls like SetForegroundWindow(), Setcapture() and SetActiveWindow()... however the best I can get any of them to do is to make the taskbar item start blinking to tell me that it wants to have focus, but something is stopping it.  BTW, I'm running this on XP SP2 and using .NET 2.0.

Is this possible?

Edit: To clarify, I am running the scripts by double-clicking on them in explorer.  So I need it to steal focus back from explorer and to the test app.

[A]
Visibility
Make the window a "Top-Most" window.  This is the way the Task-Manager can remain on top of other windows.  This is a property of a
```
Form
```
and you make the form top-most (floating above other windows) by setting the value to
```
true
```
.
You shouldn't need to override any of the "Active window" behaviour with the top-most setting.
Focus
I asked a similar question
previously here on StackOverflow
and the answer would solve your problem.  You can make the application use a low-level input hook and get notification of the key-codes coming from the scanner.  This way, your application always gets these keys even though the application does not have focus.
You may need to enhance the solution to squash the key-codes so that they are not transmitted to the "in-focus" application (e.g. notepad).
Since Windows 2000, there is no official mechanism for an application to grab focus without direct intervention of the user.  Peeking at the input streams through the RawInputDevices hook is the only sensible way to go.
A number of articles may help (C# implementations)
RawInput article on CodeProject
MSDN documentation of RawInput


q:
I'm trying to write an iterator for results from a PDO statement but I can't find any way of rewinding to the first row. I would like to avoid the overhead of calling fetchAll and storing all the result data.

// first loop works fine
foreach($statement as $result) {
    // do something with result
}

// but subsequent loops don't
foreach($statement as $result) {
    // never called
}

Is there some way of reseting the statement or seeking the first row?

[A]
You'll probably want to take a look at some of the PHP SPL classes that can be extended to provide array-like access to objects.
Standard PHP Library (SPL)
I would specifically
recommend that you look at the
ArrayIterator, ArrayObject, and
perhaps the Iterator interface.
Simple
Tutorial
Another
Quick Tutorial


q: Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?

[A]
Here's how to add a value at the top of the list. It can be an empty string, or some text.
```
```
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
    <asp:ListItem Value="-1">
       -- Choose a Category --
    </asp:ListItem>
</asp:DropDownList>
```
```
Be sure to set the DropDownList's AppendDataBoundItems=True.


q:
The new Vista Audio subsystem is set up to be a chain of devices starting with the inputs, going through all the various controls (like mixers and volumen controls) and then ending up at various endpoints (like speakers or headphones).

My question is: Is there a tool out there that will show all the endpoints devices in the system, and what devices are chained together?  Ideally, it would diagram the topology, showing what inputs where connected to what outputs, and you would be able to see all the properties for each part of the audio system.


q: What is the best way to stop a user from resizing the top-level window of an application written in WPF?

[A]
You will want to use the
```
ResizeMode.NoResize
```
on the window.
```
```
<Window x:Class="WpfApplication5.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    ResizeMode="NoResize">
</Window>
```
```


q:
I have Visual Studio setup with a VSTO word project, and when I hit run it runs fine.

But, how do I setup a word document to use my code without having Visual Studio running?

[A]
RubyCocoa is not supported at all on the iPhone. There is no bridge support library, and I do not believe there is any ruby interpreter on the phone.
You might be able to get it working in the simulator, it will not stop you from using OS X only libraries if you really try, but that still will not make it work on the iPhone.
If you really want to use RubyCocoa on the iPhone you will need to build ruby as a static library and port the bridge to the phone, which is doable, but would probably be very difficult.


q:
How would you render a tag cloud within a .NET 2.0+ WinForm application?

One solution that I am thinking of would be using the WebBrowser control and generating to some ad-hoc HTML, but that seems to be a pretty heavy solution.

Am I missing something more simple?

[A]
Well, you'll want a control with these major features:
Automatic layout of variable sized string snippets
Automatic mouse hit testing
Those are a bit hard to come by in WF controls.  A RichTextBox with ReadOnly = true gives you the automatic layout, but not the hit testing.  A ListBox with DrawItem can give you variable sized strings and hit testing, but not a natural layout.
I think I would use RTB and make hit testing work with the MouseDown event and GetCharIndexFromPosition(), reading back the tag at the clicked location.  You'll need a bit of logic to find the starting and ending white space around the word.


q: C# What is the easiest way to disable a control after 10 seconds? Using a Timer or a stopwatch? I'm new to both so thanks for the help.

[A]
Use a timer. It suits your needs better.
EDIT: As other have said, go with the
```
System.Windows.Forms.Timer
```


q:
I'm starting a project which I think would benefit from bindings (I've got a source list table, several browser views, etc), but I think it would also be quite doable, and perhaps more understandable, without them. From my limited experience I've found bindings to be difficult to troubleshoot and very "magic" (e.g. it's difficult to insert logging anywhere to figure out where stuff is breaking, everything either works or it doesn't).

Is this just my inexperience talking (in which case I could sit down and spend some time just working on my understanding of bindings and expect things to start becoming clearer/easier) or would I be better off just writing all the glue code myself in a manner which I was sure I could understand and troubleshoot.

[A]
Bindings can seem magical in nature. To understand the magic behind bindings, I think one must understand KVC/KVO thoroughly. I really do mean thoroughly.
However, in my case (new to Obj-C -- 9 months), once I got KVC/KVO bindings was a thrill. It has significantly reduced my glue code and made my life significantly easier. Debugging bindings became a case of making sure my key-value changes were observable. I find that I am able to spend more time writing what my app is supposed to do rather than making sure the view reflects the data.
I do agree though that bindings is highly intimidating at first.


q:
I'm trying to animate Visio objects with a loop, such as:

For reposition = 2 To 6
    xpos = reposition
    ypos = reposition

    sh1.SetCenter xpos, ypos

    Sleep 1000

Next reposition

While this DOES move the object from the starting position to the ending, the intermediate steps are not visible. After a delay only the final position is displayed.

If I put a MsgBox in the loop then each intermediate position is visible but one must click a distracting, center-positioned box in order to see these.

How can I make the flow visible without user interaction and covering of the screen by a modal window?

[A]
Try a
```
DoEvents
```
statement before your sleep


q:
You are given a 32-bit unsigned integer array with length up to 232, with the property that more than half of the entries in the array are equal to N, for some 32-bit unsigned  integer N. Find N looking at each number in the array only once and using at most 2 kB of memory.

Your solution must be deterministic, and guaranteed to find N.

[A]
Keep one integer for each bit, and increment this collection appropriately for each integer in the array.
At the end, some of the bits will have a count higher than half the length of the array - those bits determine N. Of course, the count will be higher than the number of times N occurred, but that doesn't matter. The important thing is that any bit which isn't part of N
cannot
occur more than half the times (because N has over half the entries) and any bit which is part of N
must
occur more than half the times (because it will occur every time N occurs, and any extras).
(No code at the moment - about to lose net access. Hopefully the above is clear enough though.)


q:
At my current job we have a CMS system that is .NET/SQL Server based. While customizing a couple of the modules for some internal use, I was a little surprised to see that instead of having APIs that returned data via your typical result set that was bound to a DataGrid/DataList/Repeater control, that the APIs returned an XML node/collection, that was then passed to an XSLT transformation and rendered on the page that way.

What are the benefits to using a model like this?


q: I have written a simple PowerShell filter that pushes the current object down the pipeline if its date is between the specified begin and end date.  The objects coming down the pipeline are always in ascending date order so as soon as the date exceeds the specified end date I know my work is done and I would like to let tell the pipeline that the upstream commands can abandon their work so that the pipeline can finish its work.  I am reading some very large log files and I will frequently want to examine just a portion of the log.  I am pretty sure this is not possible but I wanted to ask to be sure.

[A]
It is not possible to stop an upstream command from a downstream command.. it will continue to filter out objects that do not match your criteria, but the first command will process everything it was set to process.
The workaround will be to do more filtering on the upstream cmdlet or function/filter.  Working with log files makes it a bit more comoplicated, but perhaps using Select-String and a regular expression to filter out the undesired dates might work for you.
Unless you know how many lines you want to take and from where, the whole file will be read to check for the pattern.


q:
After some time I wanted to update my git repo, and then something went wrong. What is the proper way out of this situation?

mblsha@siruba:~/src/psi/ $ git status
iris: needs merge
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   src/common.cpp
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#
#   unmerged:   iris
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   gupdate.sh
mblsha@siruba:~/src/psi/ $ git submodule status
+cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master)
+cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master)
+cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master)
mblsha@siruba:~/src/psi/ $ cd iris
mblsha@siruba:~/src/psi/iris/ $ cat .git/HEAD
cf237ef8f3d9dc058dbde47e6973e6388608ce60

[A]
When it comes to git submodules, almost any problem you encounter can be solved by:
```
```
1. deleting the submodule (rm -r iris)
2. recreating it again (git submodule update)
```
```
Obviously if you have made local changes to your submodule this will DELETE them PERMANENTLY, so if you have local changes make sure you have pushed them first.


q:
I'm looking for a method to reliably extract the host name from a URL string in Ruby.

e.g.
http://www.mglenn.com/directory = www.mglenn.com
OR
http://www.mglenn.com?param=x = www.mglenn.com

[A]
You could try something like this:
```
```
require 'uri'

myUri = URI.parse( 'http://www.mglenn.com/directory' )
print myUri.host
# =>  www.mglenn.com
```
```


q:
We've converted our solution from .NET 2.0 to .NET 3.5. All projects converted just fine except for the Website Project, which still doesn't understand what I mean when using 'var' and the like.

I've looked in the property pages for the web project, and the Target Framework is set to '.NET Framework 3.5'.

Any other ideas?

[A]
By default, a new web app in 3.5 has the following References:
System System.Configuration
System.Core
System.Data
System.Data.DataSetExtensions
System.Drawing
System.EnterpriseServices
System.Web
System.WebExtensions
System.Web.Mobile
System.Web.Services
System.Xml
System.Xml.Linq
in addition, in the web.config file, you'll find the following assembly information near the top of your web.config file:
```
```
<assemblies>
      <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    </assemblies>
```
```
and you will also find the runtime assembly binding found at the bottom of the file:
```
```
<runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
          <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
          <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
        </dependentAssembly>
        <dependentAssembly>
          <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
          <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
        </dependentAssembly>
      </assemblyBinding>
    </runtime>
```
```
I'm wagering that not having all of these references is causing issues with your var declarations. Verify all of these contents were properly added/created.


q:
I must be overlooking something simple. I'm setting a variable from a query result in a MySQL stored procedure like this:

SELECT @myName := username FROM User WHERE ID=1;

So, @myName is storing the username of userid 1, which is 'Paul'. Great.

But later in the stored procedure I run an update on this record:

UPDATE User SET username = 'Fred' WHERE ID=1;

Now, for some reason, @myName = 'Fred' when it should still equal 'Paul', right? It appears MySQL is just creating a pointer to the record rather than storing a static value in the @myName variable.

So in short, I want to be able to store a value in a variable from a query result and assure the value of my variable doesn't change, even when the data in the table it was set from changes.

What am I missing? Thanks in advance!

[A]
That's very surprising, I agree.  I'm not sure how to explain it, but for what it's worth, try this instead:
```
```
SELECT username INTO myName FROM User WHERE ID=1;
```
```
See
http://dev.mysql.com/doc/refman/5.0/en/select-into-statement.html
update:
I'm trying to reproduce this problem, but I can't.  I'm using MySQL 5.0.51 on Mac OS X.
```
```
drop table if exists user;
create table user (
  id serial primary key,
  username varchar(10)
);
insert into user (username) values ('Paul');

drop procedure if exists doit;
delimiter !!
create procedure doit()
begin
  declare name varchar(10);
  select @name:=username from user where id=1;
  select @name; -- shows 'Paul' as expected
  update user set username = 'Fred' where id=1;
  select @name; -- still shows 'Paul'
end!!
delimiter ;

call doit();
```
```
Can you try the code above in your test database and let us know if it exhibits the problem you describe?


q:
I've been tasked with the awesome job of generating a look-up table for our application culture information.  The columns I need to generate data for are:

Dot Net Code

Version

Culture Name

Country Name

Language Name

Java Country Code

Java Language Code

Iso Country Code

Iso Language Code

I have found the globalization name space, but I'm sure someone out there has asked the same question, or there is a table already available.

Thanks for any help

[A]
Java uses the 2-letter ISO country and language codes. I recommend getting rid of the "Java Country Code" and "Java Language Code" fields in your lookup table, since they would be redundant.
I assume that wherever you get your ISO
country
and
language
codes, you'll find their corresponding names in English. However, the Java
Locale
API will give also you the localized names for the country and language, if you need them. (I.e., what is America called in Japan?)
For example, you can do this:
```
```
Locale l = Locale.ITALY;
System.out.println(l.getDisplayCountry() + ": " + l.getDisplayLanguage());
System.out.println(l.getDisplayCountry(l) + ": " + l.getDisplayLanguage(l));
```
```
Which, running in the US English locale prints:
```
```
Italy: Italian
Italia: italiano
```
```
Note that you can obtain 3-letter ISO codes from the Locale class, but when constructing them, be sure to only use 2-letter codes.


q:
I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:

t => t.SomeProperty.Contains("stringValue");

So far I have got:

    private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string propertyValue)
    {
        var parameterExp = Expression.Parameter(typeof(T), "type");
        var propertyExp = Expression.Property(parameter, propertyName);
        var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)
        ...
        return Expression.Lambda<Func<string, bool>>(containsMethodExp, parameterExp); //then something like this
    }

I just don't know how to reference the String.Contains() method.

Help appreciated.

[A]
Something like:
```
```
class Foo
{
    public string Bar { get; set; }
}
static void Main()
{
    var lambda = GetExpression<Foo>("Bar", "abc");
    Foo foo = new Foo { Bar = "aabca" };
    bool test = lambda.Compile()(foo);
}
static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue)
{
    var parameterExp = Expression.Parameter(typeof(T), "type");
    var propertyExp = Expression.Property(parameterExp, propertyName);
    MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    var someValue = Expression.Constant(propertyValue, typeof(string));
    var containsMethodExp = Expression.Call(propertyExp, method, someValue);

    return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
}
```
```
You might find
this
helpful.


q:
I have a RESTful web service deployed at http://example.com/v1/SomeResource. One day, a new protocol version (that is not backwards compatible) is deployed to http://example.com/v2/SomeResource. From the client of view, this upgrade could occur at any time between two HTTP requests.

How does the server indicate to the client that it no longer supports v1 calls and the client is expected to upgrade to v2? Is there an appropriate response code I can use?

I would want to provide the client with the following information:

An incompatible upgrade has taken place. There is no way for the client to use the new service because the protocol could be totally different.

The URL of the new client software.

A message explaining to the users that they must upgrade.

[A]
Best practice:
It's probably better to keep the versioning out of the URL and to make the new resources backwards compatible with the old.
Backwards compatible:
If you must keep the v1 in the URL, and are making v2 URLs, then you have to decide whether you want to support both formats, or make the old v1 obsolete.  If you decide on making the old v1 obsolete then I would recommend to return 303 or 401 for anyone requesting a v1 URL.
Making old URLs obsolete:
I would recommend using 303 See Other.  Or if there is no associated redirect, then use 410 Gone.
Source
303 See Other
The response to the request can be
  found under a different URI and SHOULD
  be retrieved using a GET method on
  that resource. This method exists
  primarily to allow the output of a
  POST-activated script to redirect the
  user agent to a selected resource. The
  new URI is not a substitute reference
  for the originally requested resource.
  The 303 response MUST NOT be cached,
  but the response to the second
  (redirected) request might be
  cacheable.
The different URI SHOULD be given by
  the Location field in the response.
  Unless the request method was HEAD,
  the entity of the response SHOULD
  contain a short hypertext note with a
  hyperlink to the new URI(s).
Note: Many pre-HTTP/1.1 user agents do not understand the 303
    status. When interoperability with such clients is a concern, the
    302 status code may be used instead, since most user agents react
    to a 302 response as described here for 303.
Document everything:
The main thing to be concerned about is whatever you chose to return, just document it in your documentation.  You can decide how you want your service to work, others that want to consume it will follow the documentation.


q:
I have some code doing this :

 var changes = document.getElementsByName(from);
 for (var c=0; c<changes.length; c++) {
   var ch = changes[c];
   var current = new String(ch.innerHTML);
   etc.
 }

This works fine in FF and Chrome but not in IE7. Presumably because getElementsByName isn't working in IE. What's the best workaround?

[A]
There are a couple of problems:
IE is indeed confusing
```
id=""
```
with
```
name=""
```
```
name=""
```
isn't allowed on
```
<span>
```
To fix, I suggest:
Change all the
```
name=""
```
to
```
class=""
```
Change your code like this:
-
```
```
var changes = document.getElementById('text').getElementsByTagName('span');
for (var c=0; c<changes.length; c++) {
 var ch = changes[c];

 if (ch.className != from)
continue;

 var current = new String(ch.innerHTML);
```
```


q:
I was looking for something like Server.MapPath in the ASP.NET realm to convert the output of Assembly.GetExecutingAssembly().CodeBase into a file path with drive letter.

The following code works for the test cases I've tried:

private static string ConvertUriToPath(string fileName)
{
    fileName = fileName.Replace("file:///", "");
    fileName = fileName.Replace("/", "\\");
    return fileName;
}

It seems like there should be something in the .NET Framework that would be much better--I just haven't been able to find it.

[A]
Can you just use
```
Assembly.Location
```
?


q: I have an asp.net image button and I want to cancel the click event incase he fails the client side validation... how do I do that?

[A]
There is an OnClientClick event you can set this to your javascript function. If you return true it will continue to the post back.  If you return false the post back will not happen.
```
```
<asp:Button ID="NavigateAway" runat="server" OnClientClick="javascript:return PromptToNavigateOff();" OnClick="NavigateAwayButton_Click" Text="Go Away" />

  <script type="text/javascript">
    function PromptToNavigateOff()
    {
        return confirm("Are you sure you want to continue  and loose all your changes?");
    }

  </script>
```
```


q: What is the best compiler to experiment with C++0x features? I have been experimenting with GNU g++ 4.4.

[A]
ConceptGCC
(wiki)
was made for that purpose, if I am not mistaken.


q:
Here is my code:

ThreadStart threadStart = controller.OpenFile;
Thread thread = new Thread(threadStart);
thread.Start();

In the OpenFile function, my code looks like:

System.Console.Error.WriteLine("Launching");

The code in OpenFile doesn't get executed for 30 seconds exactly. It starts immediately on my machine, but in our production environment it takes 30 seconds before that print statement will execute.

Is there a setting or something that might be doing this? Where would I start looking?

[A]
Do you have the same problem if you use other threading methods (for example, Threadpool)? This would tell if it's related to this method of threading, or to all methods. Also, is that WriteLine statement the only statement in your OpenFile procedure? 30 seconds is a common timeout length so maybe that's what's happening here.
Other than that, I'm not sure why the thread handler would pause for 30 seconds before processing.


q:
you would think this would be obvious, but searching through documentation, SAP forums, Googling, etc., I've been spectacularly unsuccessful.  I'm creating a file in ABAP on a solaris filesystem using the following code:

OPEN DATASET p_file FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.

the resulting file is owned and grouped according to a pre-defined admin user, which is fine, but the sticky wicket is that the permissions are set to 660/rw-rw----, meaning I can't examine the results.  is there a way (possibly using that vaguely defined TYPE addition?) I can specify the resulting permissions on the new file?

thanks!

[A]
Go to SM69, create a logical system command, you could call it ZCHMOD.
Map that command to
```
chmod
```
, then call with the proper parameter
(
```
man chmod
```
on the command line is your friend).
```
```
CALL FUNCTION 'SXPG_COMMAND_EXECUTE'
  EXPORTING
    commandname                   = 'ZCHMOD'
    additional_parameters         = l_par
    operatingsystem               = l_os
  TABLES
    exec_protocol                 = it_log
  EXCEPTIONS
    no_permission                 = 1
    command_not_found             = 2
    parameters_too_long           = 3
    security_risk                 = 4
    wrong_check_call_interface    = 5
    program_start_error           = 6
    program_termination_error     = 7
    x_error                       = 8
    parameter_expected            = 9
    too_many_parameters           = 10
    illegal_command               = 11
    wrong_asynchronous_parameters = 12
    cant_enq_tbtco_entry          = 13
    jobcount_generation_error     = 14
    OTHERS                        = 15.
```
```
Obviously, that would be a 2 step process, but it works.


q:
Our product has the requirement of exporting its native format (essentially an XML file) to Excel for viewing/editing. However, what this entails is having a dependency on Excel (or Office) itself for our product build - something that we do not want.

What we have done is export the data from our native format to a csv file which can be opened in Excel. If user selects an option to open the generated report as well, we (try to) launch Excel application to open it (ofcourse it requires Excel to be already present on the client system).

The data for most part is flat list of records.

Is there a better format (or even a better way) to handle this requirement? This is a common requirement for many products - how do you handle this?

[A]
I'm using
ExcelPackage
to create spreadsheets in one of my side projects.  Works pretty good, but (at least the version I'm using) its a bit limited when it comes to styling and calculations.
ExcelPackage lets you create OOXML docs (.xslx files) that are natively compat with 2k7, but you can
download a plugin
for previous versions of Office from MS.


q: I need to render JSON data in my JSPs for some AJAX requests. I'd like to know what's the best way to do it in terms of easy to use and stability.

[A]
Assuming you want to generate the JSON from one or more Java objects, the following is a fairly straightforward approach:
Set the Java object(s) as attributes in request/session scope
Convert the objects to JSON using a tag library such as
http://json-taglib.sourceforge.net/index.html


q:
I'm inserting an img tag into my document with the new Element constructor like this (this works just fine):

$('placeholder').insert(new Element("img", {id:'something', src:myImage}))

I would like to trigger a function when this image loads, but I can't figure out the correct syntax. I'm guess it's something like this (which doesn't work).

$('placeholder').insert(new Element("img",
    {id:'something', src:myImage, onload:function(){alert("MOO")}}))

I'm hoping to do this in the same line of code and not to have to attach an event observer separately.

EDIT: The event needs to be registered when the element is created, not after. If the image loads before the event is attached, the event will never fire.

[A]
You might have to move the function elsewhere and call it by name
```
```
$('placeholder').insert(new Element("img",
    {id:'something', src:myImage, onload:"javascript:moo()"}))

function moo() {
    alert("MOO");
}
```
```
Of course, because
```
insert
```
returns the element, you could inline
```
Element.observe
```
```
```
$('placeholder').insert(new Element("img",
    {id:'something', src:myImage})).observe('load', function(){alert("MOO")});
```
```


q: How do I set the date/time of the computer in C#?

[A]
You will need to call the
SetSystemTime
Win32 API function through P/Invoke.


q:
I'm looking to vertically align text by adding <br /> tags between characters with jQuery.

<div id="foo"><label>Vertical Text</label></div>

would look like this:

V

e

r

t

i

c

a

l

T

e

x

t

[A]
Not tested, but it should work.
```
```
var element = $( '#foo label' );
var newData = '';
var data = element.text();
var length = data.length;
var i = 0;

while( i < length )
{

    newData += data.charAt( i ) + '<br />';
    i++;

}

element.html( newData );
```
```


q:
I am trying to do this...

<Image x:Name="imgGroupImage" Source="Images\unlock.png" Margin="0,0,5,0" />

But I get this error...

Cannot convert string 'Images\unlock.png' in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. Cannot locate resource 'forms/images/unlock.png'.  Error at object 'System.Windows.HierarchicalDataTemplate' in markup file 'Fuse;component/forms/mainwindow.xaml' Line 273 Position 51.

As you can see, my form that includes this XAML is in a folder named Forms. My Images are in a folder named Images. How do I map from Forms to Images?

I tried Source="..Images\unlock.png" which does not work in WPF.

Any help?

[A]
Try slashes rather than backslashes, and use an absolute path by leading with a slash:
```
```
Source="/Images/unlock.png"
```
```
That generally works for me.
Failing that, take a look at
Pack URIs
.


q:
Would the following SQL statement automatically create an index on Table1.Table1Column, or must one be explicitly created?

Database engine is SQL Server 2000

       CREATE TABLE [Table1] (
. . .
            CONSTRAINT [FK_Table1_Table2] FOREIGN KEY
            (
                [Table1Column]
            ) REFERENCES [Table2] (
                [Table2ID]
            )

        )

[A]
SQL Server will not automatically create an index on a foreign key.  Also from MSDN:
A FOREIGN KEY constraint does not have
  to be linked only to a PRIMARY KEY
  constraint in another table; it can
  also be defined to reference the
  columns of a UNIQUE constraint in
  another table. A FOREIGN KEY
  constraint can contain null values;
  however, if any column of a composite
  FOREIGN KEY constraint contains null
  values, verification of all values
  that make up the FOREIGN KEY
  constraint is skipped. To make sure
  that all values of a composite FOREIGN
  KEY constraint are verified, specify
  NOT NULL on all the participating
  columns.


q:
When using a Silverlight-enabled WCF service, where is the best place to instantiate the service and to call the CloseAsync() method?

Should you say, instantiate an instance each time you need to make a call to the service, or is it better to just instantiate an instance as a variable of the UserControl that will be making the calls?

Then, where is it better to call the CloseAsync method?  Should you call it in each of the "someServiceCall_completed" event methods?  Or, if created as a variable of the UserControl class, is there a single place to call it?  Like a Dispose method, or something equivalent for the UserControl class.

Thanks,

Jeff

[A]
You're better off just having an instance variable for the service. Creating and destroying the service for each call creates a lot of unnecessary overhead. Just create the variable and call the methods, no need to open it since this will be
done automatically
as of beta 2 (see section #5).
As for close, whether you try to close it for clean up probably depends on how your app is structured. If when the UserControl is closed the whole app is shutting down (the user closed the browser) then you probably don't need to explicitly close it since everything will get cleaned up when the Silverlight host closes. However, if you're creating lots of these user control and closing them while keeping the app open then you might want to create some kind of close method on your control that would clean up by calling CloseAsync.
If all the user controls use the same service, then you could just create a single service wrapper class that is used by all the controls that would handle calling the service. This would keep you from having to close the services when the controls unload as well.


q: Is there a good tutorial on working with (programming) threads in Visual Studio 2005? Not MFC related, just native C++ (no .NET).

[A]
Win32 Multithreaded Programming
Also try some of the free undergraduate podcasts on operating systems. You can find theoretical discussions on locking, multithreading, etc. (
the one I know of is from Berkeley
and is based on Java, but it is still relevant).


q: What's the best way to implement friendly URL in ASP.net?

[A]
The
ASP.NET Routing Framework
provided in .NET 3.5 SP1 is a good one.
Although it is very new, it can handles many URL-related tasks and most frequently used URL-friendly schemes very well.
It can be used outside of MVC, too.


q:
Let's take a very simple example:

In my window1.xaml, i have a label
control named 'lblProduct'.

In my window1.xaml.cs, i have a
public method called
CalculateProduct(Int Var1, Int
Var2).  CalculateProduct will, as
you may have guessed, calculate the
product of the variables passed in.

I'd like to simply bind the results of 'CalculateProduct' to my label.  My actual use case is a little more complicated than this. However, if I could get this up and running not only would I be quite happy, I'd be able to figure out the rest.

I've seen interesting examples using the ObjectDataProvider to bind to a static method of a new class.  While this is well and good, I don't feel the need to create a new class when I've already instantiated the one for my window.  In addition, there may be other global variables that I'd like to take advantage of in my Window1 class.

Thanks for your time and help,

Abel.

[A]
```
ObjectDataProvider
```
has an
```
ObjectInstance
```
property that you can assign your Window instance to.


q:
I have an ASP.NET 2.0 (C#) webpage with a link that pulls a blob from a MS SQL database and ouputs it in the appropriat file format, i.e., Word, WordPerfect, PDF.

My users would like to print these files with one click. Right now they have to click the link to open the file, then click the "Print" button within the application that they file opened.

In addition, I would like to send multiple documents to the printer, using one click, if possible.

Thanks.

[A]
Do you want to print to a Printer attached to the Server, or attached to the client?
If you want to print on the Client, you won't have much chance. For HTML Content, maybe some JavaScript or Flash could trigger the Print Dialog (not sure), but if it's a File that has to be opened in a third party application (i.e. PDF, DOC, XLS etc.), you're out of luck.
If it's an internal Network, you could possibly create a Desktop Application that is installed on every Client's PC that then triggers the Print.
If it is a Printer Attached to the Server, you can use the standard .net facilities for Printing, although you again may have to work around situations where you are trying to print PDF/DOC/XLS etc., because then you need to use Automation (either COM or something like SendKeys), which will cause you headaches on a Server.
So in Short: Not much you can do with only ASP.net at your disposal.


q: I'm trying to find SQL statements that timed out using the SQL 2005 profiler. Is there a way to set such a filter?

[A]
In Profiler, you can add the event "Attention" under "Errors and Warnings".  It's definition is
Collects all attention events, such as
  client interrupt request or when a
  client connection is broken.
As far as other errors (deadlocks, contraints, etc), try "Execution Warning" (reports warning that occurred during the execution of SQL statement or procedure) or "User Error Message" (the error message displayed to the user in the case of an error or exception).


q:
I would like to use Python to script an application that advertises itself as providing an OLE component. How should I get started?

I don't yet know what methods I need to call on the COMponents I will be accessing. Should I use win32com to load those components, and then start pressing 'tab' in IPython?

[A]
You need the
win32com
package. Some examples:
```
```
from win32com.client.dynamic import Dispatch

# Excel
excel = Dispatch('Excel.Application')

# Vim
vim = Dispatch('Vim.Application')
```
```
And then call whatever you like on them.


q:
"To summarize: if you install VSTO 2005 SE on top of a clean VS 2005 Professional, you won't have the document-level templates. If you want to have them you need to have VS 2005 Team Suite/Team Edition or you need to install the previous version of VSTO: VSTO 2005. So VS 2005 Professional + VSTO 2005 + VSTO 2005 SE will give you the document-level templates!"

So my question is, does anyone have a link to a VSTO 2005 download (it is no longer available from Microsoft).

[A]
Maybe this one will help
Microsoft Visual Studio 2005 Tools for Office 2005 Runtime (VSTO 2005 RTM)
The VSTO 2005 redistributable package installs the Visual Studio Tools for Office runtime, which is required to run solutions built using VSTO 2005. This runtime supports document-level customizations for Microsoft Office Excel 2003 and Microsoft Office Word 2003, and application-level add-ins for Microsoft Office Outlook 2003.


q:
Does anyone have any experience of developing external tools for SSMS 2005.

Ideally I would like to be able to interact with the query windows directly, for example, taking the query text from the window to perform some processing on it.

Any pointers in the right direction would be great.

Thanks in advance


q:
I'm trying to read the contents of a text file, in this case a list of computer names (Computer1, computer2 etc,) and I thought that StreamReader would be what you would use but when I do the following:

StreamReader arrComputer = new StreamReader(FileDialog.filename)();

I got this exception:

The type or namespace name 'StreamReader' could not be found (are you missing a using directive or an assembly reference?)

I'm very new to C# so I'm sure I'm making a newbie mistake.

[A]
try
```
```
using System.IO;

StreamReader arrComputer = new StreamReader(FileDialog.filename);
```
```


q:
Anyone have recommendations for webcast software, similar to the Silverlight app here: http://channel9.msdn.com/pdc2008/TL57/

I looked at a couple other questions posted here, but I don't want a hosted solution.

[A]
For Flash there is
JW FLV Player
. Just put the files on your own web server. On CodePlex you can find a
Silverlight 2.0 media player
.


q: I know MSDE is no longer supported on Vista, is this also the case for Windows Server 2008?

[A]
The status is the same for Vista and all OS after Vista, which includes both Windows 2008 and Windows 7.
I do not know if you can somehow "make it work", but you will not get any Support from Microsoft.
Edit: Source is
here
, the two important bits:
MSDE 2000 will exit mainstream support on 4/8/2008 and no new deployment agreements will be allowed after June 30, 2007.
and
Yes, MSDE will be supported through the end of it's life cycle on the operating systems it is currently designed to run on.
(That was up to Windows XP and 2003 Server)


q:
What is the most elegant way of bubble-sorting in F#?

UPDATE

As pointed out in one of the answers, bubble sorting isn't efficient in a functional language to begin with. A humourously-cynical commenter also pointed out that bubble sorting is only appropriate when the list is small and it's almost sorted anyway.

However, I'm curious to see how a clever bubble-sort can be written in F#, since I've done bubble sorts in C#, C++, and Java EE in the past, and since I'm an F# newbie.

[A]
using bubble sort in a functional language isn't very efficient, because the implementation has to reverse the list many times (and this can't be really implemented very efficiently for immutable lists).
Anyway, the example from Erlang can be rewritten to F# like this:
```
```
let sort l =
  let rec sortUtil acc rev l =
    match l, rev with
    | [], true -> acc |> List.rev
    | [], false -> acc |> List.rev |> sortUtil [] true
    | x::y::tl, _ when x > y -> sortUtil (y::acc) false (x::tl)
    | hd::tl, _ -> sortUtil (hd::acc) rev tl
  sortUtil [] true l
```
```
On the other side, you can implement the same algorithm using mutable arrays. This will be more efficient and in F# you can work with arrays too if you want. The following function creates a copy of the array and sorts it.
```
```
let sort (arr:'a[]) =
  let arr = arr |> Array.copy
  let swap i j = let tmp = arr.[i] in arr.[i] <- arr.[j]; arr.[j] <- tmp
  for i = arr.Length - 1 downto 0 do
    for j = 1 to i do
      if (arr.[j - 1] > arr.[j]) then swap (j-1) j
  arr
```
```
Tomas