Question: I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?

Answer:
From the
Python Enterprise Application Kit community
:
"Eggs are to Pythons as Jars are to Java..."
Python eggs are a way of bundling
  additional information with a Python
  project, that allows the project's
  dependencies to be checked and
  satisfied at runtime, as well as
  allowing projects to provide plugins
  for other projects. There are several
  binary formats that embody eggs, but
  the most common is '.egg' zipfile
  format, because it's a convenient one
  for distributing projects. All of the
  formats support including
  package-specific data, project-wide
  metadata, C extensions, and Python
  code.
The primary benefits of Python Eggs
  are:
They enable tools like the "Easy Install" Python package manager
.egg files are a "zero installation" format for a Python
  package; no build or install step is
  required, just put them on PYTHONPATH
  or sys.path and use them (may require
  the runtime installed if C extensions
  or data files are used)
They can include package metadata, such as the other eggs they depend on
They allow "namespace packages" (packages that just contain other
  packages) to be split into separate
  distributions (e.g. zope.
, twisted.
,
  peak.* packages can be distributed as
  separate eggs, unlike normal packages
  which must always be placed under the
  same parent directory. This allows
  what are now huge monolithic packages
  to be distributed as separate
  components.)
They allow applications or libraries to specify the needed
  version of a library, so that you can
  e.g. require("Twisted-Internet>=2.0")
  before doing an import
  twisted.internet.
They're a great format for distributing extensions or plugins to
  extensible applications and frameworks
  (such as Trac, which uses eggs for
  plugins as of 0.9b1), because the egg
  runtime provides simple APIs to locate
  eggs and find their advertised entry
  points (similar to Eclipse's
  "extension point" concept).
There are also other benefits that may come from having a standardized
  format, similar to the benefits of
  Java's "jar" format.
-Adam


Question: How do I set, clear, and toggle a bit?

Answer:
Setting a bit
Use the bitwise OR operator (
```
|
```
) to set a bit.
```
```
number |= 1UL << n;
```
```
That will set the
```
n
```
th bit of
```
number
```
.
```
n
```
should be zero, if you want to set the
```
1
```
st bit and so on upto
```
n-1
```
, if you want to set the
```
n
```
th bit.
Use
```
1ULL
```
if
```
number
```
is wider than
```
unsigned long
```
; promotion of
```
1UL << n
```
doesn't happen until after evaluating
```
1UL << n
```
where it's undefined behaviour to shift by more than the width of a
```
long
```
.  The same applies to all the rest of the examples.
Clearing a bit
Use the bitwise AND operator (
```
&
```
) to clear a bit.
```
```
number &= ~(1UL << n);
```
```
That will clear the
```
n
```
th bit of
```
number
```
. You must invert the bit string with the bitwise NOT operator (
```
~
```
), then AND it.
Toggling a bit
The XOR operator (
```
^
```
) can be used to toggle a bit.
```
```
number ^= 1UL << n;
```
```
That will toggle the
```
n
```
th bit of
```
number
```
.
Checking a bit
You didn't ask for this, but I might as well add it.
To check a bit, shift the number n to the right, then bitwise AND it:
```
```
bit = (number >> n) & 1U;
```
```
That will put the value of the
```
n
```
th bit of
```
number
```
into the variable
```
bit
```
.
Changing the
n
th bit to
x
Setting the
```
n
```
th bit to either
```
1
```
or
```
0
```
can be achieved with the following on a 2's complement C++ implementation:
```
```
number ^= (-x ^ number) & (1UL << n);
```
```
Bit
```
n
```
will be set if
```
x
```
is
```
1
```
, and cleared if
```
x
```
is
```
0
```
.  If
```
x
```
has some other value, you get garbage.
```
x = !!x
```
will booleanize it to 0 or 1.
To make this independent of 2's complement negation behaviour (where
```
-1
```
has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.
```
```
number ^= (-(unsigned long)x ^ number) & (1UL << n);
```
```
or
```
```
unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);
```
```
It's generally a good idea to use unsigned types for portable bit manipulation.
or
```
```
number = (number & ~(1UL << n)) | (x << n);
```
```
```
(number & ~(1UL << n))
```
will clear the
```
n
```
th bit and
```
(x << n)
```
will set the
```
n
```
th bit to
```
x
```
.
It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like
the community wiki answer further down
) or some sort of encapsulation.


Question:
Is there a risk of legal trouble if you include  GPL or LGPL licensed icons in a closed source software?

Would it force it to become open source just to include the icon?

Does it matter if the icon is compiled as a resource?

Are the creative common licensed icons safe to use if you follow the attribution rules specified by the license?

Answer:
For GPL, yes. Any GPL Code/Content that's compiled into your Application or the Package will make it GPL. (Edit: What could be safe is if the Icon is a separate file and is used. That could be a grey area, as you are not using GPL Code to access it. But any attempt to embed it will force your program to GPL, it's one of the most restrictive licenses out there)
LGPL is fine: Any modification to LGPL Content has to be released under LGPL, but using the Code/Content is safe.
Addition: Like LGPL, CreativeCommons usually only affects the Content you're using. So if you're using a CC Icon and modify it, you will have to give out the modified item under CreativeCommons, but your Application is not affected. Just mind the "Non-Commercial" Clause if it exists.


Question:
What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP

<?php
  $class_name = 'SomeClassName';
  $object = new $class_name;
?>

This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement.

Problems that come immediately to mind are

<s>You lose the ability to pass arguments into a constructor</s> (LIES. Thanks Jeremy)

Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?)

What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?

Answer:
It looks you can still pass arguments to the constructor, here's my test code:
```
```
<?php

class Test {
    function __construct($x) {
        echo $x;
    }
}

$class = 'Test';
$object = new $class('test'); // echoes "test"

?>
```
```
That is what you meant, right?
So the only other problem you mentioned and that I can think of is the security of it, but it shouldn't be too difficult to make it secure, and it's obviously a lot more secure than using eval().


Question: Can someone explain the mechanics of a jump table and why is would be needed in embedded systems?

Answer:
From Wikipedia
:
In computer programming, a branch
  table (sometimes known as a jump
  table) is a term used to describe an
  efficient method of transferring
  program control (branching) to another
  part of a program (or a different
  program that may have been dynamically
  loaded) using a table of branch
  instructions. The branch table
  construction is commonly used when
  programming in assembly language but
  may also be generated by a compiler.
A branch table consists of a serial
  list of unconditional branch
  instructions that is branched into
  using an offset created by multiplying
  a sequential index by the instruction
  length (the number of bytes in memory
  occupied by each branch instruction).
  It makes use of the fact that machine
  code instructions for branching have a
  fixed length and can be executed
  extremely efficiently by most
  hardware, and is most useful when
  dealing with raw data values that may
  be easily converted to sequential
  index values. Given such data, a
  branch table can be extremely
  efficient; it usually consists of the
  following steps: optionally validating
  the input data to ensure it is
  acceptable; transforming the data into
  an offset into the branch table, this
  usually involves multiplying or
  shifting it to take into account the
  instruction length; and branching to
  an address made up of the base of the
  table and the generated offset: this
  often involves an addition of the
  offset onto the program counter
  register.


Question: I'm working on a project with a friend that will utilize Hbase to store it's data.  Are there any good query examples?  I seem to be writing a ton of Java code to iterate through lists of RowResult's when, in SQL land, I could write a simple query.  Am I missing something?  Or is Hbase missing something?

Answer:
I think you, like many of us, are making the mistake of treating bigtable and HBase like just another RDBMS when it's actually a column-oriented storage model meant for efficiently storing and retrieving large sets of sparse data. This means storing, ideally, many-to-one relationships within a single row, for example. Your queries should return very few rows but contain (potentially) many datapoints.
Perhaps if you told us more about what you were trying to store, we could help you design your schema to match the bigtable/HBase way of doing things.
For a good rundown of what HBase does differently than a "traditional" RDBMS, check out this awesome article:
Matching Impedance: When to use HBase
by Bryan Duxbury.


Question:
I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation.

Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point?

const int FIZZ = 6;
for(int x = 0; x < MAXCOUNT; x++)
{
    if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems
}

vs:

The way I am currently doing it:

const int FIZZ = 6;
int fizzcount = 1;
for(int x = 1; x < MAXCOUNT; x++)
{
    if(fizzcount >= FIZZ)
    {
        print("Fizz\n");
        fizzcount = 0;
    }
}

Answer:
In the embedded world, the "modulus" operations you need to do are often the ones that break down nicely into bit operations that you can do with
```
&
```
,
```
|
```
and sometimes
```
>>
```
.


Question: I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List<string>.

Answer:
Iterate through and for each element make the probability of selection = (number needed)/(number left)
So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you'll have all of them before that.
This technique is called
selection sampling
, a special case of
Reservoir Sampling
. It's similar in performance to shuffling the input, but of course allows the sample to be generated without modifying the original data.


Question:
I'm using an Ubuntu 8.04 (x86_64) machine to connect to my employer's Cisco VPN. (The client didn't compile out of the box, but I found patches to update the client to compile on kernels released in the last two years.) This all works great, until my DHCP client decides to renew its lease and updates /etc/resolv.conf, replacing the VPN-specific name servers with my general network servers.

Is there a good way to prevent my DHCP client from updating /etc/resolv.conf while my VPN is active?

Answer:
If you are running without NetworkManager handling the connections, use the resolvconf package to act as an intermediary to programs tweaking /etc/resolv.conf:
```
sudo apt-get install resolvconf
```
If you are using NetworkManager it will handle this for you, so get rid of the resolvconf package:
```
sudo apt-get remove resolvconf
```
I found out about this when setting up vpnc on Ubuntu last week. A search for
```
vpn resolv.conf
```
on ubuntuforums.org has 250 results, many of which are very related!


Question: How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?

Answer:
First make a string with all your possible characters:
```
```
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
```
```
You could also use
range()
to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the
```
$characters
```
string to get a random character, and append it to your string:
```
```
$string = '';
 $max = strlen($characters) - 1;
 for ($i = 0; $i < $random_string_length; $i++) {
      $string .= $characters[mt_rand(0, $max)];
 }
```
```
```
$random_string_length
```
is the length of the random string.


Question: Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?

Answer:
it looks like it's answered in this post:
http://forums.mysql.com/read.php?52,198596,198717#msg-198717
With mysqli PHP API:
Assume sproc myproc( IN i int, OUT j int ):
```
```
$mysqli = new mysqli(  "HOST", "USR", "PWD", "DBNAME" );
$ivalue=1;
$res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" );
if( $res ) {
  $results = 0;
  do {
    if ($result = $mysqli->store_result()) {
      printf( "Result #%u:
", ++$results );
      while( $row = $result->fetch_row() ) {
        foreach( $row as $cell ) echo $cell, " ";
      }
      $result->close();
      if( $mysqli->more_results() ) echo "
";
    }
  } while( $mysqli->next_result() );
}
$mysqli->close();
```
```


Question: Can somebody suggest a good free tool for analyzing .Net memory dumps other than Adplus/windbg/sos ?

Answer:
You can
load sos
and your memory dump into Visual Studio to at least insulate you from the 'interesting' ui that WinDbg presents.


Question:
I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page.

I know how to screen-scrape normal pages, but not those behind a secure site.

Can this be done with the .NET WebClient class?

How would I automatically login?

How would I keep logged in for the other pages?

Answer:
You can easily simulate user input. You can submit form on the web page from you program by sending post\get request to a website.
Typical login form looks like:
```
```
<form name="loginForm" method="post" Action="target_page.html">
   <input type="Text" name="Username">
   <input type="Password" name="Password">
</form>
```
```
You can send a post request to the website providing values for Username & Password fields. What happens after you send your request is largely depends on a website, usually you will be redirected to some page. You authorization info will be stored in the sessions\cookie. So if you scrape client can maintain web session\understands cookies you will be able to access protected pages.
It's not clear from your question what language\framework you're going to use. For example there is a framework for screen scraping (including login functionality) written in perl -
WWW::Mechanize
Note, that you can face some problems if site you're trying to login to uses java scripts or some kind of CAPTCHA.


Question:
I want to put songs on a web page and have a little play button, like you can see on Last.fm or Pandora. There can be multiple songs listed on the site, and if you start playing a different song with one already playing, it will pause the first track and begin playing the one you just clicked on. I think they use Flash for this, and I could probably implement it in a few hours, but is there already code I could use for this? Maybe just a flash swf file that you stick hidden on a web page with a basic Javascript API that I can use to stream mp3 files?

Also, what about WMA or AAC files? Is there a universal solution that will play these 3 file types?

http://musicplayer.sourceforge.net/

Answer:
There are
many
flash mp3 players that you can use that do this. Usually, you just have to edit a text file to point at the mp3s you want to have available.
Here is the first one that showed up on a google search for
```
flash mp3 player
```
:
http://www.flashmp3player.org/demo.html


Question:
I was looking out for a free plugin for developing/debugging JSP pages in eclipse.

Any suggestions?

Answer:
The
Eclipse Web Tools Platform Project
includes a JSP debugger. I have only ever needed to use it with Tomcat so I cannot say how well it works with other servlet containers.


Question:
In podcast #15, Jeff mentioned he twittered about how to run a regular event in the background as if it was a normal function - unfortunately I can't seem to find that through twitter. Now I need to do a similar thing and are going to throw the question to the masses.

My current plan is when the first user (probably me) enters the site it starts a background thread that waits until the alloted time (hourly on the hour) and then kicks off the event blocking the others (I am a Windows programmer by trade so I think in terms of events and WaitOnMultipleObjects) until it completes.

How did Jeff do it in Asp.Net and is his method applicable to the Java web-app world?

Answer:
Jeff's mechanism was to create some sort of cached object which ASP.Net would automatically recreate at some sort of interval - It seemed to be an ASP.Net specific solution, so probably won't help you (or me) much in Java world.
See
https://stackoverflow.fogbugz.com/default.asp?W13117
Atwood: Well, I originally asked on Twitter, because I just wanted something light weight.  I really didn't want to like write a windows service.  I felt like that was out of band code. Plus the code that actually does the work is a web page in fact, because to me that is a logical unit of work on a website is a web page.  So, it really is like we are calling back into the web site, it's just like another request in the website, so I viewed it as something that should stay inline, and the little approach that we came up that was recommended to me on Twitter was to essentially to add something to the application cache with a fixed expiration, then you have a call back so when that expires it calls a certain function which does the work then you add it back in to the cache with the same expiration.  So, it's a little bit, maybe "ghetto" is the right word.
My approach has always been to have to OS (i.e. Cron or the Windows task scheduler) load a specific URL at some interval, and then setup a page at that URL to check it's queue, and perform whatever tasks were required, but I'd be interested to hear if there's a better way.
From the transcript, it looks like FogBugz uses the windows service loading a URL approach also.
Spolsky: So we have this special page called heartbeat.asp.  And that page, whenever you hit it, and anybody can hit it at anytime: doesn't hurt.  But when that page runs it checks a queue of waiting tasks to see if there's anything that needs to be done.  And if there's anything that needs to be done, it does one thing and then looks in that queue again and if there's anything else to be done it returns a plus, and the entire web page that it returns is just a single character with a plus in it.  And if there's nothing else to be done, the queue is now empty, it returns a minus.  So, anybody can call this and hit it as many times, you can load up heartbeat.asp in your web browser you hit Ctrl-R Ctrl-R Ctrl-R Ctrl-R until you start getting minuses instead of pluses.  And when you've done that FogBugz will have completed all of its maintenance work that it needs to do.  So that's the first part, and the second part is a very, very simple Windows service which runs, and its whole job is to call heartbeat.asp and if it gets a plus, call it again soon, and if it gets a minus call it again, but not for a while.  So basically there's this Windows service that's always running, that has a very, very, very simple task of just hitting a URL, and looking to see if it gets a plus or a minus and, and then scheduling when it runs again based on whether it got a plus or a minus.  And obviously you can do any kind of variation you want on this theme, like for example, uh you could actually, instead of returning just a plus or minus you could say "Okay call me back in 60 seconds" or "Call me back right away I have more work to be done."  And that's how it works... so that maintenance service it just runs, you know, it's like, you know, a half page of code that runs that maintenance service, and it never has to change, and it doesn't have any of the logic in there, it just contains the tickling that causes these web pages to get called with a certain guaranteed frequency.  And inside that web page at heartbeat.asp there's code that maintains a queue of tasks that need to be done and looks at how much time has elapsed and does, you know, late-night maintenance and every seven days delete all the older messages that have been marked as spam and all kinds of just maintenance background tasks.  And uh, that's how that does that.


Question: Now that I know C++ I want to get into desktop application that have a UI instead of Command Prompt stuff, where should I start?, and what are some good online resources?

Answer:
I use
Codegear
's C++ Builder. It's C++ language support is not 100% but it more than makes up for it by having a great two-way RAD IDE and the ability to use a huge library of existing Delphi components.


Question:
I would like to know how people implement the following data structures in C# without using the base class library implementations:-

Linked List

Hash Table

Binary Search Tree

Red-Black Tree

B-Tree

Binomial Heap

Fibonacci Heap

and any other fundamental data structures people can think of!

I am curious as I want to improve my understanding of these data structures and it'd be nice to see C# versions rather than the typical C examples out there on the internet!

Answer:
There's a series of
MSDN articles
on this subject. However, I haven't really read the text myself. I believe that the collections framework by .NET has a broken interface and cannot be extended very well.
There's also
C5
, a libray that I am investigating right now.
For the reason mentioned above, I've had the project to implement my own collections library for .NET but I've stopped this project after the first benchmark revealed that even a straightforward, non-thread-safe generic
```
Vector
```
implementation is slower than the native
```
List<T>
```
. Since I've taken care not to produce any inefficient IL code, this means that .NET is simply not suited (yet) for writing on-par replacements for intrinsic data structures, and that the .NET framework has to use some behind-the-scenes knowledge to optimize the builtin collection classes.


Question:
I'm planning on creating a social networking + MP3 lecture downloading / browsing / commenting / discovery website using Ruby on Rails. Partially for fun and also as a means to learn some Ruby on Rails. I'm looking for a social networking framework that I can use as a basis for my site. I don't want to re-invent the wheel.

Searching the web I found three such frameworks. Which of these three would you recommend using and why?

http://portal.insoshi.com/

http://www.communityengine.org/

http://lovdbyless.com/

Answer:
I've not worked with these but am aware of this comparison:
"Unlike Insoshi and Lovd By Less, which
  are full social networking Rails
  applications, Community Engine is a
  plugin that can add social networking
  features to existing Rails
  applications"
from
http://www.rubyinside.com/community-engine-rails-plugin-that-adds-social-networking-to-your-app-901.html


Question:
I'm interested in writing eclipse plugins where do I start?

What resources have helped you?

I'm looking for:

  1. Tutorials

  2. Sites devoted to plugin development

  3. Books

Answer:
You can find a good step by step detailed tutorial here:
http://www.eclipsepluginsite.com/
Other tutorials:
http://www.ibm.com/developerworks/opensource/library/os-eclipse-snippet/index.html?ca=dgr-lnxw16RichEclipse
http://www.vogella.de/articles/EclipsePlugIn/article.html
A decent book, that I've used is "
Eclipse: Building Commercial-Quality Plug-Ins
".


Question: My gcc build toolchain produces a .map file. How do I display the memory map graphically?

Answer:
Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the
```
sections
```
and
```
symbols
```
lists).
You can control the script by modifying these lines:
```
```
with open('t.map') as f:
colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']
total_height = 32.0
```
```
map2html.py
```
```
from __future__ import with_statement
import re

class Section:
    def __init__(self, address, size, segment, section):
        self.address = address
        self.size = size
        self.segment = segment
        self.section = section
    def __str__(self):
        return self.section+""

class Symbol:
    def __init__(self, address, size, file, name):
        self.address = address
        self.size = size
        self.file = file
        self.name = name
    def __str__(self):
        return self.name

#===============================
# Load the Sections and Symbols
#
sections = []
symbols = []

with open('t.map') as f:
    in_sections = True
    for line in f:
        m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line)
        if m:
            if in_sections:
                sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5)))
            else:
                symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5)))
        else:
            if len(sections) > 0:
                in_sections = False

#===============================
# Gererate the HTML File
#

colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']
total_height = 32.0

segments = set()
for s in sections: segments.add(s.segment)
segment_colors = dict()
i = 0
for s in segments:
    segment_colors[s] = colors[i % len(colors)]
    i += 1

total_size = 0
for s in symbols:
    total_size += s.size

sections.sort(lambda a,b: a.address - b.address)
symbols.sort(lambda a,b: a.address - b.address)

def section_from_address(addr):
    for s in sections:
        if addr >= s.address and addr < (s.address + s.size):
            return s
    return None

print ""
print "  "
print ""
print "
"
for sym in symbols:
    section = section_from_address(sym.address)
    height = (total_height/total_size) * sym.size
    font_size = 1.0 if height > 1.0 else height
    print "
" % \
        (segment_colors[section.segment], height, height, font_size)
    print "%s" % (sym.name, sym.name)
    print "
"
print "
"
print ""
```
```
And here's a bad rendering of the HTML it outputs:


Question:
Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set?

For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap?

Answer:
About your first question...
List, Map and Set serve different purposes. I suggest reading about the Java Collections Framework at
http://java.sun.com/docs/books/tutorial/collections/interfaces/index.html
.
To be a bit more concrete:
use List if you need an array-like data structure and you need to iterate over the elements
use Map if you need something like a dictionary
use a Set if you only need to decide if something belongs to the set or not.
About your second question...
The main difference between Vector and ArrayList is that the former is synchronized, the latter is not synchronized. You can read more about synchronization in
Java Concurrency in Practice
.
The difference between Hashtable (note that the T is not a capital letter) and HashMap is similiar, the former is synchronized, the latter is not synchronized.
I would say that there are no rule of thumb for preferring one implementation or another, it really depends on your needs.


Question:
How do you schedule a Windows Mobile application to periodically start up to perform some background processing.  For example, assume I'm writing an email client and want to check for email every hour, regardless of whether my app is running at the time.

The app is a native C/C++ app on Windows Mobile 5.0 or later.

Answer:
the function you need is:
```
CeRunAppAtTime( appname, time )
```
that isn't the exact signature, there is also
```
CeRunAppAtEvent
```
, they should both be in the MSDN docs (but linking is useless the way MSDN urls always change)
The normal way to use these (and
```
RunAppAtTime
```
in the managed world via
```
OpenNETCF.Win32.Notify
```
) is that for periodic execution, every time your app runs, it will rescedule itself for its next run-time.
If your app is running, the new instance should bring up the already running process. If it isn't running, then it is just like starting up normally - from mmory it passes some argument to the process so it can tell it is being scheduled and not started some other way.


Question:
How would you design a database to support the following tagging features:

items can have a large number of tags

searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search)

creating/writing items may be slower to enable quick lookup/reading

Ideally, the lookup of all items that are tagged with (at least) a set of n given tags should be done using a single SQL statement. Since the number of tags to search for as well as the number of tags on any item are unknown and may be high, using JOINs is impractical.

Any ideas?

Thanks for all the answers so far.

If I'm not mistaken, however, the given answers show how to do an OR-search on tags. (Select all items that have one or more of n tags). I am looking for an efficient AND-search. (Select all items that have ALL n tags - and possibly more.)

Answer:
I don't see a problem with a straightforward solution: Table for items, table for tags, crosstable for "tagging"
Indices on cross table should be enough optimisation. Selecting appropriate items would be
```
```
SELECT * FROM items WHERE id IN
    (SELECT DISTINCT item_id FROM item_tag WHERE
    tag_id = tag1 OR tag_id = tag2 OR ...)
```
```
AND tagging would be
```
```
SELECT * FROM items WHERE
    EXISTS (SELECT 1 FROM item_tag WHERE id = item_id AND tag_id = tag1)
    AND EXISTS (SELECT 1 FROM item_tag WHERE id = item_id AND tag_id = tag2)
    AND ...
```
```
which is admittedly, not so efficient for large number of comparing tags. If you are to maintain tag count in memory, you could make query to start with tags that are not often, so AND sequence would be evaluated quicker. Depending on expected number of tags to be matched against and expectancy of matching any single of them this could be OK solution, if you are to match 20 tags, and expect that some random item will match 15 of them, then this would still be heavy on a database.


Question:
Does anyone know of a similar product to Citrix Server that'll run on the Mac OS?

Essentially, I'm looking to allow multiple remote users to log in to the same OSX Server at the same time (with full visual desktop, not SSH).

Answer:
OS X's Quartz window server has no remoting abilities, unlike
its predecessor
. X11
does
, but 'native' OS X applications don't use that; of the few Mac apps typically run in X11 (such as GIMP or CrossOver), none are specific to the Mac, so you might as well run them on a different OS.
That said, if all you want is to visually remote-control a session, it is possible to use VNC or a derivative, such as Apple Remote Desktop. Since 10.4, this allows for multiple simultaneous sessions,
as implemented with Vine Server
. Remote Desktop also has other abilities such as remotely installing and updating software.
(Unlike Citrix and X11, VNC does
not
send drawing commands over the network; it instead transmits a compressed image representation pixel-per-pixel.)
You should specify your exact needs.
You will not get a Citrix-like experience where you can run single Mac apps in their own remote session.
You will, however, get remote graphical control, and that
may
be more than enough for you.


Question:
I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this ?

The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though.

Answer:
Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does.
So to do this, just wrap your single object in an IEnumerable.
Even this would work:
```
```
DataBindObject.DataSource = new List<YourObject>().Add(YourObjectInstance);
```
```


Question:
I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target;

<target name="publish-artifacts-to-build">
    <msbuild project="my-solution.sln" target="Publish">
      <property name="Configuration" value="debug" />
      <property name="OutDir" value="builds\" />
      <arg line="/m:2 /tv:3.5" />
    </msbuild>
</target>

and all I get is this as a response;

[msbuild]          Skipping unpublishable project.

Is it possible to publish web applications via the command line in this way?

Answer:
The "Publish" target you are trying to invoke is for "OneClick" deployment, not for publishing a website...  This is why you are getting the seemingly bizarre message.
You would want to use the AspNetCompiler task, rather than the MSBuild task.  See
http://msdn2.microsoft.com/en-us/library/ms164291.aspx
for more info on this task.  Your "PublishDir" would correspond to the TargetPath property of the task.
Source


Question: I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input.

Answer:
You can use the WindowsIdentity.Impersonate method to
achieve this. This method allows code to impersonate a different Windows
user. Here is a link for more information on this method with a good sample:
http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx
Complete example:
```
```
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES:
// This sample can be run only on Windows XP.  The default Windows 2000 security policy
// prevents this sample from executing properly, and changing the policy to allow
// proper execution presents a security risk.
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked,
// it will be visible to anyone viewing the screen.
// The sample is intended to be executed in a .NET Framework 1.1 environment.  To execute
// this code in a 1.0 environment you will need to use a duplicate token in the call to the
// WindowsIdentity constructor. See KB article Q319615 for more information.

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Windows.Forms;

[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]
[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class ImpersonationDemo
{
    [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
    private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
        int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments);

    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

    // Test harness.
    // If you incorporate this code into a DLL, be sure to demand FullTrust.
    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public static void Main(string[] args)
    {
        IntPtr tokenHandle = new IntPtr(0);
        IntPtr dupeTokenHandle = new IntPtr(0);
        try
        {
            string userName, domainName;
            // Get the user token for the specified user, domain, and password using the
            // unmanaged LogonUser method.
            // The local machine name can be used for the domain name to impersonate a user on this machine.
            Console.Write("Enter the name of the domain on which to log on: ");
            domainName = Console.ReadLine();

            Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
            userName = Console.ReadLine();

            Console.Write("Enter the password for {0}: ", userName);

            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            tokenHandle = IntPtr.Zero;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);

            Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                throw new System.ComponentModel.Win32Exception(ret);
            }

            Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes" : "No"));
            Console.WriteLine("Value of Windows NT token: " + tokenHandle);

            // Check the identity.
            Console.WriteLine("Before impersonation: "
                + WindowsIdentity.GetCurrent().Name);
            // Use the token handle returned by LogonUser.
            WindowsIdentity newId = new WindowsIdentity(tokenHandle);
            WindowsImpersonationContext impersonatedUser = newId.Impersonate();

            // Check the identity.
            Console.WriteLine("After impersonation: "
                + WindowsIdentity.GetCurrent().Name);

            // Stop impersonating the user.
            impersonatedUser.Undo();

            // Check the identity.
            Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);

            // Free the tokens.
            if (tokenHandle != IntPtr.Zero)
                CloseHandle(tokenHandle);

        }
        catch(Exception ex)
        {
            Console.WriteLine("Exception occurred. " + ex.Message);
        }

    }
}
```
```


Question:
I would like to implement something similar to a c# delegate method in PHP.  A quick word to explain what I'm trying to do overall:  I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised.

I am having some problems coming up with a mechanism to do callbacks in PHP.  I have come up with a method that works for now but I am unhappy with it.  Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be.  This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of?

Answer:
How do you feel about using the
Observer
pattern? If not, you can implement a true callback this way:
```
```
// This function uses a callback function.
function doIt($callback)
{
    $data = "this is my data";
    $callback($data);
}

// This is a sample callback function for doIt().
function myCallback($data)
{
    print 'Data is: ' .  $data .  "\n";
}

// Call doIt() and pass our sample callback function's name.
doIt('myCallback');
```
```
Displays: Data is: this is my data


Question:
Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship.

However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class?

Answer:
Programming to an interface means respecting the "contract" created by using that interface. And so if your
```
IPoweredByMotor
```
interface has a
```
start()
```
method, future classes that implement the interface, be they
```
MotorizedWheelChair
```
,
```
Automobile
```
, or
```
SmoothieMaker
```
, in implementing the methods of that interface, add flexibility to your system, because one piece of code can start the motor of many different types of things, because all that one piece of code needs to know is that they respond to
```
start()
```
. It doesn't matter
how
they start, just that they
must start
.


Question:
How do I set a property of a user control in ListView's LayoutTemplate from the code-behind?

<asp:ListView ...>
<LayoutTemplate>
<myprefix:MyControl id="myControl" ... />
</LayoutTemplate>
...
</asp:ListView>

I want to do this:

myControl.SomeProperty = somevalue;

Please notice that my control is not in ItemTemplate, it is in LayoutTemplate, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item.

Answer:
Use the
FindControl
method on each ListViewItem.
```
```
var control = (MyControl)Item.FindControl("yourControlId");
```
```


Question:
What is the maximum size for a MySQL table? Is it 2 million at 50GB? 5 million at 80GB?

At the higher end of the size scale, do I need to think about compressing the data? Or perhaps splitting the table if it grew too big?

Answer:
About your first question, the effective maximum size for the
database
is usually determined by operating system, specifically the file size MySQL Server will be able to create, not by MySQL Server itself. Those limits play a big role in
table
size limits. And MyISAM works differently from InnoDB. So any tables will be dependent on those limits.
If you use InnoDB you will have more options on manipulating table sizes, resizing the tablespace is an option in this case, so if you plan to resize it, this is the way to go. Give a look at
The table is full
error page.
I am not sure the real record quantity of each table given all necessary information (OS, Table type, Columns, data type and size of each and etc...) And I am not sure if this info is easy to calculate, but I've seen simple table with around 1bi records in a couple cases and MySQL didn't gave up.


Question:
I want to write a command that specifies "the word under the cursor" in VIM.  For instance, let's say I have the cursor on a word and I make it appear twice.  For instance, if the word is "abc" and I want "abcabc" then I could type:

:s/\(abc\)/\1\1/

But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef":

:s/\(def\)/\1\1/

How can I write the command in the commandline so that it does this?

:s/\(*whatever is under the commandline*\)/\1\1

Answer:
```
<cword>
```
is the word under the cursor (:help
```
<cword>
```
).
Sorry, I should have been more complete in this answer.
You can nmap a command to it, or this series of keystrokes for the lazy will work:
```
```
b #go to beginning of current word
yw #yank to register
```
```
Then, when you are typing in your pattern you can hit
```
<control-r>0<enter>
```
which will paste in your command the contents of the 0-th register.
You can also make a command for this like:
```
```
:nmap <leader>w :s/\(<c-r>=expand("<cword>")<cr>\)/
```
```
Which will map hitting '\' and 'w' at the same time to replace your command line with
```
```
:s/\(<currentword>\)/
```
```


Question: I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code?

Answer:
It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a
```
catch
```
block is simply not true in C++ because RAII is an established idiom. Resource handling in C++
is
done by resource acquisition and garbage collection is done by implicit destructor calls.
On the other hand, explicit
```
catch
```
blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly.
RAII (including
```
ScopeGuard
```
s) isn't an obscure technique in C++ but firmly established best-practice.


Question:
Anybody know of a way to copy a file from path A to path B and suppressing the Windows file system cache?

Typical use is copying a large file from a USB drive, or server to your local machine. Windows seems to swap everything out if the file is really big, e.g. 2GiB.
Prefer example in C#, but I'm guessing this would be a Win32 call of some sort if possible.

Answer:
I am not sure if this helps, but take a look at
Increased Performance Using FILE_FLAG_SEQUENTIAL_SCAN
.
SUMMARY
There is a flag for CreateFile()
  called FILE_FLAG_SEQUENTIAL_SCAN which
  will direct the Cache Manager to
  access the file sequentially.
Anyone reading potentially large files
  with sequential access can specify
  this flag for increased performance.
  This flag is useful if you are reading
  files that are "mostly" sequential,
  but you occasionally skip over small
  ranges of bytes.


Question:
Say I have a Textbox nested within a TabControl.

When the form loads, I would like to focus on that Textbox (by default the focus is set to the TabControl).

Simply calling textbox1.focus() in the Load event of the form does not appear to work.

I have been able to focus it by doing the following:

 private void frmMainLoad(object sender, EventArgs e)
 {
     foreach (TabPage tab in this.tabControl1.TabPages)
     {
         this.tabControl1.SelectedTab = tab;
     }
 }

My question is:

Is there a more elegant way to do this?

Answer:
The following is the solution:
```
```
private void frmMainLoad(object sender, EventArgs e)
{
    ActiveControl = textBox1;
}
```
```
The better question would however be why... I'm not entirely sure what the answer to that one is.
Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.


Question:
Our design has one jvm that is a jboss/webapp (read/write) that is used to maintain the data via hibernate (using jpa) to the db. The model has 10-15 persistent classes with 3-5 levels of depth in the relationships.

We then have a separate jvm that is the server using this data.  As it is running continuously we just have one long db session (read only).

There is currently no intra-jvm cache involved - so we manually signal one jvm from the other.

Now when the webapp changes some data, it signals the server to reload the changed data.  What we have found is that we need to tell hibernate to purge the data and then reload it.  Just doing a fetch/merge with the db does not do the job - mainly in respect of the objects several layers down the hierarchy.

Any thoughts on whether there is anything fundamentally wrong with this design or if anyone is doing this and has had better luck with working with hibernate on the reloads.

Thanks,
Chris

Answer:
Chris, I'm a little confused about your circumstances. If I understand correctly, you have a both a web app (read/write) a standalone application (read-only?) using Hibernate to access a shared database. The changes you make with the web app aren't visible to the standalone app. Is that right?
If so, have you considered using a different second-level cache implementation? I'm wondering if you might be able to use a clustered cache that is shared by both the web application and the standalone application. I believe that SwarmCache, which is integrated with Hibernate, will allow this, but I haven't tried it myself.
In general, though, you should know that the contents of a given cache will never be aware of activity by another application (that's why I suggest having both apps share a cache). Good luck!


Question:
What's the "right" way to do the following as a boolean expression?

for i in `ls $1/resources`; do
    if [ $i != "database.db" ]
    then
        if [ $i != "tiles" ]
        then
            if [ $i != "map.pdf" ]
            then
                if [ $i != "map.png" ]
                then
                    svn export -q $1/resources/$i ../MyProject/Resources/$i
...

Answer:
```
```
for i in `ls $1/resources`; do
    if [ $i != "database.db" ] && [ $i != "tiles" ] && [ $i != "map.pdf" ] && [ $i != "map.png" ]; then
        svn export -q $1/resources/$i ../MyProject/Resources/$i
```
```


Question: I have to choose an online WYSIWYG editor. I'm pending between TinyMCE and Xinha. My application is developed in Asp.Net 3.5. Could you help me with with some pros and cons?

Answer:
I've never used Xinha, but I can vouch for TinyMCE. It's fast, scales well, and is infinitely customizable. I particularly like the dynamic loading of functionality, which means you only take the performance hit for the stuff you use.
It also includes language-specific
compressors
to further increase performance (C# is supported, along with PHP, Java and ColdFusion) by GZipping components.


Question:
Here is a scenario: Let's say I have site with two controllers responsible for displaying different type of content - Pages and Articles. I need to embed Partial View into my masterpage that will list pages and articles filtered with some criteria, and be displayed on each page. I cannot set Model on my masterpage (am I right?). How do I solve this task using Html.RenderPartial?

[EDIT]
Yes, I'd probably create separate partial views for listing articles and pages, but still, there is a barrier that I cannot and shouldn't set model on masterpage. I need somehow to say "here are the pages" as an argument to my renderpartial, and also for articles. Entire concept of renderpartial with data from database in masterpages is a bit blurry to me.

Answer:
The ViewData Model property should only be used for the content that you're viewing/editing on the main section of the UI.
Other parts of the view may need some data present in ViewData, so just add those to the dictionary.
I'd just pass data from the dictionary like this:  ViewData["articles"] to the partial.  (or ViewData.Get() from MvcContrib).
You might also look at the recently implemented SubController pattern implemented in
MvcContrib
.


Question:
Some e-Marketing tools claim to choose which web page to display based on where you were before. That is, if you've been browsing truck sites and then go to Ford.com, your first page would be of the Ford Explorer.

I know you can get the immediate preceding page with HTTP_REFERRER, but how do you know where they were 6 sites ago?

Answer:
Javascript this should get you started:
http://www.dicabrio.com/javascript/steal-history.php
There are more nefarius means to:
http://ha.ckers.org/blog/20070228/steal-browser-history-without-javascript/
Edit:I wanted to add that although this works it is a sleazy marketing teqnique and an invasion of privacy.


Question:
Ajax, Flex and Silverlight are a few ways to make more interactive web applications.  What kinds of factors would you consider when deciding which to use for a new web application?

Does any one of them offer better cross-platform compatibility, performance, developer tools or community support?

Answer:
The web runtimes like Flex and Silverlight all offer enticing things, but come with two big costs:
They run only within a rectangle on the page, and don't interact with normal web widgets
They are only available to people who have that plug-in installed
Even the nearly-ubiquitous Flash isn't installed on every web browser, so by choosing to use a plug-in runtime you're excluding part of your audience.
In contrast, JavaScript (or Ajax) is available on pretty much every browser, and interacts better with normal web pages, but is a more primitive and restricting language. Using it for complex animations can be tricky, and you'll need to test your applications in more versions on more platforms to make sure it works.
Cross-platform compatibility isn't the issue it used to be, so the issue is this:
Will you gain more in the features of a plug-in library than you'll lose in the audience you exclude?
My own answer has so far always been JavaScript/Ajax, but I'd re-evaluate that in any new project.


Question:
I am a bit confused about socket programming in C.

You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article <s>Network programming under Unix systems</s> to be very informative.

What confuses me is the timing of data arriving on the socket.

How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself?

My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that?

Answer: When you do a read on the socket, you tell it how many maximum bytes to read, but if it doesn't have that many, it gives you however many it's got.  It's up to you to design the protocol so you know whether you've got a partial packet or not.  For instance, in the past when sending variable length binary data, I would put an int at the beginning that said how many bytes to expect.  I'd do a read requesting a number of bytes greater than the largest possible packet in my protocol, and then I'd compare the first int against however many bytes I'd received, and either process it or try more reads until I'd gotten the full packet, depending.


Question: What is the JavaScript to scroll to the top when a button/link/etc. is clicked?

Answer:
```
```
Top
```
```


Question:
Does anybody know of a way to list up the "loaded plugins" in Vim?
I know I should be keeping track of this kind of stuff myself but
it would always be nice to be able to check the current status.

Answer:
Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following
VIM Tips
site:
```
```
" where was an option set
:scriptnames            : list all plugins, _vimrcs loaded (super)
:verbose set history?   : reveals value of history and where set
:function               : list functions
:func SearchCompl       : List particular function
```
```


Question:
I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this:

procedure TForm1.CalculateGP(..)
const
   Price : money = 0;
begin
   ...
   Price := 1.0;
   ...
end;

So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, why? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time?

Answer:
You need to turn assignable typed constants on.

Project -> Options -> Compiler -> Assignable typed Constants
Also you can add
```
{$J+}
```
or
```
{$WRITEABLECONST ON}
```
to the pas file, which is probably better, since it'll work even if you move the file to another project.


Question:
I'm building an application in C# using WPF. How can I bind to some keys?

Also, how can I bind to the Windows key?

Answer:
I'm not sure about WPF, but this may help. I used the solution described in
RegisterHotKey (user32)
(modified to my needs of course) for a C# Windows Forms application to assign a CTRL-KEY combination within Windows to bring up a C# form, and it worked beautifully (even on Windows Vista). I hope it helps and good luck!


Question: How are callbacks written in PHP?

Answer:
Implementation of a callback is done like so
```
```
// This function uses a callback function.
function doIt($callback)
{
    $data = "this is my data";
    $callback($data);
}

// This is a sample callback function for doIt().
function myCallback($data)
{
    print 'Data is: ' .  $data .  "\n";
}

// Call doIt() and pass our sample callback function's name.
doIt('myCallback');
```
```
Displays: Data is: this is my data


Question: We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading.  Is there a way to get WatiN to click a link on the page before the page finishes rendering completely?

Answer:
Here's the code we found to work:
```
```
IE browser = new IE(....);
browser.Button("SlowPageLoadingButton").ClickNoWait();
Link continueLink = browser.Link(Find.ByText("linktext"));
continueLink.WaitUntilExists();
continueLink.Click();
```
```


Question:
I am wondering if anyone has any experience using a JQuery plugin that converts a html

<select>
  <option> Blah </option>
</select>

combo box into something (probably a div) where selecting an item acts the same as clicking a link.

I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.

Your advice, experience and recommendations are appreciated.

Answer:
This bit of javascript in the 'select':
```
```
onchange="if(this.options[this.selectedIndex].value!=''){this.form.submit()}"
```
```
It's not ideal (because form submissions in ASP.NET MVC which I'm using don't appear to use the routing engine for URLs) but it does its job.


Question: Why prefer composition over inheritance?  What trade-offs are there for each approach?  When should you choose inheritance over composition?

Answer:
Think of containment as a
has a
relationship. A car "has an" engine, a person "has a" name, etc.
Think of inheritance as an
is a
relationship. A car "is a" vehicle, a person "is a" mammal, etc.
I take no credit for this approach. I took it straight from the
Second Edition of Code Complete
by
Steve McConnell
,
Section 6.3
.


Question:
Why does n not equal to 8 in the following function?

void foo(char cvalue[8])
{
  int n = sizeof (cvalue);
}

But n does equal to 8 in this version of the function:

void bar()
{
  char cvalue[8];
  int n = sizeof (cvalue);
}

Answer:
Because you can't pass entire arrays as function parameters in C.  You're actually passing a pointer to it; the brackets are syntactic sugar.  There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want.
```
```
// These all do the same thing
void foo(char cvalue[8])
void foo(char cvalue[])
void foo(char *cvalue)
```
```


Question:
I am bit confused about ADO.Net Data Services.

Is it just meant for creating RESTful web services? I know WCF started in the SOAP world but now I hear it has good support for REST. Same goes for ADO.Net data services where you can make it work in an RPC model if you cannot look at everything from a resource oriented view.

At least from the demos I saw recently, it looks like ADO.Net Data Services is built on WCF stack on the server. Please correct me if I am wrong.

I am not intending to start a REST vs SOAP debate but I guess things are not that crystal clear anymore.

Any suggestions or guidelines on what to use where?

Answer:
In my view ADO.Net data services is for creating restful services that are closely aligned with your domain model, that is the models themselves are published rather then say some form of DTO etc.
Using it for RPC style services seems like a bad fit, though unfortunately even some very basic features like being able to perform a filtered counts etc. aren't available which often means you'll end up using some RPC just to meet the requirements of your customers i.e. so you can display a paged grid etc.
WCF 3.5 pre-SP1 was a fairly weak RESTful platform, with SP1 things have improved in both Uri templates and with the availability of ATOMPub support, such that it's becoming more capable, but they don't really provide any elegant solution for supporting say JSON, XML, ATOM or even something more esoteric like payload like CSV simultaneously, short of having to make use of URL rewriting and different extension, method name munging etc. - rather then just selecting a serializer/deserializer based on the headers of the request.
With WCF it's still difficult to create services that work in a more a natural restful manor i.e. where resources include urls, and you can transition state by navigating through them - it's a little clunky - ADO.Net data services does this quite well with it's AtomPub support though.
My recommendation would be use web services where they're naturally are services and strong service boundaries being enforced, use ADO.Net Data services for rich web-style clients (websites, ajax, silverlight) where the composability of the url queries can save a lot of plumbing and your domain model is pretty basic... and roll your own REST layer (perhaps using an MVC framework as a starting point) if you need complete control over the information i.e. if you're publishing an API for other developers to consume on a social platform etc.
My 2ø worth!


Question:
So I have a function that looks something like this:

float function(){
    float x = SomeValue;
    return x / SomeOtherValue;
}

At some point, this function overflows and returns a really large negative value.  To try and track down exactly where this was happening, I added a cout statement so that the function looked like this:

float function(){
    float x = SomeValue;
    cout << x;
    return x / SomeOtherValue;
}

and it worked!  Of course, I solved the problem altogether by using a double.  But I'm curious as to why the function worked properly when I couted it.  Is this typical, or could there be a bug somewhere else that I'm missing?

(If it's any help, the value stored in the float is just an integer value, and not a particularly big one.  I just put it in a float to avoid casting.)

Answer:
Printing a value to cout should not change the value of the paramter in any way at all.
However, I have seen similar behaviour, adding debugging statements causes a change in the value. In those cases, and probably this one as well my guess was that the additional statements were causing the compiler's optimizer to behave differently, so generate different code for your function.
Adding the cout statement means that the vaue of x is used directly. Without it the optimizer could remove the variable, so changing the order of the calculation and therefore changing the answer.


Question:
Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky.  What's the normal pattern to work around this?

For example, is there a clean way to implement swap( intA, intB ) in Actionscript?

Answer:
If ActionScript works like Javascript,
```
```
[a,b] = [b,a]
```
```


Question:
I'm looking at using OpenID for my authentication scheme and wanted to know what the best .NET library is to use for MVC specific applications?

thx

Answer:
.Net OpenID project
is the best library to use right now that I know of.  I think SO used it also.  The source includes a sample ASP.NET MVC project using the library.
Scott Hanselman did a
post
on how to use the .Net OpenID project inside of ASP.NET MVC.


Question:
I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition.

I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in

MessageBox("Hello, World!");

I received the following error:

MessageBox is a 'type' but used as a 'variable'

Fair enough, it seems in C# MessageBox is an Object. I tried the following

MessageBox a = new MessageBox("Hello, World!");

I received the following error:
MessageBox does not contain a constructor that takes '1' arguments

Now I am stumped. Please help.

Answer:
Code summary:
```
```
using System.Windows.Forms;

...

MessageBox.Show( "hello world" );
```
```
Also (
as per this other stack post
): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select
```
System.Windows.Forms
```
on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.


Question:
I have a .tag file that requires a JavaScript library (as in a .js file).

Currently I am just remembering to import the .js file in every JSP that uses the tag but this is a bit cumbersome and prone to error.

Is there a way to do the importing of the .js inside the JSP tag?

(for caching reasons I would want the .js to be a script import)

Answer:
Short of just including the js in every page automatically, I do not think so. It really would not be something that tags are designed to to.
Without knowing what your tag is actually doing (presumably its its outputting something in the body section) then there is no way that it will be able to get at the head to put the declaration there.
One solution that might (in my head) work would be to have an include that copies verbatim what you have in the head after the place in the head to import tags right up to where you want to use the tag. This is really not something that you would want to do. You would have to have multiple 'header' files to import depending on the content and where you want to use the tag. Maintenance nightmare. Just a bad idea all round. Any solution I can think of would require more work than manually just adding in the declaration.
I think you are out of luck and stuck with manually putting it in.
edit: Just import it in every page. It will be cached and then this problem goes away.


Question:
I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here.  I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication.

Is there a way I can use GreaseMonkey to log me into this site automatically?

Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page.  This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit

Answer:
Why don't you use Firefox (I assume you're using Firefox) to remember your credentials using the Password Manager?
I found this link:
HTTP Authentication with HTML Forms
.  Looks like you can use javascript to do HTTP authentication.  I don't think you can have Greasemonkey interrupt when you are first navigating to a URL though.  You might have to setup some sort of launching point that you can use to have greasemonkey automatically redirect + login.  For example, you can have the local page that takes the destination URL in the query string, have Greasemonkey automatically do the authenticate + redirect.  The only problem is that you'll have to wrap the site bookmarks with your launching page for the bookmarks you use as entry points.


Question: How do I turn a python program into an .egg file?

Answer:
Setuptools
is the software that creates
.egg files
. It's an extension of the
```
distutils
```
package in the standard library.
The process involves creating a
```
setup.py
```
file, then
```
python setup.py bdist_egg
```
creates an .egg package.


Question:
The first language I learnt  was PHP, but I have more recently picked up Python. As these are all 'high-level' languages, I have found them a bit difficult to pick up. I also tried to learn Objective-C but I gave up.

So, what language should I learn to bridge between Python to C

Answer: It's not clear why you need a bridge language. Why don't you start working with C directly? C is a very simple language itself. I think that hardest part for C learner is pointers and everything else related to memory management. Also C lang is oriented on structured programming, so you will need to learn how to implement data structures and algorithms without OOP goodness. Actually, your question is pretty hard, usually people go from low level langs to high level and I can understand frustration of those who goes in other direction.


Question:
Should libraries that the application relies on be stored in source control? One part of me says it should and another part say's no. It feels wrong to add a 20mb library that dwarfs the entire app just because you rely on a couple of functions from it (albeit rather heavily). Should you just store the jar/dll or maybe even the distributed zip/tar of the project?

What do other people do?

Answer:
store everything you will need to build the project 10 years from now.I store the entire zip distribution of any library, just in case
Edit for 2017:
This answer did not age well:-). If you are still using something old like ant or make, the above still applies. If you use something more modern like maven or graddle (or Nuget on .net for example), with dependency management, you should be running a dependency management server, in addition to your version control server. As long as you have good backups of both, and your dependency management server does not delete old dependencies, you should be ok. For an example of a dependency management server, see for example
Sonatype Nexus
or
JFrog Artifcatory
, among many others.


Question: I'm considering using Flash but I'm pretty addicted to autocomplete and Step-at-a-time debugging.

Answer:
If you mean ActionScript I once heard that
PrimalScript
will do Intellisense. Never tested it though. As for debugging, MAYBE,
PrimalScope
will have that too. I'd recommend you try before you buy, though. (They both have trials.)


Question:
For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object:

Object.variable_name= 'new value'

However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround:

Object.send('variable.name=', 'new value')

However, I am wondering is there a way to escape the period so that I can use

Object.variable.name= 'new value'

Answer:
Don't do it!
Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:
```
```
attr_writer :bar
attr_reader :baz
attr_accessor :foo
```
```
Okay, now that you have been warned, here's how to do it.  Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.
```
```
class SillySetter
  def initialize path=nil
    @path = path
  end

  def method_missing name,value=nil
    new_path = @path ? "#{@path}.#{name}" : name
    if name.to_s[-1] == ?=
      puts "setting #{new_path} #{value}"
    else
      return self.class.new(path=new_path)
    end
  end
end

s = SillySetter.new
s.foo = 5              # -> setting foo= 5
s.foo.bar.baz = 4      # -> setting foo.bar.baz= 4
```
```
I didn't want to encourage ruby sillyness, but I just couldn't help myself!


Question: I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I don't want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg .ini) file. Does anyone know a clean and simple way of doing this ? Thanks.

Answer:
Don't do it!
Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:
```
```
attr_writer :bar
attr_reader :baz
attr_accessor :foo
```
```
Okay, now that you have been warned, here's how to do it.  Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.
```
```
class SillySetter
  def initialize path=nil
    @path = path
  end

  def method_missing name,value=nil
    new_path = @path ? "#{@path}.#{name}" : name
    if name.to_s[-1] == ?=
      puts "setting #{new_path} #{value}"
    else
      return self.class.new(path=new_path)
    end
  end
end

s = SillySetter.new
s.foo = 5              # -> setting foo= 5
s.foo.bar.baz = 4      # -> setting foo.bar.baz= 4
```
```
I didn't want to encourage ruby sillyness, but I just couldn't help myself!


Question:
I have a string, say '123', and I want to convert it to the integer 123.

I know you can simply do some_string.to_i, but that converts 'lolipops' to 0, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful Exception. Otherwise, I can't distinguish between a valid 0 and something that just isn't a number at all.

EDIT: I was looking for the standard way of doing it, without regex trickery.

Answer:
Ruby has this functionality built in:
```
```
Integer('1001')                                    # => 1001
Integer('1001 nights')
# ArgumentError: invalid value for Integer: "1001 nights"
```
```
As noted in answer by
Joseph Pecoraro
, you might want to watch for strings that are valid non-decimal numbers, such as those starting with
```
0x
```
for hex and
```
0b
```
for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.
Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:
```
```
Integer('23')                                     # => 23
Integer('0x23')                                   # => 35
Integer('023')                                    # => 19
Integer('0x23', 10)
# => #<ArgumentError: invalid value for Integer: "0x23">
Integer('023', 10)                                # => 23
```
```


Question:
We have some legacy code that needs to identify in the Page_Load which event caused the postback.
At the moment this is implemented by checking the Request data like this...

if (Request.Form["__EVENTTARGET"] != null

&& (Request.Form["__EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort)

       || Request.Form["btnSave"] != null            // Save button

This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this?

Rewriting each page so that it does not need to check this in Page_Load is not an option at the moment.

Answer:
This should get you the control that caused the postback:
```
```
public static Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}
```
```
Read more about this on this page:
http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx


Question:
Using the zip function, Python allows for loops to traverse multiple sequences in parallel.

for (x,y) in zip(List1, List2):

Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?

Answer:
If I'm not mistaken the zip function you use in python
creates a pair of the items found in list1 and list2
. Basically it still is a for loop with the addition that it will retrieve the data from the two seperate lists for you, instead that you have to do it yourself.
So maybe your best option is to use a
standard
for loop like this:
```
```
for i=1:length(a)
  c(i) = a(i) + b(i);
end
```
```
or whatever you have to do with the data.
If you really are talking about parallel computing then you should take a look at the
Parallel Computing Toolbox
for matlab, and more specifically at
parfor


Question:
Is it correct to link a static library (.lib) compiled with VS 2005 with a program which is compiled with VS 2008? Both library and my program are written in C++. This program is run on Windows Mobile 6 Professional emulator.

This seems to work, there are no linking errors. However the program crashes during startup because strange things happen inside the linked library. E.g. lib can return a vector of characters with size of big negative number.

There are no such problems when the program is compiled with VS 2005.

What is even more strange the problem is only when using release configuration for the build. When compiling using debug configuration the problem doesn't occur.

Answer:
It's not incorrect to link to an older library in the way you describe, but it doesn't surprise me you're seeing some odd behavior. Couple sanity checks:
Are both files using the
same versions
of the
same run-time libraries
?
Is your .EXE application "seeing" the same header files that the .LIB was built against? Make sure that the _WIN32_WINNT (etc.) macros are
declared properly
.
And when you say .LIB, do you mean a true static library (mylib.lib) or an import library for a DLL (mylib.lib -> mylib.dll)?
And what are the compile/link settings for your VS2008 executable project?


Question:
Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?

I know that marking it as disabled works but then it gets displayed differently (greyed out).

To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.

I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link.

Answer:
If you merely want to modify the appearance of the link so as not to look like a link, you can set the CSS for your "a" tags to not have underlines:
```
```
a: link, visited, hover, active {
    text-decoration: none;
}
```
```
Though I would advise against including "hover" here because there will be no other way to know that it's a link.
Anyway I agree with @pilif here, this looks like a usability disaster waiting to happen.


Question:
We have the standard Subversion trunk/branches/tags layout. We have several branches for medium- and long-term projects, but none so far for a release. This is approaching fast.

Should we:

Mix release branches and project branches together?

Create a releases folder? If so, is there a better name than releases?

Create a projects folder and move the current branches there? If so, is there a better name than projects? I've seen "sandbox" and "spike" in other repositories.

Something else altogether?

Answer:
Releases is the same as tags... Have you got multiple projects inside your trunk? In that case, I would copy the same folders inside tags
So
```
```
trunk
     fooapp
         stuff...
     barapp
         stuff...
tags
     fooapp
         1.0.0
         1.0.1
     barapp
         1.0.0
```
```


Question: Are the naming conventions similar in different languages? If not, what are the differences?

Answer:
Of course there are some common guidelines but there are also differences due to difference in language syntax\design.
For .NET (C#, VB, etc) I would recommend following resource:
Framework Design Guidelines
-
definitive book on .NET coding
guidelines including naming
conventions
Naming Guidelines
- guidelines from Microsoft
General Naming Conventions
- another set of MS guidelines (C#, C++, VB)


Question:
What all would be the requirements for the following scenario:

A GSM modem connected to a PC running
  a web based (ASP.NET) application. In
  the application the user selects a
  phone number from a list of phone nos.
  When he clicks on a button named the
  PC should call the selected phone
  number. When the person on the phone
  responds he should be able to have a
  conversation with the PC user.
  Similarly there should be a facility
  to send SMS.

Now I don't want any code listings. I just need to know what would be the requirements besides asp.net, database for storing phone numbers, and GSM modem.

Any help in terms of reference websites would be highly appreciated.

Answer:
I'll pick some points of your very broad question and answer them. Note that there are other points where others may be of more help...
First, a GSM modem is probably not the way you'd want to go as they usually don't allow for concurrency. So unless you just want one user at the time to use your service, you'd probably need another solution.
Also, think about cost issues - at least where I live, providing such a service would be prohibitively expensive using a normal GSM modem and a normal contract - but this is drifting into off-topicness.
The next issue will be to get voice data from the client to the server (which will relay it to the phone system - using whatever practical means). Pure browser based functionality won't be of much help, so you would absolutely need something plugin based.
Flash may work, seeing they provide access to the microphone, but please don't ask me about the details. I've never done anything like this.
Also, privacy would be a concern. While GSM data is encrypted, the path between client and server is not per default. And even if you use SSL, you'd have to convince your users trusting you that you don't record all the conversations going on, but this too is more of a political than a coding issue.
Finally, you'd have to think of bandwidth. Voice uses a lot of it and also it requires low latency. If you use a SIP trunk, you'll need the bandwidth twice per user: Once from and to your client and once from and to the SIP trunk. Calculate with 10-64 KBit/s per user and channel.
A feasible architecture would probably be to use a SIP trunk (they optimize on using VoIP as much as possible and thus can provide much lower rates than a GSM provider generally does. Also, they allow for concurrency), an Asterisk box (
http://www.asterisk.org
- a free PBX), some custom made flash client and a custom made SIP client on the server.
All in all, this is quite the undertaking :-)


Question:
I have a WCF service which includes UI components, which forces me to be in STA mode.

How do I set the service behaviour to STA-mode?

The service uses a reference to a WPF DLL file which opens a UI window (used as view port) for picture analysis. When the service is trying to create an instance of that item (inherits from window) it throws an exception:

The calling thread must be an STA

Answer:
I would investigate using the [STAThread] attribute to switch the threading model.
e.g.
```
```
[STAThread]
static void Main()
{
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new Host() };
        ServiceBase.Run(ServicesToRun);
}
```
```
Description of the STAThread attribute
But I'm confused why you're using UI components in a web service at all. Can you explain a bit more about why you're trying to do this?


Question:
I'm just about wrapped up on a project where I was using a commercial SVN provider to store the source code. The web host the customer ultimately picked includes a repository as part of the hosting package, so, now that the project is over, I'd like to relocate the repository to their web host and discontinue the commercial account.

How would I go about doing this?

Answer:
Assuming you have the necessary privileges to run svnadmin, you need to use the
dump
and
load
commands.


Question:
I deleted a branch in TFS and just found out that I need the changes that were on it.

How do I recover the branch or the changes done on it?

Answer:
As described in the
TFS FAQ
:
Are Deletes physical or logical? Can accidental deletes be recovered?
Deletes are fully recoverable with the “undelete” operation. You wouldn’t want to do a SQL restore because that would roll back every change to the TFS in the time since the file was deleted.


Question:
Is there a C# equivalent for the VB.NET FormatNumber function?

I.e.:

JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);

Answer:
You can use string formatters to accomplish the same thing.
```
```
double MyNumber = inv.RRP * oCountry.ExchangeRate;
JSArrayString += "^" + MyNumber.ToString("#0.00");
```
```


Question:
Is Bouncy Castle API Thread Safe ? Especially,

org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
org.bouncycastle.crypto.paddings.PKCS7Padding
org.bouncycastle.crypto.engines.AESFastEngine
org.bouncycastle.crypto.modes.CBCBlockCipher

I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here.

Please let me know if you have come across such situations using Bouncy Castle.

Answer:
It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe.
Some terminology -
```
```
E(X) = Enctrypt message X
D(X) = Dectrypt X. (Note that D(E(X)) = X)
IV = Initialization vector. A random sequence to bootstrap the CBC algorithm
CBC = Cipher block chaining.
```
```
A really simple CBC implementation can look like:
P1, P2, P3 = Plain text messages
```
```
1. Generate an IV, just random bits.
2. Calculate E( P1 xor IV) call this C1
3. Calculate E( P2 xor C1) call this C2
4. Calculate E( P3 xor C2) call this C3.
```
```
As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order).
So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe.
You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe.


Question:
I'm trying to redirect requests for a wildcard domain to a sub-directory.

ie. something.blah.example.com --> blah.example.com/something

I don't know how to get the subdomain name to use in the rewrite rule.

Final Solution:

RewriteCond %{HTTP_HOST} !^blah\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)
RewriteRule ^(.*) /%1/$1 [L]

Or as pointed out by pilif

RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$

Answer:
You should have a look at the
URL Rewriting Guide
from the apache documentation.
The following is untested, but it should to the trick:
```
```
RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$
RewriteRule ^/(.*)$           http://blah.domain.com/%1/$1 [L,R]
```
```
This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer.


Question:
How do you set your Cocoa application as the default web browser?

I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.).

Answer:
There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes.
1) Add the URL schemes your app can handle to your application's info.plist file
To add support for
```
http://
```
and
```
https://
```
you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs.
```
```
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>http URL</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>http</string>
        </array>
    </dict>
    <dict>
        <key>CFBundleURLName</key>
        <string>Secure http URL</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>https</string>
        </array>
    </dict>
</array>
```
```
2) Write an URL handler method
This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this:
```
```
- (void)getUrl:(NSAppleEventDescriptor *)event
    withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
  // Get the URL
  NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
    stringValue];

  //TODO: Your custom URL handling code here
}
```
```
3) Register the URL handler method
Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed
```
self
```
as the event handler, assuming that we're calling
```
setEventHandler
```
from the same object that defines the
```
getUrl:withReplyEvent:
```
method.
You should add this code somewhere in your application's initialisation code.
```
```
NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];
[em
  setEventHandler:self
  andSelector:@selector(getUrl:withReplyEvent:)
  forEventClass:kInternetEventClass
  andEventID:kAEGetURL];
```
```
Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following:
```
```
[em
  setEventHandler:self
  andSelector:@selector(getUrl:withReplyEvent:)
  forEventClass:'WWW!'
  andEventID:'OURL'];
```
```
4) Set your app as the default browser
Everything we've done so far as told the OS that your application is
a browser
, now we need to make it
the default browser
.
We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links:
```
```
CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier];
OSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID);
OSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID);
//TODO: Check httpResult and httpsResult for errors
```
```
(It's probably best to ask the user's permission before changing their default browser.)
Custom URL schemes
It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is
```
com.example.MyApp
```
you should consider using
```
x-com-example-myapp://
```
URLs.


Question:
Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner.

For security reasons we do not want certain pages in our application to be cached, ever, by the web browser. This must work for at least the following browsers:

Internet Explorer 6+

Firefox 1.5+

Safari 3+

Opera 9+

Chrome

Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages.

Answer:
Setting the modified http header to some date in 1995 usually does the trick.
Here's an example:
```
Expires: Wed, 15 Nov 1995 04:58:08 GMT
Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
Cache-Control: no-cache, must-revalidate
```


Question:
I'm still trying to get my head around LINQ and accessing a SQL Database.

I was always taught that you should only have execute permissions of stored procedures to your data.

You should never have select / insert / update / delete.

(This is because of performance and security)

To get the data out of LINQ you obviously need select permissions.  I know you can use stored procs with LINQ, but since I can't do joins what's the point?

Have I missed something???

Answer:
1) We're programmers, not DBA fascists.  If your requirements state that the database must be locked down 100%, Linq is not for you.  I'm not a DBA, so I believe that most of the performance/security hype is just that.  Linq is for me.
2) You can do joins with linq.
@Philippe
:  Linq automatically transforms evaluations into query parameters, so it provides some sql injection protection.  However, you still have to closely evaluate your requirements to determine how much security you need and at what levels.  Linq makes dealing with the database much easier, but it makes it easier to put secuirty design on the back burner, which is a bad thing.


Question:
What is the difference between

char str1[32] = "\0";

and

char str2[32] = "";

Answer:
Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, you can see that the first declaration makes a larger string:
```
```
char a[] = "a\0";
char b[] = "a";

printf("%i %i\n", sizeof(a), sizeof(b));
```
```
prints
```
```
3 2
```
```
This is because a ends with two nulls (the explicit one and the implicit one) while b ends only with the implicit one.


Question:
Jquery has a great language construct that looks like this:

$(document).ready(function() {
    $("a").click(function() {
        alert("Hello world!");
    });
});

As you might guess this, once the document has loaded, binds a custom function to the onClick event of all a tags.

The question is, how can I achieve this same kind of behavior in Prototype?

Answer:
```
```
Event.observe(window, 'load', function() {
     Event.observe(element, 'click', function() {
         alert("Hello World!");
     });
});
```
```
Of course you need to "select" the elements first in Prototype.


Question:
In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" rownum column. Consider the following example, which will return, at most, 10 rows.

SELECT * FROM all_tables WHERE rownum <= 10

Is there a simple, generic way to do something similar in Ingres?

Answer:
Blatantly changing my answer. "Limit 10" works for MySql and others, Ingres uses
```
```
Select First 10 * from myTable
```
```
Ref


Question:
For many years I have used two great tools BoundsChecker & Purify, but the developers of these applications have let me down, they no longer put effort into maintaining them or developing them. We have corporate accounts with both companies, and they both tell me that they have no intention of producing versions to support 64 bit applications.

Can anyone recommend either open source or commercial alternatives that support 64 bit native C++/MFC applications?

Answer:
I've used bounds checking and other dynamic analysis tools, and while the architectures are different it's the code that you're checking - in theory you could run bounds checking on any backend and the result would be the same - the code either steps outside its bounds or it does not.
The only complications are addressing more than 4GB of memory space, dealing with pieces of code you can't cross-compile to a 32-bit architecture (64 bit object files for which you have no source, etc), and general 64 bit migration issues (platform specific code such as checking for 0xFFFFFFFF instead of -1)
What other problems are you running into doing bounds checking on your program?  Are you unable to compile a 32 bit version?
It's not your ideal solution, certainly, and one should always check the code they're going to run, but in this case you might not have a choice, unless you want to do your own bounds checking (which is a good idea in any case...).
-Adam


Question: Can someone suggest some good automated test suite framework for Perl?

Answer:
I'd go for Test::More, or in general, anything that outputs
TAP