q:
How to (programmatically, without xml config) configure multiple loggers with Log4Net?
I need them to write to different files.

[A]
This thread at the log4net Dashboard details an approach
.
To summarize a little, hopefully without ripping off too much code:
```
```
using log4net;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;

// Set the level for a named logger
public static void SetLevel(string loggerName, string levelName)
{
    ILog log = LogManager.GetLogger(loggerName);
    Logger l = (Logger)log.Logger;

    l.Level = l.Hierarchy.LevelMap[levelName];
    }

// Add an appender to a logger
public static void AddAppender(string loggerName, IAppender appender)
{
    ILog log = LogManager.GetLogger(loggerName);
    Logger l = (Logger)log.Logger;

    l.AddAppender(appender);
}

// Create a new file appender
public static IAppender CreateFileAppender(string name, string fileName)
{
    FileAppender appender = new
        FileAppender();
    appender.Name = name;
    appender.File = fileName;
    appender.AppendToFile = true;

    PatternLayout layout = new PatternLayout();
    layout.ConversionPattern = "%d [%t] %-5p %c [%x] - %m%n";
    layout.ActivateOptions();

    appender.Layout = layout;
    appender.ActivateOptions();

    return appender;
}

// In order to set the level for a logger and add an appender reference you
// can then use the following calls:
SetLevel("Log4net.MainForm", "ALL");
AddAppender("Log4net.MainForm", CreateFileAppender("appenderName", "fileName.log"));

// repeat as desired
```
```


q: I am using tinyMCE and, rather annoyingly, it replaces all of my apostrophes with their HTML numeric equivalent. Now most of the time this isn't a problem but for some reason I am having a problem storing the apostrophe replacement. So i have to search through the string and replace them all. Any help would be much appreciated

[A]
did you try:
```
```
$string = str_replace("'", "<replacement>", $string);
```
```

s: huggingface

c: devops

d: intermediate


q:
I'm currently working on a pet project and need to do C++ development on Windows, Mac, Linux, and Solaris, and I've narrowed it down to Netbeans and Eclipse, so I was wonderig which is more solid as a C++ editor. I just need solid editing, good autocompletion for templated code ad external libraries, and project file management, the build tools are external, so thats irrelevant here, for my comparison.

Thus which is a better choice?

Note: I know I should be using emacs or vim, but the issue is, my theory at least, that I'm left handed, so I use my right side (design,creativity) of the brain more than the left side (logic, memory), so I just simply cannot use emacs or vim, my brain simply isn't compatible, I tried them many times too, even used emacs for a few months but it drove me crazy...

Thanks

[A]
I'm using Netbeans from time to time on Solaris and the latest (6.5) version is pretty neat. It has all the features that you need, perhaps autocompletion could work better, but I have a really bad code base so it might be the result of it. Keep in mind that you need strong machine for that, if it's your PC it's ok but Netbeans on a remote server (like I tried) is really slow unless you have a decent hardware. There are few simple refactorings for C++ with nice preview option, definitely worth a try.
You can get a whole Sun C++ pack from here:
http://developers.sun.com/sunstudio/downloads/express/


q:
What is the difference between web reference and service reference in WCF?
Which is preferable in WCF?

[A]
The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.
You can access web references via the advanced options in add service reference (if I recall correctly).
I'd use service reference because as I understand it, it's the newer mechanism of the two.


q: I have to delete some rows from a data table. I've heard that it is not ok to change a collection while iterating through it. So instead of a for loop in which I check if a row meets the demands for deletion and then mark it as deleted, I should first iterate through the data table and add all of the rows in a list, then iterate through the list and mark the rows for deletions. What are the reasons for this, and what alternatives do I have (instead of using the rows list I mean)?.

[A]
You can remove elements from a collection if you use a simple
```
for
```
loop.
Take a look at this example:
```
```
var l = new List<int>();

        l.Add(0);
        l.Add(1);
        l.Add(2);
        l.Add(3);
        l.Add(4);
        l.Add(5);
        l.Add(6);

        for (int i = 0; i < l.Count; i++)
        {
            if (l[i] % 2 == 0)
            {
                l.RemoveAt(i);
                i--;
            }
        }

        foreach (var i in l)
        {
            Console.WriteLine(i);
        }
```
```


q:
What is the fastest way to find out whether two ICollection<T> collections contain precisely the same entries? Brute force is clear, I was wondering if there is a more elegant method.

We are using C# 2.0, so no extension methods if possible, please!

Edit: the answer would be interesting both for ordered and unordered collections, and would hopefully be different for each.

[A]
Brute force takes O(n) - comparing all elements (assuming they are sorted), which I would think is the best you could do - unless there is some property of the data that makes it easier.
I guess for the case of not sorted, its O(n*n).
In which case, I would think a solution based around a
merge sort
would probably help.
For example, could you re-model it so that there was only one collection? Or 3 collections, one for those in collection A only, one for B only and for in both - so if the A only and B only are empty - then they are the same... I am probably going off on totally the wrong tangent here...


q: How much do using smart pointers, particularly boost::shared_ptr cost more compared to bare pointers in terms of time and memory? Is using bare pointers better for performance intensive parts of gaming/embedded systems? Would you recommend using bare pointers or smart pointers for performance intensive components?

[A]
Boost provide different smart pointers. Generally both the memory occupation, which varies in accordance to the kind of smart pointer, and the performance should not be an issue. For a performance comparison you can check this
http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smarttests.htm
.
As you can see only construction, copy and destruction are taken into account for the performance comparison, which means that dereferencing a smart pointer has supposedly the same cost as that of a raw pointer.
The following snippet demonstrates that there's no performance loss by using a
```
shared_ptr<>
```
in place of a raw pointer:
```
```
#include <iostream>
#include <tr1/memory>

int main()
{
#ifdef USE_SHARED_PTR
    std::tr1::shared_ptr<volatile int> i(new int(1));
#else
    volatile int * i = new int(1);
#endif

    long long int h = 0;

    for(long long int j=0;j < 10000000000LL; j++)
    {
        h += *i;
    }

    std::cout << h << std::endl;
    return 0;
}
```
```


q: Can anybody help me out to know the possible reasons for which Apple store can reject or raise objection to submit any iPhone application.

[A]
Here are possible reasons (unofficial,
from here
):
Vibration
.  It is not permitted to use continuous vibration in your apps - short bursts as warnings is all that is allowed.  Don’t bother trying to set up a timer to keep the vibration going, it will cause your app to be rejected.
Linking to private frameworks
.  This is obvious, but somehow in playing around with stuff we had linked to the MoviePlayer.framework.  That’s a no-no, and cost us about ten days while we unlinked that framework, recompiled, and then resubmitted.
Improper handling of editing in tableview cells
.  Also obvious, but be aware that if you enable table cell editing, you’ll have to manually specify which cells should respond to editing controls and which should not.  We had some random prefs cells in one of our early apps that were able to be swiped to bring up a ‘delete’ badge.  Of course it didn’t do anything, but Apple justly considered this poor design and rejected our app.
Icons
. Make sure the 57 pixel icon is identical to the 512 pixel version. Also, use a different icon if you are creating ‘lite’ and ‘pro’ versions of your app (i.e., free and paid). Using the same icon for both sends your app straight to … you guessed it … the bin.
Copying existing functionality
. This one is much more subtle and insidious, and has probably affected the great percentage of developers. In addition to the widely publicized Podcaster debacle, reports from user comments indicate that Apple is casting a wide net when looking for duplicated functionality. Mini web browsers, or apps that essentially show web pages, seem particularly vulnerable, even if they add new and/or useful functionality. Stay away from email clients as well.
Using appropriate keyboard type
. If your app asks for a phone number or other numeral-only input and you present a keyboard that also includes the possibility of entering standard alpha-numeric input … yep. (Thanks Jeremy1026)
Version numbers
. If your app is currently at
version 0.99 or below
, you’d better consider giving it a promotion as Apple seems to prefer 1.0 and above. One of ours was recently rejected for being .016, with a message suggesting that our version number wasn’t even numeric. When we resubmitted the same app from scratch as version 1.0, it went through.
Network Reachability
. If your app requires any type of network access you need to make sure it works when that access isn't available. If it doesn't it will be rejected. Apple provides sample code to test this which you can use as-is in most cases:
https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html
And last, but not least:
Flatulence
Don’t even try. ;-) UPDATE: sorry, this seems to be outdated by now. Apple makes a lot of money now with "fart apps":
see this article
.
Edit:
Here is a link to a recent article about
ten iPhone Apps That Didn't Make Apple's App Store
.
And a tip: Apple has a Mac app called
Application Loader
that you could install. Once you install it, it analyzes your app's zip file. It verifies all the certificates, icons, and other things are correct
before
submitting to Apple. Using the Application Loader  minimizes your chances of app rejection.
Another interesting resource:
App Store Roundtable: Transparency and the Approval System
(appleblog.com)
Yet another edit:
New rules by February 2010:
"No Swimsuits, No Skin, And No Innuendo"
(source:
TechCrunch article
, W
obble author's blog
)
By the way: during the iPhone 3.0 preview event (march 2009), an Apple spokesman told that 96% of all submitted application were approved.


q:
I often use this recursive 'visitor' in F#

let rec visitor dir filter=
    seq { yield! Directory.GetFiles(dir, filter)
          for subdir in Directory.GetDirectories(dir) do yield! visitor subdir filter}

Recently I've started working on implementing some F# functionality in C#, and I'm trying to reproduce this as IEnumerable, but I'm having difficulty getting any further than this:

static IEnumerable<string> Visitor(string root, string filter)
{
    foreach (var file in Directory.GetFiles(root, filter))
        yield return file;
    foreach (var subdir in Directory.GetDirectories(root))
        foreach (var file in Visitor(subdir, filter))
            yield return file;
}

What I don't understand is why I have to do a double foreach in the C# version for the recursion, but not in F#... Does the seq {} implicitly do a 'concat'?

[A]
```
yield!
```
does a 'flatten' operation, so it integrates the sequence you passed it into the outer sequence, implicitly performing a
```
foreach
```
over each element of the sequence and
```
yield
```
on each one.


q: Is it possible to get Mercurial to show progress of long-running push or pull operation? Google tells me basically "no", but does somebody know better? I was expecting something like hg pull -v...

[A]
```
```
hg pull -v
```
```
-v / --verbose
is a global option that applies to all sub-functions.
If you want extra data:
```
```
hg --debug -v pull
```
```


q:
In Postgresql you can create additional Aggregate Functions with

CREATE AGGREGATE name(...);

But this gives an error if the aggregate already exists inside the database, so how can I check if a Aggregate already exists in the Postgres Database?

[A]
```
```
SELECT * FROM pg_proc WHERE proname = 'name' AND proisagg;
```
```
http://www.postgresql.org/docs/8.3/interactive/catalogs-overview.html
http://www.postgresql.org/docs/8.3/interactive/catalog-pg-aggregate.html
http://www.postgresql.org/docs/8.3/interactive/catalog-pg-proc.html


q:
I want to float a div to the right at the top of my page. It contains a 50px square image, but currently it impacts on the layout of the top 50px on the page.

Currently its:

<div style="float: right;">
  ...
</div>

I tried z-index as I thought that would be the answer, but I couldn't get it going.

I know it's something simple I'm missing, but I just can't seem to nail it.

[A]
Try setting its
```
position
```
to absolute. That takes it out of the flow of the document.


q:
In firefox when you add an onclick event handler to a method an event object is automatically passed to that method. This allows, among other things, the ability to detect which specific element was clicked. For example

document.body.onclick = handleClick;

function handleClick(e)
{
    // this works if FireFox
    alert(e.target.className);
}

Is there any way to approximate this in IE? i need to be able to detect which element is clicked from an event handler on the body element.

[A]
I think IE uses a variable called
```
event
```
. See if that works?


q: Can anybody have good answer when should be database driven development be used and when should domain driven development be used. These both development approach have their importance in their respected areas. But I am not so clear which approach is appropriate in what type of situation. Any recommendation?

[A]
First for some background, Martin Fowler actually described three different "patterns" in his book Patterns of Enterprise Arcitecture. Transaction Script, Active Record and Domain Model. DDD uses the domain model pattern for the overall architecture and describes a lot of practices and patterns to implement and design this model.
Transaction script is an architecture where you don't have any layering. The same piece of code reads/writes the database, processes the data and handles the user interface.
Active Record is one step up from that. You split off your UI, your business logic and data layer still live together in active record objects that are modeled after the database.
A domain model decouples the business logic that lives in your model from your data-layer. The model knows nothing about the database.
And now we come to the interesting part:
The cost of this added separation is of course extra work. The benefits are better maintainability and flexibility.
Transaction script is good when you have few or no business rules, you just want to do data-entry and have no verification steps or all the verification is implemented in the database.
Active record adds some flexibility to that. Because you decouple your UI you can for example reuse the layer beneath it between applications, you can easilly add some business rules and verification logic to the business objects. But because these are still tightly coupled to the database changes in the datamodel can be very expensive.
You use a domain model when you want to decouple your business logic from the database. This enables you to handle changing requirements easier. Domain Driven Design is a method to optimally use this added flexibility to implement complex solutions without being tied to a database implementation.
Lots of tooling makes data-driven solutions easier. In the microsoft space it is very easy to visually design websites where all the code lives right behind the web-page. This is a typical transaction script solution and this is great to easilly create simple applications. Ruby on rails has tools that make working with active record objects easier. This might be a reason to go data-driven when you need to develop simpler solutions. For applications where behaviour is more important than data and it's hard to define all the behaviour up front DDD is the way to go.


q: What approach did you take to describe the benefits of SCRUM to clients / business units who do not have a technical background? Please list any analogies you thought were useful.  Finally, how did you address the concerns that the Waterfall camp had?

[A]
I basically go around about risk reduction and ROI, since these are the main things people at the higher management level care about.
Using a incremental process significantly reduces the risk of wasting money on something that's not gonna be useful, because the customer helps steer the product development in the right direction through series of planned feedback cycles. The #1 reason for project failure according to the CHAOS research is lack of customer involvement. So why not use a process that eliminates that risk?
Also, with a incremental process you start delivering something in a much shorter time than when using a waterfall approach, which effectively increases the ROI (return on investment), since the customer starts benefiting from the product after one or two months, instead of waiting 6 to 12 months in a typical waterfall project.
You can also mention improved customer satisfaction, team self-improvement and self-management, which reduces the administrative overhead, improved employee satisfaction.


q:
I am struggling to get an Epson "ESC/POS" printer to print barcodes (Using Delphi) and want to test if the printer is not faulty. Do you know where I can find a program to print a barcode in "ESC/POS"? I suppose as a last resort an OPOS program will also be OK.

Also, a demo Delphi Program that works will also be fine. All the Delphi snippets I have so far is not working.

The printer I am using is an Epson TM-L60II

[A]
Get the Microsoft POS For .Net 1.11, it's got an SDK that includes a sample application that performs all the basic operations on POS hardware. I'm using it all the time to test that cash drawers work ok for example.
There's also a source code included (in .Net), so you can see how they do it.


q:
I'm running JBoss 4.0.5 on Windows 2003 x64 and wonder if there is any way to get a dump of all threads?

It's stared with FireDaemon so I don't have a console windows in which to ctrl-break.

It's running under java 1.5 so jstack won't work.

I tried some program someone had made called sendsignal.exe, which I think actually crashed JBoss (not certain, but not going to try it again), if this was because JBoss runs under win x64 or because it runs as LocalSystem and I only have access to an "ordinary" user I don't know. It actually worked on my laptop, but it's 32-bit and I'm running as the same user as JBoss there.

Someone has any other ideas that might work?

[A]
You could just write a jsp that does
```
Thread.getAllStackTraces()
```
and print out the stacktracelements in an amenable format. Then hitting the URL of that jsp at any time would give you the stack dump of all threads at that time.


q:
I am working on a Windows application which needs to be able to update itself. When a button is pressed it starts the installer and then the parent application exits. At some point during the installer, the installer attempts to rename the directory that the parent application was running from and fails with "Access Denied" If you run the installer from the desktop it works.

I am using CreateProcess to start the installer, is there some way of using this or another API to create the installer completely independantly from the parent application so that it doesn't retain some attachment to the directory.


q: Anyone got any insight as to select x number of non-consecutive days worth of data? Dates are standard sql datetime. So for example I'd like to select 5 most recent days worth of data, but there could be many days gap between records, so just selecting records from 5 days ago and more recent will not do.

[A]
I don't know the SQL Server syntax, but you need to:
1) Select the dates (with time component truncated) in descending order
2) Pick off top 5
3) Obtain 5th value
4) Select data where the datetime >= 5th value
Something like this "pseudo-SQL":
```
```
select *
from data
where datetime >=
( select top 1 date
  from
  ( select top 5 date from
    ( select truncated(datetime) as date
      from data
      order by truncated(datetime) desc
    )
    order by date
  )
)
```
```


q: Can I integrate my exsisting C++ library in an iPhone application?

[A]
Objective C++ is well defined and supported by Apple's gcc.
But you can't mix C++ and objective C classes, which makes this rather messy pretty fast. I don't think there are many projects in the wild which mix C++ and Objective C to any serious extent.
This highly depends on your library, but if (realistically) feasible I'd wrap the C++ inside a C library, using extern "C" entrypoints for all real functionality, and link with that from inside your objective C code for your iphone app.


q: When I create a new Date object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?

[A]
```
java.util.Date
```
has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?
To be precise: the value within a
```
java.util.Date
```
is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within
```
java.util.Date
```
is the same around the world at any particular instant, regardless of local time zone.
I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using
```
Date.toString()
```
which also uses the local timezone, or a
```
SimpleDateFormat
```
instance, which, by default, also uses local timezone.
If this isn't the problem, please post some sample code.
I would, however, recommend that you use
Joda-Time
anyway, which offers a much clearer API.


q:
I'm working in C, and I have to concatenate a few things.

Right now I have this:

message = strcat("TEXT ", var);

message2 = strcat(strcat("TEXT ", foo), strcat(" TEXT ", bar));

Now if you have experience in C I'm sure you realize that this gives you a segmentation fault when you try to run it. So how do I work around that?

[A]
In C, "strings" are just plain
```
char
```
arrays. Therefore, you can't directly concatenate them with other "strings".
You can use the
```
strcat
```
function, which appends the string pointed to by
```
src
```
to the end of the string pointed to by
```
dest
```
:
```
```
char *strcat(char *dest, const char *src);
```
```
Here is an
example from cplusplus.com
:
```
```
char str[80];
strcpy(str, "these ");
strcat(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");
```
```
For the first parameter, you need to provide the destination buffer itself.  The destination buffer must be a char array buffer.  E.g.:
```
char buffer[1024];
```
Make sure
that the first parameter has enough space to store what you're trying to copy into it.  If available to you, it is safer to use functions like:
```
strcpy_s
```
and
```
strcat_s
```
where you explicitly have to specify the size of the destination buffer.
Note
: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.
The return value of
```
strcat
```
can simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:
```
```
strcat(strcat(str, foo), bar);
```
```
So your problem could be solved as follows:
```
```
char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy(str, "TEXT ");
strcat(str, foo);
strcat(str, bar);
```
```


q:
Is there a way to change all the numeric keys to "Name" without looping through the array (so a php function)?

[
    0 => 'blabla',
    1 => 'blabla',
    2 => 'blblll',
    // etc ...
]

[A]
No, there is not, for starters, it is impossible to have an array with elements sharing the same key
```
```
$x =array();
$x['foo'] = 'bar' ;
$x['foo'] = 'baz' ; #replaces 'bar'
```
```
Secondarily, if you wish to merely prefix the numbers so that
```
```
$x[0] --> $x['foo_0']
```
```
That is computationally implausible to do without looping. No php functions presently exist for the task of "key-prefixing", and the closest thing is
"extract"
which will prefix numeric keys prior to making them variables.
The very simplest way is this:
```
```
function rekey( $input , $prefix ) {
    $out = array();
    foreach( $input as $i => $v ) {
        if ( is_numeric( $i ) ) {
            $out[$prefix . $i] = $v;
            continue;
        }
        $out[$i] = $v;
    }
    return $out;
}
```
```
Additionally, upon reading XMLWriter usage, I believe you would be writing XML in a bad way.
```
```
<section>
    <foo_0></foo_0>
   <foo_1></foo_1>
   <bar></bar>
   <foo_2></foo_2>
</section>
```
```
Is not good XML.
```
```
<section>
   <foo></foo>
   <foo></foo>
   <bar></bar>
   <foo></foo>
</section>
```
```
Is better XML, because when intrepreted, the names being duplicate don't matter because they're all offset numerically like so:
```
```
section => {
    0 => [ foo , {} ]
    1 => [ foo , {} ]
    2 => [ bar , {} ]
    3 => [ foo , {} ]
}
```
```


q: I`m using Delphi 2009 and want to operate some XML data. I heard that nativeXML is one of the most convenient ways to do it. so how can I install this library?

[A]
Based on their
web site
, it sounds like you just download the .dcu file, put it in a convenient directory, and add that directory to your type library path (tools->options->library path).
After that, just add the unit to your uses clause and you should be good to go.


q: I would like to know which one is the best material that I can hand out to my students about "C# comments".

[A]
Inside VS
Comments are relatively simple.
You can use for
single line
:
```
```
//This is a single line comment
```
```
You can use for
multiple line
:
```
```
/*
Multiple lines
*/
```
```
For
method
you can use  :
```
```
/// <summary>
    /// This is a description
    /// </summary>
    /// <param name="sender">Description of variable SENDER</param>
    /// <param name="e">Description of variable E</param>
```
```
Outside VS
When you go in the
Project Property
you can output all comments into XML and manipulate them.
Good practice
Comments should not be used to describe WHAT the code do but WHY or HOW if it's not clear.


q:
Microsoft, of Cairo fame, is working on Oslo, a new modeling platform. Bob Muglia, Senior Vice President of Microsoft Server & Tools Business, states that the benefits of modeling have always been clear.

In simple, practical terms, what are the clear benefits that Oslo bestows upon its users?

[A]
In theory, there are a few benefits:
The people with the business knowledge can create the software models so you're less likely to lose anything in translation.
When non-technical shareholders create models, it forces them to "think like a developer". They see that what they considered obvious and easy is actually difficult when you formalize it.
It's more efficient. Business people have business knowledge and technical people have technical knowledge so, why not let each group design a system in their area of expertise? No more games of telephone as business experts re-explain what they mean to a developer. Developers are no longer distracted by cryptic business needs. They can focus on the interaction between highly technical systems.
In practice, it's a lot trickier:
Models are hard and that's that. Just because you push model creation to a different group doesn't mean you get foolproof models. Software development is all about modeling so developers are used to it. You may actually lose efficiency as a second group comes to grips with formalizing their understanding of a business need.
Model driven dev is tightly linked to OO concepts. OO is good for a lot of things, but not everything. What happens if what you really need falls outside the abilities of your modeling tool?
In my experience, the division between business and technical people is artificial. The most effective people are technical-minded business people or business-minded technical people. They make things happen. If you separate business tasks from technical tasks, you ruin the opportunity for cross-training and cross-thinking.


q:
I am using Apache Felix and its Declarative Services (SCR) to wire the service dependencies between bundles.

For example, if I need access to a java.util.Dictionary I can say the following to have SCR provide one:

/**
* @scr.reference name=properties interface=java.util.Dictionary
*/

protected void bindProperties(Dictionary d) {
}

protected void unbindProperties(Dictionary d) {
}

Now, I have more than one Dictionary service available, and I want to filter them using the "name" service property (I only want "name=myDictionary"). I can do that with code (using a ServiceTracker), but I'd rather specify the filter in the @scr annotation instead.

[A]
In standard DS, you can use target attribute of the reference element. In Felix world, where annotations can be used, I don't know what is the equivalent.
The target attribute is an LDAP filter, which matches against the service properties. So, your filter should be:
```
(name=myDictionary)
```


q: How do I detect when an iOS app is launched for the first time?

[A]
You can set a boolean value in the user defaults to do this. Set the key to false when you call
```
registerDefaults:
```
, and then set it to true change it to true after you've shown your initial help screen or whatever you need to do.
If you have a persistent data file that's always saved after the app closes, checking to see if it exists would be another way.


q:
I need to transform an Oracle SQL statement into a Stored Procedure therefore users with less privileges can access certain data field:

SELECT
    info_field, data_field
FROM
    table_one
WHERE
    some_id = '<id>' -- I need this <id> to be the procedure's parameter
UNION ALL

SELECT
    info_field, data_field
FROM
    table_two
WHERE
    some_id = '<id>'
UNION ALL

SELECT
    info_field, data_field
FROM
    table_three
WHERE
    some_id = '<id>'
UNION ALL

...

Given that I'm no SP expert I've been unable to figure out a good solution to loop through all the involved tables (12 aprox.).

Any ideas would be helpful. Thanks much!

[A]
Is the expectation that, among all these tables, only one will have a match for a given ID?
If no:  You need to explain what you want to do when there are multiple matches.
If yes:  You simply do the same SQL query, selecting the result into a variable that you then return.
It would look something like this:
```
```
PROCEDURE get_fields( the_id  NUMBER,
                      info_field_out  OUT  table_one.info_field%TYPE,
                      data_field_out  OUT  table_one.data_field%TYPE
                    )
  IS
  BEGIN
    SELECT info_field, data_field
      INTO info_field_out, data_field_out
      FROM (
        ... put your full SQL query here, using 'the_id' as the value to match against ..
      );

  EXCEPTION

    WHEN no_data_found THEN
      -- What do you want to do here?  Set the outputs to NULL?  Raise an error?

    WHEN too_many_rows THEN
      -- Is this an invalid condition?

  END;
```
```


q:
I'm finding myself doing a lot of things with associative arrays in PHP.

I was doing this:

 foreach ($item as $key=>$value) {
     if ($arr[$key] == null) {
         $arr[$key] = 0;
     }
     $arr[$key] += $other_arr[$value];
 }

But then I realised that it works fine if I exclude the line that initializes $arr[$key], presumably since it's null which is treated as the same as 0.

Is making that kind of assumption safe in php? And if it's safe, is it a good idea?

[A]
It is safe but I'd recommend against it.
If you put your error reporting up to E_NOTICES you'll see your code producing a lot of them, masking any real errors (such as a mistyped variable name).
What you should really be doing is:
```
```
if (!isset($arr[$key]))
    $arr[$key] = 0;
```
```
This won't raise a notice (but be very careful not to mis-type $arr inside isset()).


q:
I am using ANTLRWorks to create ANTLR grammars. I have a valid grammar and the parser and lexer source files are generated as well. I have also tried debugging the generated code and the output is as  expected in the debugger output.

But when I try to invoke the __Test__ class generated by the debugger nothing is coming up in the console. I have properly set up the classpath as I can successfully compile the __Test__.java with the same classpath.

What would be the problem? Is there any clear tutorial for writing and compiling a sample parser with antlr and antlrworks?

[A]
You could as easily have asked about implementing a first-class backend getting the server side right, while avoiding the latest trendy client-side fad. And I think it would be a legitimate goal in either case. You don't mention whether this is an existing application, but if it is, then I'd say, first memeorize the Fowler Refactoring book, and then go for it.
A lot of the churn in software is useful if you know how to properly apply what you'll need to know to accomplish your client side goals, because the same concepts (SOC, coupling-vs-cohesion, DRY, YAGNI, etc.) apply to both ends, and we increasingly have at hand useful tools for applying them (which can be accomplished more or less easily with a lot of technologies.)


q:
The team in which I work has been getting problems with the visual inheritance of the forms in the Java platform.

We want to develop a base JFrame with some controls in it and to have inherited forms from that base JFrame. The designer of the Netbeans 6.1 does not paint the controls of the base form in the inherited ones, so we can´t use it in the way we want. In the execution time the inherited forms are well painted, with the parent´s controls.

The Netbeans designer

Anyone has solved it? Should we change of IDE?

[A]
Just a general comment, not a real answer to your situation - visual components aren't made for inheritance. For example, see the horrible blunder Sun made by inheriting everything from Component- now you have a JList which you can't use .add() on to add items to. Unless you can fulfill the entire super-class contract (and I know only of several classes that can) prefer composition rather than inheritance. Expose the methods you do plan on fulfilling and a "Component getAsComponent()" method with the explicit declaration that the component shouldn't be changed directly. I find that much easier than having to think about "what should I do if someone uses add(JLabel) to my component? or setLayout()?".
Regarding your specific predicament - I'm using JFormDesigner in IntelliJ IDEA but it might apply as well. JFD has a nice way of using the component BeanInfo information (for component named "MyThingy" the info class would be "MyThingyBeanInfo"). Using that class you can define a lot of things for design-time only consumption, along with special painting methods and other niceties.


q:
I am connecting to a MySQL DB trough a terminal who only have a program with an ODBC connection to a MySQL DB. I can put querys in the program, but not access MySQL directly.

I there a way to query the DB to obtain the list of fields in a table other than

select * from table

??

(don't know why but the select returns a error)

[A]
```
```
describe *tablename*
```
```


q: I've been reading that some devs/dbas recommend using transactions in all database calls, even read-only calls. While I understand inserting/updating within a transaction what is the benefit of reading within a transaction?

[A]
So you get a consistent view of the database.  Imagine you have two tables that link to each other, but for some reason you do 2 selects... in pseuodocode:
```
```
myRows = query(SELECT * FROM A)
moreRows = query(SELECT * FROM B WHERE a_id IN myRows[id])
```
```
If between the two queries, someone changes B to delete some rows, you're going to have a problem.


q:
Is there any performance advantage to using lists over dictionaries over tuples in Python?

If I'm optimising for speed, is there any reason to prefer one over another?

[A]
Tuples will be slightly faster to construct for a small number of elements.  Although actually most of the gains will be in memory used rather than CPU cycles, since tuples require less space than lists.
With that being said, the performance difference should be negligible, and in general you shouldn't worry about these kinds of micro-optimizations until you've profiled your code and identified a section of code that is a bottleneck.


q:
How can I verify a given xpath string is valid in C#/.NET?

I'm not sure just running the XPath and catching exceptions is a valid solution (putting aside the bile in my throat for a moment) - what if tomorrow I run into some other input I haven't tested against?

[A]
How can I verify a given XPath string is valid in C#/.NET?
You try to build an
```
XPathExpression
```
from it and catch the exception.
```
```
try
{
    XPathExpression.Compile(xPathString);
}
catch (XPathException ex)
{
    MessageBox.Show("XPath syntax error: " + ex.Message);
}
```
```


q:
All,

I currently have my solution comprising of 2 Class librarys and a Web Site building within teamCity using Msbuild. Now I want to precompile the website and make it available as an artifact. However when i try to Precompile it using

<Target Name="PrecompileWeb" DependsOnTargets="Build">
    <AspNetCompiler
        PhysicalPath="$(BuildDir)\Location\"
        TargetPath="$(BuildDir)\Publish"
        Force="true"
        Debug="true"

        />
  </Target>

I get an error becasue it is looking for a virtual path (which i don't have as all I want to do it precompile the files I am not interested in publishing the site) if I put a dummy path in I get another error (correctly) about it not being an application under IIS

Any ideas

[A]
Is this a Web Site or Web Application Project? If the latter, instead of doing an AspNetCompiler task, do an MSBuild task to the csproj/vbproj file, calling the targets
```
Rebuild;ResolveReferences;_CopyWebApplication
```
and specifying the
```
OutDir
```
property.
If you are using a website, then specify the VirtualPath to be a valid IIS path. What is happening is that, when you don't specify the VirtualPath property, it tries to resolve it using the PhysicalPath and IIS. I believe that's just an artifact of how the AspNetCompiler works.


q:
I'm preparing a string that will be eval'ed. The string will contain a clause built from an existing Array. I have the following:

def stringify(arg)
    return "[ '" + arg.join("', '") + "' ]" if arg.class == Array
    "'#{arg}'"
end

a = [ 'a', 'b', 'c' ]
eval_str = 'p ' + stringify(a)
eval(eval_str)

which prints the string ["a", "b", "c"].

Is there a more idiomatic way to do this? Array#to_s doesn't cut it. Is there a way to assign the output from the p method to a variable?

Thanks!

[A]
I may be misunderstanding you, but does this look better at all?
```
```
>> a = %w[a b c]
=> ["a", "b", "c"]
>> r = "['#{a.join("', '")}']"
=> "['a', 'b', 'c']"
>> r.class
=> String
```
```
I suppose I'm confused by the need for eval, unless that's a part of something outside of what I see here.


q:
I need a method to return a random string in the format:

Letter Number Letter  Number Letter Number

[A]
You just need 2 methods.
1) Random a char (You can use
ASCII
to random between number than cast to char)
2) Random number.
Both can use this utility method:
```
```
private int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}
```
```
For the letter you need to call
```
RandomNumber(65,90);
```
and for the number you call :
```
RandomNumber(1,9);
```
You just need to concatenate.
Than you call these methods to create your string, Hope this help you.
Update
You should put the random object in your class... it was just to show you how to do it. You still need to work a little but I think it's a good start to show you how to manipulate char from ascii.


q:
What is the proper way to split up SQL statements to send to an Oracle ADO.NET client?  For instance, lets say you have the following code in a text file and want to execute these statements:

CREATE TABLE foo (bar VARCHAR2(100));
INSERT INTO foo (bar) VALUES('one');
INSERT INTO foo (bar) VALUES('two');

I believe trying to send all those in one Command will cause Oracle to complain about the ";".  My first thought would be to split on ";" character, and send them one at a time.

But, Stored procedures can contain semi-colons as well, so how would I make it so the split routine would keep the whole stored proc together?  Does it need to look for begin/end statements as well, or "/"?

Is there any difference in these respects between ODP.NET and the Micrsoft Oracle Provider?

[A]
Without the DDL, you could create an anonymous PL/SQL block by surrounding the statements with BEGIN and END:
```
```
BEGIN
  INSERT INTO foo (bar) VALUES('one');
  INSERT INTO foo (bar) VALUES('two');
END;
```
```
To perform DDL (like CREATE TABLE) you would need to use dynamic PL/SQL:
```
```
BEGIN
  EXECUTE IMMEDIATE 'CREATE TABLE foo (bar VARCHAR2(100))';
  EXECUTE IMMEDIATE 'INSERT INTO foo (bar) VALUES(:v)' USING 'one';
  EXECUTE IMMEDIATE 'INSERT INTO foo (bar) VALUES(:v)' USING 'two';
END;
```
```
The INSERTS are also dynamic, as the table does not exist prior to running the block and so it would fail to compile.
NOTE: This would be an unusual requirement: applications should not normally be creating tables!


q:
It is really annoying.

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm()); <-- pausing visual studio breaks here.

Thanks guys.

[A]
@sramey are you sure pausing always breaks on the said line? If I may hazard a guess here I think when you press the pause button you application is idle and the program is spending most of its time in the Win32 message loop abstracted by Application.Run(). Hence there is a high probability that VS breaks the execution of the main thread there.
I think pressing pause is not always the best way of debugging things. You need to make educated guesses about problem areas and set breakpoints in relevant methods (like Constructors, API calls etc)
Need more info on what you are trying to accomplish here.


q: In a comment on this answer to another question, someone said that they weren't sure what functools.wraps was doing. So, I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?

[A]
When you use a decorator, you're replacing one function with another.  In other words, if you have a decorator
```
```
def logged(func):
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging
```
```
then when you say
```
```
@logged
def f(x):
   """does some math"""
   return x + x * x
```
```
it's exactly the same as saying
```
```
def f(x):
    """does some math"""
    return x + x * x
f = logged(f)
```
```
and your function
```
f
```
is replaced with the function
```
with_logging
```
.  Unfortunately, this means that if you then say
```
```
print(f.__name__)
```
```
it will print
```
with_logging
```
because that's the name of your new function.  In fact, if you look at the docstring for
```
f
```
, it will be blank because
```
with_logging
```
has no docstring, and so the docstring you wrote won't be there anymore.  Also, if you look at the pydoc result for that function, it won't be listed as taking one argument
```
x
```
; instead it'll be listed as taking
```
*args
```
and
```
**kwargs
```
because that's what with_logging takes.
If using a decorator always meant losing this information about a function, it would be a serious problem.  That's why we have
```
functools.wraps
```
.  This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc.  And since
```
wraps
```
is itself a decorator, the following code does the correct thing:
```
```
from functools import wraps
def logged(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

@logged
def f(x):
   """does some math"""
   return x + x * x

print(f.__name__)  # prints 'f'
print(f.__doc__)   # prints 'does some math'
```
```


q:
I have a small ajax php application, which outputs data from a mysql db into a table. The rows are links, which when clicked will call an ajax function, which in turn will call another php file, which displays a different query from the same database in a layer without reloading the page.

I would like to know how to synchronize queries between both php files. So when I click on a row in the base page, the layer will be expanded to include additional information, or indeed the whole query.

I was thinking I could do this by having the primary key in the first query for the table, however I don't want it displayed and was wondering if there was a better approach to this?

[A]
You don't want it displayed, does that mean for security issues or something else.
If you want to lose the primary key in the table you can go with a query cache placed into  a session object and then just retreive by place in array.
so something like:
page1:
create array with db objects
store array into session
display objects in table
add display layer function for eachrow in table using the index from the array as a parameter.
page2:
retrieve session object
show data for array spot


q:
I'd like to find all the types inheriting from a base/interface. Anyone have a good method to do this? Ideas?

I know this is a strange request but its something I'm playing with none-the-less.

[A]
Use Assembly.GetTypes() to get all the types, and Type.IsAssignableFrom() to check for inheritance. Let me know if you need code - and also whether or not you're using .NET 3.5. (A lot of reflection tasks like this are simpler with LINQ to Objects.)
EDIT: As requested, here's an example - it finds everything in
```
mscorlib
```
which implements
```
IEnumerable
```
. Note that life is somewhat harder when the base type is generic...
```
```
using System;
using System.Collections;
using System.Linq;
using System.Reflection;

class Test
{
    static void Main()
    {
        Assembly assembly = typeof(string).Assembly;
        Type target = typeof(IEnumerable);
        var types = assembly.GetTypes()
                            .Where(type => target.IsAssignableFrom(type));

        foreach (Type type in types)
        {
            Console.WriteLine(type.Name);
        }
    }
}
```
```


q: How (i.e. using which API) is the virtual keyboard opened on Symbian S60 5th edition? The documentation seems to lack information about this.

[A]
You are right, this should obviously be a published API and it should be highlighted in the documentation. No such luck.
If you are using one of the platform native controls, the virtual keyboard will automatically popup when the user accesses a text-editing control.
If you are making a custom control, you need to deal with its selection by adding your own version of the virtual keyboard: make a new text-editing, window-owning virtual keyboard look-alike custom control with the right buttons. Reuse it accross all your applications. One day, Nokia will realize they have made an obvious mistake and make the API publicly available.
If you are using direct screen access, well, you wouldn't exactly expect the very s60-looking virtual keyboard to popup out of nowwhere. Again, draw a nice image on the screen to let the user know where the virtual keys are and react to pointer events. This is going to be less reusable unless you build a good amount of customization (background, button edges...) into it.
EDIT: Nokia may be relying on Qt to fix this issue. I would expect the control to be part of the current 4.7 version of Qt.


q:
I'm optimizing a directx graphics application to take advantage of nVidia's SLI technology.  I'm currently investigating some of the techniques mentioned in their 'Best Practices' web page, but wanted to know what advice/experience any of you have had with this?

Thanks!

[A]
This is not really an answer to you question, more of a comment on SLI.
My understanding is that SLI is only really a cost-effective means of gaining performance when you buy two cards right away, which few people actually do. Many people buy an SLI motherboard and card thinking it will give them a better upgrade path down the road, but the reality is that by the time you get to that point, it is going to be cheaper to buy a new, faster card, than it is to duplicate the one you already have just to get SLI going.
Just a thought before you pour too much energy into it. If you have a requirement to support SLI, then that's what you have to do. But personally, I would rather see optimization energy put towards non-SLI implementations.


q: How do I get the GridView control to render the <thead> <tbody> tags? I know .UseAccessibleHeaders makes it put <th> instead of <td>, but I cant get the <thead> to appear.

[A]
This should do it:
```
```
gv.HeaderRow.TableSection = TableRowSection.TableHeader;
```
```


q:
I got the following class :

class ConstraintFailureSet(dict, Exception) :
    """
        Container for constraint failures. It act as a constraint failure itself
        but can contain other constraint failures that can be accessed with a dict syntax.
    """

    def __init__(self, **failures) :
        dict.__init__(self, failures)
        Exception.__init__(self)

print isinstance(ConstraintFailureSet(), Exception)
True
raise ConstraintFailureSet()
TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet

What the heck ?

And the worst is that I can't try super() since Exception are old based class...

EDIT : And, yes, I've tried to switch the order of inheritance / init.

EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...

[A]
What version of Python?
In 2.5.1, I can't even define a class the inherits from both
```
dict
```
and
```
Exception
```
:
```
```
>>> class foo(dict, Exception):
...   pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    multiple bases have instance lay-out conflict
```
```
If you're using an older version, maybe it doesn't do this check during type definition and the conflict causes oddities later on.


q:
When generating graphs and showing different sets of data it usually a good idea to difference the sets by color. So one line is red and the next is green and so on. The problem is then that when the number of datasets is unknown one needs to randomly generate these colors and often they end up very close to each other (green, light green for example).

Any ideas on how this could be solved and how it would be possibler to generate distinctly different colors?

I'd be great if any examples (feel free to just discuss the problem and solution without examples if you find that easier) were in C# and RGB based colors.

[A]
I would start with a set brightness 100% and go around primary colors first:
FF0000, 00FF00, 0000FF
then the combinations
FFFF00, FF00FF, 00FFFF
next for example halve the brightness and do same round. There's not too many really clearly distinct colors, after these I would start to vary the line width and do dotted/dashed lines etc.


q:
Is there a way to link to a chm file, and therein to a certain topic, from a Microsoft Word docx document? Something in the lines of:

"For more information about this Property see [link ref="./SomeDirectory/somedocument.chm!Sometopic.Somesubtopic" text="MyClass.MyProperty"]

[A]
You should be able to do it by setting the hyperlink to the file and use the "#" header anchor (I'm not sure what it is called...) but here is an example:
```
```
C:\Helpfiles\Help.chm#Topic
```
```


q: Is it a simple case of just never using the this.XYZ construct?

[A]
It's only considered poor style if it violates your style guidelines. Sometimes using
```
this
```
is necessary to qualify a member variable over a local variable:
```
```
public MyType(int arg)
{
    this.arg = arg;
}
```
```
This problem can also be mitigated with style guidelines. For example, prefix members with "_":
```
```
public MyType(int arg)
{
    _arg = arg;
}
```
```


q: Let's say I have an int with the value of 1. How can I convert that int to a zero padded string, such as 00000001?

[A]
Another way is:
```
```
DECLARE @iVal int = 1
select REPLACE(STR(@iVal, 8, 0), ' ', '0')
```
```


q:
I used a new Date() object to fill a field in a MySQL DB, but the actual value stored in that field is in my local timezone.

How can I configure MySQL to store it in the UTC/GMT timezone?

I think, configuring the connection string will help but I don't know how. There are many properties in the connection string like useTimezone, serverTimzone, useGmtMillisForDatetimes, useLegacyDatetimeCode, ...

[A]
Well, if we're talking about using
```
PreparedStatement
```
s, there's a
form of setDate
where you can pass in a Calendar set to a particular time zone.
For instance, if you have a PreparedStatement named stmt, a Date named date, and assuming the date is the second parameter:
```
```
stmt.setDate(2, date, Calendar.getInstance(TimeZone.getTimeZone("GMT")));
```
```
The best part is, even if GMT is an invalid time zone name, it still returns the GMT time zone because of the default behavior of getTimeZone.


q: Is the index value of the first record in a dbf file 0 or 1?  Is the index zero-based?

[A]
i'm not sure but this might give you a clue.
http://www.dbase.com/knowledgebase/int/db7_file_fmt.htm
1.3.1 Standard Property and Constraint Descriptor Array
Table field offset - base one. 01 for
    the first field in the table, 02 for
    the second field, etc. Note: this will
    be 0 in the case of a constraint.


q:
Currently this expression "I ([a-zA-z]\d]{3} " returns when the following pattern is true:

I AAA
I Z99

I need to modify this so it will return a range of alphanumerics after the I from 2 to 13 that do not have a space.

Example:

I AAA
I A321
I ASHG310310

Thanks,

Dave

[A]
Without the quotes:
```
"I ([a-zA-Z\d]{2,13}) "
```


q:
I have an enum construct like this:

public enum EnumDisplayStatus
{
    None    = 1,
    Visible = 2,
    Hidden  = 3,
    MarkedForDeletion = 4
}

In my database, the enumerations are referenced by value. My question is, how can I turn the number representation of the enum back to the string name.

For example, given 2 the result should be Visible.

[A]
You can convert the
```
int
```
back to an enumeration member with a simple cast, and then call
```
ToString()
```
:
```
```
int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();
```
```


q:
Say I have a xml document that looks like this

<foo>
<bar id="9" />
<bar id="4" />
<bar id="3" />
</foo>

I would like to use linq to reset the id's to 0, 1 ,2.
What would be the easiest way to do this?

Thanks

[A]
```
```
XElement xml = GetXml();
var i = 0;
foreach (var e in xml.Elements("bar"))
  e.SetAttributeValue("id", i++);
```
```


q:
Currently, we're storing the user's HTTP_REFERER so we can redirect the user back to the previous page they were browsing before they logged in.

Http Referer comes from the client and can be spoofed or blank. Is there a more secure/reliable method to deliver this handy user redirect?

[A]
somehow running
```
```
history.go(-1);
```
```
is the only alternative i can think of (javascript)


q:
Is there any way to install Setuptools for Python 2.6 in Windows without having an exe installer?

There isn't one built at the moment, and the maintainer of Setuptools has stated that it will probably be a while before he'll get to it.

Does anyone know of a way to install it anyway?

[A]
First Option - Online Installation (i.e. remaining connected to the Internet during the entire installation process):
Download
setuptools-0.6c9.tar.gz
Use
7-zip
to extract it to a folder(directory) outside your Windows Python installation folder
Go the folder (refer step 2) and run ez_setup.py from the corresponding dos (command) prompt
Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory
Second Option:
Download
setuptools-0.6c9.tar.gz
Download
setuptools-0.6c9-py2.6.egg
to a folder(directory) outside your Windows Python installation folder
Use
7-zip
to extract ez_setup.py in the same folder as
setuptools-0.6c9-py2.6.egg
Go to the corresponding dos prompt and run python ez_setup.py setuptools-0.6c9-py2.6.egg from the command prompt
Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory
Third Option (assuming that you have Visual Studio 2005 or MinGW on your machine)
Download
setuptools-0.6c9.tar.gz
Use
7-zip
to extract it to a folder(directory) outside your Windows Python installation folder
Go the folder (refer step 2) and run python setup.py install from the corresponding dos (command) prompt
Please provide feedback.


q:
I'm using PayPal Website Payments Standard.  Whenever the user lands on PayPal with the variables I sent, it shows a PayPal Login form and at the bottom it shows "Don't have a PayPal account? Use your credit card or bank account (where available)."

I want it to default to always ask for credit card and maybe say "Have PayPal?  Use that!".  Any ideas?

[A]
On
a thread in the PayPal Developer Community
they explain it with cookies based visits to the checkout page.
Basically if PayPal detects you being a user and spots their cookie, they will show the login form by default.
If they can't see that cookie, then they will show the credit card option first with a note that if you already have a PayPal account, to log in.
So the answer is no.


q:
If you have a java.io.InputStream object, how should you process that object and produce a String?

Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file.

What is the easiest way to take the InputStream and convert it to a String?

public String convertStreamToString(InputStream is) {
// ???
}

[A]
A nice way to do this is using
Apache commons
```
IOUtils
```
to copy the
```
InputStream
```
into a
```
StringWriter
```
... something like
```
```
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
```
```
or even
```
```
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
```
```
Alternatively, you could use
```
ByteArrayOutputStream
```
if you don't want to mix your Streams and Writers


q:
I'm developing an iPhone app. A simple image is the background of the main view.
I've set an UIImageView in the background and set an image in, using IB.

the image is a 160dpi PNG image. It appears like CRAP in IB. When running in the simulator it is ok, crisp.

How am I supposed to work and place my controls precisely on a such poor resolution image ?
Is this a bug ?

Thanks for you help!

[A] IB is not a tool for designing a UI, it is a tool for implementing one. It is designed to perform well rather than display well (this is more important in complex desktop UI design than mobile but the tool is the same for both). The best advice is perhaps to take a cue from the publishing world (where this is a common practice for applications that display large amounts of high resolution graphics such as Adobe InDesign) and keep track of exact measurements for controls - the x,y coordinate positions and height/width. Then you can use the inspector to precisely position controls.


q:
I'm currently using Win32ShellFolderManager2 and ShellFolder.getLinkLocation to resolve windows shortcuts in Java. Unfortunately, if the Java program is running as a service under Vista, getLinkLocation, this does not work. Specifically, I get an exception stating "Could not get shell folder ID list".

Searching the web does turn up mentions of this error message, but always in connection with JFileChooser. I'm not using JFileChooser, I just need to resolve a .lnk file to its destination.

Does anyone know of a 3rd-party parser for .lnk files written in Java I could use?

I've since found unofficial documentation for the .lnk format here, but I'd rather not have to do the work if anyone has done it before, since the format is rather scary.

[A]
The code plan9assembler linked to appears to work with minor modification. I think it's just the "
```
& 0xff
```
" to prevent sign extension when
```
byte
```
s are upcast to
```
int
```
s in the
```
bytes2short
```
function that need changing. I've added the functionality described in
http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf
to concatenate the "final part of the pathname" even though in practice this doesn't seem to be used in my examples. I've not added any error checking to the header or dealt with network shares. Here's what I'm using now:
```
```
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class LnkParser {

    public LnkParser(File f) throws Exception {
        parse(f);
    }

    private boolean is_dir;

    public boolean isDirectory() {
        return is_dir;
    }

    private String real_file;

    public String getRealFilename() {
        return real_file;
    }

    private void parse(File f) throws Exception {
        // read the entire file into a byte buffer
        FileInputStream fin = new FileInputStream(f);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buff = new byte[256];
        while (true) {
            int n = fin.read(buff);
            if (n == -1) {
                break;
            }
            bout.write(buff, 0, n);
        }
        fin.close();
        byte[] link = bout.toByteArray();

        // get the flags byte
        byte flags = link[0x14];

        // get the file attributes byte
        final int file_atts_offset = 0x18;
        byte file_atts = link[file_atts_offset];
        byte is_dir_mask = (byte) 0x10;
        if ((file_atts & is_dir_mask) > 0) {
            is_dir = true;
        } else {
            is_dir = false;
        }

        // if the shell settings are present, skip them
        final int shell_offset = 0x4c;
        final byte has_shell_mask = (byte) 0x01;
        int shell_len = 0;
        if ((flags & has_shell_mask) > 0) {
            // the plus 2 accounts for the length marker itself
            shell_len = bytes2short(link, shell_offset) + 2;
        }

        // get to the file settings
        int file_start = 0x4c + shell_len;

        // get the local volume and local system values
        final int basename_offset_offset = 0x10;
        final int finalname_offset_offset = 0x18;
        int basename_offset = link[file_start + basename_offset_offset]
                                + file_start;
        int finalname_offset = link[file_start + finalname_offset_offset]
                                + file_start;
        String basename = getNullDelimitedString(link, basename_offset);
        String finalname = getNullDelimitedString(link, finalname_offset);
        real_file = basename + finalname;
    }

    private static String getNullDelimitedString(byte[] bytes, int off) {
        int len = 0;
        // count bytes until the null character (0)
        while (true) {
            if (bytes[off + len] == 0) {
                break;
            }
            len++;
        }
        return new String(bytes, off, len);
    }

    /*
     * convert two bytes into a short note, this is little endian because it's
     * for an Intel only OS.
     */
    private static int bytes2short(byte[] bytes, int off) {
        return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);
    }
}
```
```


q:
How can I initialize a const / static array of structs as clearly as possible?

class SomeClass
{

    struct MyStruct
    {
        public string label;
        public int id;
    };

    const MyStruct[] MyArray = {
          {"a", 1}
          {"b", 5}
          {"q", 29}
    };
};

[A]
Firstly, do you
really
have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with
```
ValueTuple
```
) but they're pretty rare in my experience.
Other than that, I'd just create a constructor taking the two bits of data:
```
```
class SomeClass
{

    struct MyStruct
    {
        private readonly string label;
        private readonly int id;

        public MyStruct (string label, int id)
        {
            this.label = label;
            this.id = id;
        }

        public string Label { get { return label; } }
        public string Id { get { return id; } }

    }

    static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
        (new[] {
             new MyStruct ("a", 1),
             new MyStruct ("b", 5),
             new MyStruct ("q", 29)
        });
}
```
```
Note the use of
ReadOnlyCollection
instead of exposing the array itself - this will make it immutable, avoiding
the problem exposing arrays directly
. (The code show does initialize an array of structs - it then just passes the reference to the constructor of
```
ReadOnlyCollection<>
```
.)


q:
My company has a requirement that all production sites pass an AppScan security scan. Sometimes, when we scan a SharePoint installation, the software detects a blind SQL injection vulnerability. I'm pretty sure this is a false positive--AppScan is probably interpreting some other activity in the HTTP response as success of the blind injection. But it's difficult to prove that this is the case.

I suspect that SharePoint, both MOSS 07 and WSS 3.0, uses stored procedures exclusively behind the scenes. Does anyone know if there is any documentation from Microsoft to this effect, and furthermore, whether any of the stored procedures use dynamically-generated SQL? If everything were sprocs, and none of them dynamic, we would have pretty good evidence that SharePoint has no SQL injection vulnerability.

[A]
They aren't all stored procs. In particular, things like cross-lists joins produce some horrendous syntax. For an example, look at the SQL Trace window from
this article
. Also, since both user controls and API calls can be written by developers, there is no guarantee that you aren't subject to SQL Injection if you are using custom modules.
My guess would be that SharePoint always uses, at the very least, named parameters. However, your best option might to be running a SQL trace and comparing the results. Also, if you are a large enough customer, you might just try calling your local MSFT evangelist (or posting a question on
connect.microsoft.com
) and seeing if you can get a response.


q:
(This is related to Floor a date in SQL server.)

Does a deterministic expression exist to floor a DATETIME? When I use this as a computed column formula:

DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0)

the I get an error when I place an index on that column:

Cannot create index because the key column 'EffectiveDate' is non-deterministic or imprecise.

But both DATEDIFF and DATEADD are deterministic functions by definition. Where is the catch? Is it possible?

[A]
Does your column [datetime_column] have a default value set to "getDate()" ??
If so, since getdate() function is non-deterministic, this will cause this error...
Whether a user-defined function is deterministic or nondeterministic depends on how the function is coded. User-defined functions are deterministic if:
The function is schema-bound.
All built-in or user-defined
functions called by the user-defined
function are deterministic.
The body of the function references
no database objects outside the
scope of the function. For example,
a deterministic function cannot
reference tables other than table
variables that are local to the
function.
The function does not call any
extended stored procedures.
User-defined functions that do not meet these criteria are marked as nondeterministic. Built-in nondeterministic functions are not allowed in the body of user-defined functions.


q:
I have a webservice @ http://recpushdata.cyndigo.com/Jobs.asmx but I'm not able to access it though I am adding it as a WebReference properly.

Any Help would be great.


q:
I would like to generate a list of files within a directory. Some of the filenames contain Chinese characters.

eg: [试验].Test.txt

I am using the following code:

require 'find'
dirs = ["TestDir"]
for dir in dirs
    Find.find(dir) do |path|
    if FileTest.directory?(path)
    else
        p path
    end
    end
end

Running the script produces a list of files but the Chinese characters are escaped (replaced with backslashes followed by numbers). Using the example filename above would produce:

"TestDir/[\312\324\321\351]Test.txt" instead of "TestDir/[试验].Test.txt".

How can the script be altered to output the Chinese characters?

[A]
Ruby needs to know that you are dealing with unicode in your code. Set appropriate character encoding using KCODE, as below:
```
```
$KCODE = 'utf-8'
```
```
I think utf-8 is good enough for chinese characters.


q:
GWT seems like a really nice technology for Java developers who don't like (or don't know) HTML/JS/CSS to build rich web interfaces. On the server-side Grails also looks really nice, it's often described as "Rails for Java developers". I've read that Grails' "convention over configuration" approach, together with the benefits of dynamic languages (Groovy) can really reduce the amount of (boilerplate) code that needs to be written, while still leveraging best-of-breed Java technologies such as Spring and Hibernate.

Anyway, I haven't read much about how well these technologies play together. How easy is it to integrate GWT with Grails on the server-side? I'd be interested to learn about experiences of anyone that has build an application with these technologies? Recommendations on resources (books/websites) for building a GWT-Grails website would also be very welcome.

Cheers,
Don

[A]
with the benefits of dynamic languages
  (Groovy) can really reduce the amount
  of (boilerplate) code that needs to be
  written
That's what folks from RoR camp was preaching all the time. After some initial boom RoR projects got into inevitable trouble with bigger projects. The bigger projects the more work one should delegate to compiler, i.e. the more valuable are static languages. Currently, RoR boom is all but gone.
The amount of (extra) code you need to write now with JPA/Hibernate, for instance, is almost zero. Annotations only. It even finds the mapped beans itself, in runtime, via classpath! SpringFramework makes many other "boilerplate" codepieces obsolete too.
In my GWT project (one so far, have to admit) I use JPA (Hibernate), DAO layer, business delegate pattern and it's easy and robust.


q: I'm using the StAX event based API's to modify an XML stream. The stream represents an HTML document, complete with DTD declaration. I would like to copy this DTD declaration into the output document (written using an XMLEventWriter). When I ask the factory to disregard DTD's it will not download the DTD, but remove the whole statement and only leave a "<!DOCUMENTTYPE" string. When not disregarding, the whole DTD gets downloaded, and included when verbatim outputting the DTD event. I don't want to use the time to download this DTD, but include the complete DTD specification (resolving entities is already disabled and I don't need that). Does anyone know how to disable the fetching of external DTD's.

[A]
You should be able to implement a custom XMLResolver that redirects attempts to fetch external DTDs to a local resource (if your code parses only a specific doc type, this is often a class resource right in a JAR).
```
```
class CustomResolver implements javax.xml.stream.XMLResolver {

  public Object resolveEntity(String publicID,
                              String systemID,
                              String baseURI,
                              String namespace)
                  throws XMLStreamException
  {
    if ("The public ID you expect".equals(publicID)) {
      return getClass().getResourceAsStream("doc.dtd");
    } else {
      return null;
    }
  }
```
```
Note that some documents only include the "systemID", so you should fall back to checking that. The problem with system identifier is that it's supposed to be "system" specific URL, rather than a well-known, stable URI. In practice, it's often used as if it were a URI though.
See the
setXMLResolver
method.


q: What is the difference between a const_iterator and an iterator and where would you use one over the other?

[A]
```
const_iterator
```
s don't allow you to change the values that they point to, regular
```
iterator
```
s do.
As with all things in C++, always prefer
```
const
```
, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not
```
const
```
to change the pointed-to value).


q:
I want to diaplay message boxes that looks good, with the possibillity to use bold/italic text and text with different colors. The standard MessageBox.Show doesn't provide this functionality.

I have been trying to create a message box using the WebBrowser control to display nicely formatted text using HTML-syntax. But I haven't succeeded.

Do you know if this is possible, or do you know any other way to show a message box with formatted text? I want the message box to size itself dynamically to it's content.

(For Windows Forms)

[A]
You could create your own Form class that hosts the WebBrowser control (or an RTF control) to display the formatted content. Just give it an interface (API) similar to MessageBox so you can use it much the same way (e.g., checking the user's Yes/No or Ok/Cancel/etc responses).
For the sizing, you would likely need to check the content being displayed and use some System.Drawing capabilities to get the size of the fonts/content for it. Then size your window accordingly and/or show and hide scrollbars so they're only shown when absolutely necessary.


q: How can I prevent the pocket PC device from shutting down from my application when the power button pressed? I am using C#.

[A]
You can try changing the power requirements for the device "BLK1:", which is the blacklight device. Be aware that the behavior may not be the same on all devices and version of the OS or Vendor specific Extensions.
To do this, you can write something like :
```
```
[DllImport("coredll")]
    private extern static IntPtr SetPowerRequirement(string pvDevice, int deviceState,
                int deviceFlags, IntPtr pvSystemState, int stateFlags);

    [DllImport("coredll")]
    private extern static int ReleasePowerRequirement(IntPtr handle);
```
```
and call it this way :
```
```
IntPtr handle = SetPowerRequirement("BLK1:", 0 /* D0, Full On */, 1, IntPtr.Zero, 0);
    // Do something that requires the device to stay on ...
    ReleasePowerRequirement(handle);
```
```
But this is generally not a good practice, leaving a device with the backlight on for extended periods might reduce dramatically its autonomy.


q: I'm new to development on the iPhone.  Just about every sample project (as well as the default project templates) have one or more delegates and controllers.  Can someone give me a breakdown of what the delegates are responsible for vs. what the controllers are supposed to do?

[A]
The simplest way I can think to differentiate the two are:
A delegate is a protocol (interface) that defines methods that an object implements in order to receive specific messages from other objects.  Delegates objects are most often used to receive asynchronous callbacks such as user input, I/O.
A controller is an object that usually contains UI elements (views, controls, etc.) and data, and both receives and send messages to the various objects within it.  In many cases, a controller
is
a delegate and can implement several delegate protocols to receive events from multiple objects.
Keep in mind that many UI elements and controls let you pass events back to the controller by linking them to an IBAction method in Interface Builder.  This is very handy as it doesn't require extra code to implement delegates.  However, some other APIs such as the ABPeoplePickerNavigationController or NSURLConnection have no visualization in Interface Builder and so must use delegates to handle their events.


q:
Our web team has been asked to build some user interfaces in Sharepoint.  The UI's would primarily be forms that would need to write to a  SQL Server database.

Is ASP.NET the best way to do this?  If so what's the best way to integrate the ASP.NET application into Sharepoint?

[A]
You have 4 options:
```
```
1. Build web parts
2. build user controls , and use smart part to display them.
3. use infopath
4. host the asp.net in an iframe (page viewer web part).
```
```
I would go with building web parts, however user controls and smart part are probably quicker, and quickest still is infopath, but infopath wont use the page layouts or master pages that you specify.
if the web app has already been developed then youre looking at option 4, if its not already developed then I would suggest 1 or 2 which gives you the flexibility of reusing the controls elsewhere in the site as well as utilising the sharepoint metadata.


q:
I'm writing a HTML form that's divided in fieldsets, and I need to get the form fields from a specific fiedset in a function.

Currently it's like this:

function conta(Fieldset){
    var Inputs = Fieldset.getElementsByTagName("input");
    var Selects = Fieldset.getElementsByTagName("select");
    /* Doing the stuff I need to do in two iterations, one for each field type */
}

But who knows what the future may hold, and if the form gets some new field types (radios, checkboxes) this could become awful to mantain.

I know that form elements have the  elements attribute that returns all the form fields and I was hoping I could use something like that.

(I know I still gotta discriminate the field type in a bunch of conditionals inside the iteration, but I think it would be faster and easier to keep. Unless it isn't and I should not be doing it)

[A]
Haven't tested this and don't know how it would work, but you could use JQuery here to select all the elements into a JQuery object
```
```
//$("input select textarea").each(function() {
$(":input").each(function() { //even better
    // do stuff here
});
```
```
this would at least cleanup the code, although you would still have to add conditional statements based on field type like you mentioned.


q:
I have a page with a few fields and a runtime-generated image on it. The contents of this page are inside an UpdatePanel. There is a button to take the user to a secondary page, which has a button that calls javascript:history.go(-1) when clicked.

The problem is, the first page does a full request instead of a postback or just using the state it was in before navigating away from it. That is, the fields are all reset to their default values, thereby confusing the user. I'd like their values to be retained regardless of navigation. I do not want to create a new history state for every field change.

Any ideas?


q: How do I check to see if a variable is a number, or contains a number, in UNIX shell?

[A]
Shell variables have no type, so the simplest way is to use the return type
```
test
```
command:
```
```
if [ $var -eq $var 2> /dev/null ]; then ...
```
```
(Or else parse it with a regexp)


q: How do I force Postgres to use an index when it would otherwise insist on doing a sequential scan?

[A]
Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found
here
. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.
As a very blunt hammer, useful for testing, you can use the
```
enable_seqscan
```
and
```
enable_indexscan
```
parameters. See:
Examining index usage
```
enable_
```
parameters
These are
not suitable for ongoing production use
. If you have issues with query plan choice, you should see
the documentation for tracking down query performance issues
. Don't just set
```
enable_
```
params and walk away.
Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?
For small tables, it's faster to do sequential scans.
Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
Your planner settings might be causing problems.
See also
this old newsgroup post
.


q:
In Java, what is the difference between the twin methods?

public void methodA() throws AnException {
    //do something
    throw new AnException();
}

public void methodA() {
    //do the same thing
    throw new AnException();
}

I have a intuition that it has something to do with being a well-designed method (because I put methodA in an interface, declared it the way methodA* does in its implementation and received a warning from Java that "A* cannot override A because A* doesn't throw AnException").

Is this speculation correct?

Is there any other subtle connotations in the two ways of doing things?

[A]
If AnException is a checked exception (in other words, if it doesn't extend RuntimeException) then methodA won't compile.  Checked exceptions must always be declated.
If AnException is an unchecked exception (if it does extend RuntimeException), then either is allowed by the java compiler, and either is interpreted equivalently by the java runtime.
methodA is still probably still preferred in this case, for the reasons of documentation.  The javadoc for your method will show that it might throw AnException.  It's good to let users of your method know what Exceptions they should expect.


q: Is there any way to set an event handler without doing it manually in the classname.designer.cs file other than double clicking the UI element?

[A]
If I follow your question correctly, you can just do it in your code-behind like this:
```
```
myButton.Click += myHandler;
```
```
Or you could use an anonymous delegate:
```
```
myButton.Click += delegate
{
    MessageBox.Show("Clicked!");
};
```
```


q: How do you control the column width in a gridview control in ASP.NET 2.0?

[A]
I do it using the header style for the column:
```
```
<asp:BoundField HeaderText="Name" DataField="LastName">
   <HeaderStyle Width="20em" />
</asp:BoundField>
```
```


q:
Where can I find pascal-style railroad diagrams to describe C++ syntax?
(As an alternative to EBNF)

[A] There don't exist any, as far as I know. The C++ syntax can't even be expressed in a proper EBNF - it's a context-sensitive grammar, and anything attempting to parse it has to be capable of processing C++ code at least as far as template instantiation and overload resolution (not to mention macros).


q:
I'm try to extract info from a MySQL DB into a MS SQL DB. The DB is a mess and the developer is no longer available.

All dates are in char fields, and I use

SELECT concat( mid(DueDate, 7, 4), mid(DueDate, 4, 2), mid(DueDate, 1, 2)) as DueDate FROM TableName

to get the date field in a format so MS sql server can import them.

Now, I want to export only the record with the date greater than today, so the questions are:

What is the equivalent of GetDate() in MySQL?

Is there a better way to cast the date to make the comparison?

[A]
In MySQL you can convert a string to a date using the
STR_TO_DATE
function.
An example usage is:
```
```
mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
        -> '2004-04-31'
```
```
To get the current date in MySQL simply use the NOW() function. You can then check if a parsed date is later than today using something like
```
```
WHERE STR_TO_DATE('04/31/2009', '%m/%d/%Y') > NOW()
```
```


q:
Wondering how to open many new windows with Javascript.  I have found plenty of places on the internet that show you how to open a new browser window with Javascript, but I want to open a new UNIQUE window.  For Example.

I have two links on a page.  the user clicks on both links and they are both opened in the same window.  I want each link to open a new window WITH JAVASCRIPT.

Another Example.
I just opened a window with javascript and I have a link inside my newly opened window.  I click on the link and it opens in the same window.  I want to pop it out of that window WITH JAVASCRIPT, NOT use the same window.

Help?

[A]
```
```
window.open('page.html','WindowTitle','width=400,height=200')
```
```


q: Is it only to allow logical grouping?

[A] It gives you flexibility. For example, you might have a bunch of constructors, some public, some protected, some private - wouldn't you want them all grouped together?


q:
Need to an expression that returns only things with an "I" followed by either a "J" or a "V" (No Quotes) and then a minimum of 1 number up to 3 numbers.

I J###

I V###

I J##

I V##

I J#

I v#


q:
Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):

jQuery.ajax({
    type: "GET",
    url: handlerURL,
    dataType: "jsonp",
    success: function(results){
        alert("Success!");
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert("Error");
    }
});

And also:

jQuery.getJSON(handlerURL + "&callback=?",
    function(jsonResult){
        alert("Success!");
    });

I've also tried adding the $.ajaxError but that didn't work either:

jQuery(document).ajaxError(function(event, request, settings){
   alert("Error");
});

Thanks in advance for any replies!

[A]
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.
After searching their bug tracker, there's
a patch
which may be a possible solution using a timeout callback.  See
bug report #3442
.  If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.


q: How do I learn PLC programming? Would it differ greatly for different brands of PLCs? Is ladder programming the same as PLC programming?

[A] PLC is the term used for the devices that use ladder logic.  The devices that are programmed in more typical programming languages are generally called microcontrollers.  However, there are some of us that on occasion lump them all under the PLC name.  :-)  Not sure how much ladder logic varies, but microcontroller code can vary significantly.


q: Is a cfront tool available for the new C++? For any other modern languages?

[A]
What do you mean by “cfront tool”? Cfront was the first C++ compiler. But since failure to add exception support,
it has been discontinued
. Modern C++ is way beyond the scope of Cfront.
For any other modern languages?
And what do you mean by that? If you mean whether other compilers exist that compile a high-level language into C code then the answer is yes, there are plenty. The
Glasgow Haskell Compiler
is just one out of many.


q: Is there any GUI-based tools to assist you with writing and maintaining the configuration file? Any code tools to codegen the config file? What are the best ways to make this a little bit easier? Are most people just using Castle ActiveRecord now?

[A]
I'm just learning NHibernate myself (from the
excellent Summer of NHibernate
series).  I don't know of any GUI tools, but I thought that I'd point out that if you install the NHibernate schmema files (found in the root folder of the installation) to C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas, you then get intellisense help with both the general configuration file and the mapping configuration file.  I found that to be a big help.


q: I am using Borland Builder C++ 2009. I want to add a button to a form that allows the user to open a file in Excel that I specify. I can't think of how to do this. I know how to link with other code and executables -- is there a Microsoft Excel executable that I could use? How could I specify the file then? Any hints on this, or at least a place to look online, would be greatly appreciated.

[A]
Assuming that the file type is registered with Excel, you could call ShellExecute() on the file, using the "open" verb. This will cause the file to be opened as if double clicked by the user in Explorer and will invoke Excel.
If that isn't the case, and you can assume that Excel is installed, you could instead pass "excel" to ShellExecute() as the application, and the path of the file as the parameter. (Note that I didn't test this, but it worked from the Run dialog, so I think that it should work from ShellExecute() as well).


q: When printing a single character in a C program, must I use "%1s" in the format string? Can I use something like "%c"?

[A]
yes,
```
%c
```
will print a single char:
```
```
printf("%c", 'h');
```
```
also,
```
putchar
```
/
```
putc
```
will work too. From "man putchar":
```
```
#include <stdio.h>

int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);

* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).
```
```
EDIT:
Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:
```
```
const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
```
```


q:
I can handle the process that file part, but before I go crazy, has someone built a simple wcf service & client (running under windows services or IIS) that I can use to upload a file, and download that file back? with the fewest lines of code? (C# or VB)

compression & encryption would be cool, but i'll layer that on later!!

Thanks!!

[A]
You should be able to do this fairly easily.  The service contract would probably look like this:
```
```
[ServiceContract]
public interface IFileService
{
  [OperationContract]
  byte[] ProcessFile(byte[] FileData);
}
```
```
The encryption part could be handled natively by WCF using transport level security.  I don't believe that WCF supports compression directly, but you could add that using the GZipStream class.
I have not built a file handling service as you describe, but I have built a service that handles byte array data that is passed back and forth between a WCF client and service.  It works just fine.


q:
In the tradition of this question and in light of the documentation, how does one make this function deterministic:

ALTER FUNCTION [udf_DateTimeFromDataDtID]
(
    @DATA_DT_ID int -- In form YYYYMMDD
)
RETURNS datetime
WITH SCHEMABINDING
AS
BEGIN
    RETURN CONVERT(datetime, CONVERT(varchar, @DATA_DT_ID))
END

Or this one (because of the string/date literals - and yes, I've also tried '1900-01-01'):

ALTER FUNCTION udf_CappedDate
(
    @DateTimeIn datetime
)
RETURNS datetime
WITH SCHEMABINDING
AS
BEGIN
    IF @DateTimeIn < '1/1/1900'
        RETURN '1/1/1900'
    ELSE IF @DateTimeIn > '1/1/2100'
        RETURN '1/1/2100'

    RETURN @DateTimeIn
END

[A]
From the articles you linked:
To be deterministic, the style parameter must be a constant. Additionally, styles less than or equal to 100 are nondeterministic, except for styles 20 and 21. Styles greater than 100 are deterministic, except for styles 106, 107, 109 and 113.
You need to use a style parameter in your conversions to datetime.
For example:
```
```
CONVERT(datetime, '2008-01-01', 121)
```
```
Except don't use 121...


q:
I am writing a script which is likely to be modified by users. Currently I am storing the configuration settings inside the script. It exists in the form of a hash-of-hashes.

I would like to guard against people accidentally using lowercase characters in the hash keys, because that will break my script.

It would be simple to inspect the hash keys and merely issue warnings for any keys with lowercase characters, but I would rather fix the case sensitivity automatically.

In other words, I want to convert all the hash keys in the top-level hash to uppercase.

[A]
Walk through the hash and replace any lowercase keys with their uppercase equivalents, and delete the old ones.  Roughly:
```
```
for my $key ( grep { uc($_) ne $_ } keys %hash ) {
    my $newkey = uc $key;
    $hash{$newkey} = delete $hash{$key};
}
```
```


q:
Caveat:
I try all the posibilities listed here: How can I ignore everything under a folder in Mercurial.

None works as I hope.

I want to ignore every thing under the folder test. But not ignore srcProject\test\TestManager

I try

syntax: glob
test/**

And it ignores test and srcProject\test\TestManager

With:

syntax: regexp
^/test/

It's the same thing.

Also with:

syntax: regexp
test\\*

I have install TortoiseHG 0.4rc2 with Mercurial-626cb86a6523+tortoisehg, Python-2.5.1, PyGTK-2.10.6, GTK-2.10.11 in Windows

[A]
You can use zero-width negative look-ahead and look-behind assertions to specify that you want to ignore
```
test
```
only when it's not preceded by
```
srcProject
```
and not followed by
```
TestManager
```
:
```
```
syntax: regexp
(?<!srcProject\\)test\\(?!TestManager)
```
```
Mercurial uses Python regular expressions, so you can find more info on zero-width assertions in the Python docs:
https://docs.python.org/library/re.html#regular-expression-syntax


q: In HTML in the td of a table you can break text by using <BR> between the words. This also works in the HeaderText of a TemplateItem but not the HeaderText of a BoundField. How do I  break up the Header text of a BoundField.

[A]
Set
```
HtmlEncode = false
```
inside the
```
BoundField
```
```
```
<asp:BoundField DataField="SomeDataField"
        HeaderText="SomeHeader<br />(OtherData)"
        HtmlEncode="false" />
```
```
```
BoundField.HtmlEncode
```
is true by default which means that if HTML is added in the text it will be encoded.
If HtmlEncode is set to false the text is not encoded and the br will work as expected. Unfortunately is not possible to specify this only for the header text, it will affect the cell contents as well.


q:
I'm experimenting with WCF Services, and have come across a problem with passing Interfaces.

This works:

[ServiceContract]
public interface IHomeService
{
    [OperationContract]
    string GetString();
}

but this doesn't:

[ServiceContract]
public interface IHomeService
{
    [OperationContract]
    IDevice GetInterface();
}

When I try to compile the client it fails on the GetInterface method. I get an Exception saying that it can't convert Object to IDevice.

On the clientside the IHomeService class correctly implements GetString with a string as it's returntype, but the GetInterface has a returntype of object. Why isn't it IDevice?

[A]
You need to tell the WCF serializer which class to use to serialize the interface
```
```
[ServiceKnownType(typeof(ConcreteDeviceType)]
```
```


q:
At the XmlSerializer constructor line the below causes an InvalidOperationException which also complains about not having a default accesor implemented for the generic type.

Queue<MyData> myDataQueue = new Queue<MyData>();

// Populate the queue here

XmlSerializer mySerializer =
  new XmlSerializer(myDataQueue.GetType());

StreamWriter myWriter = new StreamWriter("myData.xml");
mySerializer.Serialize(myWriter, myDataQueue);
myWriter.Close();

[A]
It would be easier (and more appropriate IMO) to serialize the
data
from the queue - perhaps in a flat array or
```
List<T>
```
. Since
```
Queue<T>
```
implements
```
IEnumerable<T>
```
, you should be able to use:
```
```
List<T> list = new List<T>(queue);
```
```


q:
My log file is:

 Wed Nov 12 blah blah blah blah cat1
 Wed Nov 12 blah blah blah blah
 Wed Nov 12 blah blah blah blah
 Wed Nov 12 blah blah blah blah cat2
     more blah blah
     even more blah blah
 Wed Nov 12 blah blah blah blah cat3
 Wed Nov 12 blah blah blah blah cat4

I want to parse out the full multiline entries where cat is found on the first line. What's the best way to do this in sed and/or awk?

i.e. i want my parse to produce:

 Wed Nov 12 blah blah blah blah cat1
 Wed Nov 12 blah blah blah blah cat2
     more blah blah
     even more blah blah
 Wed Nov 12 blah blah blah blah cat3
 Wed Nov 12 blah blah blah blah cat4

[A]
Assuming your log file does not contain the control characters
```
'\01'
```
and
```
'\02'
```
, and that a continued line begins with precisely four spaces, the following might work:
```
```
c1=`echo -en '\01'`
c2=`echo -en '\02'`
cat logfile | tr '\n' $c1 | sed "s/$c1    /$c2/g" | sed "s/$c1/\n/g" | grep cat | sed "s/$c2/\n    /g"
```
```
Explanation: this replaces each newline with ASCII 1 (a control character that should never appear in a log file) and each sequence "newline-space-space-space-space" with ASCII 2 (another control character).  It then re-replaces ASCII 1 with newlines, so now each sequence of multiple lines is put into one line, with the old line breaks replaced by ASCII 2.  This is grepped for cat, and then the ASCII 2's are re-replaced with the newline-space-space-space-space combination.