q:
Question: Is there an easy way (library function) to perform a bitwise AND or OR on numbers larger than 32-bit in ActionScript?

From the docs:
"Bitwise operators internally manipulate floating-point numbers to change them into 32-bit integers. The exact operation performed depends on the operator, but all bitwise operations evaluate each binary digit (bit) of the 32-bit integer individually to compute a new value."

Bummer...

I can't use the & or | ops - does AS expose a library function to do this for Numbers?

Specifics: I'm porting a bunch of java to flex and the java maintains a bunch of 'long' masks.  I know that I can split the Java masks into two ints on the flex side.  Since all of my mask manip is localized this won't be too painful.  However, I'd like to keep the port as 1-1 as possible.

Any suggestions?
Thanks!

[A]
According to
http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_11.html
, there are no 64-bit integers (signed or unsigned)...only 32-bit.
The Number type, as you mentioned above, has a 53-bit mantissa, which is too short for you.
I searched for a BigNum FLEX implementation, but couldn't find one.
I'm guessing that you will have to simulate this with either an array of ints or a class with a high and low int.
Good Luck,
Randy Stegbauer


q:
I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the UITableViewCell Class Reference but there are only three constants defined for Selection style (Blue, Gray, None). I saw one application that used a different color than those defined in the reference.

How can we use a color other than those defined in the reference?

[A]
Override didSelectRowAtIndexPath: and draw a UIView of a color of your choosing and insert it behind the UILabel inside the cell. I would do it something like this:
```
```
UIView* selectedView; //inside your header

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

  UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
  selectedView = [[UIView alloc] initWithFrame:[cell frame]];
  selectedView.backgroundColor = [UIColor greenColor]; //whatever

  [cell insertSubview:selectedView atIndex:0]; //tweak this as necessary
  [selectedView release]; //clean up

}
```
```
You can choose to animate this view out when it gets deselected and will satisfy your requirements.

s: huggingface

c: devops

d: intermediate


q: Please advise how to scrape AJAX pages.

[A]
Depends on the ajax page.  The first part of screen scraping is determining how the page works.  Is there some sort of variable you can iterate through to request all the data from the page?  Personally I've used
Web Scraper Plus
for a lot of screen scraping related tasks because it is cheap, not difficult to get started, non-programmers can get it working relatively quickly.
Side Note: Terms of Use is probably somewhere you might want to check before doing this.  Depending on the site iterating through everything may raise some flags.


q:
Whats the normal procedure of clearing a form after POST? Just loop through the textboxes and cleat all text? I have an ASP.NET application with several forms and I am trying to avoid them sending the data twice?

Thanks

[A]
You can inject some javascript code to execute after postback.
```
```
document.forms[0].reset();
document.forms[1].reset();
```
```
From server side, I haven't found an easy way to reset the form contents other than iterating through the controls inside a loop or doing a
Server.Transfer
back to the same page.


q:
I'm tasked with replicating a production environment to create many test/sit environments.

One of the things I need to do is build up Perl, with all the modules which have been installed (including internal and external modules) over the years. I could just use CPAN.pm autobundle, but this will result in the test environment having much newer versions of the external modules that production has.

What is the easiest/best way to get and install (a lot of) version specific Perl modules.

[A]
Make your own CPAN mirror with exactly what you want.
Stratopan.com
, a service, and
Pinto
, tools that's built on top of, can help you do that.
The CPAN tools only install the latest version of any distribution because PAUSE only indexes the latest version. However, you can create your own, private CPAN that has exactly the distributions that you want. Once you have your own CPAN mirror with only what you want, you point your CPAN tools at only that mirror so it only installs those versions. More on that in a minute.
Now, you want to have several versions of that. You can create as many mirrors as you like, and you can also put the mirrors in source control so you can check out any version of the mirror that you like.
Tools such as CPAN::Mini::Inject can help you set up your own CPAN. Check out
my talks on Slideshare
for the basic examples, and some of
my videos on Vimeo
for some of the demonstrations. Look at anything that has "CPAN" or "BackPAN" in the title. I think I might have some stuff about it in
The Perl Review
too, or should by the next issue. :)
Lately, I've been working on a program called dpan (for DarkPAN) that can look at random directories, find Perl distributions in them, and create the structure and index files that you need. You run dpan, you get a URL to point your CPAN client toward, and off you go. It's part of my MyCPAN-Indexer project, which is in
Github
. It's not quite ready for unsupervised public use because I mostly work with corporate clients to customize their setup. If you're interested in that, feel free to ask me questions though.
Also, I recently released
CPAN::PackageDetails
that can help you build the right index file. It's still a bit young too, but again, if you need something special, just ask.


q:
My question is how do I configure an EJB 3.0 style message driven bean to use a configured JMS datasource in jboss.

For example, my MDB looks something like:

@MessageDriven(mappedName = "ExampleMDB", activationConfig = {

        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "MyTopic"),
        @ActivationConfigProperty(propertyName = "channel", propertyValue = "MyChannel"),

})
@ResourceAdapter(value = "wmq.jmsra.rar")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@TransactionManagement(TransactionManagementType.BEAN)
public class MyMDB implements MessageListener {
 .....
}

But I would like the bean to attached to a given JMS datasource ( in the case of jboss 4.2.2 this is in deploy/jms/jms-ds.xml). Perhaps this is not even possible but is worth asking.


q:
I'd like to receive error logs via email. For example, if a Warning-level error message should occur, I'd like to get an email about it.

How can I get that working in CodeIgniter?

[A]
You could extend the Exception core class to do it.
Might have to adjust the reference to CI's email class, not sure if you can instantiate it from a library like this. I don't use CI's email class myself, I've been using the Swift Mailer library. But this should get you on the right path.
Make a file MY_Exceptions.php and place it in /application/libraries/ (Or in /application/core/ for CI 2)
```
```
class MY_Exceptions extends CI_Exceptions {

    function __construct()
    {
        parent::__construct();
    }

    function log_exception($severity, $message, $filepath, $line)

    {
        if (ENVIRONMENT === 'production') {
            $ci =& get_instance();

            $ci->load->library('email');
            $ci->email->from('your@example.com', 'Your Name');
            $ci->email->to('someone@example.com');
            $ci->email->cc('another@another-example.com');
            $ci->email->bcc('them@their-example.com');
            $ci->email->subject('error');
            $ci->email->message('Severity: '.$severity.'  --> '.$message. ' '.$filepath.' '.$line);
            $ci->email->send();
        }

        parent::log_exception($severity, $message, $filepath, $line);
    }

}
```
```


q:
I'm looking for suggestions for a beginner level ASP/XML test.  Essentially I'm trying to hire an extremely junior programmer.  I'm in the process of trying to hire a junior programmer to help maintain a large code base of somewhat repetitive ASP pages.  I'm slowly in the process of making more modular, maintainable code but until that happens I'm trying to get away from having to change "one little thing" too often.

Anyway I'm looking for suggestions of ways to test for ability to handle these tasks.  The applications I've been getting are people with minimal technical experience looking to "break into IT."  I'm all for giving someone a chance, but I also want to test for some base level ability.

[A]
I would ask some basic math questions involving sets, statistics and the like. That kind of question can be somewhat hard, as they don´t depend on a background in IT.
If you want to include some programming questions I would ask something in the line:
"How do you implement integer division without using the division operator"
Another idea is teach them on the spot a made up language, something like
logo
, with four basic commands and some loop directives and ask then to draw squares, circles and what not with it.


q: What does "type-safe" mean?

[A]
Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Some simple examples:
```
```
// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";
```
```
This also applies to method arguments, since you are passing explicit types to them:
```
```
int AddTwoNumbers(int a, int b)
{
    return a + b;
}
```
```
If I tried to call that using:
```
```
int Sum = AddTwoNumbers(5, "5");
```
```
The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer.
In a loosely typed language, such as javascript, I can do the following:
```
```
function AddTwoNumbers(a, b)
{
    return a + b;
}
```
```
if I call it like this:
```
```
Sum = AddTwoNumbers(5, "5");
```
```
Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:
```
```
function AddTwoNumbers(a, b)
{
    return Number(a) + Number(b);
}
```
```
Or, possibly:
```
```
function AddOnlyTwoNumbers(a, b)
{
    if (isNaN(a) || isNaN(b))
        return false;
    return Number(a) + Number(b);
}
```
```
if I call it like this:
```
```
Sum = AddTwoNumbers(5, " dogs");
```
```
Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs".
Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.
While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.
Now, back to C#...
C# supports a language feature called
covariance
, this basically means that you can substitute a base type for a child type and not cause an error, for example:
```
```
public class Foo : Bar
 {
 }
```
```
Here, I created a new class (Foo) that subclasses Bar. I can now create a method:
```
```
void DoSomething(Bar myBar)
```
```
And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.
However, you cannot do the inverse:
```
```
void DoSomething(Foo myFoo)
```
```
In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.
Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)


q:
This drop down list, displaying all the files from a folder, one of which will be selected for use. Is there a way to show which file is selected when you load the page? At the moment it says "select a file" every time.

<select name="image" type="text" class="box" id="image" value="<?=$image;?>">
<option value='empty'>Select a file</option>
<?php

$dirname = "images/";
$images = scandir($dirname);

// This is how you sort an array, see http://php.net/sort
natsort($images);

// There's no need to use a directory handler, just loop through your $images array.
foreach ($images as $file) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'>$file</option>\n"; }
    }
?>
</select>


q:
Via command line, I usually do this:

cp -rRp /path/to/a\_folder/. /path/to/another\_folder

This copies just the contents underneath a_folder to another_folder. In SVN I need to do the same thing, but can't figure it out. I always end up with this:

/path/to/another\_folder/a\_folder

SVN throws up even when I try this:

svn copy file:///path/to/a\_folder/* file:///path/to/another\_folder

It says it does not exist.

EDIT:

This would probably help. The directory structure for my project looks like this:

my_project
  /branches
  /tags
  /trunk
  /vendor
    /1.1

I need to get the contents of 1.1 under vendor into the trunk without it actually copying the 1.1 folder.

[A]
Have you considered using svn merge?
Given a repo like this:
```
```
trunk/a_folder/foo
trunk/a_folder/bar
trunk/new_folder/baz
```
```
use these commands to merge the foo and bar directories:
```
```
cd trunk/new_folder
svn merge -r1:HEAD http://svn/repo/trunk/a_folder .
```
```


q:
Can an abstract class have a constructor?

If so, how can it be used and for what purposes?

[A]
Consider this:
```
```
abstract class Product {
    int value;
    public Product( int val ) {
        value= val;
    }
    abstract public int multiply();
}

class TimesTwo extends Product {
    public int mutiply() {
       return value * 2;
    }
}
```
```
The superclass is abstract and has a constructor.


q: I have been using PLT Scheme, but it has some issues. Does anyone know of a better implementation for working through SICP?

[A]
Use
MIT Scheme
.
It's recommended by the authors of SICP, and is used at MIT for the
6.001: Structure and Interpretation of Computer Programs
course.


q:
I'm looking for one line code examples in various languages for getting a valid MD5 result (as a string, not a bytehash or what have you).  For instance:

PHP:
$token = md5($var1 . $var2);

I found VB especially troublesome to do in one line.

[A]
Python
```
```
token = __import__('md5').new(var1 + var2).hexdigest()
```
```
or, if
```
md5
```
is alrady imported:
```
```
token = md5.new(var1 + var2).hexdigest()
```
```
Thanks to Greg Hewgill


q:
Here is some simple Perl to count the number of times a value occurs in an array. This runs without any warnings.

use warnings;
use strict;

my @data = qw(1 1 2 3 4 5 5 5 9);
my %histogram;
foreach (@data)
{
    $histogram{$_}++;
}

When the loop body is changed to

$histogram{$_} = $histogram{$_} + 1;

Perl warns "Use of uninitialized value in addition".

What is going on under the hood? Why is the value initialized when supplied as an operand to the ++ operator and uninitialized with the + operator?

[A]
The + operator evaluates both the form to the left and the form to the right of it, then returns the sum of both.  The hash call evaluation does not see any special context.
The ++ operator has some special magic built in. Quoting from the perlop manpage, regarding the ++ operator:
"undef" is always treated as numeric, and in particular is changed to 0 before incrementing (so that a post-increment of an undef value will return 0 rather than "undef").
edit
: To elaborate on the difference, ++ changes the value in place, while + just takes its arguments as input.  When + sees an undefined value, typically something has gone wrong, but for ++, your hash manipulation example is very typical -- the user wants to treat undef as 0, instead of having to check and initialize everytime.  So it seems that it makes sense to treat these operators this way.


q:
I'm using a RichTextBox (.NET WinForms 3.5) and would like to override some of the standard ShortCut keys....
For example, I don't want Ctrl+I to make the text italic via the RichText method, but to instead run my own method for processing the text.

Any ideas?

[A]
Set the RichtTextBox.ShortcutsEnabled property to true and then handle the shortcuts yourself, using the KeyUp event. E.G.
```
```
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.textBox1.ShortcutsEnabled = false;
            this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
        }

        void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control == true && e.KeyCode == Keys.X)
                MessageBox.Show("Overriding ctrl+x");
        }
    }
}
```
```


q: I have a Tapestry PropertyModel for gender.  Right now the dropdown just shows Male and Female because those are the only values in my model. I'd like to add a "Choose an Option" option.  Is there a standard way to do this without having to add a fake value to my model?  I'd also like it to be smart enough to know that if the field is required, they can't leave it set to "Choose an Option".

[A]
One solution is to use the LabeledPropertySelectionModel to wrap the real model like:
```
```
new LabeledPropertySelectionModel(new GenderModel(), "Choose an Option")
```
```
The JavaDoc for that class says:
Decorates an underlying IPropertySelectionModel adding an initial property. The label option, and value of the initial property are configurable.


q: Are the two events the same or are there differences that we should take note when coding the keyboard presses?

[A]
The key down event happens as soon as the user presses a key, the key up event happens when they release the key after pressing it.
So if you use the key up event, and the user presses a key and holds it for 5 seconds, nothing will happen until they let go of it.
(Note: I know nothing about .net, I've just used 'key up' and 'key down' events in other libraries.)


q:
I've got an embedded Windows Media player in an HTML page, and when the audio gets to the end, it just starts again from the beginning.

According to the documentation, there's an autorewind parameter/attribute and also a loop.

The problem is, I've set both of those to false (and/or zero) and it doesn't seem to make any difference.

Might this be a bug? My client is WMP 10.00.00.4058. Maybe there's some kind of setting on the server which tells files to loop, is that a crazy idea?

[A]
compare your html code with this:
stolen from
http://www.programmingforums.org/post147977.html
```
```
<object width="320" height="290"
classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95"
id="mediaplayer1">
<param name="Filename" value="kids.mpg">
<param name="AutoStart" value="True">
<param name="ShowControls" value="True">
<param name="ShowStatusBar" value="False">
<param name="ShowDisplay" value="False">
<param name="AutoRewind" value="True">
<embed
type="application/x-mplayer2"
pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/MediaPlayer/"
width="320" height="290" src="/support/dreamweaver/ts/documents/kids.mpg"
filename="kids.mpg" autostart="True"
showcontrols="True" showstatusbar="False"
showdisplay="False" autorewind="True">
</embed>
</object>
```
```


q:
I have a menu with an animation going on, but I want to disable the click while the animation is happening.

<div></div>
<div></div>
<div></div>

$("div").click(function() {
  $(this).animate({height: "200px"}, 2000);
  return false;
});

However, I want to disable all the buttons while the event is happening, AND disable the div that was clicked.

I was thinking of adding a class to the div that's clicked and putting the click only on the divs without that class:

$("div").not("clicked").click(function() {
  $(this).animate({height: "200px"}, 2000).addClass("clicked");
  return false;
});

But this doesn't appear to work (I think it does logically)?

Any help appreciated.

Cheers,

Steve

[A]
```
```
$("div").click(function() {
    if (!$(this).parent().children().is(':animated')) {
        $(this).animate({height: "200px"}, 2000);
    }
    return false;
});
```
```


q: I want to increment a cookie value every time a page is referenced even if the page is loaded from cache. What is the "best" or most concise way to implement this?

[A]
Most of the old cookie handling functions I've seen use simple string manipulations for storing an retrieving values, like
this
example, you can use other libraries, like
cookie-js
, a small
(< 100 lines)
utility for cookie access.
I personally use jQuery on my projects, and I use the
jQuery Cookie Plugin
, it's really simple to use:
```
```
var cookieName = "increment";

if ($.cookie(cookieName) == null){
  $.cookie(cookieName, 1, { expires: 10 });
}else{
  var newValue = Number($.cookie(cookieName)) + 1;
  $.cookie(cookieName, newValue, { expires: 10 });
}
```
```


q: I know that this question has already been asked HERE but sadly none of the answers suggest a javascript standalone shell that has auto completion.  I am reopening this question again, in the hope that some new answers might be found.

[A]
http://www.faqts.com/knowledge_base/view.phtml/aid/1438
lists some JavaScript interpreters.  I am not about to download them to confirm they have (tab?) completion.
[I'm not sure what you mean by auto-completion, since that implies more of an IDE-type approach].
Is this for web-based development/debugging?  If so, I can really recommend the squarefree
JS shell
bookmarklet for Firefox, which was listed in the linked post.  True, it is not standalone, but does have tab completion.


q:
I wanted to try a little design by contract in my latest C# application and wanted to have syntax akin to:

public string Foo()
{
    set {
        Assert.IsNotNull(value);
        Assert.IsTrue(value.Contains("bar"));
        _foo = value;
    }
}

I know I can get static methods like this from a unit test framework, but I wanted to know if something like this was already built-in to the language or if there was already some kind of framework floating around. I can write my own Assert functions, just don't want to reinvent the wheel.

[A]
Aside from using an external library, you have a simple assert in System.Diagnostics:
```
```
using System.Diagnostics

Debug.Assert(value != null);
Debug.Assert(value == true);
```
```
Not very useful, I know.


q:
I have written a few MSBuild custom tasks that work well and are use in our CruiseControl.NET build process.

I am modifying one, and wish to unit test it by calling the Task's Execute() method.

However, if it encounters a line containing

Log.LogMessage("some message here");

it throws an InvalidOperationException:

Task attempted to log before it was initialized. Message was...

Any suggestions? (In the past I have mostly unit-tested Internal static methods on my custom tasks to avoid such problems.)

[A]
If you have implemented the interface ITask you will have to initialise the Log class yourself.
Otherwise you should just inherit from
Task
in Microsoft.Build.Utilities.dll
That implements
ITask
and does a lot of the leg work for you.
Here is the reference page for building a custom task, it explains quite a lot of it.
Building a custom MSBuild task reference
Also worth a look is
How to debug a custom MSBuild task
Other then that could you post the MSBuild XML you are using for calling your custom task.
The code itself would obviously be the most help :-)


q:
I have a web application that's branded according to the user that's currently logged in. I'd like to change the favicon of the page to be the logo of the private label, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?

I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?

[A]
The favicon is declared in the head tag with something like:
```
```
<link rel="shortcut icon" type="image/ico" href="favicon.ico">
```
```
You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag.


q:
I want to convert a BYTE* into  an gdi+ Image object.

How can I do this?

The BYTE* seems a Dib point.

I found Image has a method named Image::FromStream() which may help,
But I can not find any reference about how to convert a BYTE* into a IStream object.
How can I do this?

Thanks in advance!

Actually, it is hard to believe MS provide a IStream interface, but do not provide any c++ MemoryStream class which implements the interface.

[A]
Do you know the format of the image data the
```
BYTE
```
pointer points at? For Image to be able to construct itself from a stream, the data must be in one of the supported standard image formats (GIF, PNG, JPEG etc).
The
IStream
interface looks to be simple enough to implement on your own, if there's no suitable "memory stream" or similiar.


q:
For features comparison of Web Canoo Web Functional Test  and Selenium software, it would be good have an assessment, in terms of integration to Java platform applications, speed, how quick is it to deploy Tests, execute, and analyze results, JavaScript support etc.
I am using Canoo project, it is pretty good.

Tatyana

[A]
So I initially pursued Canoo as a direction for functional tests.
I ended up choosing Selenium as we saw that running selenium in browser
was a better fit for us than Canoo which uses HTTPUnit to run tests.
If you are running tests at build time with selenium you will need to
have the browser
software you wish to use on the build server.  It is not possible for
us to test IE on our build
server for example....So we only run the tests in Firefox.
The killer feature for us was the Selenium IDE.   We have folks using
the selenium IDE
who are not  really developers which is a great help.   The development team
works with them to make sure the tests are running properly.
Canoo has its own advantages that,  A rather biased blog entry is here:
http://mguillem.wordpress.com/2007/10/29/webtest-vs-selenium-webtest-wins-13-5/
Note that in spite of all those things I still prefer Selenium...


q:
When we submit a job, the following steps are executed sequentially.

Then what is the importance of DPRTY?

[A]
```
DPRTY
```
is a very old JCL keyword that harks back to the days of MVS/ESA. It was the dispatch priority which dictated to JES what priority individual steps should be given in a job.
On all versions of z/OS I have access to (all the supported ones), it has no effect.  This is because the WLM (workload manager) goal mode is the only mode used in z/OS 1.3 and beyond. I believe this keyword was deprecated in MVS/ESA V5R1M0 (see INFO APAR II09592).
You can safely ignore it, since JES itself ignores it - all your job steps will be executed in a top-down manner in your JCL job card, with the dispatch priority given by the
```
IEAIPSxx
```
PARMLIB member.


q:
I work on a Fedora Linux box.

I have a whole host of binaries and libraries that I've installed locally under my home directory.

I'd like to set my system up so installing software there functions the same way (for me) as if the root user installed it without a prefix.

I can run binaries installed in ~/local/bin just fine by adding that dir to my PATH variable, but what about linking to libraries in ~/local/lib and ~/local/lib64?

Is there something akin to LD_LIBRARY_PATH variable but to find the library at compile rather than runtime?  I don't want to worry about explicitly passing the path to the compiler via L~/local/lib or through flags in the ./configure script.

[A]
Set the
```
LIBRARY_PATH
```
environment variable to
```
$HOME/local/lib:$HOME/local/lib64
```
. You can also set the environment variables
```
C_INCLUDE_PATH
```
and
```
CPLUS_INCLUDE_PATH
```
to find include files in
```
$HOME/local/include
```
. These are environment variables used by GCC to find libraries and include files, so they probably won't work with other compilers.


q:
Although I grasp the concept of Bitwise Operators, I can't say that I have come across many use cases during the webdevelopment process at which I had to resort to using Bitwise Operators.

Do you use Bitwise Operators?

Why do you use them?

What are some example use cases?

Please remember that this question is specifically intended for use of Bitwise Operators in web languages.

[A]
My main use for bitwise operators could be relevant anywhere - representing a set of flags. For instance, you might have an integer in the database representing a set of security permissions for a user, and in your web app you would have to check those before continuing.
Those tend to only require
```
&
```
and
```
|
```
- e.g.
```
```
if ((permissions & Permission.CreateUser) != 0)
{
    ...
}
```
```
or
```
```
Permission requiredPermission = Permission.CreateUser
                                | Permission.ChangePassword;
```
```
Bit
shifting
operators are less useful in "business" applications in my experience.


q: We have a database that many persons have to have access to. I am looking for a way that will allow us to get notification whenever "alter" occurs on this database, so other parties can be aware of it. Please advise.

[A]
Many persons should NOT have ALTER permission on a production database - very few people should have ALTER permission on a production database.  Actually, you probably shouldn't have many people empowered to make changes in test databases, either.
You can consider whether auditing is the correct solution - in some DBMS, it would be one way of detecting changes, but alerting would be harder (other than by some variation on the theme of 'grepping the audit log').  There may be other ways in Oracle.


q: How is it possible to identify that the browser's close button was clicked?

[A]
Browsers do not have a close event so you can't really tell when the user has closed their browser, there are some potential workarounds in
This thread
If you let us know what you are trying to achieve, there may be an alternative way


q:
how is it advisable to control the cpu utilization during run time ?

poll the cpu load and insert sleeps ?

[A]
I'd recommend OS functionality. There are performance counters and WinAPI functions for this on Windows.
Here is an example using
performance counters
from
BCL Team Blog
:
```
```
foreach (Process proc in Process.GetProcesses()) {
    using (PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", proc.ProcessName)) {
        pcProcess.NextValue();
        System.Threading.Thread.Sleep(1000);
        Console.WriteLine("Process:{0} CPU% {1}", proc.ProcessName, pcProcess.NextValue());
    }
}
```
```
This code makes the same
with WMI
from
CodeProject
:
```
```
public string GetCPU()
{
    decimal PercentProcessorTime=0;
    mObject_CPU.Get();

    ulong  u_newCPU   =
      (ulong)mObject_CPU.Properties["PercentProcessorTime"].Value;
    ulong u_newNano   =
      (ulong)mObject_CPU.Properties["TimeStamp_Sys100NS"].Value;
    decimal d_newCPU  = Convert.ToDecimal(u_newCPU);
    decimal d_newNano = Convert.ToDecimal(u_newNano);
    decimal d_oldCPU  = Convert.ToDecimal(u_oldCPU);
    decimal d_oldNano = Convert.ToDecimal(u_oldNano);

    // Thanks to MSDN for giving me this formula !

    PercentProcessorTime =
      (1 - ((d_newCPU-d_oldCPU)/(d_newNano - d_oldNano)))*100m;

    // Save the values for the next run

    u_oldCPU          = u_newCPU;
    u_oldNano         = u_newNano;

    return PercentProcessorTime.ToString("N",nfi);;
}
```
```
So you can query these OS providers (or others for your OS) and sleep your thread if processor utilization is high.


q: What are all AT commands required for GPRS communication?

[A]
It depends quite a bit on:
The modem
How much of the modem's stack you plan on using
The carrier you're using
If you're using this on a computer and you have a modem configuration file (modem specific), and a carrier configuration or setup then you can intercept the serial commands and find out.
Otherwise, try going to the modem manufacturer's website and find the AT command guide for your modem.
Once you have the modem commands, setting up the connection requires several steps, including initiating the GSM connect, then a GPRS session with a server, and then the PPP session with your carrier's ISP equipement.  You'll need several pieces of information from the carrier, which the AT command set will guide you towards.
Your modem may also have a built in TCP/IP stack, in which case you also have AT commands to initiate the PPP session, and then TCP connections with internet servers.
If you post the modem/carrier/goal/etc you might be able to get more specific help.
-Adam


q:
I launch a child process in Java as follows:

final String[] cmd = {"<childProcessName>"};
Process process = Runtime.getRuntime().exec(cmd);

It now runs in the background. All good and fine.

If my program now crashes (it is still in dev :-)) the child process still seems to hang around. How can I make it automatically end when the parent Java process dies?

If it helps, I'm using Mac OS X 10.5

[A]
I worked it out myself already. I add a shutdown hook, as follows:
```
```
final String[] cmd = {"<childProcessName>"};
final Process process = Runtime.getRuntime().exec(cmd);
Runnable runnable = new Runnable() {
    public void run() {
        process.destroy();
    }
};
Runtime.getRuntime().addShutdownHook(new Thread(runnable));
```
```


q: Does anyone know of a script to colorize C++ code the same as the default MSVC IDE does?

[A]
Is
SyntaxHighlighter
the sort of thing you're looking for? There is also
GeSHi
, which has been updated more recently.


q:
I am rendering a rails partial and I want to alternate the background color when it renders the partial.  I know that is not super clear so here is an example of what I want to do:

Row One grey Background

Row Two yellow background

Row Three grey Background

Row Four yellow background

sorry stackoverflow seams to prevent the background colors from being shown but I think this makes my idea clear

This is the view code that I am using

<table>
  <%= render :partial => 'row' :collection => @rows %>
</table>

the _row.html.erb partial looks like this

<tr bgcolor="#AAAAAA">
  <td><%= row.name %></td>
</tr>

The problem is I do not know how to change the background color for every other row.  Is there a way to do this?

[A]
You could use the Cycle helper. Something like this:
```
```
<tr class="<%= cycle("even", "odd") %>">
  <%= row.name %>

```
```
Or in your case use bgcolor instead, although i would recomend using css classes.
You can cycle through more than two values: cycle(‘first’, ‘second’, ‘third’, ‘and_more’).
There is also: reset_cycle(‘cycle_name’) This makes sure that on each iteration, you will start again with your first value of the cycle list.
Check the rails
documentation
for more examples.


q:
I've written a little web site in my effort to learn vb.net and asp.net, fairly happy with it so rented some space and uploaded it, it was written using asp.net express edition 2008 and sql server express .... I've uploaded it and I've found that it was written in .NET 3.5 and my host only deals with 2.01 ... I've sorted most of that out, and trimmed my web.config file back to basics, but my forms based authentication isn't working

<compilation debug="true" strict="false" explicit="true">
        </compilation>
        <authentication mode="Forms" />
    <customErrors mode="Off"/>
  </system.web>

And it keeps reporting that the sql server does not support remote access ...... not sure what to do next, I don't have to write my own security routines do i ? I have a sql server back end

Thanks for your time

Chris

[A]
If the probllem is that you can not access your SQL Server it may be that you are using a trusted connection to it?
It is not likely to work if the website is on a ISP network and your SQL Server is on another network.
What you then need to do is take a look at your connectionstring to change it so that you pass along the username/password in the connection string. NB: This is not optimal in terms of security but it is a way to access remot SQL Servers that are in antother domain.
/joakim


q:
I need to write the content of a map (key is ID of int, value is of self-defined struct) into a file, and load it from the file later on. Can I do it in MFC with CArchive?

Thank you!

[A]
I don't know much about MFC, but your problem is rather trivially solved using
Boost.Serialization
```
```
struct MapData {
     int m_int;
     std::string m_str;

  private:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        ar & m_int;
        ar & m_str;
    }
};

std::map< int, MapData > theData;

template<class Archive>
void serialize(Archive & ar, std::map< int, MapData > & data, const unsigned int version)
{
    ar & data;
}
```
```
And then later were you want to do the real archiving:
```
```
std::ofstream ofs("filename");
boost::archive::binary_oarchive oa(ofs);
oa << theData;
```
```
That's it.
(disclaimer: code simply typed in this box, not tested at all, typo's were intended ;)


q:
I am creating my application using Django, and am wondering how I can make Django use my CSS file? What settings do I need to do to make Django see the css file?

NB: On a local machine

[A]
What settings do i need to do to make Django see the css file?
None.
Make sure your template includes the CSS file (as standard HTML does) and put the CSS file on the media server.
To clarify: With Django it is highly recommended that you serve all your media (everything that isn't dynamic html) from a different server instance. How you implement that is completely up to you but most people create a subdomain.


q:
I am currently looking at different ORM solutions for a project that is planned for this spring. Entity Framework is one of the products I am looking closer at, but EF 2.0 would be quite a lot more interesting.

Has there been any indications to when version 2.0 of Entity Framework is planned to be released? With .Net 4.0?

[A]
AFAIK it hasn't been officially announced. The best hint I saw is
here
, so it's probably coming with .NET 4.0. I bet they will release a CTP before that.


q:
I'd like to compare two consecutive elements in a std::list while iterating through the list. What is the proper way to access element i+1 while my iterator is at element i?
Thanks
Cobe

[A]
Boost has a utility called
```
next
```
(and its inverse,
```
prior
```
) for just that purpose.
```
```
*itr == *next(itr)
```
```
Edit: But, if we step back to look at the forest, the
real
question is, why custom-write your
```
adjacent_find
```
function? (I recommend Nicola Bonelli's answer to be accepted.) That's part of the STL, and doesn't require using Boost, if your code doesn't use Boost (thanks to the commenters for pointing this out).


q:
I have a batch file (in windows XP, with command extension activated) with the following line:

for /f %%s in ('type version.txt') do set VERSION=%%s

On some computer, it works just fine (as illustrated by this SO question), but on other it kills cmd (the console window just closes)

Why ?

Note: the computers seem to have a similar configuration: XpSP2, the user has administrative right, no 'Command processor" defined in HKEY_CURRENT_USER\Software\Microsoft\Command Processor...

[A]
I got a first empiric answer:
```
```
for /f %%s in (version.txt) do ...
```
```
works just fine, on every computer.
It seems
```
for /f
```
works with a filename, not with any dos command like 'type filename'.
However, it is not true for all my client's computer (on some, the 'type filename' works fine)
If you want 15 (easy ?) points ;-), you can leave an answer to the question:
why 'for /f' sometime does not work with anything else than a file name. And why it just closes the DOS session ?
Edit: 3 years later(!),
barlop
faced a similar situation, detailed in the question "
```
for /f
```
closes cmd prompt immediately?
". His conclusion was:
```
COMSPEC
```
did get listed when doing
```
SET
```
+
ENTER
.
So, I opened the environment variables window, and saw
```
COMSPEC
```
was not listed under user or system variables. I added it to System Variables, started a command prompt, and it seems to work fine.
This
thread on ss64 forum
, mentioned by
Andriy M
in his answer to barlop's question, contains the details.
The shelling out in the "
```
for
```
" loop to complete '
```
dir
```
' (or whatever command you've asked to complete) requires
```
ComSpec
```
to be set in order to reload the
```
cmd
```
window.
```
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\ComSpec=
%SystemRoot%\system32\cmd.exe
```
```


q:
In C I know about the recursive function but I heard about the re-entrant function.
What is that? And whats the difference between them?

[A]
A function is re-entrant if it supports having multiple threads of execution "going through" it at the same time. This might be due to actual multi-threading, and I use this case below, or due to other things as pointed out by other posters. Multi-threading was the first that came to mind, and is perhaps also the easiest to understand, so I focused on that case.
This means that the function cannot use static "global" data, since that data would then be accessed by two (or more) threads in parallel, often breaking horribly. A re-entrant function often has an explicit argument to hold any call-specific state, rather than storing it statically.
```
strtok()
```
is a classic case of a function in the C standard library that is well-known
not
to be re-entrant.
[Edit]: There are a bunch of insights, clarifications and corrections in the comments, so please read those as well! Thanks for the help, folks.


q:
If I declare a temporary auto deleted character buffer using

std::auto_ptr<char> buffer(new char[n]);

then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete.

However the buffer was created using new[], and so strictly speaking the buffer should be deleted using delete[].

What possibility is there that this mismatch might cause a memory leak?

[A]
The behaviour of calling delete on a pointer allocated with new[] is
undefined
. As you assumed, auto_ptr
does call delete
when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes and other odd behaviours are possible.
If you don't need to transfer the ownership of the pointer, Boost's
scoped_array
class might be what you're looking for.


q: I want to share an object between my servlets and my webservice (JAX-WS) by storing it as a servlet context attribute. But how can I retrieve the servlet context from a web service?

[A]
The servlet context is made available by JAX-WS via the message context, which can be retrieved using the web service context. Inserting the following member will cause JAX-WS to inject a reference to the web service context into your web service:
```
```
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

...

@Resource
private WebServiceContext context;
```
```
Then, you can access the servlet context using:
```
```
ServletContext servletContext =
    (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
```
```


q:
How do you calculate the number of <td> elements in a particular <tr>?

I didn't specify id or name to access directly, we have to use the document.getElementsByTagName concept.

[A]
You can use something like the following:
```
```
var rowIndex = 0; // rowindex, in this case the first row of your table
var table = document.getElementById('mytable'); // table to perform search on
var row = table.getElementsByTagName('tr')[rowIndex];
var cells = row.getElementsByTagName('td');
var cellCount = cells.length;
alert(cellCount); // will return the number of cells in the row
```
```


q:
No doubt I'm missing something really simple here but I just can't see the problem with this query which is producing the following error:

SQL query:

INSERT INTO ads(
    ad_id, author, ad_date, category, title,
    description, condition, price, fullname,
    telephone, email, status, photo, photothumb
)
VALUES (
    NULL , 'justal', '1225790938', 'Windsurf Boards',
    'test', 'test', 'Excellent', '12', 'test',
    'test', 'test', '', '', ''
);

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version
for the right syntax to use near ''ad_id', 'author',
'ad_date', 'category', 'title', 'description',
'condition', '' at line 1

Can someone with a fresh pair of eyes spot the problem?

Thanks,
Al.

[A]
Shouldn't you use back ticks instead of single quotes in column names?
```
```
INSERT INTO ads( `ad_id`, `author`, `ad_date`, `category`, `title`, `description`, `condition`, `price`, `fullname`, `telephone`, `email`, `status`, `photo`, `photothumb` )
VALUES (
NULL , 'justal', '1225790938', 'Windsurf Boards', 'test', 'test', 'Excellent', '12', 'test', 'test', 'test', '', '', ''
);
```
```


q: I'm new to Flex, and I'm trying to write a simple application. I have a file with an image and I want to display this image on a Graphics. How do I do this? I tried [Embed]-ding it and adding as a child to the component owning the Graphics', but I'm getting a "Type Coercion failed: cannot convert ... to mx.core.IUIComponent" error.

[A]
Off the top of my head I can think of two things that might help you (depending on what it is exactly that you're trying to achieve):
If you just want to display an image you've embedded, you can add an
Image
component to the stage and set the value of its
```
source
```
as the graphical asset (
```
Class
```
) that you're embedding:
```
```
[Bindable]
[Embed(source="assets/image.png")]
private var MyGfx:Class;

myImage.source = MyGfx;
```
```
If you actually want to
draw
a bitmap onto a
```
Graphics
```
object, you can do this with the
beginBitmapFill()
method:
```
```
[Bindable]
[Embed(source="assets/image.png")]
private var MyGfx:Class;

var myBitmap:BitmapData = new MyGfx().bitmapData;
myGraphics.beginBitmapFill(myBitmap);
myGraphics.endFill();
```
```
You might find the
Flex Quick Starts
articles on Adobe's site useful, especially the
"Embedding Assets"
section.


q:
Currently I have a structure like this:

A
|
+--B
|
+--C

It's mapped with one table per subclass using joined tables. For historic reasons I also use a discriminator, so the current situation is as described in Section 9.1.3 of the Hibernate manual.

Question: How do I extend the mapping for a structure like this:

A
|
+--B
|  |
|  D
|
+--C

Can I <subclass> a <subclass> in the hibernate mapping? What <key>s do I need?

[A]
not tested
but, according to the link you posted if you are using hibernate3
```
```
<hibernate-mapping>
  <class name="A" table="A">
    <id name="id" type="long" column="a_id">
      <generator class="native"/>
    </id>
    <discriminator column="discriminator_col" type="string"/>
    <property name="" type=""/>
    <!-- ... -->
  </class>
  <subclass name="B" extends="A" discriminator-value="B">
    <!-- ... -->
  </subclass>
  <subclass name="D" extends="B" discriminator-value="D">
    <!-- ... -->
  </subclass>
  <subclass name="C" extends="A" discriminator-value="C">
    <!-- ... -->
  </subclass>
</hibernate-mapping>
```
```


q:
It's been a while since I last coded arm assembler and I'm a little rusty on the details. If I call a C function from arm,  I only have to worry about saving r0-r3 and lr, right?

If the C function uses any other registers, is it responsible for saving those on the stack and restoring them? In other words, the compiler would generate code to do this for C functions.

For example if I use r10 in an assembler function, I don't have to push its value on the stack, or to memory, and pop/restore it after a C call, do I?

This is for arm-eabi-gcc 4.3.0.

[A]
It depends on the
ABI
for the platform you are compiling for. On Linux, there are two ARM ABIs; the old one and the new one. AFAIK, the new one (EABI) is in fact ARM's AAPCS. The complete EABI definitions currently live
here on ARM's infocenter
.
From
the AAPCS, §5.1.1
:
r0-r3
are the argument and scratch registers;
r0-r1
are also the result registers
r4-r8
are callee-save registers
r9
might be a callee-save register or not (on some variants of AAPCS it is a special register)
r10-r11
are callee-save registers
r12-r15
are special registers
A callee-save register must be saved by the callee (in opposition to a caller-save register, where the caller saves the register); so,
if
this is the ABI you are using, you do not have to save r10 before calling another function (the other function is responsible for saving it).
Edit:
Which compiler you are using makes no difference; gcc in particular can be configured for several different ABIs, and it can even be changed on the command line. Looking at the prologue/epilogue code it generates is not that useful, since it is tailored for each function
and
the compiler can use other ways of saving a register (for instance, saving it in the middle of a function).
Terminology: "callee-save" is a synonym for "non-volatile" or "call-preserved":
What are callee and caller saved registers?
When making a function call, you can assume that the values in r4-r11 (except maybe r9) are still there after (call-preserved), but not for r0-r3 (call-clobbered / volatile).


q: How can we handel key pressed event in asp.net

[A]
It depends on your situation. In most cases, you will have to handle keypressed event in javascript, and somehow propagate that event to server side.
Consider revising your question to include more background.


q: So far I've been using public void run() {} methods to execute my code in Java. When/why might one want to use main() or init() instead of run()?

[A]
The
```
main()
```
method is the entry point for a Java application.
```
run()
```
is typically used for new threads or tasks.
Where have you been writing a
```
run()
```
method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?


q: I want to detect whether adobe reader is installed using VB6. Also if detected that it's not installed, what would be the best solution?

[A]
There are crude ways (checking for files on Program files directory), but I'd recommend you declare full-registry functions (not getSetting from vb) as in
http://www.windowsdevcenter.com/pub/a/windows/2004/06/15/VB_Registry_Keys.html
and fetch
HKEY_CLASSES_ROOT\.pdf
If that's there, something capable of reading pdfs is there (which is what you want, right?).
As a bonus,
HKEY_CLASSES_ROOT\.pdf\OpenWithList
has a list (wow) of registered applications that open .pdf files... the key names on that list are programs you can invoke from vb using
shell("start "+ OpenAppName)


q:
I have a variable

unsigned char* data = MyFunction();

how to find the length of data?

[A]
Assuming its a
```
string
```
```
```
length = strlen( char* );
```
```
but it doesn't seem to be...so there isn't a way
without
having the function return the length.


q:
I'm trying to do the classic Insert/Update scenario where I need to update existing rows in a database or insert them if they are not there.

I've found a previous question on the subject, but it deals with stored procedures, which I'm not using.  I'd like to just use plain SQL SELECT, INSERT and UPDATE statements, unless there's something better available (the MERGE statement isn't available in SQL Server 2005).

I guess my general idea is this:

If the row is found
  update
else
  insert

As for checking for a row's existence, how expensive is it to do a SELECT statement before calling an UPDATE or an INSERT?  Or is it better to just try an UPDATE, check for the number of rows affected, and then do an INSERT if the rows affected is 0?

[A]
The most efficient way is to do the
```
UPDATE
```
, then do an
```
INSERT
```
if
```
@@rowcount
```
is zero,
as explained in this previous answer
.


q:
We have a couple of web servers using load balancer. Machines are running IIS6 on port 81. Externally, site is accessable using port 80. External name and name of the machine are different.

We're getting

System.ServiceModel.EndpointNotFoundException: The message with To '<url>' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree.

Relevant part of web.config is:

  <endpoint binding="ws2007HttpBinding" bindingConfiguration="MyServiceBinding"
    contract="MyService.IMyService" listenUriMode="Explicit" />

We tried adding listenUri, but that didn't solve our problems.

Any ideas?

[A]
What is the specific load balancer? Using an F5 BIG-IP we got it working fairly easily, but we were using the same port and (relative) uri on the nlb as individual machines (so we can treat an individual machine the same as the farm if we choose). Obviously each machine has a different name, but this setup also allows you to test individual servers by spoofing the host - for example, by editing your HOSTS file to point [your farm name] to [test server IP].
The biggest pain we had was SSL; using TransportWithMessageCredential security, WCF refuses inbound http connections - so we had to set up the nlb to re-encrypt between the nlb and the server node - but not a biggie.
The only other issue we had was with hosting WCF inside IIS, and WCF not being able to correctly identify the intended site (although IIS was fine) over http (but fine over https). To fix this I wrote a custom factory that simply ignored http completely (only listened on https) - which ties in neatly with the TransportWithMessageCredential requirements anyway, so I wasn't bothered by this.
I wonder if you wouldn't get more joy by hosting on a standard port but as a different site (IP/host-header/etc).


q:
I'm currently working with Db2 Enterprise Server V 8.2 with FixPak 10

And I want to retrieve list of all the open active connections with an instance.

In Oracle there is a utility program called "Top Session" which does the similar task. Is there any equivalent in DB2?

[A]
The command you seek is:
```
```
LIST APPLICATIONS
```
```
In the DB2 Command Center there is a tool which list the applications and displays them in a human friendly format as well.


q:
I have a large set of files, some of which contain special characters in the filename (e.g. ä,ö,%, and others). I'd like a script file to iterate over these files and rename them removing the special characters. I don't really mind what it does, but it could replace them with underscores for example e.g.

Störung%20.doc would be renamed to St_rung_20.doc

In order of preference:

A Windiws batch file

A Windows script file to run with cscript (vbs)

A third party piece of software that can be run from the command-line (i.e. no user interaction required)

Another language script file, for which I'd have to install an additional script engine

Background: I'm trying to encrypt these file with GnuPG on Windows but it doesn't seem to handle special characters in filenames with the --encrypt-files option.

[A]
Have you tried setting cmd.exe into another codepage before you feed the file names to gnupg? Issue
```
chcp 65001
```
to set cmd.exe to Unicode beforehand and try again.
If that fails, the following VBScript would do it:
```
```
Option Explicit

Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim invalidChars: Set invalidChars = New RegExp

' put all characters that you want to strip inside the brackets
invalidChars.Pattern =  "[äöüß&%]"
invalidChars.IgnoreCase = True
invalidChars.Global = True

If WScript.Arguments.Unnamed.Count = 0 Then
  WScript.Echo "Please give folder name as argument 1."
  WScript.Quit 1
End If

Recurse fso.GetFolder(WScript.Arguments.Unnamed(0))

Sub Recurse(f)
  Dim item

  For Each item In f.SubFolders
    Recurse item
    Sanitize item
  Next
  For Each item In f.Files
    Sanitize item
  Next
End Sub

Sub Sanitize(folderOrFile)
  Dim newName: newName = invalidChars.Replace(folderOrFile.Name, "_")
  If folderOrFile.Name = newName Then Exit Sub
  WScript.Echo folderOrFile.Name, " -> ", newName
  folderOrFile.Name = newName
End Sub
```
```
call it like this:
```
```
cscript replace.vbs "c:\path\to\my\files"
```
```
You can also drag&drop a folder onto it in Windows Explorer.


q: What is the command to match brackets in Emacs (the equivalent of the % command in Vim)?

[A]
See
```
show-paren-mode
```
as described in
5.27 How do I show which parenthesis matches the one I'm looking at?


q:
I'm by no means a sysadmin so please correct me if I'm wrong.

I want to run aspnet_regiis.exe -s.
This requires the metabase path of my website.

How do I find this metabase path?

[A]
Just run aspnet_regiis.exe -lk to see a list of the registered applications, their metabase paths and the version of the .NET framework installed for this application.
Also, here are a couple of links that you can use to find the metabase path:
http://msdn.microsoft.com/en-us/library/ms524682.aspx
http://www.windowsdevcenter.com/pub/a/windows/2005/10/25/hacking-iis6-with-metabase-explorer.html
http://www.codersource.net/csharp_iis_metabase.html
HTH,
Don


q:
I'm getting the following error when my win32 (c#) app is calling web services.

The request failed with HTTP status 504: Gateway timeout server response timeout.

I understand 'I think' that this is because the upstream request does not get a response in a timely fashion.

But my question is this?  How do I change the app.config settings in my win32 application to allow more time to process its data.  I assume I require these changes to be made on my app settings as the webservices and IIS hosting the ws are setup with extended times.

Look forward to a response and thank you in advance.

[A]
CheckUpDown has
a nice explanation of the 504 error
:
A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.
This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.
This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.


q:
Is there a way to drop a validation that was set in Rails plugin (or included module)?
Let's say I have some model with module included in it:

class User < ActiveRecord::Base
  include SomeModuleWithValidations
  # How to cancel validates_presence_of :something here?
end

module SomeModuleWithValidations
  def self.included(base)
    base.class_eval do
      validates_presence_of :something
    end
  end
end

My only idea so far was to do something like:

validates_presence_of :something, :if => Proc.new{1==2}

which would work, I think, but it isn't particulary pretty.

[A]
You could overload the validates_precense_of in the class. Something like:
```
```
def self.validates_presence_of(*args)
  return if args.first == :foo
 super
end
```
```
Or if you have validates_presence_of :foo you could do:
```
```
def foo
  self[:foo] || ""
end
```
```
However, none of those solutions are very nice. It would most likely be easier to just uncomment it in the module, or redefine it to no-op in just that module.


q: How to insert data into a particular cell in a Excel Work sheet in Asp.net

[A]
Does the worksheet already exist? If it does you can open the worksheet using the open-source component
Koogra
og the commercial component from
Infragistics
(there are others as well) and modify it in code. The alternative is to open the worksheet using excel automation, but that is not recommended in a web project.
By the way.
You are not the first to ask this question.


q:
I was wondering how to make a toolbar in MFC that used 24bit or 256 colour bitmaps rather than the horrible 16 colour ones.

Can anyone point me in the direction of some simple code?

Thanks

[A]
The reason this happens is that the MFC CToolbar class uses an image list internally that is initialised to use 16 colours only. The solution is to create our own image list and tell the toolbar to use that instead. I know this will work for 256-colours, but I haven't tested it with higher bit-depths:
First, load a 256-colour bitmap from a resource:
```
```
HBITMAP hBitmap = (HBITMAP) ::LoadImage(AfxGetInstanceHandle(),
    MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_BITMAP,
    0,0, LR_CREATEDIBSECTION | LR_LOADMAP3DCOLORS);
CBitmap bm;
bm.Attach(hBitmap);
```
```
Next, create a 256-colour image list and add our bitmap to it:
```
```
CImageList m_imagelist.Create(20, 20, ILC_COLOR8, 4, 4);
m_imagelist.Add(&bm, (CBitmap*) NULL);
```
```
Finally, we need to tell the toolbar to use the new image list:
```
```
m_toolbar.GetToolBarCtrl().SetImageList(&m_imagelist);
```
```
It's also possible that the new MFC version in VS2008 may have solved this problem as I know that many of the UI elements have been updated. I haven't actually tried using it yet so I can't be certain.


q:
I'm looking for suggestions on possible IPC mechanisms that I can implement in my self-made OS for an AVR32 board.

My current choice is implementing the massage passing mechanism described in the books written by Tanenbaum.

Is this a good choice? Are there easier way to implement IPC?

Thanks

[A]
My suggestion is to review the message passing primitives that QNX RTOS (www.qnx.com) supports before making any decisions.  I spent several years programming a complex multi-process system in that environment, and it stands out as the best message-based O/S I have ever encountered.
Some specific points that spring to mind (it's been a while now):
Message data copied between process memory space by the kernel so that a bug in one process cannot affect another.
Ability to send and block for a reply.
Ability to drop a message on a queue and move on immediately.
Ability to send a message an block indefinitely until the receiver responds; the receiver may receive and process other messages in the meantime - this is way more valuable than you at first think it will be.


q:
Is there an efficient algorithm for detecting cycles within a directed graph?

I have a directed graph representing a schedule of jobs that need to be executed, a job being a node and a dependency being an edge. I need to detect the error case of a cycle within this graph leading to cyclic dependencies.

[A]
Tarjan's strongly connected components algorithm
has
```
O(|E| + |V|)
```
time complexity.
For other algorithms, see
Strongly connected components
on Wikipedia.


q:
This declaration causes an overflow in VBA:

Const OVERFLOWS As Long = 10 * 60 * 60

whereas setting the value directly is fine:

Const COMPILES_OK As Long = 36000

How do you persuade VBA to treat literal integers as longs?

Thanks

[A]
Add the
```
long
```
suffix
```
&
```
to at least one number:
```
```
Const OVERFLOWS As Long = 10& * 60 * 60
```
```
Note that using the
```
CLNG
```
function to convert the values to
```
long
```
will not work, because VBA does not allow assigning the return value of a function to a constant.


q:
In C# Is there a way of getting a finer granularity with SQL exceptions?

I'm aware that an aweful lot can go wrong but I want to deal with certain cases differently and parsing the Error message doesn't seem to be very elegant.

Also Are the error messages created by the framework or are they db specific?

For example If i have a primary key violation on INSERT is the error message going to always be:

Violation of PRIMARY KEY constraint 'PK_tblProduct'. Cannot insert duplicate key in object 'dbo.tblProduct'.

or is that SQLServer specific.

Update

I looks like I'm after the error number, any idea where I can get the various error numbers?

best I can do with a quick google is:
18456: Logon Failed
18488: Password Expired

[A]
If you are catching a
```
SqlException
```
, you should have access to
```
.Number
```
, which gives you the SQL error number; this is probably your best approach... (you can get the same from the
```
InfoMessage
```
event as well for non-fatal errors).
Of course, this won't distinguish between tables - you could argue that if you need this level of granularity, you should check first (in a serializable isolation level, ideally with UPDLOCK), raising your own error if there is conflicting data.


q:
I need to hide a Windows form from the taskbar but I can't use WS_EX_TOOLWINDOW because I need the system menu and min/max buttons on the form's title bar.

If I switch the form to a tool window at runtime the form skinning is stuffed up. From searching on the Web I see that VB has a ShowInTaskbar property and I'm wondering if this would do what I want, and whether it can be implemented in Delphi 2006. Also this project is a COM server and has no MainForm, etc.

[A]
With thanks to
http://www.scalabium.com/faq/dct0096.htm
.
```
```
procedure TForm1.FormCreate(Sender: TObject);
begin
  ShowWindow(Application.Handle, SW_HIDE);
  SetWindowLong(Application.Handle, GWL_EXSTYLE,
    GetWindowLong(Application.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW);
  ShowWindow(Application.Handle, SW_SHOW);
end;
```
```
I tested it and it worked with Delphi2006. And windows menu and min/max buttons are still visible.


q:
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time-restricted license file.

If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file.

Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".

Is there a good way to handle this problem?

[A]
Python, being a byte-code-compiled interpreted language, is very difficult to lock down.  Even if you use a exe-packager like
py2exe
, the layout of the executable is well-known, and the Python byte-codes are well understood.
Usually in cases like this, you have to make a tradeoff.  How important is it really to protect the code?  Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid?  Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.
If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.


q:
I have a list of tuples like this:

[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]

I want to iterate through this keying by the first item, so, for example, I could print something like this:

a 1 2 3
b 1 2
c 1

How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...


q:
I have a TreeView windows forms control with an ImageList, and I want some of the nodes to display images, but the others to not have images.

I don't want a blank space where the image should be.  I don't want an image that looks like the lines that the TreeView would draw if it didn't have an ImageList.  How do I get it to draw images for some items and not others, without resorting to clumsy hacks like that?

[A]
I tried this once and I don't think it is possible.
If you try to set both
```
ImageKey
```
and
```
ImageIndex
```
to "not set" values the control just defaults
```
ImageIndex
```
to 0. The following code:
```
```
treeView.ImageKey = "Value";
Debug.WriteLine(treeView.ImageIndex);
treeView.ImageKey = null;
Debug.WriteLine(treeView.ImageIndex);
treeView.ImageIndex = -1;
Debug.WriteLine(treeView.ImageIndex);
```
```
Produces output:
```
```
-1
0
0
```
```
This kind of tells you that the control developers wanted to make sure that there was always a default image. That just leaves you with the hack options I'm afraid.


q:
Is it possible to define an implicit conversion of enums in c#?

something that could achieve this?

public enum MyEnum
{
    one = 1, two = 2
}

MyEnum number = MyEnum.one;
long i = number;

If not, why not?

[A]
If you define the base of the enum as a long then you can perform explicit conversion. I don't know if you can use implicit conversions as enums cannot have methods defined on them.
```
```
public enum MyEnum : long
{
    one = 1,
    two = 2,
}

MyEnum number = MyEnum.one;
long i = (long)number;
```
```
Also, be aware with this that an uninitalised enumeration will default to the 0 value, or the first item - so in the situation above it would probably be best to define
```
zero = 0
```
as well.


q:
Do you know a way to organize boolean expressions in a database while allowing infinite nesting of the expressions?

Example:

a = 1 AND (b = 1 OR b = 2)

The expression as a whole shouldn't be stored as varchar to preserve data integrity.

[A]
An expression is a treelike structure. So you need a way to present the tree in a table.
You can for example use the fields:
ID
TypeExpression (and, or etc...)
FirstChildID
SecondChildID
In this case, you have the following types:
AND, Children point to other expression.
OR, Children point to other expression.
Equal, Children point to other expression.
Literal, FirstChild points to an entry in a literal table.
VariableLookup, FirstChild points to an entry in a varable table.
But I think there are better ways to organise expression. I once made a simple expression evaluator that accepts a string and produces a numeric result.


q:
I'm looking for a dummy SQL statement that will work from a C# SQL connection to check for connectivity.

Basically I need to send a request to the database, I don't care what it returns I just want it to be successful if the database is still there and throw an exception if the database isn't.

The scenario I'm testing for is a loss of connectivity to the database, where the SQLConnections State property seems to still be "Open" but there is no connectivity.

[A]
Most SQL databases have a 'table' for this purpose.
In DB2, it's:
```
```
select * from sysibm.sysdummy1
```
```
while Oracle has, from memory,
```
```
select * from dual
```
```
It'll depend on the database at the back end.


q:
is it somehow possible to call a rails function or to access a rails object from within jQuery?
I'd like to do something like:

jQuery(document).ready(function($) {
$('#mydiv').html("<%= @object.name %>");
});

OR

jQuery(document).ready(function($) {
$('#mydiv').html("<%= render :partial => "contacts" %>");
});

At the moment I'm keeping all my jQuery stuff in my application.js, which is included in my layout. Oh yeah....and I'm not using Rails Edge.

Regards,

Sebastian

[A]
You'll have to have a method in the controller that will render what you need, if you want to do that. Another way to do it is to use view blocks, like in the end of your layout view
```
```
<script type="text/javascript">
<%= yield :footerjs %>
</script>
```
```
and in the view do something like:
```
```
<% content_for :footerjs do %>
jQuery(document).ready(function($) {
$('#mydiv').html('<%= escape_javascript(render :partial => "contacts") %>');
});
<% end %>
```
```
You'll need to make sure that the partial you'll be rendering won't have characters that may cause javascript errors (like finishing the quotes before the end of the string, etc). Also, some browsers don't like multi-line strings, so you'll have to fiddle with that as well.


q:
I am debugging some code and have encountered the following SQL query (simplified version):

SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9

I'm getting very strange results from the query and I think its because the first OR is negating the AND operators that are found before it.

This results in getting results back for ads of all types and not just for the type 13.

Each time the query is called there may be a differnt amount of county entities that need to be looked up.

Any help on the correct way to go about this would be appreciated.

[A]
Put parentheses around the "OR"s:
```
```
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
    ads.county_id = 2
    OR ads.county_id = 5
    OR ads.county_id = 7
    OR ads.county_id = 9
)
```
```
Or even better, use IN:
```
```
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
```
```


q:
i have a server - client application that runs on java 1.3; i want to change to java 1.6 step by step, meaning first few clients, than rest of the clients and finally server...
i was wondering could you direct me to some common problems that can come along and what should i look after?

[A]
Off the top of my head, look for the names
```
enum
```
and
```
assert
```
in fields and local variables... These words have become keywords in java 1.4 and 5. The java 6 compiler will mark them as compilation errors if it sees them.
Yuval =8-)


q:
I have use IlMerge to merge all the dlls of my projects in one exe. I use a targets file which is referenced in the "import" of the main csproj.

The ExecCommand in the targets is:

  <Exec Command="&quot;$(ProgramFiles)\Microsoft\Ilmerge\Ilmerge.exe&quot; /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(IlmergeAssemblies->'&quot;%(FullPath)&quot;', ' ')" />

This works.

But then I have a Setup Project, when it builds, it ignores the "import" and it doesn't merge the dlls. How can I use the targets file with the Setup Project?

I have tried writing this same code for Ilmerge in the Post-build event (in properties of the project) of the main project but it gives me error code 1.

[A]
I'd recommend that you check out the ILMerge Task in the
MSBuild Community Tasks
. Documentation for the ILMerge Task is included in the
download
. It will take away the complexity of specifying the exact command line arguments as you are doing now.
On your specific issue, other than the error code 1, are you getting any other error message as a result?  Comment, and I'll edit my response as best I can.


q:
I want to use jQuery with asp.net webfoms.  Do I need to get a special toolkit so the .net controls spit out friendly Control ID's?

Reason being, I don't want to write javascript referencing my html ID's like control_123_asdfcontrol_234.

Has this been addressed in version 3.5?  (I remember reading you have to get some special dll that makes ID's friendly).

[A]
You can use
```
myControlId = "<%= myControl.ClientID %>";
```
to output the (non-friendly) id used to reference it in Javascript.


q: Can anyone recommend an SVN client for use in Excel with VBA (code modules only).  Ideally, I would also like SVN to ignore case when diffing prior to committing changes so as to avoid excessive churn in the repository (VBA has an annoying habit of changing the case of variables all over the project).

[A]
TortoiseSVN
integrates well with the Windows File Explorer and allows for the integration of an external diff tool (like
Beyond Compare
.
Beyond Compare
has a specific plugin for Visual Basic code that appears to ignore case for 'unimportant text', meaning anything
not
in quotes.
I don't think this will solve the SVN churn issue, however.  I don't believe that SVN uses the external diff program to decide whether a file has changed prior to committing, and I don't know of any way to override this behavior.


q:
Which method is preferred?

Session.Remove("foo");

Session["foo"] = null;

Is there a difference?

[A]
I would go with Remove but can not honestly say if there is a difference.  At a guess there may still be an empty key kept for that null value but not sure.  Remove would give me little doubt and if that's what you want to do it
reads better
in code as well.


q:
I have been running Apache HTTPD in 64bit mode by stripping out the 32bit architecture from the binary (along with the ppc parts). I did this to make it more compatible for python and mysql.

However I have another machine that needs it to be run in 32bit mode (it has all four original architectures still in it). Is it possible to make sure that it is running in 32 bit mode and that anything compiled against it uses said mode.

Are my options limited to stripping it, or are there start up optiosn that I do not know about.

[A]
You can use the
```
arch(1)
```
command to change the which architecture is used. This will try Intel 32-bit first and then PPC 32-bit:
```
```
% arch -i386 -ppc /usr/sbin/httpd
```
```


q:
I am an advocate of ORM-solutions and from time to time I am giving a workshop about Hibernate.

When talking about framework-generated SQL, people usually start talking about how they need to be able to use "hints", and this is supposedly not possible with ORM frameworks.

Usually something like: "We tried Hibernate. It looked promising in the beginning, but when we let it loose on our very very complex production database it broke down because we were not able to apply hints!".

But when asked for a concrete example, the memory of those people is suddenly not so clear any more ...

I usually feel intimidated, because the whole "hints"-topic sounds like voodoo to me...
So can anybody enlighten me? What is meant by SQL-hints or DB-Hints?

The only thing I know, that is somehow "hint-like" is SELECT ... FOR UPDATE. But this is supported by the Hibernate-API...

[A]
A SQL statement, especially a complex one, can actually be executed by the DB engine in any number of different ways (which table in the join to read first, which index to use based on many different parameters, etc).
An experienced dba can use hints to
encourage
the DB engine to choose a particular method when it generates its execution plan. You would only normally need to do this after extensive testing and analysis of the specific queries (because the DB engines are usually pretty darn good at figuring out the optimum execution plan).
Some MSSQL-specific discussion and syntax here:
http://msdn.microsoft.com/en-us/library/ms181714.aspx
Edit: some additional examples at
http://geeks.netindonesia.net/blogs/kasim.wirama/archive/2007/12/31/sql-server-2005-query-hints.aspx


q:
I got tired of trying Delphi every year hoping that I will find a stable version to upgrade from my good old Delphi 7.

Should I bother to try Delphi 2009? Or it is as unstable as the previous versions and should I wait until Delphi 2010?

Thanks

[A]
This is kind of an open-ended question, but the short answer is that Delphi 2009 is stable, fast, and a leap forward from older versions (especially 2005).
The IDE has evolved a bit since Delphi 7 and has more Visual Studio and Eclipse-like features. It also has some updated controls that make building the more 'modern' Windows applications easier, like the Ribbon you see in Office. I find the response time in drag and drop operations to be a lot quicker than previous versions, and overall the reaction time in IDE operations just seem a lot snappier.
So far the IDE hasn't crashed on me at all, but I'm admittedly not a heavy day-to-day user. I mainly use Delphi 2009 for a side project I work on in my own time.


q:
I need to modify a (xml-)file from Apache Ant. "loadfile" task allows to load the file's content in a property. But how to store the property's value back to a file after its (property) modification?

Of course I could write custom task to perform this operation but I would like to know if there's some existing implementation.

[A]
You can use the
echo
task.
```
```
<echo file="${fileName}" message="${xmlProperty}"/>
```
```
The
echoxml
task might be of interest to you as well.


q: Is it possible to obtain the maximum column length for a VARCHAR, CHAR etc?

[A]
In pure T-SQL you can use this query:
```
```
select max_length from sys.columns as c inner join sys.objects o on c.object_id = o.object_id where o.name = 'myTable' and c.name = 'myColumn'
```
```
For linq-to-sql you need it rewrite into linq.


q:
I am trying to do something like this:

while @nrOfAuthlevels >= @myAuthLevel
begin
    set @myAuthLevel = @myAuthLevel + 1
    SELECT      Role.name, Role.authorityLevel
    FROM        [dbo].[Role]
    ORDER BY Role.authorityLevel
end

The result of this stored procedure shall be a table with all Role.authorityLevel below my own. But this generates several tables.

[A]
Create a temp table before the loop and don't select data, but insert data to this temp table:
```
```
create table #tmp (
 Name type,
 authorityLevel type
)

while @nrOfAuthlevels >= @myAuthLevel
begin
        set @myAuthLevel = @myAuthLevel + 1
        insert into #tmp values(
            SELECT          Role.name, Role.authorityLevel
            FROM        [dbo].[Role]
            where ...
        )
end
```
```


q:
The following doesn't work, but something like this is what I'm looking for.

select *
from Products
where Description like (@SearchedDescription + %)

SSRS uses the @ operator in-front of a parameter to simulate an 'in', and I'm not finding a way to match up a string to a list of strings.

[A]
Have you tried to do:
```
select * from Products where Description like (@SearchedDescription + '%')
```
(Putting single quotes around the % sign?)


q:
I've been developing a Smalltalk variant for just the fun of it and I wonder what would be a fellow stackoverflowers choice when it comes to targeting a back-end. These were my current considerations:

.NET, JVM: These two VM's are mainly for statically typed languages and I assume it would be quite hard to target such a dynamic language like smalltalk.

Python (as source code): Seems to be the simplest way. Also it would be better if I could emit Python bytecode but it's not well documented as other VM's AFAIK (Need to dig Python's source code for details!).

Self made interpreter: Out of the question as it's no fun :-)

LLVM, NekoVM, Parrot are other options I'm checking out. What would be your take on this?

[A]
I would choose the JVM, but mainly because I'm familiar with it.
Objective reasons for
JVM
are: main platforms are supported, many libraries and good performance (within the choices you have given it may have the best performance).
.Net works best on Windows. If you choose it, you should test on
Mono
to be more platform-neutral.
Python
seems a good choice as well. But I think for the JVM more libraries are available.
Parrot
is in my opinion too fresh, it needs some time to mature. But an interesting alternative for the future.
The other choices are new to me, I will take a look at them.


q:
What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap?

What is the behavior of SQL Server 2005 when it happen?

[A]
You will get an overflow error when the maximum value is reached
. If you use the bigint datatype with a maximum value of
```
9,223,372,036,854,775,807
```
this will most likely never be the case.
The error message you will get, will look like this:
```
```
Msg 220, Level 16, State 2, Line 10
Arithmetic overflow error for data type tinyint, value = 256.
```
```
(Source)
As far as I know MS SQL provides no functionality to fill the identity gaps, so you will either have to do this by yourself or change the datatype of the identity column.
In addition to this you can set the start value to the smallest negative number, to get an even bigger range of values to use.
Here is a good blog post about this topic
.


q:
I am looking to clean up some of the HTML generated by a .NET 2.0 TreeView controller.  Switching to another version/model is not an available option.

My first crack yielded an extended TreeView, with an overridden Render that Regex'd out the text I didn't need and output to the page.

The problem was when I tried to collapse/expanded nodes of the tree, my postback event wasn't fired.  My assumption was that I didn't need to do any more overriding as the parent TreeView controller would handle the postback events.

What am I missing?

[A]
Use the ASP.NET CSS Control Adapters:
http://www.asp.net/CSSAdapters/TreeView.aspx
Without adapters both use HTML <table> tags. Control adapters can be used so that nested <ul> tags are rendered instead. A combination of CSS and JavaScript can then be used to show and hide portions of the hierarchy of the tree or menu.
  When the CSS and JavaScript are removed the adapted HTML degrades into simple nested unordered lists that are easily interpreted by screen readers, etc. You can see this for yourself by setting the theme to None in the Theme Chooser on the left.


q:
Basically, what I want to is be able to explore an ActiveX DLL.
I normally fire up VB 6, add the DLL to the "References" of the project, and use Object Explorer.

However, in this particular machine I can't install VB / VS.

I'm sure there's a tool out there that does this. Does anyone know of one?

Thanks

[A]
Is it possible to download the component from that machine and examine it locally in Visual Studio? (That'd be my first suggestion.) (And BTW, the .NET versions of Visual Studio also feature a VB6-like Object Explorer which works nicely for this.)
Alternatively, and it's not free, but you might try
ActiveXplorer
. (I haven't tried this, but it looks promising.)
(Discontinued)


q:
I have a image button. I wanted to add a text "Search" on it. I am not able to add it because the "imagebutton" property in VS 2008 does not have text control in it. Can anyone tell me how to add text to a image button??

  <asp:ImageButton ID="Searchbutton" runat="server" AlternateText="Search"
        CssClass="bluebutton"
        ImageUrl="../Graphics/bluebutton.gif" Width="110px"
        onclick="Searchbutton_Click"/>

[A]
```
```
<button runat="server"
  style="background-image:url('/Content/Img/stackoverflow-logo-250.png')" >
  your text here
and some more

 and some more ....
  </button>
```
```


q: I know SQL Injection is one... what are the others...

[A]
Buffer overflows
are the classic if you're writing C, as they often allow the execution of arbitrary code by an attacker.


q:
I have a page where my combo box has hundreds of elements which makes it very hard to pick the one item I want. Is there a good Javascript replacement that would do better than

<select id="field-component" name="field_component">
                  <option selected="selected">1</option><option>2</option>...
</select>

Is there something with "Intellisense"-like auto-complete?

[A]
You have
dhtmlCombo
, using ajax to retrieve data when you are filling the input field.
dhtmlxCombo is a cross-browser JavaScript combobox with autocomplete feature.
It extends basic selectbox functionality to meet the requirements of the most up-to-date web applications.
dhtmlxCombo can be converted from existing HTML SELECT or populated with JavaScript. Supporting AJAX, it can also
get list values from the server datasource dynamically
.


q:
I've got menu items that look like this

<ul>
  <li>Item1<span class="context-trigger"></span></li>
  <li>Item2<span class="context-trigger"></span></li>
  <li>Item3<span class="context-trigger"></span></li>
</ul>

with CSS that turns the above into a horizontal menu, and JS that turns the [spans] into buttons that bring up contextual menus. Vaguely like this:

Item1^  Item2^  Item3^

If the menu gets too wide for the browser width, it wraps, which is what I want. The problem is that sometimes it's putting in line-breaks before the [spans]. I only want it to break between [li]s. Any ideas?

[A]
try using
```
```
white-space: nowrap;
```
```
in the css definition of your context-trigger class.
Edit: I think patmortech is correct though, putting nowrap on the span does not work, because there is no "white space" content. It might also be that sticking the style on the LI element does not work either, because the browser might breakup the parts because the span is a nested element in li. You might reconsider your code, drop the SPAN element and use css on the LI elements.


q: Sooo...it's only sort of programming related, but I figure it's election day, right? Is there a single good reason why they aren't, not necessarily open source in that anyone can contribute, but open source in that anyone could inspect the source?

[A]
the problem is opensourcing the software would be a no-op.
They don't have any decent cryptography, and there has been demonstrated and relatively easy ways to contravene them simply by hot-swapping a ROM chip in the voting booth, or Having a device that augments the records in the record cartridge.
Youtube: Sequoia Part 1 Those with access can hack with programmed ROM chip
Youtube: Sequoia Part 2 Logic and Accuracy Test vs Election Mode with vote-stealing firmware
Youtube: Sequoia Part 5 Manipulating Sequoia Voting Results Cartridges from Precincts
@Mnementh
The bad cryptography and the possibility to swap the ROM-chip has nothing
  to do with open-sourcing the code? So there is the point?
There are only 3 logical reasons for opensourcing this code:
To put under scrutiny how the votes are counted to be certain its doing it right.
For somebody to be able to modify that code for their own needs.
To put the software into public domain so public committers can improve on it.
Points 1 and 3 are blown out of the water in terms of usefulness and "proving your vote counts" because you have no assurance that the code you are seeing/improving runs on these devices.
So that leaves only condition 2 being useful, and as you are not going to
own
your own voting machine, and have no need for one for anything more than nefarious causes
or
to simply prove their vulnerability.
For the majority of cases all it would mean is that there would be more information publically available on
how
to contravene these machines, so you would no longer need physical access to one in order to attempt reverse engineer their software and develop compromised ROM chips for use in said devices, grossly reducing the barrier to entry for the compromise of the voting system.
Granted, even in a non-opensource state this information can still leak, and you just have a false sense of security because you assume "theres no leak, I am safe", but on the contrary, if you open source it people will assume "hundreds of people have looked at the source code, I am safe" which is an equally bad false sense of security.
People are looking for a silver bullet safe way of voting, and sadly, there is none. Not without growing a race of purified peoples whom are brought up by non-committal monks in isolationist shrines to have a breed of people simply for the task of witnessing and counting votes accurately, whom are trained to be amoral and can't be bribed to switch the vote.
( It would sort of be like the 'dark angel' series except with voting agents instead of assassins, and we all know how that show works out, one of them would go rouge, we'd trust them, and they'd screw us all )


q:
In our project we have a large number (hundreds) of FLA files created by the artists in CS3, from which we compile SWFs to use in our Flex/AS3 application.

As part of a streamlined build/deploy system, it would be really handy to be able to automate publishing all these FLAs, and ideally deploying the SWFs too. I found some ways to do the batch publishing from CS3 using JSFL, but was surprised to discover CS3 doesn't apparently have any command-line functionality for this?

This is on a Linux system for what it's worth, I don't have experience with JSFL to know if you can run scripts from the command line somehow?

note: I should have said "Linux is preferred"... I don't use Linux but our server/build PC is Linux... I didn't realise CS3 was not compatible so I guess we can do this part on Windows.

[A]
How you are running Flash CS3 on Linux ?
you cannot run JSFL from command line but compiling a FLA file should be possible
some old example
http://www.mikechambers.com/blog/2003/11/01/flashcommand-flash-2004-command-line-compiler/
newer stuff from Mike Chambers
http://code.google.com/p/flashcommand/
for OSX
so it's definitely possible seems only through semi automated IDE publishing,
too bad Flex compiler is not capable of such a thing, together with ANT tasks it's a killer...
with FDT editor things are pretty cool and automated


q:
I have read about a technique involving writing to disk a rendered dynamic page and using that when it exists using mod_rewrite. I was thinking about cleaning out the cached version every X minutes using a cron job.

I was wondering if this was a viable option or if there were better alternatives that I am not aware of.

(Note that I'm on a shared machine and mod_cache is not an option.)

[A]
You could use your cron job to run the scripts and redirect the output to a file.
If you had a php file index.php, all you would have to do is run
```
php index.php > (location of static file)
```
You just have to make sure that your script runs the same on command line as it does served by apache.


q:
I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a ° character - Unicode U+00B0 (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a UnicodeDecodeError.

My first attempt to fix the issue simply caught that error (because the app apparently does send some bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the wxTextCtrl can display?

[A]
I can't say mych about wxPython itself, but I am guessing that it is trying to convert the text to Unicode before displaying it, If you have a string like
```
'123\xB0'
```
and try to convert it to Unicode with teh default encoding (ASCII) then it will throw
```
UnicodeDecodeError
```
. You can probably fix this by replacing
```
```
s = message.get_string()
```
```
with
```
```
s = message.get_string().decode('ISO8859-1')
```
```
(where I am assuming a function
```
get_string()
```
that gets the message as a string). The difference here is that by handong the conversion to Unicode yourself you get to specify the encoding.


q: How can I use CRTP in C++ to avoid the overhead of virtual member functions?

[A]
I had to look up
CRTP
. Having done that, however, I found some stuff about
Static Polymorphism
. I suspect that this is the answer to your question.
It turns out that
ATL
uses this pattern quite extensively.


q: How do I create a toolbar for Excel using an XLA document?

[A]
Not sure if this is what you're looking for but I thought this might help you out:
Excel -- Macro Toolbar
Since you don't specify a version of Excel I'm not sure if this will work for you or not but perhaps it will furnish you with a good starting point.


q: In the iPhone is there a way I can use JavaScript to close the browser and return to the home screen? After the last page a wizard I am calling out to another iPhone app (ex: maps) and I do NOT what the user to come back to the browser screen when they are done. My backup plan is to have a "Complete" page but that is not the best experience for the client.

[A]
Knowing Apple, this may not be possible with JavaScript. Have you tried anything yet? If not, try one of these guys out:
```
```
javascript:self.close();
window.close();
```
```
EDIT: I found this thru google, this may bypass the confirmation box, but I don't think it works with the modern browsers anymore:
```
```
window.opener='x';
window.close();
```
```
I just checked, doesn't look like it will work (IE7 box pops up, FF3 does nothing, Opera 9.61 doesnt have a prompt box at all).


q: When I get a reference to a System.Diagnostics.Process, how can I know if a process is currently running?

[A]
This is a way to do it with the name:
```
```
Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
  MessageBox.Show("nothing");
else
  MessageBox.Show("run");
```
```
You can loop all process to get the ID for later manipulation:
```
```
Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
   Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
}
```
```


q:
In oracle, I want to create a delete sproc that returns an integer based on the outcome of the deletion.

this is what i have so far.

create or replace
PROCEDURE Testing
(
iKey IN VARCHAR2
)
 AS

BEGIN
  delete from MyTable WHERE
  TheKey = iKey;

END Testing;

i've tried putting a RETURNS INTEGER in but the sproc won't compile.

[A]
A procedure does not return a value.  A function returns a value, but you shouldn't be doing DML in a function (otherwise you cannot do things like reference the function in a SQL statement, you confuse permission grants since normally DBAs want to be able to grant read-only users access to all the functions so that users are doing computations consistently, etc.).
You can add an OUT parameter to the procedure to return the status.  If "success" means that one or more rows were updated, you can use SQL%ROWCOUNT to get a count of the number of rows modified by the prior SQL statement and use that to populate the return parameter, i.e.
```
```
CREATE OR REPLACE PROCEDURE test_proc (
  p_iKey    IN VARCHAR2,
  p_retVal OUT INTEGER
)
AS
BEGIN
  DELETE FROM myTable
   WHERE theKey = p_iKey;

  IF( SQL%ROWCOUNT >= 1 )
  THEN
    p_retVal := 1;
  ELSE
    p_retVal := 0;
  END IF;
END test_proc;
```
```
Of course, from a general code clarity standpoint, I'm dubious about OUT parameters that appear to be trying to return a status code.  You are generally much better served by assuming success and throwing exceptions in the event of an error.