q:
What is a  free tool to compare two Sql Server tables (data and schema).

It would be great if the tool can script the differences found.

I also went through some older posts. The closest I have seen is SQLDBDiff but I would love to try more options.

[A]
TableDiff.exe should have everything you need. It is one of the
hidden gems in SQL Server 2005
. So you don't have to download anything.
• Table Difference tool allows you to discover and reconcile differences between a source and destination table or a view. Tablediff Utility can report differences on schema and data. The most popular feature of tablediff is the fact that it can generate a script that you can run on the destination that will reconcile differences between the tables. TableDiff.exe takes 2 sets of input;
• Connectivity - Provide source and destination objects and connectivity information.
• Compare Options - Select one of the compare options
• Compare schemas: Regular or Strict
• Compare using Rowcounts, Hashes or Column comparisons
• Generate difference scripts with I/U/D statements to synchronize destination to the source.
TableDiff was intended for replication but can easily apply to any scenario where you need to compare data and schema.
You can find more information about command line utilities and the Tablediff Utility in Books Online for SQL Server 2005.


q: I found this extremely old document which appears to say that many of the web client features are not availiable when running on express edition--scheduling, subscription, etc--as well as no access to the report builder. Is that information still current, and are there any other features which are unavailable?

[A]
Subscriptions and scheduling are indeed absent in both MSSQLEx2005 and MSSQLEx2008, but I have never found this to be much of a problem. The underlying platform has a scheduler and the web service will do all the rendering, so you can recreate the missing elements without too much trouble.
The report builder is also absent, and
this
is non-trivial to replicate. You could always install SQLEx locally and let them use BIDS. Or you could stop being cheap. It's pretty good for free.
I recommend you use SSRS2008 rather than 2005 because it no longer requires IIS, and there are several sexy new capabilities in the report engine. In particular it now supports flow-based rich text with inline fields for mail-merge type reports.
Compatibility is excellent but some applications reject a newer database engine version. If this is a problem, continue to use SQLExpr2005 for the database.
So, are you saying that A) SSRS 2005
  requires IIS whereas 2008 does not,
  and that B) SSRS2008 is backwards
  compatible with a SQL2005 database?
  (It sounds like you might be saying
  that SSRS 2008 could be used with
  somebody running 2005 DBs
Yes, I am indeed saying that
SSRS 2005 requires IIS whereas 2008 does not
SSRS 2008 is backwards compatible with a SQL2005 database
SSRS 2008 could be used with somebody running 2005 DBs, or even 2000 DBs.
You can use SSRS with any database server for which ADO.NET drivers are available, including Oracle and MySQL.

s: huggingface

c: devops

d: intermediate


q:
func()
{
    Object* pNext;
    func1(pNext);
}

func1(Object* pNext)
{
    pNext = Segement->GetFirstPara(0);
}

I was expecting it to be pointer to firstpara returned from func1() but I'm seeing NULL can some explain and how to fix it to actually return the firstpara() pointer?

[A]
To change a pointer, you need to pass a pointer to the pointer, ie
```
Object** pNext
```
. To change the value of a variable inside a function, you pass a pointer. Hence, by extension, to change the value of a pointer inside a function, pass a pointer to the pointer.
```
```
func() {
    Object* pNext;
    func1(&pNext);
}

func1(Object** pNext) { *pNext = Segement->GetFirstPara(0); }
```
```


q: As I recall BOOST_MPL_ASSERT was once preferred.  Is this still true?  Anyone know why?

[A]
```
BOOST_MPL_ASSERT
```
is (still) generally considered better. The messages from it are somewhat easier to see (and understand, if you use
```
BOOST_MPL_ASSERT_MSG
```
). There was some talk a few months ago about deprecating
```
BOOST_STATIC_ASSERT
```
, though I think everyone eventually agreed that there's still room for it in the world.


q: What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone?

[A]
```
timezone_offset_get()
```
```
```
$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);
```
```
Untested, but should work


q:
I have stumbled into several methods of looping in JavaScript, what I like the most is:

for(var i = 0; i < a.length; i++){
    var element = a[i];
}

But as tested here (http://www.robertnyman.com/2008/04/11/javascript-loop-performance/), it should probably be written so that the length is only calculated once.

In jQuery there is a .each that you can stick a function. I like this a little better, because I don't have to type the array twice, like in the above solution.

If JavaScript supported macros it would be a piece of cake to roll your own, but sadly it does not.

So what do you guys use?

[A]
You could just always use a while loop, and compute the array limit before hand.
```
```
Var max = a.length-1;
var i = 0;

while(i <= max)
{
var element = a[i];
i++;
}
```
```


q:
Intuitively, it would seems that a compiler for language Foo cannot itself be written in Foo. More specifically, the first compiler for language Foo cannot be written in Foo, but any subsequent compiler could be written for Foo.

But is this actually true? I have some very vague recollection of reading about a language whose first compiler was written in "itself". Is this possible, and if so how?

[A]
This is called "bootstrapping".  You must first build a compiler (or interpreter) for your language in some other language (usually Java or C).  Once that is done, you can write a new version of the compiler in language Foo.  You use the first bootstrap compiler to compile the compiler, and then use this compiled compiler to compile everything else (including future versions of itself).
Most languages are indeed created in this fashion, partially because language designers like to use the language they are creating, and also because a non-trivial compiler often serves as a useful benchmark for how "complete" the language may be.
An example of this would be Scala.  Its first compiler was created in Pizza, an experimental language by Martin Odersky.  As of version 2.0, the compiler was completely re-written in Scala.  From that point on, the old Pizza compiler could be completely discarded, due to the fact that the new Scala compiler could be used to compile itself for future iterations.


q: I have managed to create an Ext.tree.TreePanel that loads child nodes dynamically, but I'm having a difficult time clearing the tree and loading it with new data.  Can someone help me with the code to do this?

[A]
I finally found an answer in their forums.  For anyone interested it is here:
```
```
if (tree)
{
    var delNode;
    while (delNode = tree.root.childNodes[0])
        tree.root.removeChild(delNode);
}
```
```


q: When I give Java and C large floats and doubles (in the billion range), they convert them to scientific notation, losing precision in the process. How can I stop this behavior?

[A]
For Java, check out
BigDecimal


q:
Is it possible to create a footer div that sits at the bottom of a site regardless of how much information is present in the middle?

Currently the div I have is positioned depending on how much content i have in the body.

See also:

How do you get the footer to stay at the bottom of a Web page?

[A]
I am by no means a css expert, but this works for me across the major browsers:
```
```
.d_footer
{
    position:fixed;
    bottom:0px;
    background-color: #336699;
    width:100%;
    text-align:center;
    padding-top:5px;
    padding-bottom:5px;
    color:#ffffff;
}
```
```


q:
Can I put the painter into the class variables? :

protected:
QPainter *myPainter;

...

void MyWidget::paintEvent(QPaintEvent *event)
{
    myPainter = new QPainter(this);

[A]
don't do that.  just put it on the stack so that when it is destroyed in the destructor it will perform the painting automatically.
```
```
void MyWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    // use painter
    ...
    // paint object automatically closes and paint on desctruction
}
```
```


q:
Classic ASP had 'server side includes' so that one could easily design a generic layout for the header, footer, left or right side bar.

In ASP.NET, I think we must use 'Page Templates'. Although most people say that it is easy to use, I find it rather complicated, as we must copy the whole HTML code inside the 'Render' function. Is there a simpler method? Can I load the code from a HTML file instead pasting the whole code in the 'Render' function?

Or is there any better alternative to 'Page Templates'?

[A] ASP.Net 2.0+ utilize Master Pages.


q:
I enabled PHP5 on my website and my webhost needs me to add the following to .htaccess files for PHP5 to work:

AddHandler application/x-httpd-php5 .php5 .php4 .php .php3 .php2 .phtml

  AddType application/x-httpd-php5 .php5 .php4 .php .php3 .php2 .phtml

Locally, I am running XAMPP to develop code, but XAMPP does not want to work with the .htaccess file above.

I think it is an issue with XAMPP not recognizing php5 (but it does recognize php if I use "application/x-httpd-php" instead of "application/x-httpd-php5")

How do I resolve this?! I need the .htaccess files to look like above so they work with my webhost, but I need XAMPP to work locally with the same files without making changes!

[A]
So, you're in kind of a tough place; ideally speaking your webhost should not need you to put extra gunk in your htaccess files. Not knowing XAMPP too well, I can't offer a specific solution, but I can give you some pointers:
Your webhost is running a custom compiled version of PHP that uses application/x-httpd-php5; while it is totally possible to build PHP yourself or find a custom build that has the SAPI layer configured appropriately, you probably
don't
want to do this.
Depending on how much leeway your host is giving htaccess files, it may be possible to use <IfDefine> or <IfModule> to only conditionally execute the PHP fudge code.  I haven't tested, and your webhost may have disabled this functionality. Also, you will have to find an appropriate conditional to test against.
My favorite answer would be to suck it up, and maintain separate htaccess files. I do this on my website; I have a .htaccess.in file which contains "global" declarations, and an htaccess.php file which generates the real .htaccess file based on configuration, etc.
Hope that helps.


q: I am working on developing a pair of libraries to work with a REST API.  Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes).  Are there any best practices to follow in the development of the libraries to help maintain my own sanity?

[A]
Well, the obvious one would be to keep your naming consistent.  Functions and classes should be named similarly (if not identically) in both implementations.  This usually happens naturally whenever you implement an API separately in two different languages.  The big ticket item though (at least in my book) is to follow language-specific idioms.  For example, let's assume that I were implementing a REST API in two languages I'm more familiar with: Ruby and Scala.  The Ruby version might have a class
```
MyCompany::Foo
```
which contains method
```
bar_baz()
```
.  Conversely, the Scala version of the same API would have a class
```
com.mycompany.rest.Foo
```
with a method
```
barBaz()
```
.  It's just naming conventions, but I find it goes a long way to helping your API to feel "at home" in a particular language, even when the design was created elsewhere.
Beyond that I have only one piece of advise: document, document, document.  That's easily the best way to keep your sanity when dealing with a multi-implementation API spec.


q:
recently I've been reading through Scott Meyers's excellent Effective C++ book. In one of the last tips he covered some of the features from TR1 - I knew many of them via Boost.

However, there was one that I definitely did NOT recognize: tr1::reference_wrapper.

How and when would I use tr1::reference_wrapper?

[A]
It's like boost::ref, as far as I know. Basically, a reference which can be copied. Very useful when binding to functions where you need to pass parameters by reference.
For example (using boost syntax):
```
```
void Increment( int& iValue )
{
    iValue++;
}

int iVariable = 0;
boost::function< void () > fIncrementMyVariable = boost::bind( &Increment, boost::ref( iVariable ));

fIncrementMyVariable();
```
```
This Dr. Dobbs article
has some info.
Hope this is right, and helpful. :)


q:
What is a preferred way to store recurring time windows?

For example. If I have a calendar system where I need to be able to accommodate daily, weekly or monthly recurring events, what sort of time management system is best?

How is this best represented in a database?

More Details

The Specific goal of this is to provide sets of open time windows. Once we have these time windows, the code needs to test if a message that arrives to the system falls within one of the time windows.


q: I hear that tr1::result_of gets used frequently inside of Boost... I'm wondering if there are any good (simple) use cases for tr1::result_of I can use at home.

[A]
A description of result_of is given at
open_std.org
.  Microsoft has a quick example of a
unit test wrapper
that uses result_of.


q:
atoi() is giving me this error:

error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
        Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast

from this line:
int pid = atoi( token.at(0) );
where token is a vector

how can i go around this?

[A]
You'll have to create a string:
```
```
int pid = atoi(std::string(1, token.at(0)).c_str());
```
```
... assuming that token is a std::vector of char, and using std::string's constructor that accepts a single character (and the number of that character that the string will contain, one in this case).


q: I have been a developer for 10+ years and so far my IIS knowledge is just enough for deploying stuff on it and get it running. Recently I have been playing with IIS 6 and realize the huge difference on the worker process model. I think I would need some good guide to update my knowledge in this area. Any good article/book recommendation?

[A]
There are several online resources, starting with this one:
Performance Tuning (IIS 6.0)


q:
Is there a free XML formatting (indent) tool available where I can past an XML string and have it formatted so I can read the XML document correctly?

Thanks

Edit ~ I am using XML Notepad on Windows XP.

[A]
Use the following:
```
xmllint
```
```
--format
```


q:
We are currently evolving our development processes in an effort to become CMMI compliant (we will start with level 2, and move up from there).  We are trying to locate a tool that is inexpensive (or free) that will allow us to develop requirements in the spirit of CMMI.  In other words, we need to be able to enter our requirements, track changes to them, provide alerts to individuals when requirements change, perform traceability, etc.  Our projects are typically small (typically 3 - 7 developers and a tester or two).

We have looked at many of the commercial tools, but they cost more than we are able to afford.  We looked at a few on SourceForge (OSRM and others) but could not find anything that was sufficiently mature that also had the features that we needed.

We are looking for suggestions for a tool that meets the above requirements.

[A]
How about starting of with a Wiki? We use
TWiki
but there are many others available. The wiki we uses
sends an email when any pages change
stores the history of changes to each page
by using the auto-linking of wikis you can create a hierarchy of requirements
This seems to cover most of your items. Wikis like TWiki have plugins which may also help you.
If you only have 3-7 developers on a project using one of the big commercial tools may be far too complex for what you need.


q: I have 2-3 different column names that I want to look up in the entire database and list out all tables which have those columns. Is there any easy script?

[A]
```
```
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%wild%';
```
```


q: Is LINQ a kind of Object-Relational Mapper?

[A]
LINQ to SQL (part of Visual Studio 2008) is an OR Mapper.
LINQ is a new query language that can be used to query many different types of sources.


q:
How can I change a file's extension using PHP?

Ex: photo.jpg to photo.exe

[A]
You may use the
```
rename(string $from, string $to, ?resource $context = null)
```
function.


q:
I'm looking to move some of my lighter weight metaprogramming from Nemerle to Boo and I'm trying to figure out how to define custom operators.  For example, I can do the following in Nemerle:

macro @<-(func, v) {
    <[ $func($v) ]>
}

Then these two are equivalent:

foo <- 5;
foo(5);

I can't find a way of doing this in Boo -- any ideas?

[A]
I'm not sure if this is exactly what you need but you can create syntactic macros in Boo. There's some information on the CodeHaus site,
http://boo.codehaus.org/Syntactic+Macros
, but the syntax has changed in one of the recent releases. I don't know of any tutorials on the new syntax but the source release for Boo 0.8.2 has some examples (some of the language structures are implemented as macros). If you don't want to download the full source a view of the SVN repository is available,
https://svn.codehaus.org/boo/boo/trunk/src/Boo.Lang.Extensions/Macros/
. The assert macro would be a good place to start.
HTH
Stoo


q: I want to do a conditional rendering at the layout level based on the actual template has defined content_for(:an__area), any idea how to get this done?

[A]
Ok I am going to shamelessly do a self reply as no one has answered and I have already found the answer :)
Define this as a helper method either in application_helper.rb or anywhere you found convenient.
```
```
def content_defined?(symbol)
    content_var_name="@content_for_" +
      if symbol.kind_of? Symbol
        symbol.to_s
      elsif symbol.kind_of? String
        symbol
      else
        raise "Parameter symbol must be string or symbol"
      end

    !instance_variable_get(content_var_name).nil?

  end
```
```


q:
Would this be right??

Black Box

1.1 Functional

    1.1.1 Equivalence
    1.1.2 BVA
    1.1.3 Use case
    1.1.4 Regression
    1.1.5 UAT

1.2 Non Functional

    1.2.1 Testing the System Design

White box

2.1. Functional

       2.1.1 Unit
       2.1.2 Integration
       2.1.3 System

Do the above fall under the right categories?

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

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


q:
I have the following character string:

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

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

What is the best way to do it in C?

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


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

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

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


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

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

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

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


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

import X
import X as Y
from A import B

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

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

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


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

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


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

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


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

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

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


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

Examples

IsInteger("sss") => false

IsInteger("123") => true

IsInterger("123.45") =>false

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


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

enable "save" button only when something has changed

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

Ideas?

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


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

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

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

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

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

thanx
imkin

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


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

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

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

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

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

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


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

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


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

For example,

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

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

// how to check if ch is playing?

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

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

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

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

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

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

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


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

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

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

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


q:
I'm using:

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

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

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

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


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

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

Here's how I render each frame:

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

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

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


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

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

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

string[] s = new string[2];

?

I tried

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

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

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

// populate str somehow

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


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

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

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


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

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

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


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

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


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

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


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

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


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

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

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

Much appreciated.

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


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

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

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


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

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

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

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

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

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

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


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

- file path

- the string I am looking for

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

How to such a program should be constructed?

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


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

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

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


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

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

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


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

Thanks.

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

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

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


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

and thanks for all who read or try to help me

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


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

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

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

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

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

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


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

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

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

p.s. statfs (2) does not differentiate

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


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

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

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


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

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


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

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

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


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

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

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

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


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

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

Basically, I forgot to add the little dot:

$ find . -name \*.plist

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

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


q:
If I have a method such as:

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

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

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

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

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

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

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

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

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

    path = matches[1];

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

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


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

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

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

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

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


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

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

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


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

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


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

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

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


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

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

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

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

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


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

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

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

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

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


q:
I have 2 classes for accessing the database:

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

and

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

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

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

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


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

set[obj] = true;

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

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

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


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

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

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


q:
I got one big question.

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

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

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

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

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

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

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

Help anyone?

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


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

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

string unformattedXml;
string formattedXml;

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

Console.WriteLine(formattedXml);

Output:

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

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

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


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

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

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

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

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

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


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

wickedweather
liquidweather
driveourtrucks
gocompact
slimprojector

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

wicked weather
liquid weather
drive our trucks
go compact
slim projector

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

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

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


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

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


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

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

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

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

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

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


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

So far I have:

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

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

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

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

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


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

How can I do that?

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

@implementation MyClass

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

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


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

Some more clarification:

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

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


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

I want to be able to detect

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

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


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

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


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

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

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

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

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

  deleteContact(dct)           {contact-ids}

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

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

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

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

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

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


q:
Very simply put:

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

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

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

    ...

    test();
};

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

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

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


q:
I have the following template

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

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

[A]
```
```
<xsl:if test="one">

one

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

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

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

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


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

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

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


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

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

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

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


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

Base string: abcd

Combinations:

bacd

acbd

abdc

etc.

Edit

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

What's the best way to do this?

Edit

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

Speed test

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

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

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


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

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

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

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

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


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

why is Class.newInstance() "evil"?

this in response to the code sample:

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

so, why is it Evil?

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


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

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


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

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

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

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

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

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


q:
How is it possible for this to be true

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

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


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

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

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

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

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

select * from foo

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

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

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


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

Welcome M...

Hi Iain if I've ...

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

Any Ideas?

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


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

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