q: Is there ever a circumstance in which I would not want to use the AndAlso operator rather than the And operator?  …or in which I would not want to use the OrElse operator rather than the Or operator?

[A]
Is there ever a circumstance in which I would not want to use the AndAlso operator rather than the And operator?
Sure: if you want to make sure that
both
sides of the expression are evaluated.  This might be the case if, for example, both sides are method calls that return booleans as a result of some other operation that has a side effect.
But in general, use
```
AndAlso
```
/
```
OrElse
```
whenever you would use
```
&&
```
/
```
||
```
in C/C++/C#, which of course is the vast majority of the time.


q:
Rehsarper 4.0 - Renaming a class does not rename the file…

I probably set something on accident in the options, but I can't find it. Any ideas?

[A]
When I do a rename in Resharper there's a checkbox below the textbox where you type the new name that says "Synchronise file name with class name". Check that and the file is renamed too.
Be sure you're using Resharper's rename (right-click/Refactor/Rename) rather than Visual Studio's (right-click/Rename), as the latter definitely doesn't rename the file.

s: huggingface

c: devops

d: intermediate


q: What’s the best way to capitalize the first letter of each word in a string in SQL Server.

[A]
From
http://www.sql-server-helper.com/functions/initcap.aspx
```
```
CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN

DECLARE @Index          INT
DECLARE @Char           CHAR(1)
DECLARE @PrevChar       CHAR(1)
DECLARE @OutputString   VARCHAR(255)

SET @OutputString = LOWER(@InputString)
SET @Index = 1

WHILE @Index <= LEN(@InputString)
BEGIN
    SET @Char     = SUBSTRING(@InputString, @Index, 1)
    SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
                         ELSE SUBSTRING(@InputString, @Index - 1, 1)
                    END

    IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
    BEGIN
        IF @PrevChar != '''' OR UPPER(@Char) != 'S'
            SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
    END

    SET @Index = @Index + 1
END

RETURN @OutputString

END
GO
```
```
There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."):
http://www.devx.com/tips/Tip/17608


q:
I'm building a Django project that needs search functionality, and until there's a django.contrib.search, I have to choose a search app. So, which is the best? By "best" I mean...

easy to install / set up

has a Django- or at least Python-friendly API

can perform reasonably complex searches

Here are some apps I've heard of, please suggest others if you know of any:

djangosearch

django-sphinx

I'd also like to avoid using a third-party search engine (like Google SiteSearch), because some of the data I'd like to index is for site members only and should not be public.

[A]
Justin, I'd try
djangosearch
first: Jacob Kaplan-Moss (Django's lead developer) is working on it.
Potential hazards:
The home page warns the API might not be entirely stable
Potential benefits:
“The long term goal is for this to become
```
django.contrib.search
```
.”


q:
I'm pretty sure the answer to this question is no, but in case there's some PHP guru

is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of '@'

Much like empty and isset do. You can pass in a variable you just made up and it won't error.

ex:

empty($someBogusVar); // no error

myHappyFunction($someBogusVar); // Php warning / notice

[A]
No, because this isn't really anything to do with the function; the error is coming from attempting to de-reference a non-existent array key. You can change the warning level of your PHP setup to surpress these errors, but you're better off just not doing this.
Having said that, you
could
do something like
```
```
function safeLookup($array, $key)
{
  if (isset($array, $key))
    return $array[$key];

  return 0;
}
```
```
And use it in place of array key lookup
```
```
defaultValue(safeLookup($foo, "bar"), "baz);
```
```
Now I need to take a shower :)


q: Does anyone have any experience with a good wpf pivot table control?

[A]
DevExpress Grid control
has good pivot functionality. Used it for Winforms a lot. I think the WPF version is also available.


q:
I have a Linq query that I want to call from multiple places:

var myData = from a in db.MyTable
             where a.MyValue == "A"
             select new  {
                            a.Key,
                            a.MyValue
                          };

How can I create a method, put this code in it, and then call it?

public  ???  GetSomeData()
{
   // my Linq query
}

[A]
```
IQueryable
```
So your method declaration would look like
```
```
public IQueryable GetSomeData()
```
```


q:
Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.

What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?

For example, you had this:

d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}

I want to print the associated values in the following sequence sorted by key:

this is a
this is b
this is c

[A]
This snippet will do it. If you're going to do it frequently, you might want to make a 'sortkeys' method to make it easier on the eyes.
```
```
keys = list(d.keys())
keys.sort()
for key in keys:
    print d[key]
```
```
Edit:
dF's solution
is better -- I forgot all about
```
sorted()
```
.


q:
What is the operator precedence order in Visual Basic 6.0 (VB6)?

In particular, for the logical operators.

[A]
Arithmetic Operation Precedence Order
```
^
```
```
-
```
(unary negation)
```
*
```
,
```
/
```
```
\
```
```
Mod
```
```
+
```
,
```
-
```
(binary addition/subtraction)
```
&
```
Comparison Operation Precedence Order
```
=
```
```
<>
```
```
<
```
```
>
```
```
<=
```
```
>=
```
```
Like
```
,
```
Is
```
Logical Operation Precedence Order
```
Not
```
```
And
```
```
Or
```
```
Xor
```
```
Eqv
```
```
Imp
```
Source:
Sams Teach Yourself Visual Basic 6 in 24 Hours — Appendix A: Operator Precedence


q:
What would be the best strategy to generate anagrams.

An anagram is a type of word play, the result of rearranging the letters
of a word or phrase to produce a new  word or phrase, using all the original
letters exactly once;
ex.

Eleven plus two is anagram of Twelve plus one

A decimal point is anagram of I'm a dot in place

Astronomers is anagram of Moon starers

At first it looks straightforwardly simple, just to jumble the letters and generate all possible combinations. But what would be the efficient approach to generate only the words in dictionary.

I came across this page, Solving anagrams in Ruby.

But what are your ideas?

[A] Off the top of my head, the solution that makes the most sense would be to pick a letter out of the input string randomly and filter the dictionary based on words that start with that.  Then pick another, filter on the second letter, etc.  In addition, filter out words that can't be made with the remaining text.  Then when you hit the end of a word, insert a space and start it over with the remaining letters.  You might also restrict words based on word type (e.g. you wouldn't have two verbs next to each other, you wouldn't have two articles next to each other, etc).


q:
What is the best way of implementing a cache for a PHP site? Obviously, there are some things that shouldn't be cached (for example search queries), but I want to find a good solution that will make sure that I avoid the 'digg effect'.

I know there is WP-Cache for WordPress, but I'm writing a custom solution that isn't built on WP. I'm interested in either writing my own cache (if it's simple enough), or you could point me to a nice, light framework. I don't know much Apache though, so if it was a PHP framework then it would be a better fit.

Thanks.

[A]
The best way to go is to use a proxy cache (Squid, Varnish) and serve appropriate Cache-Control/Expires headers, along with ETags : see
Mark Nottingham's Caching Tutorial
for a full description of how caches work and how you can get the most performance out of a caching proxy.
Also check out
memcached
, and try to cache your database queries (or better yet, pre-rendered page fragments) in there.


q:
I have seen the references to VistaDB over the years and with tools like SQLite, Firebird, MS SQL et. al. I have never had a reason to consider it.

What are the benefits of paying for VistaDB vs using another technology?  Things I have thought of:

1. Compact Framework Support.  SQLite+MSSQL support the CF.

2. Need migration path to a 'more robust' system.  Firebird+MSSQL.

3. Need more advanced features such as triggers. Firebird+MSSQL

[A]
Well, the main thing is that it is pure managed code - for what that is worth; it works not only on your typical Windows machines running .NET, but works wherever you run the Compact Framework and even works on
Mono
. Here are some noteworthy bullet points from their homepage:
Small < 1 MB footprint truly embedded ZeroClick
Microsoft SQL Server 2005 compatible data types and T-SQL syntax
None of the SQL CE limits
Single user, multi user local or using shared network.
Partially trusted shared hosting is no problem.
Royalty-free distribution - single CPU deployment of SQL Server costs more than a site license of VistaDB!
One thing worth noting is that Rob Howard's company,
telligent
, uses it as the default database for their new CMS software, "
Graffiti
."
I have played with it here and there but have yet to build anything against it.


q:
When objects from a CallList intersect the near plane I get a flicker..., what can I do?

Im using OpenGL and SDL.

Yes it is double buffered.

[A]
Try to put the near clipping plane a little bit further :
for example with gluPerspective -> third parameter
zNear
http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/glu/perspective.html


q: I use Emacs primarily for coding Python but sometimes I use IDLE. Is there a way to change the key bindings easily in IDLE to match Emacs?

[A]
There's a program for Windows called
```
XKeymacs
```
that allows you to specify emacs keybindings for different programs.  It should work with IDLE.
http://www.cam.hi-ho.ne.jp/oishi/indexen.html
-Mark


q:
I'm using Windows and I'm trying to get ANT to work.

When I do an ant build from the command line, I get:
C:\dev\Projects\springapp\${%ANT_HOME%}\lib not found.

I look into the build.xml file and I find:
appserver.home=${user.home}/apache-tomcat-6.0.14 (which I just copied and pasted straight from a tutorial)

I changed it to:

appserver.home="C:\Program Files\Apache Software Foundation\Tomcat 6.0"

but now I get:

C:\dev\Projects\springapp\"C:Program FilesApache Software FoundationTomcat 6.0"\lib not found.

It seems like the white space in Program Files and Tomcat 6.0 are causing the build to fail.  How do you deal with these in xml files without re-creating the directory with a path with no white space?

[A]
Change it to
```
```
appserver.home="C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0"
```
```


q:
I want to grab the value of a hidden input field in HTML.

<input type="hidden" name="fooId" value="12-3456789-1111111111" />

I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format

<input type="hidden" name="fooId" value="**[id is here]**" />

Can someone provide an example in Python to parse the HTML for the value?


q:
This question is the other side of the question asking, "How do I calculate relative time?".

Given some human input for a relative time, how can you parse it?  By default you would offset from DateTime.Now(), but could optionally offset from another DateTime.

(Prefer answers in C#)

Example input:

"in 20 minutes"

"5 hours ago"

"3h 2m"

"next week"

Edit:  Let's suppose we can define some limits on the input.  This sort of code would be a useful thing to have out on the web.

[A]
That's building a DSL (Domain specific language) for date handling. I don't know if somebody has done one for .NET but the construction of a DSL is fairly straightforward:
Define the language precisely, which input forms you will accept and what will you do with ambiguities
Construct the grammar for the language
Build the finite state machine that parses your language into an actionable AST
You can do all that by yourself (with the help of
the Dragon Book
, for instance) or with the help of tools to the effect, as shown in this
link
.
Just by thinking hard about the possibilities you have a good chance, with the help of good UI examples, of covering more than half of the actual inputs your application will receive. If you aim to accept everything a human could possibly type, you can record the input determined as ambiguous and then add them to the grammar, whenever they can be interpreted, as there are things that will be inherently ambiguous.


q:
I've a class which is a wrapper class(serves as a common interface) around another class implementing the functionality required. So my code looks like this.

template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}

Now, how do I make sure that ImplementationClass can be derived from a set of classes only, similar to java's generics

<? extends BaseClass>

syntax?

[A]
In the current state of things, there is no good way other than by comments or a third-party solution. Boost provides a
concept check library
for this, and I think gcc also has an implementation. Concepts are on the list of C++0x improvements, but I'm not sure if you can specify subtypes - they are more for "must support these operations" which is (roughly) equivalent.
Edit:
Wikipedia has this
section
about concepts in C++0x, which is significantly easier to read than draft proposals.


q:
I've been thinking about the number of projects we have in-house that are still being developed using visual studio 6 and how best to migrate them forward onto visual studio 2008. The projects range in flavours of C/C++ and VB.

Is it better to let VS2008 convert the work-spaces into solutions, fix any compile errors and be on your merry way? Or, is it better to start with a clean solution and migrate code across project by project discarding dead code along the way?

[A]
The Microsoft p&p team has recommended some
strategies
that answers this. Basically they recommend something like the project by project approach you mention. Of course, they're assuming a neatly architected application that has no nasty, dark corners from which late nights of coding and copious amounts of coffee spring from.
It doesn't hurt to let VS2008 convert the project for you and see how much effort is required to fix the errors.


q:
I sometimes use the feature 'Reconcile Offline Work...' found in Perforce's P4V IDE to sync up any files that I have been working on while disconnected from the P4 depot. It launches another window that performs a 'Folder Diff'.

I have files I never want to check in to source control (like ones found in bin folder such as DLLs, code generated output, etc.) Is there a way to filter those files/folders out from appearing as "new" that might be added. They tend to clutter up the list of files that I am actually interested in.  Does P4 have the equivalent of Subversion's 'ignore file' feature?

[A]
As of version 2012.1, Perforce supports the
```
P4IGNORE
```
environment variable. I updated my answer to
this question about ignoring directories
with an explanation of how it works. Then I noticed this answer, which is now superfluous I guess.
Assuming you have a client named "CLIENT", a directory named "foo" (located at your project root), and you wish to ignore all .dll files in that directory tree, you can add the following lines to your workspace view to accomplish this:
```
-//depot/foo/*.dll //CLIENT/foo/*.dll
-//depot/foo/.../*.dll //CLIENT/foo/.../*.dll
```
The first line removes them from the directory "foo" and the second line removes them from all sub directories.  Now, when you 'Reconcile Offline Work...', all the .dll files will be moved into "Excluded Files" folders at the bottom of the folder diff display. They will be out of your way, but can still view and manipulate them if you really need to.
You can also do it another way, which will reduce your "Excluded Files" folder to just one, but you won't be able to manipulate any of the files it contains because the path will be corrupt (but if you just want them out of your way, it doesn't matter).
```
-//depot/foo.../*.dll //CLIENT/foo.../*.dll
```


q:
I'm working with a snippet of code that recursively calls itself and tries to pull out a MIME Type part of text/html from an email (if it exists) for further processing.

The "text/html" could exist inside other content such as multipart/alternative, so I'm trying to find out if there is a defined hierarchy for email MIME Types.

Anybody know if there is and what it is? i.e. what types can parent other types?

[A] Your question assumes that mail clients follow the RFC standards for MIME encoding, which they don't. I'd advise you collect a bunch of mail from sources and try and process it as-it-exists. The problem you are facing is extremely difficult (perhaps impossible) to solve 100%.


q:
As part of my integration strategy, I have a few SQL scripts that run in order to update the database. The first thing all of these scripts do is check to see if they need to run, e.g.:

if @version <> @expects
    begin
        declare @error varchar(100);
        set @error = 'Invalid version. Your version is ' + convert(varchar, @version) + '. This script expects version ' + convert(varchar, @expects) + '.';
        raiserror(@error, 10, 1);
    end
else
    begin
        ...sql statements here...
    end

Works great! Except if I need to add a stored procedure. The "create proc" command must be the only command in a batch of sql commands. Putting a "create proc" in my IF statement causes this error:

'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.

Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to?

[A]
Here's what I came up with:
Wrap it in an EXEC(), like so:
```
```
if @version <> @expects
    begin
        ...snip...
    end
else
    begin
        exec('CREATE PROC MyProc AS SELECT ''Victory!''');
    end
```
```
Works like a charm!


q:
I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.

int globalgarbage;
unsigned int anumber = 42;

But what about static ones defined within a function?

void doSomething()
{
  static bool globalish = true;
  // ...
}

When is the space for globalish allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when doSomething() is first called?

[A]
Static variables are allocated inside a code segment -- they are part of the executable image, and so are mapped in already initialized.
Static variables within function scope are treated the same, the scoping is purely a language level construct.
For this reason you are guaranteed that a static variable will be initialized to 0 (unless you specify something else) rather than an undefined value.
There are some other facets to initialization you can take advantage off -- for example shared segments allow different instances of your executable running at once to access the same static variables.
In C++ (globally scoped) static objects have their constructors called as part of the program start up, under the control of the C runtime library.  Under Visual C++ at least the order that objects are initialized in can be controlled by the
init_seg
pragma.


q:
Background:

Some time ago, I built a system for recording and categorizing application crashes for one of our internal programs. At the time, I used a combination of frequency and aggregated lost time (the time between the program launch and the crash) for prioritizing types of crashes. It worked reasonably well.

Now, The Powers That Be want solid numbers on the cost of each type of crash being worked on. Or at least, numbers that look solid. I suppose I could use the aggregate lost time, multiplied by some plausible figure, but it seems dodgy.

Question:

Are there any established methods of calculating the real-world cost of application crashes? Or failing that, published studies speculating on such costs?

Consensus

Accuracy is impossible, but an estimate based on uptime should suffice if it is applied consistently and its limitations clearly documented. Thanks, Matt, Orion, for taking time to answer this.

[A]
I've not seen any studies, but a reasonable heuristic would be something like :
( Time since last application save when crash occurred + Time to restart application ) * Average hourly rate of application operator.
The estimation gets more complex if the crashes have some impact on external customers such, or might delay other things (i.e. create a bottle neck such that another person winds up sitting around waiting because some else's application crashed).
That said, your 'powers that be' may well be happy with a very rough estimate so long as it's applied consistently and they can see how it is changing over time.


q:
I need to generate some passwords, I want to avoid characters that can be confused for each other. Is there a definitive list of characters I should avoid? my current list is

il10o8B3Evu![]{}

Are there any other pairs of characters that are easy to confuse? for special characters I was going to limit myself to those under the number keys, though I know that this differs depending on your keyboards nationality!

As a rider question, I would like my passwords to be 'wordlike'do you have a favoured algorithm for that?

Thanks :)

[A]
My preferred method is to get a word list of 3, 4 and 5 letter words.  Then select at least 2 of those, and place a random 2 digit number or special symbol (%&*@#$) between each word.  If you want to you can capitalize up to one character per word at random.
Depending on your strength requirements you end up with easy-to-remember and communicate passwords like:
lemon%desk
paper&boy32hat
Keep in mind you occasionally get interesting or inappropriate combinations of words (I'll let you use your imagination).  I usually have a button allowing the generation of a new password if the one presented is disliked.
As a rule, only use symbols that people commonly know the name for.  On a US Standard keyboard I would avoid ~`'/\^
I guess this more answered your rider question than your main question . ..
Good luck!


q: I've only recently started working with asp.net and c#. Is there a standard practice set of web.config settings for a live final website? There seem to be a ton of options available and I'm looking to streamline performance, close possible security holes and other unnecessary options.

[A]
An empty web.config (or at least an absent
```
<
```
system.web>
element) would mean that all of the framework's recommended defaults would take effect. You would then just need to be concerned with the host (e.g., IIS) set-up.


q:
As it stands now, I'm a Java and C# developer. The more and more I look at Ruby on Rails, the more I really want to learn it.

What have you found to be the best route to learn RoR?  Would it be easier to develop on Windows, or should I just run a virtual machine with Linux?

Is there an IDE that can match the robustness of Visual Studio?  Any programs to develop that give a good overhead of what to do? Any good books?

Seriously, any tips/tricks/rants would be awesome.

[A]
```
IDE: NetBeans
Book:
Agile Web Development With Rails
Installation:
Instant Rails
```


q: I want to test the web pages I create in all the modern versions of Internet Explorer (6, 7 and 8 beta) but I work mainly on a Mac and often don't have direct access to a PC.

[A]
Update:
Microsoft now provide virtual machine images for various versions of IE that are ready to use on all of the major OS X virtualisation platforms (
VirtualBox
,
VMWare Fusion
, and
Parallels
).
Download the appropriate image from:
https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/
On an Intel based Mac you can run Windows within a virtual machine. You will need one virtual machine for each version of IE you want to test against.
The instructions below include free and legal virtualisation software and Windows disk images.
Download some virtual machine software. The developer disk images we're going to use are will work with either
VMWare Fusion
or
Sun Virtual Box
. VMWare has more features but costs $80, Virtual Box on the other hand is more basic but is free for most users (see
Virtual Box licensing FAQ
for details).
Download the IE developer disk images, which are free from Microsoft:
http://www.microsoft.com/downloads/...
Extract the disk images using
cabextract
which is available from
MacPorts
or as source code (Thanks to
Clinton
).
Download Q.app from
http://www.kju-app.org/
and put it in your /Applications folder (you will need it to convert the disk images into a format VMWare/Virtual Box can use)
At this point, the process depends on which VM software you're using.
Virtual Box users
Open a Terminal.app on your Mac (you can find it in /Applications/Utilities) and run the following sequence of commands, replacing
input.vhd
with the name of the VHD file you're starting from and
output.vdi
with the name you want your final disk image to have:
```
```
/Applications/Q.app/Contents/MacOS/qemu-img convert -O raw -f vpc "input.vhd" temp.bin
VBoxManage convertdd temp.bin "output.vdi"
rm temp.bin
mv "output.vdi" ~/Library/VirtualBox/VDI/
VBoxManage modifyvdi "output.vdi" compact
```
```
Start Virtual Box and create a new virtual machine
Select the new VDI file you've just created as the boot hard disk
VMWare fusion users
Open a Terminal.app on your Mac (you can find it in /Applications/Utilities) and run the following commands, replacing
input.vhd
and
output.vmdk
with the name of the VHD file you're working on and the name you want your resulting disk image to have:
```
```
/Applications/Q.app/Contents/MacOS/qemu-img convert -O vmdk -f vpc "input.vhd" "output.vmdk"
mv "output.vmdk" ~/Documents/Virtual\ Machines.localized/
```
```
This will probably take a while (It takes around 30 minutes per disk image on my 2.4GHz Core 2 Duo MacBook w/ 2Gb RAM).
Start VMWare Fusion and create a new virtual machine
In the advanced disk options select "use and existing disk" and find the VMDK file you just created


q:
What is the best way to use multiple EVAL fields in a GridView ItemTemplate?

Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc.

[A]
I had previously used this (bad, I know):
```
```
<%# Eval("Name1", "{0} - ")%> <%#Eval("Name2")%>
```
```
Result = 'John - Smith'
But just discovered that I can also put TWO (or more) Evals in the same data-bound group:
```
```
<%#Eval("Name1") & " - " & Eval("Name2")%>
```
```
Result = 'John - Smith'
Or
```
```
<%# "First Name - " & Eval("Name1") & ", Last Name - " & Eval("Name2")%>
```
```
Result = 'First Name - John, Last Name - Smith'


q: WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a console documentation for Firebug, but where can I find the console documentation for Safari/WebKit?

[A]
Supported methods were originally:
```
console.log()
```
```
console.error()
```
```
console.warn()
```
```
console.info()
```
Newer versions of WebKit also add the following methods making the WebKit console API almost identical to
Firebug's console API
:
```
console.count()
```
```
console.debug()
```
```
console.profileEnd()
```
```
console.trace()
```
```
console.dir()
```
```
console.dirxml()
```
```
console.assert()
```
```
console.time()
```
```
console.profile()
```
```
console.timeEnd()
```
```
console.group()
```
```
console.groupEnd()
```
(New information based on the WebKit nightly build WebKit-SVN-r37126, at the time of writing these methods aren't available in Safari)


q: In prior versions of Windows before Vista you could have a Windows Service interact with the current logged in desktop user to easy display information on the screen from the service. In Windows Vista Session 0 was added for security to isolate the services from the desktop. What is an easy way to communicate between a service and an application running outside of Session 0? So far I have gotten around this by using TCP/IP to communicate between the two but it seems to be kind of a sloppy way to do it.

[A]
You can use shared memory or named pipe to facilitate IPC as well. Conceptually this is similar to TCP/IP, but you don't have to worry about finding an unused port.
You have to make sure that the named objects you create are prefixed with "Global\" to allow them to be accessed by all sessions as described
here
.
AFAIK there is no way for a service to directly interact with the desktop any more.


q: What is the best practice of Unicode processing in C++?

[A]
Here is a checklist for Windows programming:
All strings enclosed in _T("my string")
strlen() etc. functions replaced with _tcslen() etc.
Use LPTSTR and LPCTSTR instead of char * and const char *
When starting new projects in Dev Studio, religiously make sure the Unicode option is selected in your project properties.
For C++ strings, use std::wstring instead of std::string


q:
I'm going to be implementing a PHP/mySQL setup to store credit card information.

It seems like AES_ENCRYPT/AES_DECRYPT is the way to go,

but I'm still confused on one point:

How do I keep the encryption key secure?

Hardwiring it into my PHP scripts (which will live on the same server as the db) seems like a major security hole.

What's the "best practice" solution here?

[A]
You should think long and hard about whether you REALLY need to keep the CC#. If you don't have a great reason, DON'T! Every other week you hear about some company being compromised and CC#'s being stolen. All these companies made a fatal flaw - they kept too much information. Keep the CC# until the transaction clears. After that, delete it.
As far as securing the server, the best course of action is to secure the hardware and use the internal system socket to MySQL, and make sure to block any network access to the MySQL server. Make sure you're using both your system permissions and the MySQL permissions to allow as little access as needed. For some scripts, you might consider write-only authentication. There's really no encryption method that will be foolproof (as you will always need to decrypt, and thus must store the key). This is not to say you shouldn't - you can store your key in one location and if you detect system compromise you can destroy the file and render the data useless.


q:
What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

No legacy browser compatibility required, Safari, Opera and Firefox will do.

[A]
Hey, this is in dojo, just cause it's what I had the code in already for a project.
It should be fairly Obvious how to convert it back to non dojo vanilla JavaScript.
```
```
function onMouseClick(e) {
      var x = e.clientX;
      var y = e.clientY;
  }
  var canvas = dojo.byId(canvasId);
  dojo.connect(canvas,"click",onMouseClick);
```
```
Hope that helps.


q:
In effect, if I have a class c and instances of $c1 and $c2
which might have different private variable amounts but all their public methods return the same values I would like to be able to check that $c1 == $c2?

Does anyone know an easy way to do this?

[A]
You can define PHP's
__toString
magic method inside your class.
For example
```
```
class cat {
    private $name;
    public function __contruct($catname) {
        $this->name = $catname;
    }

    public function __toString() {
        return "My name is " . $this->name . "\n";
    }
}

$max = new cat('max');
$toby = new cat('toby');
print $max; // echoes 'My name is max'
print $toby; // echoes 'My name is toby'

if($max == $toby) {
    echo 'Woohoo!\n';
} else {
    echo 'Doh!\n';
}
```
```
Then you can use the equality operator to check if both instances are equal or not.
HTH,
Rushi


q:
I want to write a word addin that does some computations and updates some ui whenever the user types something or moves the current insertion point. From looking at the MSDN docs, I don't see any obvious way such as an TextTyped event on the document or application objects.

Does anyone know if this is possible without polling the document?

[A]
As you've probably discovered,
Word has events
, but they're for really coarse actions like a document open or a switch to another document.  I'm guessing MS did this intentionally to prevent a crappy macro from slowing down typing.
In short, there's no great way to do what you want.
A Word MVP confirms that in this thread.


q: Is there a simple method of parsing XML files in C#? If so, what?

[A]
I'd use
LINQ to XML
if you're in .NET 3.5 or higher.


q:
I am following the M-V-VM pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple.

Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class?

[A]
Can you not just handle the TextChanged event and execute the command from there?
```
```
private void _textBox_TextChanged(object sender, EventArgs e)
{
    MyCommand.Execute(null);
}
```
```
The alternative, as you say, is to create a
```
TextBox
```
that acts as a command source, but that does seem like overkill unless it's something you're planning on sharing and leveraging in many places.


q: In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?

[A]
```
```
catch (...)
{
   // Handle exceptions not covered.
}
```
```
Important considerations:
A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.
catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from.  Catching them in this way and then swallowing them and continuing could cause further serious problems in your program.
Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown.  In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up.  However you should read up on the
RAII pattern
if you choose this route.


q:
I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask).

What's the best way to determine the image format in .NET?

The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose.

[A]
Try loading the stream into a System.IO.BinaryReader.
Then you will need to refer to the specifications for each image format you need, and load the header byte by byte to compare against the specifications.  For example here are the
PNG specifications
Added:  The actual
file structure
for PNG.


q:
Is it possible to detect when the user clicks on the browser's back button?

I have an Ajax application and if I can detect when the user clicks on the back button I can display the appropriate data back

Any solution using PHP, JavaScript is preferable. Hell a solution in any language is fine, just need something that I can translate to PHP/JavaScript

Edit: Cut and paste from below:

Wow, all excellent answers. I'd like to use Yahoo but I already use Prototype and Scriptaculous libraries and don't want to add more ajax libraries. But it uses iFrames which gives me a good pointer to write my own code.

[A]
There are multiple ways of doing it, though some will only work in certain browsers.  One that I know off the top of my head is to embed a tiny near-invisible iframe on the page.  When the user hits the back button the iframe is navigated back which you can detect and then update your page.
Here
is another solution.
You might also want to go view source on something like gmail and see how they do it.
Here's
a library for the sort of thing you're looking for by the way


q:
Is there a web service of some sort (or any other way) to pull a current time zone settings for a (US) city. For the parts of the country that don't follow the Daylight Saving Time and basically jump timezones when everyone else is switching summer/winter time... I don't fancy creating own database of the places that don't follow DST. Is there a way to pull this data on demand?

I need this for the database server (not for client workstations) - there entities stored in the database that have City, State as properties. I need know current timezone for these entities at any moment of time.

[A]
earthtools.org provides a free web service to get the time zone from a city here:
http://www.earthtools.org/webservices.htm#timezone
You just pass in the long/lat values like this: (This is for New York)
http://www.earthtools.org/timezone-1.1/40.71417/-74.00639
EDIT:
It seems like earthtools has been shut down. A good alternative (That did not exist in 2008 when this question was answered) is the Google Time Zone API. To use it you must first
activate the Time Zone API
on your account. It is free if you stay below these limits:
2500 requests per 24 hour period.
5 requests per second.
The documentation
is available on Google Developers.


q:
I've recently had to switch from Visual Studio to Eclipse CDT.

It would seem that Eclipse "workspaces" are not quite like VS solution files.

Eclipse workspaces use the .metadata folder for managing multiple projects, but there doesn't seem to be a simple distinction between user settings or IDE preferences and project/solution settings.

What I want is a way to group a collection of related (and dependent) projects together and have that data live in source control without all the other user specific stuff that developers don't need to share.
You know, like a .sln file in Visual Studio.

Does Eclipse just not work this way?  (And if not, then why not?)

[A]
I often find IDE's have a preferred way to work. Sure, you might be able to get the IDE to do it your way, but you'll probably end up fighting it all the way.
Try to use your IDE like their makers intended you to. They have made presumptions on how you are supposed to do your work. They have optimized the user experience according to those presumptions.
Go with the flow. Anything else will make you gnarly, bitter, wrinkly and give you gastly breath!
Corollary
: If you can, choose the IDE that makes the same presumptions about workflow as you do!


q: is there an alternative for mysql_insert_id() php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....

[A]
Check out the
RETURNING optional clause
for an INSERT statement. (Link to official PostgreSQL documentation)
But basically, you do:
```
```
INSERT INTO table (col1, col2) VALUES (1, 2) RETURNING pkey_col
```
```
and the INSERT statement itself returns the id (or whatever expression you specify) of the affected row.


q:
I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop.  I'm not being lazy.  Far from it.  It's that I'm overwrought with exception handling ambivalence.  It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill.

I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen.

So, what are your exception handling best practices?  In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered?

Sorry for the vague the question but I really want to close the book on this once and for all.

[A]
Microsoft's
Patterns & Practices team
did a good job incorporating best practices of exception management into Enterprise Library
Exception Handling Application Block
Event if wouldn't use Enterprise Library, I
highly
recommend you to read their documentation. P&P team describes common scenarios and best practices for exceptions handling.
To get you started I recommend read following articles:
Exception Handling
on MSDN
Exception Management in .NET
on MSDN
Exception Handling Best Practices in .NET
on CodeProject
ASP.NET specific articles:
User Friendly ASP.NET Exception Handling
Global Exception Handling with
ASP.NET
Exception handling in C# and ASP
.Net


q: I need some software to explore and modify some SQLite databases.  Does anything similar to SQL Server Management Studio or MySQLAdmin exist for it?

[A]
As a Firefox plugin
(aimed mainly at gears, but should work)
As a (sucky) web based app
And
a big list of management tools


q:
I know how to test an object to see if it is of a type, using the IS keyword e.g.

if (foo is bar)
{
  //do something here
}

but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result.

BTW  - I have a horrible feeling this is soooo obvious, so apologies in advance...


q:
What is the difference between const and readonly in C#?

When would you use one over the other?

[A]
I believe a
```
const
```
value is the same for all objects (and must be initialized with a literal expression), whereas
```
readonly
```
can be different for each instantiation...


q: According to the documentation, they're pretty much interchangeable.  Is there a stylistic reason to use one over the other?

[A]
Your team's taste or your project's coding guidelines.
If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of '


q:
I am working with fixtures on rails and I want one of the fixture fields to be blank.

Example:

two:
name: test
path: - I want this blank but not to act as a group heading.
test: 4

But, I do not know how to leave path: blank without it acting as a group title.  Does anybody know how to do that?

[A]
Google
says
the following should work:
```
```
path: \"\"
```
```


q:
I'm having some internationalisation woes:

My UTF-8 string fields are being rendered in the browser as ???? after being returned from the database.

After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger.

However Struts2/Tiles is rendering these strings as ???? in the HTML sent to the browser.

The charset directive is present in the HTML header:

Perhaps I need to add something to my struts2 or tiles configurations?

[A]
Try setting the lang attribute on the <html/> element.
HTML example:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja">
```
XHTML example:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
```


q:
How can i stop the host machine entering standby mode while my application is running?

Is there any win32 api call to do this?

[A]
This article
http://www.codeguru.com/cpp/w-p/system/messagehandling/article.php/c6907
provides a demo of how to do this from C++ (thought he article is framed as if you want to do it from Java, and provides a Java wrapper).
The actual code in in a zip file at
http://www.codeguru.com/dbfiles/get_file/standbydetectdemo_src.zip?id=6907&lbl=STANDBYDETECTDEMO_SRC_ZIP&ds=20040406
and the C++ part of it is under com/ha/common/windows/standbydetector.
Hopefully it will give you enough of a direction to get started.


q: I know about the "cooperative" threading of ruby using green threads. How can I create real "OS-level" threads in my application in order to make use of multiple cpu cores for processing?

[A]
Ruby 1.8 only has green threads, there is no way to create a real "OS-level" thread.  But, ruby 1.9 will have a new feature called fibers, which will allow you to create actual OS-level threads.  Unfortunately, Ruby 1.9 is still in beta, it is scheduled to be stable in a couple of months.
Another alternative is to use JRuby.  JRuby implements threads as OS-level theads, there are no "green threads" in it.  The latest version of JRuby is 1.1.4 and is equivalent to Ruby 1.8


q:
I have a project which is source controlled using Subversion and VisualSVN. Since the version of web.config is different on the server and the developers' computers I want the file to remain on the computers but to be ignored by Subversion. I added it to the svn:ignore but it still remains (and still has a red exclamation mark too since we are not committing it).

How can I remove it from Subversion safely without it being deleted from the files system

Thanks,
Adin

[A]
```
```
svn rm --force web.config
svn commit
```
```
Be careful to back up your local copy (of web.config) before doing this, since it will be deleted.


q:
I am trying to write a formula in ActionScript 3 that will give me var "z" (please see image below) in degrees, which I will then convert to radians.

I will already know the value of vars "x" and "y". Using trigonometry, how can I calculate the length of the hypotenuse and therefore the variable angle of var z?  A solution in either AS3 or psuedocode would be very helpful. Thanks.

[A]
z is equivalent to 180 - angle of yH. Or:
```
```
180 - arctan(x/y) //Degrees
pi - arctan(x/y) //radians
```
```
Also, if actionscript's math libraries have it, use arctan2, which takes both the x and y and deals with signs correctly.


q:
I have used IPC in Win32 code a while ago - critical sections, events, and semaphores.

How is the scene in the .NET environment?
Are there any tutorial explaining all available options and when to use and why?

[A]
Most recent Microsoft's stuff in IPC is
Windows Communication Foundation
. Actually there is nothing new in the lower level (tcp, upd, named pipes etc) But WCF simplifies IPC development greatly.
Useful resource:
Interprocess Communication with WCF
on Dr. Dobb's portal
WCF Communication Options in the .NET Framework 3.5
and of course
MSDN on WCF


q:
Can I run a 64-bit VMware image on a 32-bit machine?

I've googled this, but there doesn't seem to be a conclusive answer.

I know that it would have to be completely emulated and would run like a dog - but slow performance isn't necessarily an issue as I'm just interested in testing some of my background services code on 64-bit platforms.

[A]
I honestly doubt it, for a number of reasons, but the most important one is that there are some instructions that are allowed in 32-bit mode, but not in 64-bit mode.  Specifically, the REX prefix that is used to encode some instructions and registers in 64-bit mode is a byte of the form 0x4f:0x40, but in 32 bit mode the same byte is either INC or DEC with a fixed operand.
Because of this, any 64-bit instruction that is prefixed by REX will be interpreted as either INC or DEC, and won't give the VMM the chance to emulate the 64-bit instruction (for instance by signaling an undefined opcode exception).
The only way it might be done is to use a trap exception to return to the VMM after each and every instruction so that it can see if it needs special 64-bit handling.  I simply can't see that happening.


q:
How do you store file permissions in a repository? A few files need to be read-only to stop a third party program from trashing it but after checking out of the repository they are set to read-write.

I looked on google and found a blog post from 2005 that states that Subversion doesn't store file-permissions. There are patches and hook-scripts listed (only one url still exists). Three years later does Subversion still not store file permissions and are hooks the only way to go about this? (I've never done hooks and rather use something that is native to Subversion.)

[A]
Consider using
```
svn lock
```
to disallow others from writing to the file.


q: How to obtain Vista Edition programmatically, that is Home Basic, Home Premium, Business or Ultimate ?

[A]
MSDN gives extensive answer:
Getting the System Version


q:
I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?

This is similar to what I'm actually doing:

import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love &aacute; letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')

# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love &amp;aacute;
letters'</script></head><body><h1>And I like the fact that 3 &gt; 1</h1>
</body></html>

[A]
don't you actually want something like:
```
```
html(head(script(type='text/javascript', content='var a = ...')),
body(h1('And I like the fact that 3 < 1'), p('just some paragraph'))
```
```
I think I saw something like that somewhere. This would be wonderful.
EDIT:
Actually, I went and wrote a library today to do
just that
:
magictree
You can use it like this:
```
```
from magictree import html, head, script, body, h1, p
root = html(
         head(
           script('''var a = 'I love &aacute; letters''',
                  type='text/javascript')),
         body(
           h1('And I like the fact that 3 > 1')))

# root is a plain Element object, like those created with ET.Element...
# so you can write it out using ElementTree :)
tree = ET.ElementTree(root)
tree.write('foo.xhtml')
```
```
The magic in
```
magictree
```
lies in how the importing works: The
```
Element
```
factories are created when needed. Have a
look at the source
, it is
based on an answer to another StackOverflow question
.


q:
We're building a CMS. The site will be built and managed by the users in aspx pages, but we would like to create a static site of HTML's.
The way we're doing it now is with code I found here that overloads the Render method in the Aspx Page and writes the HTML string to a file. This works fine for a single page, but the thing with our CMS is that we want to automatically create a few HTML pages for a site right from the start, even before the creator has edited anything in the system.
Does anyone know of any way to do this?

[A]
Calling the
```
Render
```
method is still pretty simple. Just create an instance of your page, create a stub
```
WebContext
```
along with the
```
WebRequest
```
object, and call the
```
Render
```
method of the page. You are then free to do whatever you want with the results.
Alternatively, write a little
```
curl
```
or
```
wget
```
script to download and store whichever pages you want to make static.


q:
I need to specify a date value in a sybase where clause. For example:

select *
from data
where dateVal < [THE DATE]

[A]
Use the convert function, for example:
```
```
select * from data
where dateVal < convert(datetime, '01/01/2008', 103)
```
```
Where the convert style (103) determines the date format to use.


q:
Is anyone out there using D for real world applications? If so, what are you using it for? I can't seem to find anything big on the web written in D.

Despite the lack of known big users, D seems like a very promissing language to me, and according to TIOBE, it's fairly popular.

[A]
I suppose we can read something into the lack of immediate answers to this question and that is that not many/any of the acive stackoverflow responders are using D. I was also a little surprised about the level of its ranking in the TIOBE listing that you link to.
Having said that, Walter Bright has been working on the language for quite a number of years now and I think he has quite a number of `followers' who remember what a good job he did with the Zortech C++ compiler back in the '90s. I also note that the language appears to be leaning towards the functional direction now.


q:
Suppose that two tables exist: users and groups.

How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?

The result of the search must distinguish between the two types.

[A]
The trick is to combine a
```
UNION
```
with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:
```
```
SELECT "group" type, name
   FROM groups
  WHERE name LIKE "%$text%"
UNION ALL
 SELECT "user" type, name
   FROM users
  WHERE name LIKE "%$text%"
```
```
NOTE
: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it.


q:
I have a class in system-C with some data members as such:

long double x[8];

I'm initializing it in the construction like this:

for (i = 0; i < 8; ++i) {
    x[i] = 0;
}

But the first time I use it in my code I have garbage there.

Because of the way the system is built I can't connect a debugger easily.  Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?

Edit:
@Prakash:
Actually, this is a typo in the question, but not in my code...  Thanks!


q:
I'm starting to learn ruby. I'm also a day-to-day C++ dev.
For C++ projects I usually go with following dir structure

/
 -/bin <- built binaries
 -/build <- build time temporary object (eg. .obj, cmake intermediates)
 -/doc <- manuals and/or Doxygen docs
 -/src
 --/module-1
 --/module-2
 -- non module specific sources, like main.cpp
 - IDE project files (.sln), etc.

What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable?

[A]
Why not use just the same layout? Normally you won't need build because there's no compilation step, but the rest seems OK to me.
I'm not sure what you mean by a module but if it's just a single class a separate folder wouldn't be necessary and if there's more than one file you normally write a module-1.rb file (at the name level as the module-1 folder) that does nothing more than require everything in module-1/.
Oh, and I would suggest using
Rake
for the management tasks (instead of make).


q:
I am writing a unit test to check that a private method will close a stream.

The unit test calls methodB and the variable something is null

The unit test doesn't mock the class on test

The private method is within a public method that I am calling.

Using emma in eclipse (via the eclemma plugin) the method call is displayed as not being covered even though the code within the method is

e.g

public methodA(){

    if (something==null) {
        methodB(); //Not displayed as covered
    }
}

private methodB(){
    lineCoveredByTest; //displayed as covered
}

Why would the method call not be highlighted as being covered?

[A]
I assume when you say 'the unit test calls
```
methodB()
```
', you mean not directly and via
```
methodA()
```
.
So, is it possible
```
methodB()
```
is being called elsewhere, by another unit test or
```
methodC()
```
maybe?


q:
I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments.

For horizontal alignment I can use text-anchor with left, middle or right. I can't find a equivalent for vertical alignment; alignment-baseline doesn't seem to do it, so at present I'm using dy="0.5ex" as a kludge for centre alignment.

Is there a proper manner for aligning with the vertical centre or top of the text?

[A]
It turns out that you don't need explicit text paths. Firefox 3 has only partial support of the vertical alignment tags (
see this thread
). It also seems that dominant-baseline only works when applied as a style whereas text-anchor can be part of the style or a tag attribute.
```
```
<path d="M10, 20 L17, 20"
      style="fill:none; color:black; stroke:black; stroke-width:1.00"/>
<text fill="black" font-family="sans-serif" font-size="16"
      x="27" y="20" style="dominant-baseline: central;">
  Vertical
</text>

<path d="M60, 40 L60, 47"
      style="fill:none; color:red; stroke:red; stroke-width:1.00"/>
<text fill="red" font-family="sans-serif" font-size="16"
      x="60" y="70" style="text-anchor: middle;">
  Horizontal
</text>

<path d="M60, 90 L60, 97"
      style="fill:none; color:blue; stroke:blue; stroke-width:1.00"/>
<text fill="blue" font-family="sans-serif" font-size="16"
      x="60" y="97" style="text-anchor: middle; dominant-baseline: hanging;">
  Bit of Both
</text>
```
```
This works in Firefox. Unfortunately Inkscape doesn't seem to handle dominant-baseline (or at least not in the same way).


q:
We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client.  We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects?

Thanks for your time!

[A]
I have no Dabo experience at all but this question is on the top of the list fo such a long time that I decided to give it a shot:
Framework selection
Assumptions:
medium-to-big project: we're talking about a team of more than 20 people working on something for about a year for the first phase. This is usually an expensive and very important effort for the client.
this project will have significant amount of users (around a hundred) so performance is essential
it's an ERP project so the application will work with large amounts of information
you have no prior Dabo experience in your team
Considerations:
I could not open Dabo project site right now. There seems to be some server problem. That alone would make me think twice about using it for a big project.
It's not a well-known framework.  Typing Dabo in Google returns almost no useful results, it does not have a Wikipedia page, all-in-all it's quite obscure. It means that when you will have problems with it (and you will have problems with it) you will have almost no place to go. Your question was unanswered for 8 days on SO, this alone would make me re-consider. If you base your project on an obscure technology you have no previous experience with - it's a huge risk.
You don't have people who know that framework in your team. It means that you have to learn it to get any results at all and to master it will require quite significant amount of time. You will have to factor that time into your project plan. Do you really need it?
What does this framework give you that you cannot do yourself? Quite a lot of time my team tried to use some third-party component or tool only to find that building a custom one would be faster than dealing with third-party problems and limitations. There are brilliant tools available to people nowadays and we would be lost without them - but you have to carefully consider if this tool  is one of them
Dabo project version is 0.84. Do you know if they spend time optimising their code for performance at this stage? Did you run any tests to see it will sustain the load you have in your NFRs.
Hope that helps :) Good luck with your project


q: I've got it configured, but I want more from it...maybe Cygwin isn't the right tool, but I like how it provides a *nix-like environment within Windows.

[A]
I'm quite interested in this question myself. I've used the
Cygwin Setup guide
to get set up, but it doesn't get you all the way. One thing that I learned from it, though, is that it recommends leaving the setup.exe in the directory with Cygwin so that you can quickly add packages, since apt-get apparently doesn't work that well in Cygwin. The article also talks about cyg-get as an alternative.


q:
I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (FROM WINDOWS, not fox):

Windows-No disk
Exception Processing Message c0000012 Parameters .....

Any help please
Nelson Marmol

[A]
Nelson:
"That's how foxpro does it and there is no way around it"?
I'm using FOX since FoxPro 2.5 to Visual FoxPro 9, and you are NEVER forced in any way to hard-code a path, you can use SET PATH TO (sYourPath), you can embed the icons and bitmaps in your EXE / APP file and therefore there's no need of including this resources externally.
You say that you have a "Foxpro App": which version? Old MS-DOS FoxPro o Visual FoxPro?
If you're using VFP 8+, you can use SYS(2450, 1):
```
```
Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on.

You can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.

SYS(2450 [, 0 | 1 ])

Parameters
0
Search along path and default locations before searching in the application. (Default)

1
Search within the application for the specified procedure or UDF before searching the path and default locations.
```
```
One quick workaround could be assign another letter to your USB via the Disk Manager.


q:
I am looking for a reliable technique for adding Ajax to a working ASP.NET MVC application. I want to use jQuery, and understand how to use the AJAX functionality from jQuery.

What I need to know is how I should write my controller so that I can run the site without JavaScript, but at the same time make AJAX calls possible without the need for a separate view, separate controller, or any kind of route hack. My goal is to have a working application enhanced when JavaScript is enabled without the need to duplicate or recreate elements of the app.

[A]
Typically you would create your site so that it works without JavaScript being enabled. Then you would add the
unobtrusive JavaScript
needed to enhance your site with Ajax e.g. adding event handlers for links, form submits, etc. to make GET / POST requests and update your UI accordingly.
The only changes you would need in your MVC app would be to handle the Ajax requests and return the data as JSON, XML, etc.


q:
I'm trying to send messages to Objective-C objects in gdb.

(gdb) p $esi
$2 = (void *) 0x1268160
(gdb) po $esi
<NSArray: 0x1359c0>
(gdb) po [$esi count]
Target does not respond to this message selector.

I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?

[A]
Is it possible that you need to cast
```
$esi
```
?
```
```
p (NSUInteger)[(NSArray *)$esi count]
```
```


q:
I am looking for a way to interact with a standalone full version of Windows Media Player.

Mostly I need to know the Path of the currently played track.

The iTunes SDK makes this really easy but unfortunately there really isn't any way to do it with Windows Media Player, at least not in .Net(C#) without any heavy use of pinvoke, which I am not really comfortable with.

Thanks

Just to clearify: I don't want to embedded a new instance of Windows Media Player in my app, but instead control/read the "real" full version of Windows Media Player, started seperatly by the user

[A]
I had this
https://social.msdn.microsoft.com/Forums/vstudio/en-US/dbd43d7e-f3a6-4087-be06-df17e76b635d/windows-media-player-remoting-in-c?forum=clr
in my bookmarks but have NOT tested it in anyway. Just a pointer in the right direction. It's nothing official and will require a bit of digging, but you should get a fairly simple wrapper (which will still use PInvoke under the hood - but you won't see it) around Windows Media Player.
Hope that helps.
Oh, I misunderstood. I thought you were talking about controlling the currently running Windows Media Player instance. If you are hosting Windows Media Player yourself then WMPLib is certainly the better solution.


q: In C# are the nullable primitive types (i.e. bool?) just aliases for their corresponding Nullable<T> type or is there a difference between the two?

[A]
A
```
Nullable<T>
```
is a structure consisting of a T and a bit flag indicating whether or not the T is valid.  A
```
Nullable<bool>
```
has three possible values: true, false and null.
Edit:
Ah, I missed the fact that the question mark after "bool" was actually part of the type name and not an indicator that you were asking a question :).  The answer to your question, then, is "yes, the C#
```
bool?
```
is just an alias for
```
Nullable<bool>
```
".


q: How do you perform a CROSS JOIN with LINQ to SQL?

[A]
A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.
```
var combo = from p in people
            from c in cars
            select new
            {
                p.Name,
                c.Make,
                c.Model,
                c.Colour
            };
```


q: Does a new SessionFactory and Session object have to be created for each database? I have a data store for my application data, and a separate data store for my employee security, which is used to validate users. Do I have to create a new SessionFactory ans Session object for calls to the 2 different databases?

[A]
ok so this doesn't answer your question directly but it might offer an insight as to why you should create multiple session objects for each datastore.
This article
explains how you can implement a thread safe lazy singleton for each type of Session you need so that you only have one session per datastore but it's shared across the entire application. So at most you're only ever going to have 2 session objects.
To directly answer your question however, you will need 1 session object per database.


q:
Possible Duplicate:

  Debugging JavaScript in IE7

Firefox has Web Developer plugin and Firebug for troubleshooting html/css/javascript issues. Google Chrome and Safari have a very similar console and right-click options for "Inspect Element".

Does IE7 have anything similar for troubleshooting layout/html/css issues?

[A]
Web Development Helper
Web Development Helper is a free browser extension for Internet Explorer that provides a set of tools and utilities for the Web developer, esp. Ajax and ASP.NET developers. The tool provides features such as a DOM inspector, an HTTP tracing tool, and script diagnostics and immediate window.
Web Development Helper works against IE6+, and requires the .NET Framework 2.0 or greater to be installed on the machine.
Once installed, the tool can be activated using the Tools | Web Development Helper command. You can also customize your browser's toolbar to add a button for this command to facilitate frequest use. Clicking on the menu command or browser button brings up the tool's console window and set of commands.
Page Features:
DOM inspector allows viewing all elements, selected elements, or elements matching an ID or CSS class, their attributes and styles.
Capturing a screen shot of the current page.
Viewing page information such as metadata, tags, and linked resources.
.......


q: I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log?

[A]
Here is a simple and
very inelegant
&
potentially dangerous
way.
Backup DB
Detach DB
Rename Log file
Attach DB
New log file will be recreated
Delete Renamed Log file.
I'm guessing that you are not doing log backups. (Which truncate the log). My advice is to change recovery model from
full
to
simple
. This will prevent log bloat.


q:
Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments.  It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen.  (To see an example, click here.)

My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down?  I know this will involve a combination of CSS and javascript.  I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?

[A]
Okay, I figured it out.  I will post it here in case it help anyone else.  This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think.
```
```
var MenuManager = Class.create({
    initialize: function initialize(menuElt) {
        this.menu = $(menuElt);
        this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) };
        registerEvent(document, 'scroll', this.handleScroll.bind(this));
        this.handleScroll();
    },
    handleScroll: function handleScroll() {
        this.scrollOffset = document.viewport.getScrollOffsets().top;
        if (this.scrollOffset > this.homePosn.y) {
            this.menu.style.position = 'fixed';
            this.menu.style.top = 0;
            this.menu.style.left = this.homePosn.x;
        } else {
            this.menu.style.position = 'absolute';
            this.menu.style.top = null;
            this.menu.style.left = null;
        }
    }
});
```
```
Just call the constructor with the id of your menu, and the class will take it from there.


q:
I want to convert a number that is in PRTime format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a DateTime.

Note that this is slightly different than the usual "number of milliseconds since 1/1/1970".

[A]
```
```
Dim prTimeInMillis As UInt64
prTimeInMillis = prTime/1000

Dim prDateTime As New DateTime(1970, 1, 1)
prDateTime = prDateTime.AddMilliseconds(prTimeInMillis)
```
```


q:
I am building on C++ dll, by writing code in C#.

I get an error, saying

LoaderLock was detected Message:
  Attempting managed execution inside OS
  Loader lock. Do not attempt to run
  managed code inside a DllMain or image
  initialization function since doing so
  can cause the application to hang.

I tried seraching what this error exactly means, but I am drawing pointless articles, mostly saying that it's just a warning, and I should switch that off in Visual Studio.
The other solutions seem to be due to ITunes, or this problem occurring when programming with DirectX. My problem is connected to neither.

Can anybody explain, what this actually means?

[A]
The general idea of loader lock:
The system runs the code in DllMain inside a lock (as in - synchronization lock). Therefore, running non-trivial code inside DllMain is "asking for a deadlock", as described
here
.
The question is, why are you trying to run code inside DllMain? Is it crucial that this code run inside the context of DllMain or can you spawn a new thread and run the code in it, and not wait for the code to finish execution inside DllMain?
I believe that the problem with manged code specifically, is that running managed code might involves loading the CLR and suchlike and there's no knowing what could happen there that would result in a deadlock... I would not heed the advice of "disable this warning" if I were you because most chances are you'll find your applications hangs unexpectedly under some scenarios.


q:
If you have an NSMutableArray, how do you shuffle the elements randomly?

(I have my own answer for this, which is posted below, but I'm new to Cocoa and I'm interested to know if there is a better way.)

Update: As noted by @Mukesh, as of iOS 10+ and macOS 10.12+, there is an -[NSMutableArray shuffledArray] method that can be used to shuffle. See https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc for details. (But note that this creates a new array, rather than shuffling the elements in place.)

[A]
I solved this by adding a category to NSMutableArray.
Edit:
Removed unnecessary method thanks to answer by Ladd.
Edit:
Changed
```
(arc4random() % nElements)
```
to
```
arc4random_uniform(nElements)
```
thanks to answer by Gregory Goltsov and comments by miho and blahdiblah
Edit:
Loop improvement, thanks to comment by Ron
Edit:
Added check that array is not empty, thanks to comment by Mahesh Agrawal
```
```
//  NSMutableArray_Shuffling.h

#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#include <Cocoa/Cocoa.h>
#endif

// This category enhances NSMutableArray by providing
// methods to randomly shuffle the elements.
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end

//  NSMutableArray_Shuffling.m

#import "NSMutableArray_Shuffling.h"

@implementation NSMutableArray (Shuffling)

- (void)shuffle
{
    NSUInteger count = [self count];
    if (count <= 1) return;
    for (NSUInteger i = 0; i < count - 1; ++i) {
        NSInteger remainingCount = count - i;
        NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
        [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
    }
}

@end
```
```


q: I have an application running under Windows XP, and I'm accessing the Processor and Memory performance counters.  When I try to run the same code and access them on XP Embedded, the counters don't seem to be present.  They are present in the image - I can see them all in perfmon.  What's the missing piece here?

[A]
Have you added all the WMI components? As far as I know, you need all the WMI components to access the counters!
The Performance Counter Windows Management Instrumentation (WMI) Provider component provides a bridge between the performance registry interface and the WMI interface. This component allows WMI clients to access performance counters through WMI scripts, and allows management applications built using WMI to access performance counters. Without this component, applications must directly use the registry interface or the performance data helper interface to access performance counters.
Thank you TimK for the link (
http://msdn.microsoft.com/en-us/library/aa939695.aspx
)


q:
Summary

What's the best way to ensure a table cell cannot be less than a certain minimum width.

Example

I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space.

Browser compatibility

I possible I would like to find a solution that works in

IE 6-8

FF 2-3

Safari

In order of preference.

[A]
This CSS should suffice:
```
```
td { min-width: 100px; }
```
```
However, it's not always obeyed correctly (the min-width attribute) by all browsers (for example, IE6 dislikes it a great deal).
Edit:
As for an IE6 (and before) solution, there isn't one that works reliably under all circumstances, as far as I know.  Using the nowrap HTML attribute doesn't really achieve the desired result, as that just prevents line-breaks in the cell, rather than specifying a minimum width.
However, if nowrap is used in conjunction with a regular cell width property (such as using width: 100px), the 100px will act
like
a minimum width and the cell will still expand with the text (due to the nowrap).  This is a less-than-ideal solution, which cannot be fully applied using CSS and, as such, would be tedious to implement if you have many tables you wish to apply this to.  (Of course, this entire alternative solution falls down if you want to have dynamic line-breaks in your cells, anyway).


q:
I hope not everyone is using Rational Purify.

So what do you do when you want to measure:

time taken by a function

peak memory usage

code coverage

At the moment, we do it manually [using log statements with timestamps and another script to parse the log and output to excel. phew...)

What would you recommend? Pointing to tools or any techniques would be appreciated!

EDIT: Sorry, I didn't specify the environment first, Its plain C on a proprietary mobile platform

[A]
nProf
- Free, does that for .NET.
Gets the job done, at least enough to see the 80/20. (20% of the code, taking 80% of the time)


q:
In Windows, is there an easy way to tell if a folder has a subfile that has changed?

I verified, and the last modified date on the folder does not get updated when a subfile changes.

Is there a registry entry I can set that will modify this behavior?

If it matters, I am using an NTFS volume.

I would ultimately like to have this ability from a C++ program.

Scanning an entire directory recursively will not work for me because the folder is much too large.

Update: I really need a way to do this without a process running while the change occurs.  So installing a file system watcher is not optimal for me.

Update2: The archive bit will also not work because it has the same problem as the last modification date.  The file's archive bit will be set, but the folders will not.

[A]
If you can't run a process when the change occurs, then there's not much you can do except scan the filesystem, and check the modification date/time.  This requires you to store each file's last date/time, though, and compare.
You can speed this up by using the
archive bit
(though it may mess up your backup software, so proceed carefully).
An archive bit is a file attribute
  present in many computer file systems,
  notably FAT, FAT32, and NTFS. The
  purpose of an archive bit is to track
  incremental changes to files for the
  purpose of backup, also called
  archiving.
As the archive bit is a binary bit, it
  is either 1 or 0, or in this case more
  frequently called set (1) and clear
  (0). The operating system sets the
  archive bit any time a file is
  created, moved, renamed, or otherwise
  modified in any way. The archive bit
  therefore represents one of two
  states: "changed" and "not changed"
  since the last backup.
Archive bits are not affected by
  simply reading a file. When a file is
  copied, the original file's archive
  bit is unaffected, however the copy's
  archive bit will be set at the time
  the copy is made.
So the process would be:
Clear the archive bit on all the files
Let the file system change over time
Scan all the files - any with the archive bit set have changed
This will eliminate the need for your program to keep state, and since you're only going over the directory entries (where the bit is stored) and they are clustered, it should be very, very fast.
If you can run a process during the changes, however, then you'll want to look at the
FileSystemWatcher
class.  Here's an
example
of how you might use it.
It also exists in
.NET
(for future searchers of this type of problem)
Perhaps you can leave a process running on the machine watching for changes and creating a file for you to read later.
-Adam


q:
Just got a request from my boss for an application I'm working on. Basically we're getting an email address setup for an external client to submit excel files to.

What I need is a way to automatically pick up any email sent to this address, so I can take the attachment, process it and save it to a folder.

Any information of even where to start would be helpful.\

Note: We're using a lotus notes server to do this, but a generic way would be more helpful (If possible).

[A]
Email -> mailserver ->[something] -> file-on-disk.
File on disk is pretty easy to parse, use
JavaMail
.
The [something] could be:
listener for smtp connections (overkill)!
Pop3
/
imap
client
Maildir
/Mailbox


q: When using an aggregate control in some reports you would prefer to see a blank field instead of 0.  There does not appear to be a way to do this automatically.  Does anyone have a way that this can be done.  Note, you want to maintain the '0' value for the field in cases when you export, but you want to show a blank when rendering to PDF or HTML.

[A]
There are a number of ways to solve this.  The two primary are to use either visibility rules or highlights to create conditional formatting.  The visibility is particularly attractive since it is easy to only apply the format rules to particular types of output (e.g. HTML).
For this particular case, there are two problems with these approaches.  First, I want a general solutions where I don't have to specify the text color.  In other words, when the condition is true (value of 0) then I want my text color to match the background color.  In that way if someone changes the backgroundColor for the control, the code still works.
The other issue is that in this case I am using dynamic column binding which does not support value lookup.
The solution that I created was to add a JavaScript function called hideMe as shown below.
```
```
function hideText (dataControl){
    if (dataControl.getValue() == 0) {
        var color = dataControl.getStyle().getBackgroundColor();
        var parentItem = dataControl.getParent();
        do {
            if (color == null && parentItem != null) {
                color = parentItem.getStyle().getBackgroundColor();
                parentItem = parentItem.getParent();
            } else {
                break;
            }

        } while (color == null);
        dataControl.getStyle().color = color;
    }
}
```
```
Once this function has been added to the report (in my case an included javascript file) I just call it from the OnCreate method of the control.
```
```
hideText(this);
```
```
This can also be done using Java Event Handlers but this method seems to be easier.


q:
Is the standard Java 1.6 javax.xml.parsers.DocumentBuilder class thread safe? Is it safe to call the parse() method from several threads in parallel?

The JavaDoc doesn't mention the issue, but the JavaDoc for the same class in Java 1.4 specifically says that it isn't meant to be concurrent; so can I assume that in 1.6 it is?

The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.

[A]
Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:
```
```
private static final ThreadLocal<DocumentBuilder> builderLocal =
    new ThreadLocal<DocumentBuilder>() {
        @Override protected DocumentBuilder initialValue() {
            try {
                return
                    DocumentBuilderFactory
                        .newInstance(
                            "xx.MyDocumentBuilderFactory",
                            getClass().getClassLoader()
                        ).newDocumentBuilder();
            } catch (ParserConfigurationException exc) {
                throw new IllegalArgumentException(exc);
            }
        }
    };
```
```
(Disclaimer: Not so much as attempted to compile the code.)


q: Is there a way to access file system info via some type of Windows API? If not what other methods are available to a user mode developer?

[A]
Not very clean, but you can use
```
DeviceIoControl()
```
Open volume as a file, pass resulting handle to
```
DeviceIoControl()
```
together with control code. Check MSDN for control codes, there is something like "read journal record".


q:
Is there a difference (performance, overhead) between these two ways of merging data sets?

MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);

and

MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);

Which do you recommend?

[A]
Those two lines do different things.
The first one creates a new set, and then merges a second set into it.
The second one sets the ds reference to point to the second set, so:
```
```
MyTypedDataSet ds1 = new MyTypedDataSet();
ds1.Merge(anotherDataSet);
//ds1 is a copy of anotherDataSet
ds1.Tables.Add("test")

//anotherDataSet does not contain the new table

MyTypedDataSet ds2 = anotherDataSet;
//ds12 actually points to anotherDataSet
ds2.Tables.Add("test");

//anotherDataSet now contains the new table
```
```
Ok, let's assume that what you meant was:
```
```
MyClass o1 = new MyClass();
o1.LoadFrom( /* some data */ );

//vs

MyClass o2 = new MyClass( /* some data */ );
```
```
Then the latter is better, as the former creates an empty object before populating it.
However unless initialising an empty class has a high cost or is repeated a large number of times the difference is not that important.


q:
I'm creating an ASP.NET web site where all pages hang off a database-driven tree-hierarchy.  Pages typically present HTML content.  But, some will execute programming.

Examples:

a "contact us" form

a report generator

How should I represent/reference the programming within the database?  Should I have a varchar value of a Web User Control (.ascx) name?  Or a Web Form (.aspx) name?  Something else?  Or should it just be an integer or other such ID in a dictionary within my application?

Can I make an ASP.NET Site Map Provider with this structure?

See more information here: Which is the best database schema for my navigation?

[A]
Our development team has had success with defining the name of a Web User Control in the database. Upon page load it checks too see what controls to dynamically load from the database.
We use Web User Controls instead of Web Forms in order to ensure we can use the control on any page.
You can also dynamically build a site map using ASP.Net's provider.
CodeProject
has a good example.


q:
I was reviewing some code that a consultant checked in and notice they were using SQLCLR.  I don't have any experience with it so thought I would research what it was about.  I noticed that they used

Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" & sDb)

instead of

DIM conn As New SqlConnection("context connection=true")

I'm wondering what the difference since it's localhost on the first?

[A]
The context connection uses the user's already established connection to the server.  So you inherit things like their database context, connection options, etc.
Using localhost will connect to the server using a normal shared memory connection.  This can be useful if you don't want to use the user's connection (i.e. if you want to connect to a different database, or with different options, etc).
In most cases you should use the context connection, since it doesn't create a separate connection to the server.
Also, be warned that using a separate connection means you are not part of the user's transaction and are subject to normal locking semantics.


q:
The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:

n = 5.59
round(n, 1) # 5.6

But, in actuality, good old floating point weirdness creeps in and you get:

5.5999999999999996

For the purposes of UI, I need to display 5.6. I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. See here also.

Short of creating my own round library, is there any way around this?

[A]
What about:
```
```
round(n,1)+epsilon
```
```


q: My application has a need to let the user choose a date from a list of dates conforming to a certain pattern. For instance, they may need to choose a monday from a list Monday's for a month. Is there a way to get a UIDatePicker to limit date choices to a certain subset or should I just use a UIPickerView?

[A]
You cannot limit which dates are selectable in a
```
UIDatePicker
```
. You could change the date when the value changed event is sent, but since the user cannot tell which dates are "good" and which are not, it's a bad UI choice to do so.
Use a
```
UIPickerView
```
of your own making instead.


q: I have heard that the Liskov Substitution  Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?

[A]
Would implementing ThreeDBoard in terms of an array of Board be that useful?
Perhaps you may want to treat slices of ThreeDBoard in various planes as a Board. In that case you may want to abstract out an interface (or abstract class) for Board to allow for multiple implementations.
In terms of external interface, you might want to factor out a Board interface for both TwoDBoard and ThreeDBoard (although none of the above methods fit).


q:
A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results?

I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like.

(Any sample web service can be chosen as an example.)

[A]
```
```
import org.restlet.Client;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Response;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.Node;

/**
 * Uses YAHOO!'s RESTful web service with XML.
 */
public class YahooSearch {
    private static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";

    public static void main(final String[] args) {
        if (1 != args.length) {
            System.err.println("You need to pass a search term!");
        } else {
            final String term = Reference.encode(args[0]);
            final String uri = BASE_URI + "?appid=restbook&query=" + term;
            final Response response = new Client(Protocol.HTTP).get(uri);
            final DomRepresentation document = response.getEntityAsDom();

            document.setNamespaceAware(true);
            document.putNamespace("y", "urn:yahoo:srch");

            final String expr = "/y:ResultSet/y:Result/y:Title/text()";
            for (final Node node : document.getNodes(expr)) {
                System.out.println(node.getTextContent());
            }
        }
    }
}
```
```
This code uses
Restlet
to make a request to Yahoo's RESTful search service. Obviously, the details of the web service you are using will dictate what your client for it looks like.


q:
I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.

if (YesNoDialog.ask("Are you sure?") == true) {
  // yes was chosen
} else {
  // no was chosen
}

[A]
I dont have programed in Java ME, but i found in it's reference for optional packages the
Advanced Graphics and User Interface API
, and it's used like the Java SE API to create these dialogs with the
JOptionPane Class
```
int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object >message, java.lang.String title, int optionType)
```
Return could be
```
JOptionPane.YES_OPTION
```
,
```
JOptionPane.NO_OPTION
```
,
```
JOptionPane.CANCEL_OPTION
```
...


q:
Encouraged by SO, I'm trying to write an ASP.NET site that uses OpenID for user authentication.  It's a regular WinForms site (not MVC.NET), using the DotNetOpenId library for authentication.

Is it safe for me to permit/deny administrative functions on the site by simply comparing the current session's "ClaimedID" (as returned in the OpenIdLogin_LoggedIn event, as member DotNetOpenId.RelyingParty,OpenIdEventArgs.Response.ClaimedIdentifier) to a known administrator's OpenID (i.e. mine)?

If so, is it safe for this ID to be visible (e.g. in open source code), or should it be "hidden" in a configuration file or a database row?  (I know it's better design to make it configurable, my question is just about safety.)

[A]
My solution is to follow the same idea of the Roles table. After you've authenticated the user, look up that user's roles. If the user has role "Administrator" in the UserRoles table, then they can do whatever the Administrator can do.
I don't broadcast open ID's in my app. They're stored in the table. On every action result, I'm hitting the Users table, since I have also modified mine to store various user state information. With the exception of the home page, there is going to be some user information that I need from that table. I'm using LINQ, so I include the .LoadWith() to load the User with his list of roles when it serializes.


q:
We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...

I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:

Value
----------
   143.55
  3532.13
     1.75

How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".

I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.

Thank you.

[A]
The
STR function
has an optional length argument as well as a number-of-decimals one.
```
```
SELECT STR(123.45, 6, 1)

------
 123.5

(1 row(s) affected)
```
```


q:
The code

private SomeClass<Integer> someClass;
someClass = EasyMock.createMock(SomeClass.class);

gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>".

[A]
The two obvious routes are to suppress the warning or mock a subclass.
```
```
private static class SomeClass_Integer extends SomeClass<Integer>();
private SomeClass<Integer> someClass;
...
    someClass = EasyMock.createMock(SomeClass_Integer.class);
```
```
(Disclaimer: Not even attempted to compile this code, nor have I used EasyMock.)


q:
In the following snippet:

public class a {
    public void otherMethod(){}
    public void doStuff(String str, InnerClass b){}
    public void method(a){
        doStuff("asd",
            new InnerClass(){
                public void innerMethod(){
                    otherMethod();
                }
            }
        );
    }
}

Is there a keyword to refer to the outer class from the inner class?  Basically what I want to do is outer.otherMethod(), or something of the like, but can't seem to find anything.

[A]
In general you use
```
OuterClassName.this
```
to refer to the enclosing instance of the outer class.
In your example that would be
```
a.this.otherMethod()
```


q:
I'm currently looping through a datareader and calling the System.Net.Mail.SmtpClient's Send() method. The problem with this is that it's slow. Each email takes about 5-10 seconds to send (it's possible this is just an issue with my host). I had to override the executionTimeout default in my web.config file (it defaults to 90 seconds) like this:

 <httpRuntime executionTimeout="3000" />

One caveat: I'm on a shared host, so I don't think it is possible for me to send using the PickupDirectoryFromIis option (at least, it gave me errors when I turned it on).

[A]
You could send the mail asynchronous. That way the timeout should not interrupt your sending.
This article should help you get started with that:
Sending Emails Asynchronously in C#
.
There is another approach here:
http://www.vikramlakhotia.com/Sending_Email_asynchronously_in_AspNet_20.aspx
And off course there are several commercial clients available, but the only one that i have tried and can recommend is
http://www.aspnetemail.com/


q:
A Sprint cellular modem plugs into a laptop - often the PCMCIA slot. To connect, the user opens a program called the Connection Manager. This program has a menu option to display the serial number and phone number of the modem that's currently inserted.

Does that imply that the serial/phone number of the modem could be available to other programs running on the system? (Note: let's assume this is Windows XP.)

Specifically, could a company's VPN software be configured to pass along information about which modem is being used to connect?

Finally, is there existing VPN software that already does this, or would it have to be custom-programmed?


q:
What CSS should I use to make a cell's border appear even if the cell is empty?

IE 7 specifically.

[A]
If I recall, the cell dosn't exist in some IE's unless it's filled with something...
If you can put a
```

```
(non-breaking space) to fill the void, that will usually work. Or do you require a pure CSS solution?
Apparently, IE8 shows the cells by default, and you have to hide it with
```
empty-cells:hide
```
But it doesn't work at all in IE7 (which hides by default).


q: I want to create dynamic content based on this. I know it's somewhere, as web analytics engines can get this data to determine how people got to your site (referrer, search terms used, etc.), but I don't know how to get at it myself.

[A]
You can use the "referer" part of the request that the user sent to figure out what he searched for. Example from Google:
http://www.google.no/search?q=stack%20overflow
So you must search the string (in ASP(.NET) this can be found be looking in
```
Request.Referer
```
) for "q=" and then URLDecode the contents.
Also, you should take a look at this article that talks more about referrers and also other methods to track your visitors:
http://www.15seconds.com/issue/021119.htm