q:
I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.

How can I do it?

When I click the submit button for the textbox below, the message box must show Lorem ipsum. Because "Lorem ipsum" is selected in the area.

If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.

Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.

How is it to be done?

[A]
For Opera, Firefox and Safari, you can use the following function:
```
```
function getTextFieldSelection(textField) {
    return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}
```
```
Then, you just pass a reference to a text field element (like a textarea or input element) to the function:
```
```
alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));
```
```
Or, if you want <textarea> and <input> to have a getSelection() function of their own:
```
```
HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
    var ss = this.selectionStart;
    var se = this.selectionEnd;
    if (typeof ss === "number" && typeof se === "number") {
        return this.value.substring(this.selectionStart, this.selectionEnd);
    }
    return "";
};
```
```
Then, you'd just do:
```
```
alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());
```
```
for example.


q:
I need to get the values in the registers with GCC.

Something similar to this:

EAX=00000002  EBX=00000001  ECX=00000005  EDX=BFFC94C0
ESI=8184C544  EDI=00000000  EBP=0063FF78  ESP=0063FE3C
CF=0  SF=0  ZF=0  OF=0

Getting the 32-bit registers is easy enough, but I'm not sure what the simplest way to get the flags is.

In the examples for this book: http://kipirvine.com/asm/

They do it by getting the whole EFLAGS register and shifting for the bit in question. I also thought of doing it using Jcc's and CMOVcc's.

Any other suggestions on how to do it? Some test cases to verify would also be useful.

[A]
I think using Jcc's would be longer and not as clear using inline assembly.
Here is what I currently have, using CMOVcc's:
```
void dump_regs()
{
  int eax = 0;
  int ebx = 0;
  int ecx = 0;
  int edx = 0;

  int esi = 0;
  int edi = 0;
  int ebp = 0;
  int esp = 0;

  int cf = 0;
  int sf = 0;
  int zf = 0;
  int of = 0;

  int set = 1; // -52(%ebp)

  asm(
    "movl  %eax, -4(%ebp)\n\t"
    "movl  %ebx, -8(%ebp)\n\t"
    "movl  %ecx, -12(%ebp)\n\t"
    "movl  %edx, -16(%ebp)\n\t"
    "movl  %esi, -20(%ebp)\n\t"
    "movl  %edi, -24(%ebp)\n\t"
    "movl  %ebp, -28(%ebp)\n\t"
    "movl  %esp, -32(%ebp)\n\t"

    "movl  $0, %eax\n\t"
    "cmovb -52(%ebp),%eax\n\t" // mov if CF = 1
    "movl  %eax, -36(%ebp) \n\t" // cf

    "movl  $0, %eax\n\t"
    "cmovs -52(%ebp),%eax\n\t" // mov if SF = 1
    "movl  %eax, -40(%ebp)\n\t" // sf

    "movl  $0, %eax\n\t"
    "cmove -52(%ebp),%eax\n\t" // mov if ZF = 1
    "movl  %eax, -44(%ebp)\n\t" // zf

    "movl  $0, %eax\n\t"
    "cmovo -52(%ebp),%eax\n\t" // mov if OF = 1
    "movl  %eax, -48(%ebp)\n\t" // of

    "movl  -4(%ebp), %eax\n\t" // restore EAX
  );

  printf("EAX = %#08x\tEBX = %#08x\tECX = %#08x\tEDX = %#08x\n",eax,ebx,ecx,edx);
  printf("ESI = %#08x\tEDI = %#08x\tEBP = %#08x\tESP = %#08x\n",esi,edi,ebp,esp);
  printf("CF = %d\tSF = %d\tZF = %d\tOF = %d\n",cf,sf,zf,of);
}
```
One important thing I haven't worked out yet are side-effects, I want to be able to call this without disturbing the state, any tips in that direction are welcome.

s: huggingface

c: devops

d: intermediate


q:
How can I draw something in JPanel that will stay the same and not be repainted, I am doing a traffic simulation program and I want the road to be drawn once because It will not change.
Thanks

[A]
To my knowledge, no, unless there is a trick with transparent overlays.
Most graphical applications I saw (and did) just re-draw the whole panel on each repaint. Now, you can do that once, in a graphic buffer, and then just paint the whole background at once, quickly, by copying the graphic buffer to the JPanel. It should be faster than calling all graphical primitives to draw the road.
Or, the way some 2D games do, perhaps paint it once and update the moving parts, like sprites: it needs to erase the old place used by the sprites (restore the background there) and re-draw the sprites at the new place. So you still have a copy of the road in a graphic buffer but instead of re-drawing it whole each time, you update only some small parts. Can be slightly faster.


q: Can anyone explain the difference between Server.MapPath("."), Server.MapPath("~"), Server.MapPath(@"\") and Server.MapPath("/")?

[A]
Server.MapPath
specifies the relative or virtual path to map
to a physical directory
.
```
Server.MapPath(".")
```
1
returns the current physical directory of the file (e.g. aspx) being executed
```
Server.MapPath("..")
```
returns the parent directory
```
Server.MapPath("~")
```
returns the physical path to the root of the application
```
Server.MapPath("/")
```
returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
An example:
Let's say you pointed a web site application (
```
http://www.example.com/
```
) to
```
```
C:\Inetpub\wwwroot
```
```
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
```
```
D:\WebApps\shop
```
```
For example, if you call
```
Server.MapPath()
```
in following request:
```
```
http://www.example.com/shop/products/GetProduct.aspx?id=2342
```
```
then:
```
Server.MapPath(".")
```
1
returns
```
D:\WebApps\shop\products
```
```
Server.MapPath("..")
```
returns
```
D:\WebApps\shop
```
```
Server.MapPath("~")
```
returns
```
D:\WebApps\shop
```
```
Server.MapPath("/")
```
returns
```
C:\Inetpub\wwwroot
```
```
Server.MapPath("/shop")
```
returns
```
D:\WebApps\shop
```
If Path starts with either a forward slash (
```
/
```
) or backward slash (
```
\
```
), the
```
MapPath()
```
returns a path as if Path was a full, virtual path.
If Path doesn't start with a slash, the
```
MapPath()
```
returns a path relative to the directory of the request being processed.
Note: in C#,
```
@
```
is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
```
Server.MapPath(null)
```
and
```
Server.MapPath("")
```
will
produce this effect too
.


q:
E.g.

What's best out of these:

std::string f() {}

or

const std::string& f() {}

[A]
If you return a reference to a variable that is local to the function then you're going to end up with issues (depending on the compiler and its settings).
If you return a reference to an instance that's still in scope when the function returns then it will be faster, as no copy of the string is being created.
So the latter is more efficient (technically) but may not function as expected depending on what you return a reference to.


q: Does anybody know if Microsoft has already decided which version of the .NET framework will be shipped in Windows 7 next year (2009)? Will it .NET 3.5 (SP 1) or maybe 4.0?

[A]
In my mind, it depends on the release dates.
If Windows 7 is released before .NET 4.0 (which should be released with Visual Studio 2010), then it can not have .NET 4.0. But with .NET 3.5 is sure thing.


q:
Is anyone using Castle MonoRail and ELMAH with success?

We are using a number of Resuces to present users with friendly error messages, but if we do this the exceptions never get as far as ELMAH as the MonoRail rescue intercepts them.

Ideally we want the user to see the rescue, but for the exception to be logged in ELMAH.

Any ideas/pointers?

Cheers,

Jay.

[A]
After also posting on
Google Groups
it looks like Atif may have pointed me in the right direction.
You might want to look into error
  signaling in ELMAH. It is designed for
  scenarios where you want to pass an
  exception through ELMAH's pipeline
  even if it is being handled/swallowed.
  Here are some pointers to get started
  with error signaling:
http://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Error_Signa...
http://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Signaling_e...
-Atif


q: I am getting an 'Access to the path is denied" error message when running in debug mode. I have tried granting permissions to {MACHINENAME}\ASPNET and to NETWORK SERVICE but this hasn't made any difference. I have also tried < impersonate = true /> using an admin account, this also made no difference. So how do I establish exactly which account is being used?

[A]
To find out which NT account your app is running under at any given time, do something like (in VB.NET):
```
```
Dim User = System.Security.Principal.WindowsIdentity.GetCurrent.User
    Dim UserName = User.Translate(GetType(System.Security.Principal.NTAccount)).Value
```
```
When using ASP.NET, this account will match the identity of the application pool, which you configure using IIS Manager. Note that the anonymous IIS user isn't much involved with ASP.NET requests.


q:
I have  a heap of unit tests that need to check XML outputs.

I have started out comparing strings but this isn't going to scale as formatting and superficial differences get in the way.

What is the easiest way in .NET to evaluate whether the generated XML is semantically the same as what the test expects?

Closed as duplicate of How would you compare two XML Documents?

[A]
Microsoft offers its XML Diff tools/classes
here
. I haven't personally used it, but it sounds like it'll get you started:
"By using the XMLDiff class, the
  programmer is able to determine if the
  two files are in fact different based
  on the conditions that are important
  to their application"
It seems to cope with different ordering, spacing, namespace prefixes etc.


q:
Frequently, I've dug into apropos and docs looking for something like the following only to give up to get back to the task at hand:

(repeat-last-command)

do the last C- or M- command I just executed (to be rebound to a fn key)

or sometimes the related:

(describe-last-function)

what keystroke did I just mistakenly issue, the effect of which I'd like to add to my bag of tricks. describe-key is close, but requires knowing what I typed.

Am I simply asking too much from my trusty sidekick?

[A]
Repeat functionality is provided by the
```
repeat.el
```
Emacs Lisp package, which is included with standard Emacs distributions.  From
```
repeat.el
```
's documentation:
This package defines a command that
  repeats the preceding command,
  whatever that was, including its
  arguments, whatever they were. This
  command is connected to the key C-x z.
  To repeat the previous command once,
  type C-x z. To repeat it a second time
  immediately after, type just z. By
  typing z again and again, you can
  repeat the command over and over.
To see additional information about the repeat command, type
C-h F repeat RET
from within Emacs.


q:
Suppose I have code like this:

template<class T, T initial_t> class Bar {
  // something
}

And then try to use it like this:

Bar<Foo*, NULL> foo_and_bar_whatever_it_means_;

GCC bails out with error (on the above line):

could not convert template argument
  '0' to 'Foo*'

I found this thread: http://gcc.gnu.org/ml/gcc-help/2007-11/msg00066.html, but I have to use NULL in this case (ok, I could probably refactor - but it would not be trivial; any suggestions?). I tried to overcome the problem by creating a variable with value of NULL, but GCC still complains that I pass variable and not address of variable as a template argument. And reference to a variable initialized with default ctor would not be the same as NULL.

[A]
Have you tried:
```
```
Bar<Foo*, (Foo*)NULL> foo_and_bar_whatever_it_means_;
```
```
?
or reinterpret_cast(0)?


q:
My client gets a sec_error_unknown_issuer error message when visiting https://mediant.ipmail.nl with Firefox.
I can't reproduce the error myself. I installed FF on a Vista and a XP machine and had no problems. FF on Ubuntu also works fine.

Does anyone get the same error and does anyone have some clues for me so I can tell my ISP to change some settings?
The certificate is a so called wild-card SSL certificate that works for all subdomains (*.ipmail.nl). Was I wrong to pick the cheapest one?

[A]
Which version of Firefox on which platform is your client using?
The are people having the same problem as documented
here in the Support Forum for Firefox
. I hope you can find a solution there. Good luck!
Update:
Let your client check the settings in Firefox: On "Advanced" - "Encryption" there is a button "View Certificates".
Look for "Comodo CA Limited"
in the list. I saw that Comodo is the issuer of the certificate of that domain name/server. On two of my machines (FF 3.0.3 on Vista and Mac) the entry is in the list (by default/Mozilla).


q: Use HttpWebRequest to download web pages without key sensitive issues

[A]
[update: I don't know why, but both examples below now work fine! Originally I was also seeing a 403 on the page2 example. Maybe it was a server issue?]
First,
```
WebClient
```
is easier. Actually,
I've seen this before
. It turned out to be case sensitivity in the url when accessing wikipedia; try ensuring that you have used the same case in your request to wikipedia.
[updated] As Bruno Conde and gimel observe, using %27 should help make it consistent (the intermittent behaviour suggest that maybe some wikipedia servers are configured differently to others)
I've just checked, and in this case the case issue doesn't seem to be the problem... however,
if
it worked (it does
n't
), this would be the easiest way to request the page:
```
```
using (WebClient wc = new WebClient())
        {
            string page1 = wc.DownloadString("http://en.wikipedia.org/wiki/Algeria");

            string page2 = wc.DownloadString("http://en.wikipedia.org/wiki/%27Abadilah");
        }
```
```
I'm afraid I can't think what to do about the leading apostrophe that is breaking things...


q:
I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript.
HTML:

<div id="menu">
    <div class="menuItem"><a href=#>Bla</a></div>
    <div class="menuItem"><a href=#>Bla</a></div>
    <div class="menuItem"><a href=#>Bla</a></div>
</div>

CSS:

.menuItem{
  display:inline;
  height:30px;
  width:100px;
  background-color:#000;
}

Javascript:

$('.menuItem').hover( function(){
     $(this).css('background-color', '#F00');
},
function(){
     $(this).css('background-color', '#000');
});

EDIT: I forgot to say that I had reasons not to want to use the css way.

And I indeed forgot to check if the DOM was loaded.

[A]
Your code looks fine to me.
Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:
```
```
$(function() {
   $('.menuItem').hover( function(){
      $(this).css('background-color', '#F00');
   },
   function(){
      $(this).css('background-color', '#000');
   });
});
```
```


q:
I have a form that tries to modify a JComponent's graphics context. I use, for example,

((Graphics2D) target.getGraphics()).setStroke(new BasicStroke(5));

Now, immediately after I set the value and close the form, the change is not visible. Am I not allowed to modify a JComponent's graphics context? How else would I modify the stroke, color and transformations?

Thanks,

Vlad

[A]
There are several problems with that approach. The first is that most components will set these things themselves when ever they are asked to repaint themselves. This means that your change will be lost every time the component gets to the point where it would actually use it. But, on an even more fundamental level than that, Graphics2D objects are not persistant. They are typically instantiated every time the component is redrawn, meaning that the Graphics2D object you got won't be the same the component will be using when redrawing.
What you need to do, to achieve this kind of thing is either to reimplement the specific component yourself, or implement a new look and feel that will affect the entire set of swing components. Have a look at the following link for further details about this:
http://today.java.net/pub/a/today/2006/09/12/how-to-write-custom-look-and-feel.html


q:
I have the string

a.b.c.d

I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner.

(Previously I had expressed this constraint as "without a loop", in case you're wondering why everyone's trying to answer without using a loop).

[A]
Sooner or later,
something
has to loop. It's far simpler for you to write the (very simple) loop than to use something like
```
split
```
which is much more powerful than you need.
By all means encapsulate the loop in a separate method, e.g.
```
```
public static int countOccurrences(String haystack, char needle)
{
    int count = 0;
    for (int i=0; i < haystack.length(); i++)
    {
        if (haystack.charAt(i) == needle)
        {
             count++;
        }
    }
    return count;
}
```
```
Then you don't need have the loop in your main code - but the loop has to be there somewhere.


q:
I have a list of say 100 unsorted items. Each item belongs to a group. The group the item belongs to is simply a member of the item class.

Using C/C++ I'm looking for the most efficient way of scanning through the list of items, checking which group they are in and printing the item to the screen. Here's the catch though. Once an item from a group has been printed to the screen, I don't want to print any more items belonging to that group.

I'm using a pre STL compiler and the size of the executable is critical so I don't want to start defining my own Hash classes.

[A]
You can create a dictionary/hashmap of groups and for each group store a bool saying if a item of that group was printed or not.
Sample code:
```
```
#include <unordered_map>
#include <string>
#include <iostream>

std::string getGroupForNumber( int num )
{
//
}

int main()
{
    typedef std::tr1::unordered_map< std::string, bool > hashmap;
    hashmap groupsPrinted;

    for( int i = 0 ; i < 100 ; ++i ) {
        if ( groupsPrinted[ getGroupForNumber( i ) ] == false ) {
            groupsPrinted[ getGroupForNumber( i ) ] = true;
            std::cout << i << std::endl;
        }
    }
    return 0;
}
```
```


q:
when i create an aspx page, the header includes something like this:-

<%@ Page
    Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    AutoEventWireup="true"
    CodeBehind="Create.aspx.cs"
    Inherits="My.Mvc.Views.Blah" %>

With ASP.NET MVC apps, do we:

need to include this AutoEventWireUp attribute?

What happens if we set this to false?

what does this attribute really do? is it valid for ASP.NET MVC?

thanks heaps folks!

[A]
You can get rid of this attribute, or set it to false (which is the default).
AutoEventWireup means ASP.NET will use reflection at runtime to look for methods on your web form class in the form of Page_EventName (like Page_Load, Page_Init, etc), and automatically wire the methods to the corresponding page lifecycle events. I have some more details here:
http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx
In MVC you should, as a general rule, avoid wiring up event handlers for the page lifecycle and code-behind in general.


q:
I'm pretty new to HQL (well, nHibernate in general) and am currently building a simple app to learn more about it.

I've run into problems trying to express the following SQL as HQL though, and would be very grateful for any ideas.

Here's the query:

select * from parent p
where p.id in (select p.parentid from child c where c.createdby = 2)
and
(select top 1 createdby
 from child where parentid = p.id order by createdon desc) != 2


q:
I need to move backwards through an array, so I have code like this:

for (int i = myArray.Length - 1; i >= 0; i--)
{
    // Do something
    myArray[i] = 42;
}

Is there a better way of doing this?

Update: I was hoping that maybe C# had some built-in mechanism for this like:

foreachbackwards (int i in myArray)
{
    // so easy
}

[A]
That's definitely the best way for any array whose length is a signed integral type.  For arrays whose lengths are an unsigned integral type (e.g. an
```
std::vector
```
in C++), then you need to modify the end condition slightly:
```
```
for(size_t i = myArray.size() - 1; i != (size_t)-1; i--)
    // blah
```
```
If you just said
```
i >= 0
```
, this is always true for an unsigned integer, so the loop will be an infinite loop.


q:
I am currently working on a web application that uses PHP and MySQL, but I do not have shell access to the server (working on that problem already...).  Currently, I have source control with subversion on my local computer and I have a database on the local computer that I make all changes to.  Then, once I've tested all the updates on my local computer I deploy the site manually.  I use filezilla to upload the updated files and then dump my local database and import it on the deployment server.

Obviously, my current solution is not anywhere near ideal.  For one major thing, I need a way to avoid copying my .svn files...  Does anyone know what the best solution for this particular setup would be?  I've looked into Capistrano a bit and Ant, but both of those look like it would be a problem that I do not have shell access...

[A]
I'm using
Weex
to synchronize a server via FTP. Weex is basically a non-interactive FTP client that automatically uploads and deletes files/directories on the remote server. It can be configured to not upload certain paths (like SVN directories), as well as to keep certain remote paths (like Log directories).
Unfortunately I have no solution at hand to synchronize MySQL databases as well...
Maybe you could log your database changes in "SQL patch scripts" (or use complete dumps), upload those with Weex and call a remote PHP script that executes the SQL patches afterwards.


q:
I like Nant very much. I do a lot of scripting with NAnt. It is a great little tool.

Since NAnt is pre 1.0, when problems occur, I often think if that it is a problem with NAnt itself, but this is not always the case.

One funny example: After running the oracle scripts I parsed the log output to make sure there was no problem. I was testing this with a small log file and it was fine.

I used the  task to load the file contents to a string property and used a regex to search for errors.

When I used this script for a large log file, I stopped getting the "build failed" message at the bottom, because I was printing the error messages.

Because the "build failed" was hiding at the top, I thought NAnt crashed, but it worked fine.

It would be better for NAnt to have a 1.0 release. Any reasons why not?

[A]
NAnt is an open source project that has been around a long while and is quite stable. While they have their reasons for not calling it version "1", does the version number really matter that much in this case? It's just a label.
I'd contact the team and find out what needs to be done before they label it as such and perhaps you can contribute some bug fixes etc...
The nice thing about the source being open is if you find a bug, you can fix it yourself. Hence the risk of it not being 1.0 is mitigated slightly if you're willing to invest a bit of time.


q:
I want to write a regular expression that will replace the word Paris by a link, for only the word is not ready a part of a link.

Example:

    i'm living <a href="Paris" atl="Paris link">in Paris</a>, near Paris <a href="gare">Gare du Nord</a>,  i love Paris.

would become

    i'm living.........near <a href="">Paris</a>..........i love <a href="">Paris</a>.

[A]
Regular expression:
```
```
!(<a.*.*)*Paris!isU
```
```
Replacement:
```
```
$1Paris
```
```
$1 referes to the first sub-pattern (at least in PHP). Depending on the language you use it could be slightly different.
This should replace all occurencies of "Paris" with the link in the replacement. It just checks whether all opening a-Tags were closed before "Paris".
PHP example:
```
```
<?php
$s = 'i\'m living in Paris, near Paris Gare du Nord, i love Paris.';
$regex = '!(<a.*.*)*Paris!isU';
$replace = '$1Paris';
$result = preg_replace( $regex, $replace, $s);
?>
```
```
Addition:
This is not the best solution. One situation where this regex won't work is when you have a img-Tag, which is not within an a-Element. When you set the title-Attribute of that image to "Paris", this "Paris" will be replaced, too. And that's not what you want.
Nevertheless I see no way to solve your problem completely with a simple regular expression.


q:
As we all know, global data, like the locale settings affecting the numeric decimal point printf() and strtod() are using, is evil. Fortunately, MSVC++ 9 allows to use per-thread locales by a _configthreadlocale(_ENABLE_PER_THREAD_LOCALE) call. Unfortunately, it seems that the localeconv() function does not notice this and still returns the global locale settings, e.g. localeconv()->decimal_point seems to always return the global locale setting before the _configthreadlocale() call. Is this a bug in the MSVC library or is this expected?

TIA
Paavo

[A]
The call to the
```
_configthreadlocale
```
sets the property, before the call, nothing special happens. So yes, this is expected behavior. You first must call this function, and then you can take advantage of thread-local locales.


q: My ASP.NET application allows users to upload and download large files. Both procedures involve reading and writing filestreams. What should I do to ensure the application doesn't hang or crash when it handles a large file? Should the file operations be handled on a worker thread for example?

[A]
Make sure you properly buffer the files so that they don't take inordinate amounts of memory in the system.
e.g. excerpt from a download application, inside the while loop that reads the file:
```
```
// Read the data in buffer.
length = iStream.Read(buffer, 0, bufferSize);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
```
```
Where bufferSize is something reasonable, e.g. 100000 bytes, the trade-off is that it will be slower for smaller buffer sizes.
http://support.microsoft.com/kb/812406
Edit: Also be sure that IIS is set to take a large enough
request length
(IIS7) and timeout.


q:
I want to read a mac id from command line and convert it to an array of uint8_t values to use it in a struct. I can not get it to work.  I have a vector of string for the mac id split about : and I want to use stringstream to convert them with no luck. What I am missing?

int parseHex(const string &num){
  stringstream ss(num);
  ss << std::hex;
  int n;
  ss >> n;
  return n;
}

uint8_t tgt_mac[6] = {0, 0, 0, 0, 0, 0};
  v = StringSplit( mac , ":" );
  for( int j = 0 ; j < v.size() ; j++ ){
    tgt_mac[j] = parseHex(v.at(j));
  }

[A]
I think you are using the std::hex in the wrong place:
```
```
#include <sstream>
#include <iostream>

int main()
{
    std::string     h("a5");
    std::stringstream   s(h);
    int x;

    s >> std::hex >> x;
    std::cout << "X(" << x << ")\n";
}
```
```


q:
Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?

I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are generaly fatal, unrecoverable errors.

something like:

global_catch()
{
    MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR);
    exit(-1);
}
global_catch(Exception *except)
{
    MessageBox(NULL,L"Fatal Error", except->ToString(), MB_ICONERROR);
    exit(-1);
}

[A]
This can be used to catch unexpected exceptions.
```
```
catch (...)
{
    std::cout << "OMG! an unexpected exception has been caught" << std::endl;
}
```
```
Without a try catch block, I don't think you can catch exceptions, so structure your program so the exception thowing code is under the control of a try/catch.


q:
I have been using netbeans as a tool for my java, and i have a problem. I read this tutorial and then i tried to create a table using this SQL:

CREATE TABLE CUSTOMERS (
    ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
    FIRST_NAME VARCHAR(20),
    LAST_NAME VARCHAR(30),
    ADDRESS VARCHAR(30),
    CITY VARCHAR(30),
    STATE_ VARCHAR(30),
    ZIP VARCHAR(15),
    COUNTRY_ID INTEGER,
    PHONE VARCHAR(15),
    EMAIL_ADDRESS VARCHAR(50)
)ENGINE=INNODB;

When i tried to run it, I got this error message:

sql state 42X01 : Syntax error :
  encountered "AUTO_INCREMENT" at line 2
  column 29

and when i delete the AUTO_INCREMENT, another error:

detected ENGINE=INNODB;

can someone help me? Thanks.

[A]
my sugestion would be the following
```
```
CREATE TABLE CUSTOMERS
( ID INTEGER NOT NULL auto_increment,
FIRST_NAME VARCHAR(20),
LAST_NAME VARCHAR(30),
ADDRESS VARCHAR(30),
CITY VARCHAR(30),
STATE_ VARCHAR(30),
ZIP VARCHAR(15),
COUNTRY_ID INTEGER,
PHONE VARCHAR(15),
EMAIL_ADDRESS VARCHAR(50),
PRIMARY KEY (ID));
```
```
Dunno what the engine=innodb is for, have you tried without it?


q:
How do I let Microsoft know about a problem I've found in one of their core library routines? Do they have a central repository to report these things?

I am not a member of Microsoft Development Network (MSDN).

Or should I even bother?

[A]
There is no official way to report bugs to Microsoft for an end-user. If you are participating in a beta program for an upcoming release, the beta program includes a bug-reporting channel. Otherwise, if the bug causes problems that you want to get resolved, you can call Microsoft support, and they will help you solving the problem (be it by providing a patch, or a work-around); if the problem turns out to be caused by a bug indeed, they will refund the costs of the support call.
Microsoft does have a central repository (perhaps separate ones per product), but this repository is not accessible for the general public.


q:
Using ASP.net 2.0, how do I present the information to the user similar to the Questions list on SO where each question has some child items (like the tags).

I would probably be making two separate queries, one to first find the list of questions, then another query to find all tags which belonged to the list of questions.

Approach 1:

Then I would probably be using nested repeaters and doing a select statement in the code-behind on each nested repeater "OnItemDataBind"...

Approach 2:

Or with the two datasets, I would use C# code to create a business entity of each of the "Questions" and have a property called "Tags". I would then loop through my tags dataset and assign the property.

What's more efficient? Are there any other alternatives?

[A]
If you do two separate queries, you can still make them in one call to the database, and get back two resultsets.
Instead of DataSets, you could use the more efficient DataReader (with two resultsets). Loop through the resultsets and populate Question objects with associated Tag objects or properties. Put those objects in an ArrayList or a generic List, and you can bind it to your Repeater.
Instead of doing anything in code-behind, you should consider moving that code to at least a data access layer (class) if you don't need a business logic layer (another class).
All of these suggestions only apply if your app is non-trivial. Using OO methods does add to the code, but if you are doing anything beyond displaying the information, it would be better to start off with a good OO architecture (DAL and BLL, if not MVC).


q:
I have a web-server, that serves different domain-names, but has only one IP-address assigned. That works fine with virtual hosts in Apache. Now I want SSL-encrypted connections for the websites. How can I set different SSL-certificates for the different vhosts?

Using different IP's for the different hostnames would be an solution - not very elegant but possible. But I want to know, how I can use different SSL-certificates for different vhosts. So I look for a solution with only one IP-address.

[A]
UPDATE: 2013
It appears that SNI is finally beginning take hold as older browsers are falling away.  Here are the
docs for Apache SNI
and here is a
wikipedia article on SNI
that includes a chart on browsers that support it.  In short, all the major browsers support it in supported versions; if supporting older browsers is important, you may have to take that into consideration.
------ previous answer ------------
SSL Hosts must be tied to a unique IP address/port combination, thus you cannot use virtual hosting (Or at least, it can only have one ssl host per IP address).  This is due to the fact that https begins encryption before the Host: parameter is sent in http, and thus it cannot determine which cipher to use from the hostname - all it has is the IP address.
This would be silly easy to fix if HTTP had a TLS command so it could start SSL after asking for the hostname, but no one asked me.
For the definitive answer, see
http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#vhosts2


q:
What are your favorite C++ coding style idioms? I'm asking about style or coding typography such as where you put curly braces, are there spaces after keywords, the size of indents, etc.  This is opposed to best-practices or requirements such as always deleting arrays with delete[].

Here is an example of one of my favorites:   In C++ Class initializers, we put the separators at the front of the line, rather than the back.  This makes it easier to keep this up to date.  It also means that source code control diffs between versions are cleaner.

TextFileProcessor::
TextFileProcessor( class ConstStringFinder& theConstStringFinder )

    : TextFileProcessor_Base( theConstStringFinder )

    , m_ThreadHandle  ( NULL )
    , m_startNLSearch (    0 )
    , m_endNLSearch   (    0 )
    , m_LineEndGetIdx (    0 )
    , m_LineEndPutIdx (    0 )
    , m_LineEnds      ( new const void*[ sc_LineEndSize ] )
{
    ;
}

[A]
Write each method or function argument on a separate line such that it can be easily commented.
```
```
int ReturnMaxValue(
    int* inputList,   /* the list of integer values from which to get the maximum */
    long size,        /* count of the number of integer values in inputList */
    char* extraArgs   /* additional arguments that a caller can provide.    */
)
```
```


q:
Does anyone know which property sets the text color for disabled control?
I have to display some text in a disabled TextBox and I want to set its color to black.

[A]
NOTE:
see Cheetah's answer below as it identifies a prerequisite to get this solution to work.  Setting the
```
BackColor
```
of the
```
TextBox
```
.
I think what you really want to do is enable the
```
TextBox
```
and set the
```
ReadOnly
```
property to
```
true
```
.
It's a bit tricky to change the color of the text in a disabled
```
TextBox
```
.  I think you'd probably have to subclass and override the
```
OnPaint
```
event.
```
ReadOnly
```
though should give you the same result as
```
!Enabled
```
and allow you to maintain control of the color and formatting of the
```
TextBox
```
.  I think it will also still support selecting and copying text from the
```
TextBox
```
which is not possible with a disabled
```
TextBox
```
.
Another simple alternative is to use a
```
Label
```
instead of a
```
TextBox
```
.


q: Is there any example code of a cpython (not IronPython) client which can call Windows Communication Foundation (WCF) service?

[A]
Even if there is not a specific example of calling WCF from Python, you should be able to make a fully SOAP compliant service with WCF. Then all you have to do is find some examples of how to call a normal SOAP service from Python.
The simplest thing will be to use the BasicHttpBinding in WCF and then you can support your own sessions by passing a session token with each request and response.


q: C++0x will allow template to take an arbitrary number of arguments. What is the best use of this feature other than implementing tuples ?

[A]
Type-safe
```
printf
```


q:
I am a Web developer who spends 99% of his time in Linux, but I need to develop a super simple application with VB or possibly C# (.Net).  The only version of Visual Studio I have is the most current free ones.  There MIGHT be a copy of 2001 lying around somewhere.  Anyways, the machine I need to develop this for is running Windows NT4.  I cannot change this because another piece of software runs on that requires it.

Is there a way to develop an app with the new VS and keep it compatible with such an old version of the .Net framework (1.1)?

If nothing else I could install Perl on the machine and write a command line type script, but given the people that will be using it GUI would be better.

[A]
I don't believe you can target .Net 1.1 in Visual Studio 2008. Here's one of the developer's explanations, from a comment in
this blog entry
:
Visual Studio 2008 will not support targeting .Net Framework 1.1.  This is something we really wanted to be able to support - since we know there are a lot of .NET developers working on .NET 1.1 applications.  However, it would have been significantly more difficult to go back and support .NET 1.1 which was a substantially different runtime.
Thus, to fit in this release, the
  decision ended up being either to not
  support multitargeting at all - or to
  support only targeting .NET2.0 and
  greater.  Because we really wanted
  Visual Studio 2008 to be a great tool
  for at least both .NET 3.0 and .NET
  3.5 - we decided to put in the most multitargeting support we could fit in
  this release.


q:
I have a table in a database that represents dates textually (i.e. "2008-11-09") and I would like to replace them with the UNIX timestamp. However, I don't think that MySQL is capable of doing the conversion on its own, so I'd like to write a little script to do the conversion. The way I can think to do it involves getting all the records in the table, iterating through them, and updating the database records. However, with no primary key, I can't easily get the exact record I need to update.

Is there a way to get MySQL to assign temporary IDs to records during a SELECT so that I refer back to them when doing UPDATEs?

[A]
If for some reason you do have to iterate (the other answers cover the situation where you don't), I can think of two ways to do it (these aren't MySQL-specific):
Add a column to the table that's an auto-assigned number. Use that as the PK for your updates, then drop the column afterwards (or just keep it around for future use).
In a table with no defined PK, as long as there are no exact duplicate rows, you can use the entire row as a composite PK; just use every column in the row as your distinguishing characteristic. i.e., if the table has 3 columns, "name", "address", and "updated", do the following:
UPDATE mytable SET updated = [timestamp value] WHERE name = [name] AND address = [address] AND timestamp = [old timestamp]
Many data access frameworks use this exact strategy to implement optimistic concurrency.


q:
I have this form:

<form name="customize">
    Only show results within
        <select name="distance" id="slct_distance">
            <option>25</option>
            <option>50</option>
            <option>100</option>
            <option value="10000" selected="selected">Any</option>
    </select> miles of zip code
    <input type="text" class="text" name="zip_code" id="txt_zip_code" />
    <span id="customize_validation_msg"></span>
</form>

How can I select the input and select with one jQuery selector?

I tried this but it selected all of the selects and inputs on the page:

$("form[name='customize'] select,input")

[A]
For me your suggestion worked. You could also use
```
```
form[name='customize'] select, form[name='customize'] input
```
```
Both selectors work as I see it. Maybe the the problem lies somewhere else?
I tried
```
```
$("form[name='customize'] select, input").css( 'font-size', '80px' );
```
```
on your example HTML. The font size for select and input changed.
--- edit ---
My suggestion above is the right one. It selects just the elements in the customize-form.


q:
I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound.

The error is "IOError: [Errorno
  Invalid output device (no default
  output device)] -9996

Is there another library I could try to use? Another method?

[A]
Have you looked at pymedia? It looks as easy as this to play a WAV file:
```
```
import time, wave, pymedia.audio.sound as sound
f= wave.open('YOUR FILE NAME', 'rb')
sampleRate= f.getframerate()
channels= f.getnchannels()
format= sound.AFMT_S16_LE
snd= sound.Output(sampleRate, channels, format)
s= f.readframes(300000)
snd.play(s)
while snd.isPlaying(): time.sleep(0.05)
```
```
Ref:
http://pymedia.org/tut/play_wav.html
Of course, you can have a look at the Python wiki under Audio (
http://wiki.python.org/moin/Audio/
) for other libraries such as
https://docs.python.org/library/wave.html
or again in Python's wiki under Game Libraries (
http://wiki.python.org/moin/PythonGameLibraries
) that will point you to bindings to OpenAL or Pygame that has sound modules.
And finally, although I don't know the limitations of pyaudio, your error message sounds more like the library is not able to find the default output device more than the device is in use by another process. Maybe have a look at what output device is returned by the
```
get_default_output_device_info
```
of pyaudio and compare it to whatever's your default setting in Ubuntu.


q:
Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?

Scenario:
My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown.  So how can I know how much CPU the app is using?

Target platform is *nix, however I would like to do it on a Win host also.

[A]
The
```
resource
```
module provides
```
getrusage
```
which can give you the information you need, at least for Unix-like platforms.
Note that CPU usage as a percentage is always measured over a time interval. Essentially, it is the amount of time taken by your program doing something divided by the interval time.
For example, if your application takes 2 seconds of CPU time over a 5 second period, then it can be said to be using 40% of the CPU.
Note that this calculation, as simple as it seems, can get tricky when using a multiprocessor system. If your application uses 7 seconds of CPU time in 5 seconds of wall clock time on a two-processor system, do you say it is uses 140% or 70% CPU?
Update: As
gimel
mentions, the
```
os.times
```
function also provides this information in a platform-independent way. The above calculation notes still apply, of course.


q: When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in Django?

[A]
You can't.
301 is an HTTP return code that is directly acted upon by the browser. Many sites handle these two issues by first sending the user to a redirect-er page that tells the user about the change and then X seconds later sends them to the new page. But the redirect-er page
must
have a 200 code.
One small variant is to detect search engine spiders (by IP and/or user agent) and give
them
the 301. That way the search results point to your new page.


q:
I am using sfOpenID plugin for Symfony, which doesn't support OpenID 2.0. That means, for example, that people using Yahoo! OpenID can't login to my site.

There is an OpenID 2.0 plugin that works with sfGuard, but I am not using nor planning to use sfGuard. Plus, it requires to install Zend framework, too, which is an overkill in my scenario.

So I've got two questions, really:

is there another OpenID plugin for Symfony supporting OpenID 2.0?

what would be the hack required to make sfOpenID support OpenID 2.0?

I suppose I could study OpenID specs and hack it myself, but then, I am a lazy programmer :)

[A]
I think you've covered all your options with sfOpenID and taOpenIDsfGuardPlugin for Symfony's plugins.
Without studying OpenID's specs in detail though, you could try one of those PHP libraries (
http://wiki.openid.net/Libraries
) by dropping it in your lib and connecting to a
```
sfUser
```
, or whatever you're using for authentication. There is also the OpenID Enabled library (
http://openidenabled.com/php-openid/
) which still uses PHP4 although compatible with PHP5 if you
tweak the error reporting level
to exclude some warnings.
There are a few tutorials out there that explains how to enable OpenID on your site with PHP:
http://www.saeven.net/openid.htm
or
http://www.plaxo.com/api/openid_recipe
.
And better yet, use this knowledge to
make a sfPlugin out of it
afterwards.


q:
Is there a way to create a Zip archive that contains multiple files, when the files are currently in memory?  The files I want to save are really just text only and are stored in a string class in my application.  But I would like to save multiple files in a single self-contained archive.  They can all be in the root of the archive.

It would be nice to be able to do this using SharpZipLib.

[A]
Yes, you can use SharpZipLib to do this - when you need to supply a stream to write to, use a
```
MemoryStream
```
.


q:
I need to

convert my Sandcastle Help File
Builder (SHFB) output that is a Web
site (HTML) to Media wiki format

Find a way to transfer/include the
converted pages directly into the
MediaWiki we have set up.

Any ideas? we have over 1000 pages of HTML files inthe Website (output of SHFB).

I thought of using a html2wiki converter ..I could think of looking around for a script to convert those 1000 pages into wiki format... that could take care of (1).

But I would still be left with the block in the last bit of the pipeline - how to feed converted pages directly into the Wiki?

[A]
I did some work with ingesting existing material from several sites into a comprehensive Wiki. It did not involve Sandcastle, but if you're dealing with HTML it shouldn't matter much.
html2wiki
extensions are out there, and from what I have read they can solve a lot of problems. I needed a little more control over each node in the DOM, so i used
Simple HTML DOM Parser
. It's in PHP and was easily dropped into Mediawiki's includes.
For creating the new pages, I ended up writing a small script that uses Mediawiki's Article class, specifically the
doEdit function
. this allows you to create new articles programatically, without user interaction. Of course, you'd want to be careful with this... The last thing you need is to create 1000 pages that are no good and have to be deleted. But perhaps this will help get you going.


q:
I could really do with updating a user's session variables from within my HTTPModule, but from what I can see, it isn't possible.

UPDATE: My code is currently running inside the OnBeginRequest () event handler.

UPDATE: Following advice received so far, I tried adding this to the Init () routine in my HTTPModule:

AddHandler context.PreRequestHandlerExecute, AddressOf OnPreRequestHandlerExecute

But in my OnPreRequestHandlerExecute routine, the session state is still unavailable!

Thanks, and apologies if I'm missing something!

[A]
HttpContext.Current.Session
should Just Work, assuming your HTTP Module isn't handling any
pipeline events
that occur prior to the session state being initialized...
EDIT, after clarification in comments: when handling the
BeginRequest event
, the Session object will indeed still be null/Nothing, as it hasn't been initialized by the ASP.NET runtime yet. To work around this, move your handling code to an event that occurs after
PostAcquireRequestState
-- I like
PreRequestHandlerExecute
for that myself, as all low-level work is pretty much done at this stage, but you still pre-empt any normal processing.


q:
Say I have a C program which is broken to a set of *.c and *.h files. If code from one file uses functions from another file, where should I include the header file? Inside the *.c file that used the function, or inside the header of that file?

E.g. file foo.c includes foo.h, which contains all declarations for foo.c; same for bar.c and bar.h. Function foo1() inside foo.c calls bar1(), which is declared in bar.h and defined in bar.c. Now the question is, should I include bar.h inside foo.h, or inside foo.c?

What would be a good set of rules-of-thumb for such issues?

[A]
I include the most minimal set of headers possible in the
```
.h
```
file, and include the rest in the
```
.c
```
file. This has the benefit of sometimes reducing compilation times. Given your example, if
```
foo.h
```
doesn't really need
```
bar.h
```
but includes it anyway, and some other file includes
```
foo.h
```
, then that file will be recompiled if
```
bar.h
```
changes, even though it may not actually need or use
```
bar.h
```
.


q: How can I place a MFC CFormView inside a CDockablePane which was introduced in the VS 2008 MFC Feature Pack?

[A]
Check the
BCGSoft
Samples for doing this with a cview.  The class names are a little different but its more or less the same stuff since they provided CDockablePane to Microsoft.


q:
Possible Duplicate:

  Bootstrapping a language

What's the importance of having an interpreter for a given language written in the target language (for example, PyPy)?

[A]
I'm sure there are many different reasons for doing it. In some cases, it's because you truly believe the language is the best tool... so writing the language interpreter or compiler in the language itself can be seen as a form of dogfooding. If you are really interested in this subject, the following article is a really amazing read about the development of squeak. The current version of squeak is a smalltalk runtime written in smalltalk.
http://users.ipa.net/~dwighth/squeak/oopsla_squeak.html


q:
With LINQ to SQL most likely going to not get as much active development as Entity Framework do you think it's best to switch to Entity Framework?

I've personally found EF to be very clunky and hard to use compared to LINQ to SQL which feels very natural.

EDIT: I recently posted an article on my blog about my feelings towards this potential decision...

ADO.NET v LINQ to SQL

[A]
IMO, not at the moment.
It is clear (from
recent announcements
especially) that EF is in for some heavy revisions as the "
thunderdome
" scenario plays out between LINQ-to-SQL and EF. Whatever happens, EF (in a few years) will almost certainly look quite different to EF today. Or certainly "different enough" ;-p
As such, my view is: stick with simple. And simple is LINQ-to-SQL.
I don't see much benefit learning a notoriously complex system if I know it is going to change very soon.
And I'm 100% with you on LINQ-to-SQL ;-p
If I needed something more than LINQ-to-SQL right now, I'd look at
NHibernate
or maybe
LLBLGen Pro
.
(
edit
- as an update, my position has softened a little bit,
here
and
here
- but I'm still using LINQ-to-SQL as my primary tool; also - LINQ-to-SQL
isn't quite dead yet
;-p).


q:
When I was at university a lecturer said how some people managed to code using sequence diagrams, this to me seems a good way of programming but of course the devil is in the details.  I have a few questions.

Does this actually happen or was I
misinterpreting what he said?

Has
anyone here actually done this?

Is it more productive?

What are the disadvantages?

What tools would be needed when using Java?

[A]
I've found that "normal" sequence diagrams are almost always more of a pain than they're worth (although I have found them useful for showing data flow in LINQ). Doing a "rough and ready" diagram and explaining it (preferably in person, but with plenty of words either way) works better in my experience.
I think it's a good idea to have a diagram (or several) showing a sort of "vertical slice" of your application - how each layer talks to another, and perhaps showing the course of a request/response in suitable cases. However, this doesn't need to be at the "individual method call and always 100% accurate" level - making sure that you convey the right general impression is more important, assuming the reader can then dive into the real code.
Having said all of this, my views on UML in general are much the same, so if you're a big fan of precise diagrams always being kept meticulously in sync with reality etc, take it all with a pinch of salt :)


q:
I'm trying to write rules for detecting some errors in annotated multi-threaded java programs.  As a toy example, I'd like to detect if any method annotated with @ThreadSafe calls a method without such an annotation, without synchronization.  I'm looking for a tool that would allow me to write such a test.

I've looked at source analyzers, like CheckStyle and PMD, and they don't really have cross-class analysis capabilities.  Bytecode analysers, like FindBugs and JLint seem rather difficult to extend.

I'd settle for a solution to something even simpler, but posing the same difficulty: writing a custom rule that checks whether each overriden method is annotated with @Override.

[A]
A simple tool to checkup on annotations is apt (
http://java.sun.com/j2se/1.5.0/docs/guide/apt/
also part of Java 6 api in javax.annotation.processing) however this only has type information (ie I couldn't find a quick way to get at the inheritance hierarchy using the javax.lang.model api, however if you can load the class you can get that information using reflection).


q:
I saw a potential answer here but that was for YYYY-MM-DD: JavaScript date validation

I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:

String.prototype.isValidDate = function()
{
     var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
     var matches = IsoDateRe.exec(this);
     if (!matches) return false;
     var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
     return ((composedDate.getMonth() == (matches[1] - 1)) &&
      (composedDate.getDate() == matches[2]) &&
      (composedDate.getFullYear() == matches[3]));
}

How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?

Thanks.

[A]
You can simplify it somewhat by changing the first two lines of the function to this:
```
```
var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
```
```
Or, just change the parameter to the RegExp constructor to be
```
```
^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$
```
```


q:
I need to build a function which parses the domain from a URL.

So, with

http://google.com/dhasjkdas/sadsdds/sdda/sdads.html

or

http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html

it should return google.com

with

http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html

it should return google.co.uk.

[A]
Check out
```
parse_url()
```
:
```
```
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'
```
```
```
parse_url
```
doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls.


q:
I'm looking to implement something in Java along the lines of:

class Foo{
 private int lorem; //
 private int ipsum;

 public setAttribute(String attr, int val){
  //sets attribute based on name
 }

 public static void main(String [] args){
  Foo f = new Foo();
  f.setAttribute("lorem",1);
  f.setAttribute("ipsum",2);
 }

 public Foo(){}
}

...where a variable is set based on the variable name without the variable names hard-coded and without using any other data structures. Is this possible?

[A]
In general, you want to use Reflection. Here is a good introduction to the
topic with examples
In particular, the "Changing Values of Fields" section describes how to do what you'd like to do.
I note that the author says, "This feature is extremely powerful and has no equivalent in other conventional languages." Of course, in the last ten years (the article was written in 1998) we have seen great strides made in dynamic languages. The above is fairly easily done in Perl, Python, PHP, Ruby, and so on. I suspect this is the direction you might have come from based on the "eval" tag.


q: I'm going to running thousands of queries into SQL and I need to prevent the duplication of field 'domain'. Never had to do this before and any help would be appreciated.

[A]
You probably want to create a "UNIQUE" constraint on the field "Domain" - this constraint will raise an error if you create two rows that have the same domain in the database. For an explanation, see
this tutorial in W3C school
-
http://www.w3schools.com/sql/sql_unique.asp
If this doesn't solve your problem, please clarify the database you have chosen to use (MySql?).
NOTE: This constraint is completely separate from your choice of PHP as a programming language, it is a SQL database definition thing. A huge advantage of expressing this constraint in SQL is that you can trust the database to preserve the constraint even when people import / export data from the database, your application is buggy or another application shares the database.


q:
Running Mongrel 1.1.5 on Rails 2.1.2 using PostgreSQL 8.3 via ruby-pg 0.7.9 on OS X 10.4 server...

Added restful_authentication and exception_notification, the latter of which appears to be doing me no good when Mongrel simply dies with "Illegal instruction" every time I select /RESOURCE_NAME/new.

Doesn't matter what resource.

In development.log I see it's declaring its intent to render /layouts/RESOURCE_NAME.html.erb and then ... nothing. No stack trace, no anything. server.log is empty.

This is something of a showstopper and I'm not sure what to do. I tried running webbrick, a la:

script/server webbrick --force

But it ignores my wishes and loads mongrel anyway.

Any pointers would be appreciated.


q:
In vs2008, is it possible to write an extension methods which would apply to any enumeration.

I know you can write extension methods against a specific enumeration, but I want to be able to every enumeration using a single extension method. Is this possible?

[A]
Yes, just code against the base
```
Enum
```
type, e.g.
```
```
public static void Something(this Enum e)
{
    // code here
}
```
```
The down-side is you'll probably end up doing some quite nasty stuff like finding the real base type using
```
Enum.GetUnderlyingType
```
, casting, and going down different branches depending on what the base type of the enum is, but you can find some good uses for it (e.g. we have
```
IsOneOf
```
and
```
IsCombinationOf
```
methods that apply to all enums).
PS: Remember when writing the method that, although ill advised, you can use
```
float
```
and
```
double
```
as the base types for enums so you'll need some special cases for those as well as unsigned values.


q: Can Emacs support the concept of projects? That would be where several configuration options varies depending on what project you are working on.

[A]
You generally wouldn't expect emacs to know about differences in build requirements---you let the build system (make or whatever) take care of that. To handle different coding standard define local
```
yourproject.el
```
files to set variables, load and unload local modes, etc... (use
```
M-x load-file
```
to run it).


q: In php I need to get the contents of a url (source) search for a string "maybe baby love you" and if it does not contain this then do x.

[A]
Just read the contents of the page as you would read a file. PHP does the connection stuff for you. Then just look for the string via regex or simple string comparison.
```
```
$url = 'http://my.url.com/';
$data = file_get_contents( $url );

if ( strpos( 'maybe baby love you', $data ) === false )
{

    // do something

}
```
```


q:
I'm using Excel 2007 to create a log-scale chart of numbers (specifically the Zimbabwean dollar exchange rate) over time. I'm using an x-y scatterplot and noticing one odd quirk.

The range of y values (numbers) spans a factor of about 10^30. On every chart I make using this data, half the gridlines are missing. Specifically, only the gridlines corresponding to the largest values show up. In fact, regardless of the total range only the top factor of 10^13 or so have gridlines. This is not dependent on the log base.

Am I doing something wrong? Is this a known bug? I can't find any references to this issue on google or microsoft's bug reports.

[A]
I'm having the same problem, it's definitely a bug.
Try a sequence 1, 10, 100, 1e+12, 1e+30 vs 0..4 and plot x,y scatter, and clearly the scale grid is messed-up even in linear, and in log is the behaviour you described.
My workaround was to make a transformation of the values and depict them scaled down (by a Million factor). That way the data the graph is handling is never above 10e9 (the value I started to hit issues).
So, my suggestion is: graph a Log version of the data (and clearly make a legend for it)


q: Given a pointer to some variable.. is there a way to check whether it was statically or dynamically allocated??

[A] Can you hook into malloc() itself, like the malloc debuggers do, using LD_PRELOAD or something? If so, you could keep a table of all the allocated pointers and use that. Otherwise, I'm not sure. Is there a way to get at malloc's bookkeeping information?


q:
I've been studying OOP for quite a while now and I have a good grasp of the theory.  I read the Head First book on OOP and, while it reinforced a lot of the theory, I found the case studies to be somewhat trivial.

I find that I'm applying OOP principles to my code each day, but I'm not sure if I'm applying them correctly.  I need to get to the point where I am able to look at my code and know whether I'm using inheritance appropriately, whether my object is cohesive enough, etc.

Does anyone have any good recommendations (books, online guides, blogs, walk-throughs, etc.) for taking the next step in developing solid OOP skills?

I am working primarily in .NET (visual basic), but I welcome suggestions that incorporate various platforms.

[A]
Consider looking into Design Patterns. Although it seems like they aren't commonly used in enterprise applications (I've seen them more commonly used in API's and Frameworks than embedded into enterprise code), they could be applied to make software simpler or more robust in a lot of situations if only developers knew how to apply them.
The key is to understand the design patterns first, then with experience you'll learn how to apply them.
There is a
Head First book on design patterns
that teaches the concept pretty simply, although if you want a book that really covers design patterns in detail, check out the
Gang of Four design patterns book
, which is basically what made design patterns mainstream and is referred to almost every time the topic is brought up.
Design patterns can be applied in pretty much any object-oriented language to some degree or another, although some patterns can be overkill or over engineering in some cases.
EDIT:
I also want to add, you should check out the book
Code Complete 2
. It's a very influential book in the world of software development. It covers a lot of different concepts and theories. I learn something new every time I read it. It's such a good book that if I read it every 6 months to a year, I look at it from a different perspective that makes me a better programmer just by re-reading it. No matter how much you might think you know, this book will make you realize just how little you really know. It's really a great book. I can't stress how much you should own this book.


q:
I have an application where I have potentially many processes must send a message to one process.  I figured the most expedient way to do this would be to just send a UDP datagram.

When opening a socket, I need to specify which port to listen to.  As I just want to fire and forget the UDP datagram, I'd like to just have the OS pick an available port.  I'd rather not have to hunt for one, especially as many instances of my process may be running.  Is there a way I can tell the OS to just pick an available port (or better yet, not even open a listening socket) to fire and forget my UDP datagram?

[A]
Answering the "Problem" rather than the "Question"
If all the processes are operating on the same PC, you might want to look into shared files or some other means of communications other than a networking stack.
I'd suggest you explore the options in Boost's Interprocess library
http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess.html
Quick guide here:
http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess/quick_guide.html
Specifically, I suggest you use a named pipe or shared memory between your processes.


q:
I have got 3 text files (A, B and C), each with several hundred email addresses. I want to merge list A and list B into a single file, ignoring differences in case and white space. Then I want to remove all emails in the new list that are in list C, again ignoring differences in case and white space.

My programming language of choice is normally C++, but it seems poorly suited for this task. Is there a scripting language that could do this (and similar tasks) in relatively few lines?

Or is there software already out there (free or commercial) that would allow me to do it? Is it possible to do it in Excel, for example?

[A]
The fastest way to do this probably wouldn't necessarily require coding.  You could import files A and B into Excel in one worksheet, then (if necessary) do a filter on that resulting list of addresses to remove any duplicates.
The next step would be to import file C into a second worksheet.  In a third worksheet, you'd do a VLOOKUP to pick out all the addresses in your first list and remove them if they're in your "List C".
The VLOOKUP would look something like this:
=IF(ISNA(VLOOKUP(
email_address_cell
, Sheet2!
email_duplicates_list
, 1, false), "", (VLOOKUP(
email_address_cell
, Sheet2!
email_duplicates_list
, 1, false)))
I've also included a check to see if the formula returns a "Value Not Available" error, in which case the cell just shows a blank value.  From there, you just need to remove your white-space and there's your final list.
Now having said all that, you could still do a VBA macro to do much the same thing, but perhaps clean the lists up a bit, depending on what you need.  Hope that helps!


q:
C#: What is the proper way to change the font style (underline) from a Label at runtime?

So far I understand that if you want to change font related properties at runtime from a label, mainly all font properties, you would have to use,

 lblName.Font = new Font(... etc. etc.

Is there a shortcut to the above but only assign nothing but a new Font style such FontStyle.Underline?

or

Would I have to proceed with using the "new Font()" method and assign all fields along with it too just to underline my label?

[A]
How about (I'm using .Net Framework 2.0)  Okay so this works for a Web Application.  In a forms application it is read-only.
lblName.Font.Underline = true;
Here's the definition:
```
```
//
    // Summary:
    //     Gets or sets a value that indicates whether the font is underlined.
    //
    // Returns:
    //     true if the font is underlined; otherwise, false. The default value is false.
    [DefaultValue(false)]
    [NotifyParentProperty(true)]
    public bool Underline { get; set; }
```
```


q:
Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks

edit: Resolved myself thanks

[A]
The easiest answer is to put the code you are trying to run inside a function like this
(inside your module that you are importing now):
```
```
def main():
    # All the code that currently does work goes in here
    # rather than just in the module
```
```
(The module that does the importing)
```
```
import your_module #used to do the work

your_module.main() # now does the work (and you can call it multiple times)
# some other code
your_module.main() # do the work again
```
```


q:
I'm someone who writes code just for fun and haven't really delved into it in either an academic or professional setting, so stuff like these bitwise operators really escapes me.

I was reading an article about JavaScript, which apparently supports bitwise operations. I keep seeing this operation mentioned in places, and I've tried reading about to figure out what exactly it is, but I just don't seem to get it at all. So what are they? Clear examples would be great! :D

Just a few more questions - what are some practical applications of bitwise operations? When might you use them?

[A]
These are the bitwise operators, all supported in JavaScript:
```
op1 & op2
```
-- The
```
AND
```
operator compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0.
```
op1 | op2
```
-- The
```
OR
```
operator compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0.
```
op1 ^ op2
```
-- The
```
EXCLUSIVE-OR
```
operator compares two bits and returns 1 if either of the bits are 1 and it gives 0 if both bits are 0 or 1.
```
~op1
```
-- The
```
COMPLEMENT
```
operator is used to invert all of the bits of the operand.
```
op1 << op2
```
-- The
```
SHIFT LEFT
```
operator moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1 by 2.
```
op1 >> op2
```
-- The
```
SHIFT RIGHT
```
operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half.  The left-most sign bit is preserved.
```
op1 >>> op2
```
-- The
```
SHIFT RIGHT
```
-
```
ZERO FILL
```
operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half.  The left-most sign bit is discarded.


q: I have a T-Mobile G1 and I'm going to download the developer SDK and see if I can create a few simple apps for my phone.  If you've done similar development, please answer below and tell me about your experience.  Please share any links you found especially useful.

[A]
I started from here
http://code.google.com/android/kb/commontasks.html
I got my environment and emulator up and running within about 15 minutes.
First impressions are its fun to work with.
Paul


q:
I have a CSS like this

ul {
    list-style-image:url(images/bulletArrow.gif);
}

ul li {
    background: url(images/hr.gif) no-repeat left bottom;
    padding: 5px 0 7px 0;
}

But the bullet image doesn't align properly in IE (it's fine in Firefox).
I already have a background image for li, so I can't use the bullet image as a background.
Is there any solution to this?

Thanks in advance.

[A]
There is a good explanation and solution of this here:
http://css.maxdesign.com.au/listutorial/master.htm
It says that using
```
list-style-image
```
results in inconsistent placement of the image with different browsers. Then it explains how to use background images for the bullets for a better result.


q:
I want to retrieve a list of the files that has been added or deleted from our Subversion repository over, for example, the last month.

I'd prefer to have the file names, and not just a count.

Is this possible from the Subversion command line, or would I need to use a script to trawl the log?

[A]
I don't think you can do it with just the command-line tools, but outputting it with an XML format and doing some grepping or filtering would probably give you what you want.
Try this for a start:
```
```
svn log -v --xml | grep 'action="[A|D]"'
```
```


q:
I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.

The alternatives I tried were:

Boost.Python

I liked the cleaner API produced by Boost.Python, but the fact that it would have required that users install an additional dependency made us switch to SWIG.

SWIG

SWIG's main advantage for us was that it doesn't require end users to install it to use the final program.

What have you used to do this, and what has been your experience with it?

[A]
I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions.  Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's.  However, SWIG has
much
better documentation, no external dependencies, and if you get the library wrapped in SWIG for Python you're more than half-way there to getting a Java/Perl/Ruby wrapper as well.
I don't think there's a clear-cut choice: for smaller projects, I'd go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.


q:
(define (repeated f n)
   if (= n 0)
   f
   ((compose repeated f) (lambda (x) (- n 1))))

I wrote this function, but how would I express this more clearly, using simple recursion with repeated?

I'm sorry, I forgot to define my compose function.

(define (compose f g) (lambda (x) (f (g x))))

And the function takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f.

[A]
What
is
your function trying to do, just out of curiosity? Is it to run
```
f
```
,
```
n
```
times? If so, you can do this.
```
```
(define (repeated f n)
  (for-each (lambda (i) (f)) (iota n)))
```
```


q:
are there any free Team Foundation Server sites we can use for our private development? Please don't say CodePlex (which I love) because that means the code is all opensource.

Lastly, I also understand that some people might raise the issue of having their private code hosted somewhere by people they do not know, etc.. so please don't raise any security concerns.

I'm guessing there are no free services because of licensing reasons?

[A]
I would find it doubtful that there would be a free one.  Team Foundation Server was very expensive for us to implement so I would be surprised if someone was hosting for free.  Other than the CodePlex type options.
There are services where you can pay per user per month like
this one
or
this one
>
I find it doubtful you will find free though.


q:
The last week on the ACM ICPC Mexico competition, I missed a "return 0" on a C++ program. For this reason we got punished with 20 minutes.

I had read that the standard does not oblige us to write it at the end of a main function. It is implicit, isn't it? How can I prove it?

We were using a Fedora system with a G++ compiler.

[A]
You refer to the C++ Standard, chapter 3.6.1 paragraph 5:
A return statement in main has the
  effect of leaving the main function
  (destroying any objects with automatic
  storage duration) and calling
  exit with the return value as the
  argument. If control reaches the end
  of main without encountering a return
  statement, the effect is that of
  executing
```
return 0;
```
If you haven't got the Standard at hand, you can show then the paragraph in a Working Draft. Here is one for c++98, which already had this defined.
You can learn more
here
.


q:
I believe I already know the answer, but I am not 100% sure, so just a quick question: What does Red/Green Testing actually mean?

I understand it as "Write your tests first, so that they all fail (= all red), then write your code and watch how each test turns green, and when all are green, you're fine".

I heard this in Scott's MVC Talk at Mix, so I do not know if this is an "official" term or if he just made it up. (Edit: Scott actually also explains it starting at 55:00 Minutes, and he made a good remark why he beleives in it)

[A]
It does refer to TDD or Test Driven Development, but it would apply to each test.  Write the test first, then write the code to pass the test.  It would be wrong to write ALL the tests first.  TDD is an incremental development approach.
The basic idea is no code is written before there is failing test (RED).  When you have a failing test, then you write the code to pass the test (GREEN).  Now you are ready to write the next test -- i.e., no new tests until all are green. Or refactor, as @Brian points out.


q:
I wrote this function that's supposed to do StringPadRight("Hello", 10, "0") -> "Hello00000".

char *StringPadRight(char *string, int padded_len, char *pad) {
    int len = (int) strlen(string);
    if (len >= padded_len) {
        return string;
    }
    int i;
    for (i = 0; i < padded_len - len; i++) {
        strcat(string, pad);
    }
    return string;
}

It works but has some weird side effects... some of the other variables get changed.  How can I fix this?

[A]
The argument you passed "Hello" is on the constant data area. Unless you've allocated enough memory to char * string, it's overrunning to other variables.
```
```
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
strncpy(buffer, "Hello", sizeof(buffer));
StringPadRight(buffer, 10, "0");
```
```
Edit: Corrected from stack to constant data area.


q:
How and why do 7- and 35-pass erases work?
Shouldn't a simple rewrite with all zeroes be enough?

[A]
A single pass with zeros doesn't completely erase magnetic artifacts from a disk. It's still possible to recover the data from the drive. A 7-pass erasure using random data will do a pretty complete job to prevent reconstruction of the data on the drive.
Wikipedia has a number of different articles relating to this topic.
http://en.wikipedia.org/wiki/Data_remanence
http://en.wikipedia.org/wiki/Computer_forensics
http://en.wikipedia.org/wiki/Data_erasure


q:
Is there a way short of writing a seperate batch file or adding a system call to pause or getch or a breakpoint right before the end of the main function to keep a command window open after a command line application has finished running?

Put differently, is there a way in the project properties to run another command after running the target path? If my program is "foo.exe", something equivalent to a batch file containing

@foo
@pause

Edit: added "or a getch or a breakpoint"

[A]
In C++
```
```
#include <conio.h>

// .. Your code

int main()
{
  // More of your code

  // Tell the user to press a key
  getch();      // Get one character from the user (i.e a keypress)

  return 0;

}
```
```
If you are in a batch file, the command "pause" outputs "Press any key to continue" and waits for a keypress.


q:
Or should they always be a function when business logic is invloved ?

Example: Order.RequiresPayment

property or function ?
There are business rules as for when it is true or not

IS there a pattern that may determine this?

[A]
When in doubt, consider maintenance of your code as a guideline.
If
```
OrderRequiresPayment
```
is determined very simply (for example, set
```
true
```
on order creation,
```
false
```
when payment is received), a property is fine.
If it's determined by a formula, or if it's updated in many places, it's probably best to encapsulate it in a function.


q:
I would like to dynamically hide a button in one of my views depending on a certain condition.

I tried adding some code to the view controller's -viewWillAppear method, to make the button hidden before displaying the actual view, but I still don't know how to do that.

I have a reference to the button through an IBOutlet, but I'm not sure how to move forward from here. For reference, this is a UIBarButtonItem instance.

[A]
Just set the button's hidden property to true:
```
```
myButton.hidden = YES;
```
```


q:
In a progression of languages, I have been learning C and C++.  Now I would like to learn C#.  I know there are some drastic differences between them - such as the removal of pointers and garbage collection.  However, I don't know many of the differences between the two.

What are the major differences that a C++ programmer would need to know when moving to C#?  (For example, what can I use instead of STL, syntactic differences between them, or anything else that might be considered important.)

[A]
C# for C++ Developers
is a great place to start.  It is a table that lists the most important comparisons between the two languages.
Once you have explored some of these differences, you might choose a self-contained project you have written in the past in C++, and re-write it in C#.  In your first pass, you will probably just end up translating directly across, using the same design and algorithms.  As you become more comfortable with C#, you will recognize ways to take advantage of language features only available in C#, as well as the incredibly versatile .NET Framework.


q:
When a user clicks in certain places in my control, I want to change the color of some rows and columns in my grid, then fade it back to the normal color, within say 500ms or so.  I haven't decided whether to use Winforms or WPF yet, so advice in either of those technologies would work.  Thank you.

Edit: I understand I could do this by just calling Paint in a loop within the click event, properly setting the drawing parameters.  However I believe that would block the UI, and I would like to be more responsive than that.

[A]
At its simplest, a fade effect like this just requires a timer of some sort that gradates the color back towards normal with each tick.  The faster the time, the more discrete colors you will display from start to finish, and the smoother the overall effect will be (WPF may have something built-in to do this).
You definitely
do not
want to repaint in a loop.  As you pointed out this will block the UI, and also you would not be able to control how long the loop takes (different machines will render the same number of steps from highlight color to normal in different lengths of time).


q:
I'm looking at using CompositeWPF (http://www.codeplex.com/CompositeWPF) - aka Prism, to build an application I am working on.

The application isn't a traditional LOB application, however it does present data and state information to the user.

One thing which I am unsure of is if CompositeWPF supports more than one Window or Shell. I would like to have my application notify users with a border-less window which appears in the lower RHS of the screen (think MSN notification) but still use the idea of views being injected into the region etc.

In addition to this I would like to be able to react to a user action (e.g. double click on something), hide the main window and present a progress dialog while work is being performed.

So, is this possible?


q:
Using MySQL, I can do something like:

SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;

My Output:

shopping
fishing
coding

but instead I just want 1 row, 1 col:

Expected Output:

shopping, fishing, coding

The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a lot more rows than I'd like.

I've looked for a function on MySQL Doc and it doesn't look like the CONCAT or CONCAT_WS functions accept result sets.

So does anyone here know how to do this?

[A]
You can use
```
GROUP_CONCAT
```
:
```
```
SELECT person_id,
   GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
```
```
As Ludwig stated in
his comment,
you can add the
```
DISTINCT
```
operator to avoid duplicates:
```
```
SELECT person_id,
   GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
```
```
As Jan stated in
their comment,
you can also sort the values before imploding it using
```
ORDER BY
```
:
```
```
SELECT person_id,
       GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
```
```
As Dag stated in
his comment,
there is a 1024 byte limit on the result. To solve this, run this query before your query:
```
```
SET group_concat_max_len = 2048;
```
```
Of course, you can change
```
2048
```
according to your needs. To calculate and assign the value:
```
```
SET group_concat_max_len = CAST(
                     (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
                           FROM peoples_hobbies
                           GROUP BY person_id) AS UNSIGNED);
```
```


q: Besides the sample applications featured in the books Beginning Groovy and Grails and The Definitive Guide to Grails, are there any applications out there written in Grails that are good examples from which to learn best practices? Such as real applications that are open-source? Thanks.

[A]
Yes.  IBM has an excellent series of articles building on to a sample application at  IBM's developerworks site:
Part I:
http://www.ibm.com/developerworks/java/library/j-grails01158/
The Series:
http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=mastering+grails


q:
recently I downloaded this open source project and I am trying to compile it.

However, one of the line is giving me an error.

"import com.sun.org.apache.xpath.internal.functions.WrongNumberArgsException;"

Seems that i am missing a library.... is there a way to know WHICH library do I need?

I tried searching on google for com.sun.org.apache.xpath.internal.functions,
while there seem to be a result on kickjava.com/src containing the source code.

I think i need the Jar file right?

I tried downloading xalan from apache and it didn't work.
I tried to see if there's a xpath library, but I dont think there's a xpath library?
searching for xpath led me to xalan.
I have also tried Xerces-J-bin.2.9.1 .

Thanks!

[A]
The
WrongNumberArgsException
class in Xalan is in the
```
org.apache.xpath.functions
```
package.  With the Xalan jar in your project, you should just be able to change the import statement in the open source code to use the correct path.


q:
Scanner can only get input from system console? not be able to get from any dialog window?

Thanks.

[A]
A
Scanner
can read text from any object which implements the
Readable
interface.
That includes
```
BufferedReader
```
,
```
CharArrayReader
```
,
```
CharBuffer
```
,
```
FileReader
```
,
```
FilterReader
```
,
```
InputStreamReader
```
,
```
LineNumberReader
```
,
```
PipedReader
```
,
```
PushbackReader
```
, and
```
StringReader
```
(from the
```
Readable
```
javadoc).  Unfortunately, that does not include any dialog windows.
The easiest way to hook a dialog window to a
```
Scanner
```
would probably be to build a
```
Scanner
```
using the constructor that takes a
```
String
```
, passing the user input from the dialog directly to the
```
Scanner
```
.


q:
For quite a while, I thought that Free Software was Open Source Software.  I've found out that this view is incorrect, and that Open Source Software is not necessarily Free Software.  I honestly can't see any differences.

What am I missing here?  What are the distinguishing traits of both parties?

[A]
Both are basically the same, except the free software movement puts more emphasis on the freedom to modify and redistribute the code. For example, GNU GPL would be more "free" than MIT licence, because MIT license does not enforce copyleft and thus someone can develop closed-source software based on the code.
See also
Wikipedia chapter about this
, which mentions Microsoft shared source inititive, that can provide you with very unfree source code of their applications.


q:
When the program runs, there is a series of ListView forms. We populated one of them with items (as strings) and we check whether the state of selection has changed. Once it's changed, we grab the text of the selected item using FocusedItem.Text. The first time works just fine but when another selection is made, the selected item returns as null.

The only way we can temporarily get around this issue is to clear and repopulate the form. The disadvantage is that we lose the highlighted item. There got to be another way around this. Maybe we're not clear on how ListView really works?

Any ideas?

[A]
I have run a test program and see no instance where FocusedItem could be nulls.
Could you post some code?
Here is what I got after I selects the item 'a' then selects the item 'b' and then click on an empty space:
```
```
ItemSelectionChanged
    Item         : ListViewItem: {a}
    IsSelected   : True
    SelectedItem : ListViewItem: {a}
    FocusedItem  : ListViewItem: {a}
SelectedIndexChanged
    SelectedItem : ListViewItem: {a}
    FocusedItem  : ListViewItem: {a}
ItemSelectionChanged
    Item         : ListViewItem: {a}
    IsSelected   : False
    SelectedItem : null
    FocusedItem  : ListViewItem: {a}
SelectedIndexChanged
    SelectedItem : null
    FocusedItem  : ListViewItem: {a}
ItemSelectionChanged
    Item         : ListViewItem: {b}
    IsSelected   : True
    SelectedItem : ListViewItem: {b}
    FocusedItem  : ListViewItem: {b}
SelectedIndexChanged
    SelectedItem : ListViewItem: {b}
    FocusedItem  : ListViewItem: {b}
ItemSelectionChanged
    Item         : ListViewItem: {b}
    IsSelected   : False
    SelectedItem : null
    FocusedItem  : ListViewItem: {b}
SelectedIndexChanged
    SelectedItem : null
    FocusedItem  : ListViewItem: {b}
```
```
Noticed that
```
FocusedItem
```
is never null.
Is it the same in your case?
Would a simple
```
if (listView.FocusedItem == null)
```
check do for your case?


q: I need to load a bunch of words (about 70,000) from a text file, add it to a hashtable (using soundex as a key) and sort the values. While doing all these I want to show a progress bar using JProgressBar. Articles such as this and this, only gives a non-real example (a while loop). Can anyone suggest me how should I proceed. How can I get a number from above condition to set the value for the progress bar? Also it seems that there are different ways to do it - using thread, timer etc. Which could be the best method for the situation such as above?

[A]
I would read the text file in a loop on a dedicated work thread, not the event-dispatch thread (EDT). If I know the total number of words to be read, then I can compute the percentage completed at each iteration of the loop and update the progress bar accordingly.
Sample Code
The following code puts the progress bar in indeterminate mode during preprocessing and postprocessing, displaying an animation that indicates work is occurring. Determinate mode is used when reading iteratively from the input file.
```
```
// INITIALIZATION ON EDT

// JProgressBar progress = new JProgressBar();
// progress.setStringPainted(true);

// PREPROCESSING

// update progress bar (indeterminate mode)
SwingUtilities.invokeLater(new Runnable()
{
    @Override
    public void run()
    {
        progress.setIndeterminate(true);
        progress.setString("Preprocessing...");
    }
});

// perform preprocessing (open input file, determine total number of words, etc)

// PROCESSING

// update progress bar (switch to determinate mode)
SwingUtilities.invokeLater(new Runnable()
{
    @Override
    public void run()
    {
        progress.setIndeterminate(false);
    }
});

int count = 0;

while (true)
{
    // read a word from the input file; exit loop if EOF

    // compute soundex representation

    // add entry to map (hash table)

    // compute percentage completed
    count++;
    final int percent = count * 100 / total;

    // update progress bar on the EDT
    SwingUtilities.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            progress.setString("Processing " + percent + "%");
            progress.setValue(percent);
        }
    });
}

// POSTPROCESSING

// update progress bar (switch to indeterminate mode)
SwingUtilities.invokeLater(new Runnable()
{
    @Override
    public void run()
    {
        progress.setIndeterminate(true);
        progress.setString("Postprocessing...");
    }
});

// perform postprocessing (close input file, etc)

// DONE!

SwingUtilities.invokeLater(new Runnable()
{
    @Override
    public void run()
    {
        progress.setIndeterminate(false);
        progress.setString("Done!");
        progress.setValue(100);
    }
});
```
```
Suggestions
Consider writing a convenience method to update the progress bar on the EDT, so as to reduce clutter in your code (
```
SwingUtilities.invokeLater... public void run()...
```
)


q: What are the benefits of having a member variable declared as read only?  Is it just protecting against someone changing its value during the lifecycle of the class or does using this keyword result in any speed or efficiency improvements?

[A]
The
```
readonly
```
keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime.  This differs from a constant declared with the
```
const
```
modifier, which must have its value set at compile time.  Using
```
readonly
```
you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.
Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).


q:
Let's say I've got a setup that look something like

phd/code/
phd/figures/
phd/thesis/

For historical reasons, these all have their own git repositories. But I'd like to combine them into a single one to simplify things a little. For example, right now I might make two sets of changes and have to do something like

cd phd/code
git commit
cd ../figures
git commit

It'd be (now) nice to just to perform

cd phd
git commit

There seems to be a couple of ways of doing this using submodules or pulling from my sub-repositories, but that's a little more complex than I'm looking for. At the very least, I'd be happy with

cd phd
git init
git add [[everything that's already in my other repositories]]

but that doesn't seem like a one-liner. Is there anything in git that can help me out?

[A]
The sequence you suggested
```
```
git init
git add *
git commit -a -m "import everything"
```
```
will work, but you will lose your commit history.


q: I have created a VB.Net lending application for a cooperative that caters to widows. The application tracks the members' loans and payments, and is also used as an accounting system. In my first release, the users felt that showing a messagebox every time an error occurs is very annoying. My solution is to output errors in a label control. The users accepted the modification, but i feel i am doing it wrong.

[A]
They were probably annoyed with a modal dialog that interrupted their input flow.  Imagine if Word interrupted you every time you typed a word it couldn't find in the dictionary, instead of just underlining it in red and letting you fix your typos later.  You'd type pretty slow.
I recommend you just highlight input errors and let them come back and fix them when they're done.  If they try to submit the form (or whatever the analogue would be), then show the dialog and don't let them submit until they fix or acknowledge the fields flagged with errors.


q:
My code processes all the files in a folder on a Windows box. I want to offer the user (who happens to also be me) the option to select the folder to be processed, using the standard File Chooser dialog.

I am trying to use the GetOpenFileName function to make this happen. (I am actually calling it from Python via pywin32, but that shouldn't be relevant.)

I can get it to select a particular file, but I can't see any options to let the user select a folder instead.

Is there a flag combination I haven't understood, am I calling the wrong function entirely or is there another idiom for doing this?

[A]
Unfortunately, I think you're calling the wrong function entirely. It's been a while since I've done Win32 gui stuff.. but I seem to recall that there was a different way of bringing up a "select directory" box. It wasn't a straight Win32 function, but was some shell API function that required a whole heap of code to do the simplest thing.
Update: A bit of google reveals the
SHBrowseForFolder
function.
Update two: And here is an
example for Python
.


q:
How can I refer a custom function in xml?  Suppose that I have a function written in Java and want it to refer by the xml tag, how is this possible?

Current senario: I am using XACML2.0 which contains xml tags and I want to refer some function in Java that will talk to the backend data, I'm unable to refer a function in xacml.  Could you help me please?

[A]
You should read up on Reflection in Java.
The following example would invoke the method
myObjectThatContainsMethod#methodNameAsString(Integer arg1, Integer arg2)
```
```
Integer[] params = {new Integer(123),new Integer(567)};
Class cl=Class.forName("stringParsedFromYourXML");
Class[] par=new Class[2];
par[0]=Integer.TYPE;
par[1]=Integer.TYPE;
Method mthd=cl.getMethod("methodNameAsString", parameterTypes);
mthd.invoke(new myObjectThatContainsMethod(), params);
```
```
hope that helps..


q:
I'm working on a System Preferences Pane. It opens fine on some computers, but on other Macs (all running 10.5.5), the preference pane refuses to load and simply hangs, spitting the following into the console:

11/9/08 8:38:50 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:50 Macintosh.local System Preferences[369] <Error>: Failed to create window context device
11/9/08 8:38:50 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:50 Macintosh.local System Preferences[369] <Error>: CGWindowContextCreate: failed to create context delegate.
11/9/08 8:38:55 PM [0x0-0x31031].com.apple.systempreferences[369] Sun Nov 9 20:38:55 Macintosh.local System Preferences[369] <Error>: Failed to create window context device

Any ideas why this is happening?

Thanks.


q: I am tired of doing typical CRUD programming type applications. I would like to work on some interesting (not too hard) programming problems.  Are there any sites out there to help me exercise my brain?

[A]
Project Euler:
http://projecteuler.net/
is a nice collection of randomly interesting problems.
Somewhat related (not always programming, but generally interesting to programmers) is the IBM ponder this site:
http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/pages/index.html


q: What is the best way to find the total number of words in a text file in Java? I'm thinking Perl is the best on finding things such as this. If this is true then calling a Perl function from within Java would be the best? What would you have done in condition such as this? Any better ideas?

[A]
I'd initialize a
```
word_count
```
int to 1, then loop through each character in the file and increment
```
word_count
```
for every whitespace character
unless
the previous character was a whitespace character. (A space, tab, or newline.)