Question: Is there a built-in way to escape user input in java using the JDBC? Something similar to the php version mysql_real_escape() function. What's the best way to validate input?

Answer:
If you mean how do you make sure user input can't be used in SQL injection attacks, the way to do this (and the way all SQL should be written in JDBC) is using Prepared Statements. JDBC will automatically handle any necessary escaping.
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html


Question: For the most part, you just take whatever Visual Studio sets it for you as a default... I'm referring to the BuildAction property for each file selected in Solution Explorer. There are a number of options and it's difficult to know what each one of them will do.

Answer:
From the documentation:
The BuildAction property indicates
  what Visual Studio does with a file
  when a build is executed. BuildAction
  can have one of several values:
None - The file is not included in the
  project output group and is not
  compiled in the build process. An
  example is a text file that contains
  documentation, such as a Readme file.
Compile - The file is compiled into
  the build output. This setting is used
  for code files.
Content - The file is not compiled,
  but is included in the Content output
  group. For example, this setting is
  the default value for an .htm or other
  kind of Web file.
Embedded Resource - This file is
  embedded in the main project build
  output as a DLL or executable. It is
  typically used for resource files.


Question:
There is a webpage loaded in the firefox sidebar and another webpage loaded in the main document. Now, how do I ask access the main document object through the Firefox sidebar? An example to do this through Javascript code in the firefox sidebar document to access the main document would be helpful.

Thanks for the answers. I have to refine my question however. The main window has some webpage loaded and the sidebar has a webpage. I want the sidebar window to know what text the user has selected on the main window when a link on the sidebar window is clicked. I know how to get the selected text from a window. Only that the sidebar element adds complexity to the problem that I am not able to surpass.

@PConory:

I like your answer, but when I try it there is an error:

Error: Permission denied to create wrapper for object of class
  UnnamedClass.

Thanks.

Answer:
Accessing the main window from a sidebar is much trickier than going back the other way.
The DOM tree you'll need to traverse, according to
Mozilla's developer centre
, is:
```
```
#document
  window                 main-window
    ...
      browser
        #document
          window         sidebarWindow
```
```
From the above link, the following code will allow you to get at the
```
mainWindow
```
object:
```
```
var mWin = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
               .getInterface(Components.interfaces.nsIWebNavigation)
               .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
               .rootTreeItem
               .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
               .getInterface(Components.interfaces.nsIDOMWindow);
```
```


Question:
Is there a open source or free suite that can integrate testcases, tests, bugs and possibly the fixes(source code) together. Maintaining the requirements in this system is not a necessity (though, it would be nice to enter a requirement id for each testcase in a custom field). We are a small organization and cannot afford something like HP Quality Center.

We have coding skills (Java, SQL), so if it comes to integration of different tools using Java APIs, it should not be a problem. Similarly, a practical solution using export/import of results/data should also be fine (we could automate where possible).

Has anybody used PushToTest TestMaker as part of such a solution.

Answer:
This link
http://www.testingfaqs.org/t-management.html
has a list of test case management tools, both freeware and commercial. Maybe there is something on that list which can meet your needs.
Another posibility is something like
Trac
. That is not really designed as a test case management tool but it integrates a Subversion repository browser, a bug tracker and a Wiki. If you can manage organising the test cases on the Wiki then that will let you link the Wiki pages to bugs and bugs to Subversion commits. We used to use Trac and were quite happy with it. We switched to Jira because we wanted some more bug tracking features.
I have not used it, but Trac does have a testcase management
plugin
listed on their web page.


Question:
What is your favorite, lossless image format for games (namely 2d games)? And why?

Some things to take into consideration are size on disk, overhead for converting to a usable format, and features of the format (ie alpha support).

There is no best answer, but be sure to back yours up the best you can!

Answer:
I'd suggest PNG. Most software supports writing it, most libraries support reading it, it's lossless and supports alpha transparency. And it's a standard format.
And, maybe important for hobbyist 2D games, very small images also result in very small files (i.e. a 16x16 icon can be 1KB or less).


Question:
Clicking through to the download-page if see that the last version of the download is over one year old and it's also "just" a Release Candidate of version 1.0. There are really no news on any development.

Yes, you can find newer versions from the nightly builds, but that's not a real serious option.

Also, the "getting-started" and description-pages are sometimes not even started and some not completed.

What's the deal? Any C# 3.0 features on the way or what?

Answer:
I'd suggest PNG. Most software supports writing it, most libraries support reading it, it's lossless and supports alpha transparency. And it's a standard format.
And, maybe important for hobbyist 2D games, very small images also result in very small files (i.e. a 16x16 icon can be 1KB or less).


Question:
I have a little dilemma on how to set up my visual studio builds for multi-targeting.

Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project.
Right now, the platform target is set to x86 so it can be run on Windows x64.

The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program.

This raises some questions which I haven't got the answers to yet.
I want to have the exact same code base.
I must build with references to either the 32bit set of DLL's or 64bit DLL's.
(Both 3rd party and SQL Server Compact)

Can this be solved with 2 new sets of configurations (Debug64 and Release64) ?

Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi?

Any ideas and/or recommendations would be welcomed.

Answer:
Not sure of the total answer to your question - but thought I would point out a comment in the Additional Information section of the
SQL Compact 3.5 SP1 download page
seeing you are looking at x64 - hope it helps.
Due to changes in SQL Server Compact
  SP1 and additional 64-bit version
  support, centrally installed and mixed
  mode environments of 32-bit version of
  SQL Server Compact 3.5 and 64-bit
  version of SQL Server Compact 3.5 SP1
  can create what appear to be
  intermittent problems. To minimize the
  potential for conflicts, and to enable
  platform neutral deployment of managed
  client applications, centrally
  installing the 64-bit version of SQL
  Server Compact 3.5 SP1 using the
  Windows Installer (MSI) file also
  requires installing the 32-bit version
  of SQL Server Compact 3.5 SP1 MSI
  file. For applications that only
  require native 64-bit, private
  deployment of the 64-bit version of
  SQL Server Compact 3.5 SP1 can be
  utilized.
I read this as "include the 32bit SQLCE files
as well as
the 64bit files" if distributing for 64bit clients.
Makes life interesting I guess.. must say that I love the "what appears to be intermittent problems" line... sounds a bit like "you are imagining things, but just in case, do this..."


Question: What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today?

Answer:
Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference?  Not noticeably enough on modern hardware for most.  But it can make a difference, which is enough for some people.
Marking something inline does not give you a guarantee that it will be inline.  It's just a suggestion to the compiler.  Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved.  And sometimes the compiler just chooses not to use it.
I could see a situation like this making a detectable difference:
```
```
inline int aplusb_pow2(int a, int b) {
  return (a + b)*(a + b) ;
}

for(int a = 0; a < 900000; ++a)
    for(int b = 0; b < 900000; ++b)
        aplusb_pow2(a, b);
```
```


Question:
All,

As part of an application I'm writing I need to have a HTTP PUT webservice which accepts incoming imagedata, which will by analyzed, validated, and added to a local file store.

My issue arises after the size validation as the

$_SERVER['CONTENT_LENGTH']

has a > 0 value, and this value is identical to the test file size, so I can assume that all is going well up to this point but when I try to read the incoming stream data using

file_get_contents('php://stdin');

I get an empty string. I've also tried using

file_get_contents('php://input');

And this give me the same result of an empty string.

Any help, suggestions or direction will be appreciated.

NB: I'm using

PHP 5.2.6

Apache 2.0

Answer:
The
```
r
```
you've got as the second arg isn't right.
```
file_get_contents
```
doesn't use the
```
a/r/w/a+/r+/w+
```
arguments that
```
fopen
```
uses.  You probably want to remove it and just do:
```
```
file_get_contents('php://input');
```
```
See
http://us3.php.net/file_get_contents
.


Question:
I have an array of integers:

int[] number = new int[] { 2,3,6,7 };

What is the easiest way of converting these into a single string where the numbers are separated by a character (like: "2,3,6,7")?

I'm using C# and .NET 3.5.

Answer:
```
```
var ints = new int[] {1, 2, 3, 4, 5};
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
Console.WriteLine(result); // prints "1,2,3,4,5"
```
```
As of (at least) .NET 4.5,
```
```
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
```
```
is equivalent to:
```
```
var result = string.Join(",", ints);
```
```
I see several solutions advertise usage of StringBuilder. Someone complains that the Join method should take an IEnumerable argument.
I'm going to disappoint you :) String.Join requires an array for a single reason - performance. The Join method needs to know the size of the data to effectively preallocate the necessary amount of memory.
Here is a part of the internal implementation of String.Join method:
```
```
// length computed from length of items in input array and length of separator
string str = FastAllocateString(length);
fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here
{
    UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
    buffer.AppendString(value[startIndex]);
    for (int j = startIndex + 1; j <= num2; j++)
    {
        buffer.AppendString(separator);
        buffer.AppendString(value[j]);
    }
}
```
```


Question: I could not find any pointers on how to create a menubar icon on OSX using wx. I originally thought that the wxTaskBarIcon class would do, but it actually creates an icon on the Dock. On Windows, wxTaskBarIcon creates a Systray icon and associated menu, and I would think that on mac osx it would create a menubar icon, I guess not.

Answer:
You have to set
```
wxTaskBarIconType
```
to
```
STATUSITEM
```
, not
```
DOCK
```
. The Cocoa APIs for this are
```
NSStatusBar
```
and
```
NSStatusItem
```
;
here's the code in wxWidgets that calls to them
.


Question:
I've got a sections table, and an items table.

The problem is each item may be in one or more sections, so a simple 'section_id' for each item won't work, and sql doesn't have a way to store arrays where I can do say "WHERE 5 in section_ids"...

I've considered storing the list of ids as a comma separated string, the problem is I see no way to then check if an item is in a given section from the sql query. The only option I see here is to select the entire table, and parse the strings in php. Needless to say that with 1000's of items this isn't a good idea.

Is there a better way to 'link' an item with multiple sections, and be able to easily select all items for a given section id?

Answer:
You need a third table itemsPerSection with a primary key composed of both itemid and sectionid, this way you can have a N to N relationship and it's very easy to search on.
So:
```
```
Items   -   ItemsPerSection   -   Secion
itemid  <->   itemid
             sectionid        <->   sectionid
```
```


Question:
I'm doing some Android development, and I much prefer Visual Studio, but I'll have to use Eclipse for this.

Has anyone made a tool which can make Eclipse look and behave more like visual studio? I mainly can't stand its clippyesqe suggestions on how I should program (Yes, I know I have not yet used that private field! Thanks Eclipse!), or its incredibly lousy intellisense.

For example, in eclipse, if I don't type this first, its intellisense won't realise I want to look for locally scoped members. Also, the TAB to complete VS convention is drilled into my head, and Eclipse is ENTER to complete, I could switch everything by hand but that would take hours, and I was hoping someone had some sort of theme or something that has already done it.

Answer:
Have you tried using the Visual Studio keybindings available in Eclipse Ganymede (3.4)?
(You may want to know that "IntelliSense" is a Visual Studio-term, an probably unknown to anyone without Visual Studio-experience. "Autocompletion" is probably a more widely used term.)


Question:
From time to time I browse the web and look for interesting algorithms and datastructures to put into my bag of tricks. A year ago I came across the Soft Heap data-structure and learned about near sorting.

The idea behind this is that it's possible to break the O(n log n) barrier of compare based sorts if you can live with the fact that the sort algorithm cheats a bit. You get a almost sorted list but you have to live with some errors as well.

I played around with the algorithms in a test environement but never found a use for them.

So the question: Has anyone ever used near sorting in practice? If so in which kind of applications? Can you think up a use-case where near sorting is the right thing to do?

Answer:
This is a total flying guess, but given the inherent subjectivity of "relevance" measures when sorting search results, I'd venture that it doesn't really matter whether or not they're perfectly sorted. The same could be said for recommendations. If you can somehow arrange that every other part of your algorithm for those things is O(n) then you might look to avoid a sort.
Be aware also that in the worst case your "nearly sorted" data
does not
meet one possible intuitive idea of "nearly sorted", which is that it has only a small number of inversions. The reason for this is just that if your data has only O(n) inversions, then you can finish sorting it in O(n) time using insertion sort or cocktail sort (i.e. two-way bubble sort). It follows that you cannot possibly have reached this point from completely unsorted, in O(n) time (using comparisons). So you're looking for applications where a majority subset of the data is sorted and the remainder is scattered,
not
for applications requiring that every element is close to its correct position.


Question:
I'm writing an interactive function that I'd like to have remember the last argument the user supplied and use it as the default.

(defun run-rake (param)
  (interactive "sTask: ")
  (shell-command (format "rake %s" task)))

The first time the function is invoked I want it to remember the argument the user supplied so that the next time they invoke the function they can just press enter and it will use the value they supplied the previous time.

I can't seem to find this in the documentation - how do you do this in elisp?

Answer:
I figured out how to do this manually using a defvar (global), but this feels like the kind of thing that should already be provided by the core library (kind of like scheme's make-parameter).  This just seems like more code, and more manual than it should be:
```
```
(defvar *editconf-ruby-run-rake-last-rake-task* nil)

(defun editconf-ruby-run-rake-last-rake-task (&optional new-val)
  (when new-val
    (setf *editconf-ruby-run-rake-last-rake-task* new-val))
  *editconf-ruby-run-rake-last-rake-task*)

(defun editconf-ruby-run-rake (task-name)
  "Execute rake `task-name'.  See
`krb-ruby-get-rakefile-path-for-current-buffer' for how the
Rakefile is located.."
  (interactive
   (let* ((rakefile (krb-ruby-get-rakefile-path-for-current-buffer))
          (rake-tasks (krb-ruby-get-rake-tasks rakefile))
          (default-task (or (editconf-ruby-run-rake-last-rake-task)
                            (editconf-ruby-run-rake-last-rake-task (car rake-tasks)))))
     (list
      (read-string (format "Task [%s|%s]: "
                           rake-tasks
                           default-task)
                   nil nil default-task))))
  (editconf-ruby-run-rake-last-rake-task task-name)
  (let ((cmd (format "cd %s; rake %s"
                     (krb-lisp-strip-path-suffix rakefile 1)
                     task-name)))
    (message "editconf-ruby-run-rake: cmd='%s'" cmd)
    (shell-command cmd)))
```
```


Question: I'm making a study on refactoring limitations on improving existing software architecture and I would be interested to hear your experiences where you have found refactoring to be not enough or still too immature to accomplish your goals.

Answer:
Refactoring can be risky
Refactoring is often difficult because the refactorer often isn't the same person as the original designer. Therefore, he or she doesn't have the same background in the system and the decisions that went behind the original design. You always run the risk that bugs avoided in the original design may creep up in the new design.
This may be especially true when a new or young team member, not fully experienced with this system, decides to inject new-cool-wizbang technology or ideas into an otherwise stable system. Often when the new team members are not integrated well into the team and are not given sufficient guidance, they may begin forcing the project in directions unintended by the whole team.
This is just a risk, however, there's also a chance that the team is wrong and the new team member, if put in charge and was allowed to do his or her thing, would actually make a serious improvement.
These problems often come up amongst a team working on legacy systems. Often there are no world-altering enhancements planned, so the team is conservative with their design. Their goal is to prevent new bugs from being injected and fix old ones with a couple extra features thrown in. A new team member might come along and upset the apple cart by insisting that, he rewrite certain subsystems of the code. New bugs are created and users of a fairly stable product are upset because the software, from there perspective is getting worst.
So if your goal is long-term stability without major functionality changes, often major refactoring is not what you want.
If you have larger functionality changes in the pike however, have a user-base that expects your product to not be fully baked quite yet (ie you're in some sort of beta), then its a much better situation to consider serious refactoring because the long-term benefits of the superior design will pay off and you're less likely to disrupt a large user base.


Question:
I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";

            illegal = illegal.Trim(Path.GetInvalidFileNameChars());
            illegal = illegal.Trim(Path.GetInvalidPathChars());

            Console.WriteLine(illegal);
            Console.ReadLine();
        }
    }
}

Answer:
For starters,
Trim only removes characters from the beginning or end of the string
. Secondly, you should evaluate if you really want to remove the offensive characters, or fail fast and let the user know their filename is invalid. My choice is the latter, but my answer should at least show you how to do things the right AND wrong way:
StackOverflow question showing how to check if a given string is a valid file name
. Note you can use the regex from this question to remove characters with a regular expression replacement (if you really need to do this).


Question:
I need to randomly fade my background images in and out.

It will be a timed function, like once every 5 seconds.

I need to do it with ASP.NET, Javascript, CSS or all three.

Please help me out here guys.  Thank you.

Answer:
This is the Answer:
never mind guys, after making a bit more exact search on Google.  I found a good solution.
```
```

JS-Examples.com

```
```
Found it here
.


Question:
Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used?  The only solution I've found is to create, for example, a class like:

Dictionary<string, List<object>>

But this is quite irritating to actually use.  In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET.

Answer:
I think something like
```
List<KeyValuePair<object, object>>
```
would do the Job.


Question:
In Nant, I would like to be able to extract the last name of the directory in a path.

For example, we have the path 'c:\my_proj\source\test.my_dll\'

I would like to pass in that path and extract 'test.my_dll'

Is there a way to easily do this?

Answer:
See the
script
task.  You can write custom code in C# or whatever, and return a value that you can assign to a property.


Question:
I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected).

I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas.

Answer:
The easiest way to do this is to supply a template for the "ItemContainerStyle" and NOT the "ItemTemplate" property. In the code below I create 2 data templates: one for the "unselected" and one for the "selected" states. I then create a template for the "ItemContainerStyle" which is the actual "ListBoxItem" that contains the item. I set the default "ContentTemplate" to the "Unselected" state, and then supply a trigger that swaps out the template when the "IsSelected" property is true. (Note: I am setting the "ItemsSource" property in the code behind to a list of strings for simplicity)
```
```
<Window.Resources>

<DataTemplate x:Key="ItemTemplate">
    <TextBlock Text="{Binding}" Foreground="Red" />
</DataTemplate>

<DataTemplate x:Key="SelectedTemplate">
    <TextBlock Text="{Binding}" Foreground="White" />
</DataTemplate>

<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
    <Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
        </Trigger>
    </Style.Triggers>
</Style>

</Window.Resources>
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource ContainerStyle}" />
```
```


Question:
I have a templated class defined (in part) as

template <class T> MyClass
{
public:
   void DoSomething(){}
};

If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.

My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.

Has anyone any suggestions?

Answer:
Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.
Something like this:
```
```
class Base {
public:
  virtual ~Base(){}
  virtual void DoSomething() = 0;
}

template <class T> class MyClass : public Base {
public:
    void DoSomething(){}
};

std::vector<Base *> objects;
objects.push_back(new MyClass<int>);
objects.push_back(new MyClass<char>);
```
```


Question:
With a huge influx of newbies to Xcode, I'm sure there are lots of Xcode tips and tricks to be shared.

What are yours?

Answer:
⌘ Command
+
```
Double-Click on a symbol
```
: Jump to Definition of a symbol.
⌥ Option
+
```
Double-Click on a symbol
```
: Find Text in Documentation of a symbol. (Only works if you have they symbol's Doc Set installed.)
Favorites Bar:
Favorites bar is just like you have in Safari for storing - well - favorites. I often use it as a place to store shortcuts (which you can do by drag-dropping) to files I am using right now. Generally this is more useful when I'm working with a large or unfamiliar project.
To show the Favorites Bar, select the following menu option:
```
View
```
>
```
Layout
```
>
```
Show Favorites Bar
```


Question:
Are there some principles of organizing classes into namespaces?

For example is it OK if classes from namespace N depends on classes from N.X?
And if classes from N.X depends on classes from N?

Answer:
Classes in
```
N.X
```
can rely on classes in
```
N
```
. But classes in
```
N
```
shouldn't rely on classes in
```
N.X
```
; that's bad design.
Some namespace guidelines:
Namespace Naming Guidelines
Names of Namespaces


Question:
I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.

So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?

$database = 'live';
if (some staging environment variable is true) {
    $database = 'testing'; // and not live
}

If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile

Hope this makes sense

many thanks

Ian

Answer:
Yep...you can do this:
```
```
SetEnv DATABASE_NAME testing
```
```
and then in PHP:
```
```
$database = $_SERVER["DATABASE_NAME"];
```
```
or
```
```
$database = getenv("DATABASE_NAME");
```
```


Question:
I am trying to figure out this:

c = 1
def f(n):
    print c + n
def g(n):
    c = c + n

f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment

Thanks!

Answer:
Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the
```
global
```
statement:
```
```
def g(n):
    global c
    c = c + n
```
```
This is one of the quirky areas of Python that has never really sat well with me.


Question:
I work for a small web development company (only 2 to 3 developers) that work on a wide range of projects for different customers (everything from CMS's to eCommerce sites).

Usually we work on our own projects but occasionally we need to work together on one. We use subversion as our source control software and sites are developed in .NET using VS 2008 and SQL 2005.

After reading through plenty of posts regarding unit testing and other "enterprise" level coding practices I was wondering what other developers do for small projects that only require minimal maintenance and have short development times?

I am thinking in particular of things like is unit testing necessary, etc.

Answer:
Unit testing IS necassary no matter what. If you write code, you unit test. I work by myself alot too. I still test. I dont know how I ever wrote code before it.
Heres the way I look at it. you dont necassarily need the same expensive tools as the big boys, but if you want to be big, you have to think big. Do the same htings, follow the same practices. As your needs grow, get better tools. For example, if you do any UML diagramnming, you porbably dont need any saftware. Just a whiteboard/paper. But still use UML. When your needs grow, you can look at getting special software.
Even project management. You dont necassarily need the expensive tools to track projects, as long as you do it. As your needs grow, you can get specialized softwaare.
In short, do the same things you would do if you were bigger, but you dont necassarily need the same tools. Aquire as needed.
EDIT: I should mention though that some of what you do of course is dependant on your methodolies/processes that you use. For example, do you do agile development? Being small you dont necassarily need to do everything exactly the same. For example, I try to be agile, but I obviously dont pair program :). You just need to learn to adapt them to what works for you.


Question: I have just started reading Introduction to 80x86 Assembly Language and Computer Architecture.I am trying to use NASM, to run the first example shown in chapter 3 ,but unsuccessfully.Has anyone read the book,and run the examples?

Answer:
According to Google Books, you should be using
MASM
, not NASM. Try that.
For reference guys, page 47
here
.


Question:
I'd like to get uniform distribution in range [0.0, 1.0)

If possible, please let the implementation make use of random bytes from /dev/urandom.

It would also be nice if your solution was thread-safe. If you're not sure, please indicate that.

See some solution I thought about after reading other answers.

Answer:
```
```
#include <stdlib.h>
printf("%f\n", drand48());
```
```
/dev/random:
```
```
double c;
fd = open("/dev/random", O_RDONLY);
unsigned int a, b;
read(fd, &a, sizeof(a));
read(fd, &b, sizeof(b));
if (a > b)
   c = fabs((double)b / (double)a);
else
    c = fabs((double)a / (double)b);
```
```
c is your random value


Question:
I am thinking of changing my web site's homegrown search engine. Before I break out Visual Studio, I wondered if anyone can suggest an alternative that gives me what I need. This being:

Works with an ASP.NET site (is a .NET project)

Creates a file-based index

Fast search across hundreds or thousands of pages

Performs word-stemming to find variations upon words

Gives full control over the output styles

Is cheap (or better still, free!)

Answer:
You can't really beat
Google Site Search
for this.  It's fully customizable - and no need for embedding or maintaining.
EDIT: found this
ASP.NET opensource search engine
that you can take and run with, In response to your comment about knowing what google does, this is
well documented and they have TONS of webmaster tools for you
.


Question:
In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string.  For example:

>>> a = (1,"Hello",7.2)
>>> print "these are the values %d, %s, %f" % a
these are the values 1, Hello, 7.200000

Is there some way to use any array or collection in a java printf statement in a similar way?

I've looked at the documentation and it appears to have built in support for some types like Calendar, but I don't see anything for collections.

If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)?

Answer:
printf will have a declaration along the lines of:
```
```
public PrintString printf(String format, Object... args);
```
```
... means much the same as
```
[]
```
. The difference is
```
...
```
allows the caller to omit explicitly creating an array. So consider:
```
```
out.printf("%s:%s", a, b);
```
```
That is the equivalent of:
```
```
out.printf("%s:%s", new Object[] { a, b });
```
```
So, getting back to your question, for an array, you can just write:
```
```
out.printf("%s:%s", things);
```
```
For a collection:
```
```
out.printf("%s:%s", things.toArray());
```
```


Question:
I can't figure out a use case for being able to annotate interfaces in Java.

Maybe someone could give me an example?

Answer:
More an example, but
Local
and
Remote
annotations in EJB3. According to the java doc,
When used on an interface, designates
  that interface as a local business
  interface.
I guess the use case here is that the interface has a special function best denoted by an annotation.


Question:
I have a file temp.txt, that I want to sort with the sort command in bash.

I want the sorted results to replace the original file.

This doesn't work for example (I get an empty file):

sortx temp.txt > temp.txt

Can this be done in one line without resorting to copying to temporary files?

EDIT: The -o option is very cool for sort. I used sort in my question as an example. I run into the same problem with other commands:

uniq temp.txt > temp.txt.

Is there a better general solution?

Answer:
Read up on the non-interactive editor,
```
ex
```
.


Question:
Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met.

Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel.  Is this possible with C#?

Main thing I am looking for is how to catch a program starting up, rest should be easy.

Answer:
I'm not sure if you can catch it starting up, but you could try to look for the program in the list of windows (was it ENUM_WINDOWS? I can never remember) and shut it down as soon as it shows up.
You could probably even do this in AutoIt!
Drag out the Petzold and have some fun with windows...
EDIT:
Check out sysinternals for source on how to list the active processes - do this in a loop and you can catch your program when it starts. I don't think the official site still has the source though, but it's bound to be out there somewhere...


Question:
I've come across this term POD-type a few times.

What does it mean?

Answer:
POD
stands for
Plain Old Data
- that is, a class (whether defined with the keyword
```
struct
```
or the keyword
```
class
```
) without constructors, destructors and virtual members functions.
Wikipedia's article on POD
goes into a bit more detail and defines it as:
A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.
Greater detail can be found in
this answer for C++98/03
. C++11 changed the rules surrounding POD, relaxing them greatly, thus
necessitating a follow-up answer here
.


Question: Can some one specify the windows API, one need to use in order to be able to change programmatically the screen refresh rate?

Answer:
I found this via a google search. Hope it helps some.
http://www.codeproject.com/KB/winsdk/changerefresh.aspx
http://msdn.microsoft.com/en-us/library/ms533260(VS.85).aspx


Question:
Say I'm writing some ruby code and I want to use the standard Date type to get the current date. Instead of using a search engine, is there a faster way to find the documentation for this class?  I know I can get the methods for Date by typing Date.methods, but as far as I know this doesn't provide details about argument types or return value.

Editor-specific answers are welcomed.  My editor of choice is Emacs.

Answer:
On your console use "ri"
```
```
ri Date
```
```
That works with all classes. (e.g. ri String)
To see documentation for a particular method you use this:
```
```
ri Date#yourMethod
```
```


Question: I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories?

Answer:
Blockquote
```
```
delete from table where id not in (
    select id from table
    order by id desc
    limit 50
)
```
```
You select the ids of the data you don't want to delete, and the you delete everything NOT IN these value...


Question:
I have a couple of header files, which boil down to:

tree.h:

#include "element.h"

typedef struct tree_
{
    struct *tree_ first_child;
    struct *tree_ next_sibling;
    int tag;
    element *obj;
    ....
} tree;

and element.h:

#include "tree.h"

typedef struct element_
{
    tree *tree_parent;
    char *name;
    ...
} element;

The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.

This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.

How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)?

Answer:
These are known as "once-only headers." See
http://developer.apple.com/DOCUMENTATION/DeveloperTools/gcc-4.0.1/cpp/Once_002dOnly-Headers.html#Once_002dOnly-Headers


Question:
Has anyone successfully built an Adobe Air application with Maven?  If so, what are the steps to get it working?

I have been trying to use flex-mojos to build an Air applications.  When I set the packaging type to "aswf", as suggested in the DashboardSamplePom, Maven complains that aswf is an unknown packaging type.  I also found their air-super-pom, but could not figure out how to reference it as the parent of my POM.

Answer:
When a plugin declares a new packaging type, like 'aswf', you need to declare it as an extension. In your top-level pom, add the extensions element to the plugin config.
```
```
<plugin>
  <groupId>...</groupId>
  <artifactId>...</artifactId>
  <extensions>true</extensions>
...
</plugin>
```
```


Question:
In ruby I am parsing a date in the following format: 24092008.
I want to convert each section (year, month, date) into a number.

I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.

  date =~ /^([\d]{2})([\d]{2})([\d]{4})/
  year = Integer($3)
  month = Integer($2)
  day = Integer($1)

When it hits the month line it crashes as follows:

`Integer': invalid value for Integer: "09" (ArgumentError)

It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").

Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?

Thanks.

Answer:
I'm not familiar with regexes, so forgive me if this answer's off-base.  I've been assuming that $3, $2, and $1 are strings.  Here's what I did in IRB to replicate the problem:
```
```
irb(main):003:0> Integer("04")
=> 4
irb(main):004:0> Integer("09")
ArgumentError: invalid value for Integer: "09"
    from (irb):4:in `Integer'
    from (irb):4
    from :0
```
```
But it looks like .to_i doesn't have the same issues:
```
```
irb(main):005:0> "04".to_i
=> 4
irb(main):006:0> "09".to_i
=> 9
```
```


Question: Puzzled by the Lua 5.0 documentation references to things like _LOADED, LUA_PATH, _ALERT and so on (that I could not use in Lua 5.1), I discovered all of those have been removed and the functionality put elsewhere. Am I right in thinking that the only one global variable left in Lua 5.1 is _VERSION?

Answer:
I'm not familiar with regexes, so forgive me if this answer's off-base.  I've been assuming that $3, $2, and $1 are strings.  Here's what I did in IRB to replicate the problem:
```
```
irb(main):003:0> Integer("04")
=> 4
irb(main):004:0> Integer("09")
ArgumentError: invalid value for Integer: "09"
    from (irb):4:in `Integer'
    from (irb):4
    from :0
```
```
But it looks like .to_i doesn't have the same issues:
```
```
irb(main):005:0> "04".to_i
=> 4
irb(main):006:0> "09".to_i
=> 9
```
```


Question: So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures?

Answer:
When you will need a function in the future which performs a task that you have decided upon now.
For example, if you read a config file and one of the parameters tells you that the
```
hash_method
```
for your algorithm is
```
multiply
```
rather than
```
square
```
, you can create a closure that will be used wherever you need to hash something.
The closure can be created in (for example)
```
config_parser()
```
; it creates a function called
```
do_hash_method()
```
using variables local to
```
config_parser()
```
(from the config file). Whenever
```
do_hash_method()
```
is called, it has access to variables in the local scope of
```
config_parser()
```
even though it's not being called in that scope.
A hopefully good hypothetical example:
```
```
function config_parser()
{
    // Do some code here
    // $hash_method is in config_parser() local scope
    $hash_method = 'multiply';

    if ($hashing_enabled)
    {
        function do_hash_method($var)
        {
            // $hash_method is from the parent's local scope
            if ($hash_method == 'multiply')
                return $var * $var;
            else
                return $var ^ $var;
        }
    }
}

function hashme($val)
{
    // do_hash_method still knows about $hash_method
    // even though it's not in the local scope anymore
    $val = do_hash_method($val)
}
```
```


Question:
I need to store a list of key value pairs of (integer, boolean) in .NET

When I use a dictionary it re-orders them.  Is there a built in collection that will handle this.

Answer:
```
```
List<KeyValuePair<int, bool>> l =
                        new List<KeyValuePair<int, bool>>();
    l.Add(new KeyValuePair<int, bool>(1, false));
```
```


Question:
For some reason when I create a new namespace in Visual Studio 2008 its not being recognized. I'm using asp.net mvc, I don't know if that has anything to do with it.

Has anyone come across this before?...and how do you fix it?
Also is there a way to force Visual Studio to maybe re-examine new namespaces?

Answer:
I figured out the problem...check it.

Answer:
Questions:
Is the namespace and class thats not being picked up in the same project or is it referenced?
Is this a vb or a c# project? - I cant remember which way round (think its c#) but one of them defaults the root namespace to the project name. You can run into problems or get a confusing namespace e.g MyProject.MyProject if you create one at the same level of the root namespace.
Couple of things to try:
Press ctrl alt b to rebuild the project does it pick up the namespace?
Add a new method to an existing class that is working - is this picked up?
Try creating a completley different namespace is this picked up e.g.
namespace StackOverflow.Test
{
}
Finally have seen studio not pick up new namespaces and methods when its not compiling properly. This can be due to NTFS permissions and read only permissions. Check the build date of the dll. You can also try clearing ASP.net temporary files.


Question: What are the best SNMP libraries to use with .NET?  Specifically for listening for traps or sending set or get requests.

Answer:
here's a library and a few examples
http://www.c-sharpcorner.com/UploadFile/malcolmcrowe/SnmpLib11232005011613AM/SnmpLib.aspx


Question:
Specifically, when you create an interface/implementor pair, and there is no overriding organizational concern (such as the interface should go in a different assembly ie, as recommended by the s# architecture) do you have a default way of organizing them in your namespace/naming scheme?

This is obviously a more opinion based question but I think some people have thought about this more and we can all benefit from their conclusions.

Answer:
What I generally do is to create an Interfaces namespace at a high level in my hierarchy and put all interfaces  in there (I do not bother to nest other namespaces in there as I would then end up with many namespaces containing only one interface).
```
```
Interfaces
|--IAnimal
|--IVegetable
|--IMineral
MineralImplementor
Organisms
|--AnimalImplementor
|--VegetableImplementor
```
```
This is just the way that I have done it in the past and I have not had many problems with it, though admittedly it might be confusing to others sitting down with my projects.  I am very curious to see what other people do.


Question:
I can't use the Get*Profile functions because I'm using an older version of the Windows CE platform SDK which doesn't have those. It doesn't have to be too general.

[section]
name = some string

I just need to open the file, check for the existence of "section", and the value associated with "name". Standard C++ is preferred.

Answer:
I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:
```
```
MyDependencyProperty.OverrideMetadata(typeof(MyNewType),
                     new PropertyMetadata());
```
```


Question:
I am using virtual machines for development,but each time I need a new VM, I copy the file and create a new server, but I need a new name for the server to add it to our network.

After renaming the server, the Sharepoint sites have many errors and do not run.

Answer:
I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:
```
```
MyDependencyProperty.OverrideMetadata(typeof(MyNewType),
                     new PropertyMetadata());
```
```


Question:
I have a project the requires the use of the exec family. My project consist of making an interactive shell. The shell will implement a few basic commands like cd, ls, echo, etc. I have been researching the use of exec, but have not found a useful site. Any suggested links would help.

int ret;
ret = execl ("/bin/ls", "ls", "-1", (char *)0);

How would i get the output of this operation to show on the screen?

Answer:
doing
```
```
int fd = 1;
dup(fd);
close(fd);
```
```
gets the output to the screen.


Question:
I am a firm believer in the idea that one of the most important things you get from learning a new language is not how to use a new language, but the knowledge of concepts that you get from it. I am not asking how important or useful you think Assembly is, nor do I care if I never use it in any of my real projects.

What I want to know is what concepts of Assembly do you think are most important for any general programmer to know? It doesn't have to be directly related to Assembly - it can also be something that you feel the typical programmer who spends all their time in higher-level languages would not understand or takes for granted, such as the CPU cache.

Answer:
Memory, registers, jumps, loops, shifts and the various operations one can perform in assembler.  I don't miss the days of debugging my assembly language class programs - they were painful! - but it certainly gave me a good foundation.
We forget (or never knew, perhaps) that all this fancy-pants stuff that we use today (and that I love!) boils down to all this stuff in the end.
Now, we can certainly have a productive and lucrative career without knowing assembler, but I think these concepts are good to know.


Question:
How can I access UserId in ASP.NET Membership without using Membership.GetUser(username) in ASP.NET Web Application Project?

Can UserId be included in Profile namespace next to UserName (System.Web.Profile.ProfileBase)?

Answer:
Is your reason for this to save a database call everytime you need the UserId? If so, when I'm using the ASP.NET MembershipProvider, I usually either do a custom provider that allows me to cache that call, or a utility method that I can cache.
If you're thinking of putting it in the Profile, I don't see much reason for doing so, especially as it also will still require a database call and unless you are using a custom profile provider there, it has the added processing of parsing out the UserId.
If you're wondering why they did not implement a GetUserId method, it's simply because you're not always guaranteed that that user id will be a GUID as in the included provider.
EDIT:
See
ScottGu's article on providers
which provides a
link to downloading the actual source code for i.e. SqlMembershipProvider
.
But the simplest thing to do really is a GetUserId() method in your user object, or utility class, where you get the UserId from cache/session if there, otherwise hit the database, cache it by username (or store in session), and return it.
For something more to consider (but be very careful because of cookie size restrictions):
Forms Auth: Membership, Roles and Profile with no Providers and no Session


Question: Is there any way to see an overview of what kind of queries are spent the most time on every day on MySQL?

Answer:
You can always set up query logging as described here:
http://dev.mysql.com/doc/refman/5.0/en/query-log.html


Question:
I have the following problem:

I have an HTML textbox (<input type="text">) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).

I want to be notified in my script every time the value of that textbox changes, so I can react to it.

I've tried this:

txtStartDate.observe('change', function() { alert('change' +  txtStartDate.value) });

which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.

Is there another event I can listen to, that i'm not aware of?

I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com)

Answer:
As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events.  Your only solution is to find some hook into the control that you can hook up to your listener.
Here is how I would do it:
```
```
basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) {
  myListener(year,month,day);
  return orig(year,month,day,hide);
});
```
```
That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well.


Question:
I'm writing some semi-portable code and want to be able to detect when I'm compiling for iPhone. So I want something like #ifdef IPHONE_SDK....

Presumably Xcode defines something, but I can't see anything under project properties, and Google isn't much help.

Answer:
It's in the SDK docs under "Compiling source code conditionally"
The relevant definitions are TARGET_OS_IPHONE (and he deprecated TARGET_IPHONE_SIMULATOR), which are defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:
```
```
#include "TargetConditionals.h"
```
```
but this is no longer necessary on the current (xCode 6/iOS8) toolchain.
So, for example, if you want to only compile a block of code if you are building for the device, then you should do
```
```
#if !(TARGET_OS_SIMULATOR)
...
#endif
```
```


Question:
One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a this. For example: this.process(this.event).

A few of my students commented on this, and I'm wondering if I am teaching bad habits.

My rationale is:

Makes code more readable — Easier to distinguish fields from local variables.

Makes it easier to distinguish standard calls from static calls (especially in Java)

Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.

Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?

Note: I turned it into a CW since there really isn't a correct answer.

Answer:
I think it's less readable, especially in environments where fields are highlighted differently from local variables.  The only time I want to see "this" is when it is required, for example:
```
```
this.fieldName = fieldName
```
```
When assigning the field.
That said, if you need some way to differentiate fields for some reason, I prefer "this.fieldName" to other conventions, like "m_fieldName" or "_fieldName"


Question: When you create a new web user control in visual studio it by default adds the Page_Load event.  What is the advantage to using this rather than overriding the base OnLoad event on the control?  Is it just that the Page_Load event fires before OnLoad?

Answer:
The
```
OnLoad
```
method should be the place where the
```
Load
```
event is raised.  I personally always try to handle the event unless I need to do extra processing around raising the event.
I recommend handling the event itself under normal circumstances.


Question: Is there a way to have Visual Studio 2008 automatically add heading information to files? For example, "Copyright 2008" or something along those lines. I've been digging through the options, but nothing seems to be jumping out at me.

Answer:
I assume you'd like to modify the class file templates.  They're in:
```
```
%ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033
```
```
More specific details here


Question:
In other words, is it correct to use:

public class CustomerList : System.Collections.Generic.List<Customer>
{
    /// supposed to be empty
}

instead of:

using CustomerList = System.Collections.Generic.List<Customer>

I'd rather use the first approach because I'd just define CustomerList once, and every time I needed a customer list I'd always use the same type. On the other hand, using the name aliasing approach not only forces me to have to redefine it everywhere, but also a different alias could be given every time someone wanted to use it (think of a big team), and thus cause the code to be less readable.

Please note that the intention in this case would never be to extend the class, just to create an alias.

Answer:
well, unless you are adding some functionality to the base class there is no point in creating a wrapper object.  I would go with number two if you really need to, but why not just create a variable?
```
```
List<Customer> customerList = new List<Customer>();
```
```


Question:
I am programming a UNIX shell and I have to use the execv() system call to create a process.
One of the parameters for execv() is the filepath for the executable.  So if somebody types in /bin/ls, it will run the ls executable.  But what I need is a function such that when ls is typed, it will search for the filepath of ls (like the which command).  Is there a function which allows me to do that?

Unfortunately, this is a school project and I am not allowed to use execvp(). I need to implement some path searching function and then add that filepath to the execv() parameter.

Answer:
I think execvp() does what you need.
Edit:
So you're actually asking how to do this manually? In that case...
Find your PATH in envp (3rd argument to main())
Split this into individual paths
Check for your program's existance in each of these with stat()
Execute the first one you find to exist
Or if you want a
really
solid implementation, use
this
. It might set off the plagarism detectors though :)


Question: Does iPhone support XML-RPC, Is their any open source framework which I can use?

Answer:
Checkout the source for the wordpress app.  They might be using XML-RPC. :)
http://iphone.wordpress.org/


Question:
I'm not asking this question because of the merits of garbage collection first of all.  My main reason for asking this is that I do know that Bjarne Stroustrup has said that C++ will have a garbage collector at some point in time.

With that said, why hasn't it been added?  There are already some garbage collectors for C++.  Is this just one of those "easier said than done" type things?  Or are there other reasons it hasn't been added (and won't be added in C++11)?

Cross links:

Garbage collectors for C++

Just to clarify, I understand the reasons why C++ didn't have a garbage collector when it was first created.  I'm wondering why the collector can't be added in.

Answer:
What type? should it be optimised for embedded washing machine controllers, cell phones, workstations or supercomputers?
Should it prioritise gui responsiveness or server loading?
should it use lots of memory or lots of CPU?
C/c++ is used in just too many different circumstances.
I suspect something like boost smart pointers will be enough for most users
Edit - Automatic garbage collectors aren't so much a problem of performance (you can always buy more server) it's a question of predicatable performance.
Not knowing when the GC is going to kick in is like employing a narcoleptic airline pilot, most of the time they are great - but when you really need responsiveness!


Question:
I am trying to understand some assembly.

The assembly as follows, I am interested in the testl line:

000319df  8b4508        movl   0x08(%ebp), %eax
000319e2  8b4004        movl   0x04(%eax), %eax
000319e5  85c0          testl  %eax, %eax
000319e7  7407          je     0x000319f0

I am trying to understand that point of testl between %eax and %eax? I think the specifics of what this code isn't important, I am just trying to understand the test with itself - wouldn't the value always be true?

Answer:
It tests whether
```
eax
```
is 0, or above, or below. In this case, the jump is taken if
```
eax
```
is 0.


Question:
What web app architecture works well receiving/sending SMS text messages? By "architecture, I mean specific architecture, not generally, such as MVC.

Background: I'm building a web app that receives queries from/sends answers to cell phones. The app design (and business model) expects to communicate with cell devices via SMS text messages. IOW: There is no MVC web page "view". The cell phone screen is effectively the "view".

Answer:
This depends on how you will be receiving and sending the SMS messages.
There is a specific Short message protocol (SMPP -
http://en.wikipedia.org/wiki/SMPP
).
For that you will need an SMPP server.
If you are using a one of the various SMS over HTTP providers (such as Clickatell -
http://www.clickatell.com
), then a web framework such as RoR is fine as both the sending and receiving of SMS messages are actually web requests.
In this case your system view is the HTTP response to the gateway, not the cellphone screen. There are actually quite a few steps involved:
```
Cellphone -> Cellular Network -> Gateway -> Your Service
```
and the reply:
```
Cellphone <- Cellular Network <- Gateway <- Your Service
```


Question:
What is the practical benefit of using HTTP GET, PUT, DELETE, POST, HEAD? Why not focus on their behavioral benefits (safety and idempotency), forgetting their names, and use GET, PUT or POST depending on which behavior we want?

Why shouldn't we only use GET, PUT and POST (and drop HEAD, DELETE)?

Answer:
The [REST][1] approach uses POST, GET, PUT and DELETE to implement the CRUD rules for a web resource.  It's a simple and tidy way to expose objects to requests on the web.  It's web services without the overheads.
Just to clarify the semantic differences.  Each operation is rather different.  The point is to have nice HTTP methods that have clear, distinct meanings.
POST creates new objects.  The URI has no key; it accepts a message body that defines the object.  SQL Insert.  [
Edit
While there's no technical reason for POST to have no key, the REST folks suggest strongly that for POST to have distinct meaning as CREATE, it should not have a key.]
GET retrieves existing objects. The URI
may
have a key, depends on whether you are doing singleton GET or list GET.  SQL Select
PUT updates an existing object.  The URI has a key; It accepts a message body that updates an object.  SQL Update.
DELETE deletes an existing object.  The URI has a key.  SQL Delete.
Can you update a record with POST instead of PUT?  Not without introducing some ambiguity.  Verbs should have unambiguous effects.  Further, POST URI's have no key, where PUT must have a key.
When I POST, I expect a 201 CREATED.  If I don't get that, something's wrong.  Similarly, when I PUT, I expect a 200 OK.  If I don't get that, something's wrong.
I suppose you could insist on some ambiguity where POST does either POST or PUT.  The URI has to be different; also the associated message could be different.  Generally, the REST folks take their cue from SQL where INSERT and UPDATE are different verbs.
You could make the case that UPDATE should insert if the record doesn't exist or update if the record does exist.  However, it's simpler if UPDATE means UPDATE and failure to update means something's wrong.  A secret fall-back to INSERT makes the operation ambiguous.
If you're not building a RESTful interface, then it's typical to only use GET and POST for retrieve and create/update. It's common to have URI differences or message content differences to distinguish between POST and PUT when a person is clicking submit on a form.   It, however, isn't very clean because your code has to determine if you're in the POST=create case or POST=update case.


Question:
I'm wondering how you'd implement the following use-case in REST. Is it even possible to do without compromising the conceptual model?

Read or update multiple resources within the scope of a single transaction. For example, transfer $100 from Bob's bank account into John's account.

As far as I can tell, the only way to implement this is by cheating. You could POST to the resource associated with either John or Bob and carry out the entire operation using a single transaction. As far as I'm concerned this breaks the REST architecture because you're essentially tunneling an RPC call through POST instead of really operating on individual resources.

Answer:
You'd have to roll your own "transaction id" type of tx management.  So it would be 4 calls:
```
```
http://service/transaction (some sort of tx request)
http://service/bankaccount/bob (give tx id)
http://service/bankaccount/john (give tx id)
http://service/transaction (request to commit)
```
```
You'd have to handle the storing of the actions in a DB (if load balanced) or in memory or such, then handling commit, rollback, timeout.
Not really a RESTful day in the park.


Question: Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to display: none;, the table with shrinks to fit the contents of the visible rows.

Answer:
If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:
```
```
table.style.width = table.clientWidth + "px";
table.rows[3].style.display = "none";
```
```
However, this may cause the individual columns to reflow when you hide the row. A possible way to mitigate this is by adding a style to your table:
```
```
table {
  table-layout: fixed;
 }
```
```


Question: I have a T-SQL table variable (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done?

Answer:
Truncating the table will dump ALL the data, and reset the identity seed.
Otherwise, you can use this call to reset the identity while retaining any of the data:
```
```
DBCC CHECKIDENT (yourtableName, reseed, @NewStartSeedValue)
```
```


Question: The GetVersions() call to the Versions.asmx web service in SharePoint 2003 returns a localised date format, with no way of determining what the format is. It's the site regional setting of date format, but I can't find a way to get even that out of SharePoint 2003. Locally, it looks like SPRegionalSettings can be used (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spregionalsettings.aspx) but what about a web service version of this?

Answer:
Sadly, it isn't available. However, you can specify a query option to specify that you want the values returned in UTC:
http://www.sharepointblogs.com/pm4everyone/archive/2006/10/03/sharepoint-2003-querying-with-gmt-datetime.aspx


Question:
Here's what I am trying to do:

typedef enum { ONE, TWO, THREE } Numbers;

I am trying to write a function that would do a switch case similar to the following:

char num_str[10];
int process_numbers_str(Numbers num) {
  switch(num) {
    case ONE:
    case TWO:
    case THREE:
    {
      strcpy(num_str, num); //some way to get the symbolic constant name in here?
    } break;
    default:
      return 0; //no match
  return 1;
}

Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above?

Answer:
There's no built-in solution. The easiest way is with an array of
```
char*
```
where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse
```
enum
```
(one that doesn't start at 0 or has gaps in the numbering) where some of the
```
int
```
mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.


Question:
I currently have heavily multi-threaded server application, and I'm shopping around for a good multi-threaded memory allocator.

So far I'm torn between:

Sun's umem

Google's tcmalloc

Intel's threading building blocks allocator

Emery Berger's hoard

From what I've found hoard might be the fastest, but I hadn't heard of it before today, so I'm skeptical if its really as good as it seems. Anyone have personal experience trying out these allocators?

Answer: Maybe this is the wrong way to approach what you are asking, but maybe a different tactic could be employed altogether. If you are looking for a really fast memory allocator maybe you should ask why you need to be spending all that time allocating memory when you could perhaps just get away with stack allocation of variables. Stack allocation, while way more annoying, done right could save you lots in the way of mutex contention, as well as keeping strange memory corruption issues out of your code. Also, you potentially have less fragmentation which could help.


Question:
I need to accept form data to a WCF-based service. Here's the interface:

[OperationContract]
[WebInvoke(UriTemplate = "lead/inff",
    BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int Inff(Stream input);

Here's the implementation (sample - no error handling and other safeguards):

public int Inff(Stream input)
{

    StreamReader sr = new StreamReader(input);
    string s = sr.ReadToEnd();
    sr.Dispose();

    NameValueCollection qs = HttpUtility.ParseQueryString(s);
    Debug.WriteLine(qs["field1"]);
    Debug.WriteLine(qs["field2"]);

    return 0;
}

Assuming WCF, is there a better way to accomplish this besides parsing the incoming stream?

Answer:
I remember speaking to you about this at DevLink.
Since you have to support form fields the mechanics of getting those (what you are currently doing) don't change.
Something that might be helpful, especially if you want to reuse your service for new applications that don't require the form fields is to create a channel that deconstructs your stream and repackages it to XML/JSON/SOAP/Whatever and have your form clients communicate with the service through that while clients that don't use forms can use another channel stack. Just an idea...
Hope that helps. If you need help with the channel feel free to let me know.


Question:
In general, what needs to be done to convert a 16 bit Windows program to Win32? I'm sure I'm not the only person to inherit a codebase and be stunned to find 16-bit code lurking in the corners.

The code in question is C.

Answer:
The original win32 sdk had a tool that scanned source code and flagged lines that needed to be changed, but I can't remember the name of the tool.
When I've had to do this in the past, I've used a brute force technique - i.e.:
1 - update makefiles or build environment to use 32 bit compiler and linker. Optionally, just create a new project in your IDE (I use Visual Studio), and add the files manually.
2 - build
3 - fix errors
4 - repeat 2&3 until done
The pain of the process depends on the application you are migrating. I've converted 10,000 line programs in an hour, and 75,000 line programs in less than a week. I've also had some small utilities that I just gave up on and rewrote (mostly) from scratch.


Question: In one of my ASP.NET Web Applications, I am using a BulkEditGridView (a GridView which allows all rows to be edited at the same time) to implement an order form. In my grid, I have a column which calculates the total for each item (cost x quantity) and a grand total field at the bottom of the page. Currently, however, these fields are only refreshed on every post-back. I need to have these fields updated dynamically so that as users change quantities, the totals and grand total update to reflect the new values. I have attempted to use AJAX solutions to accomplish this, but the asynchronous post-backs interfere with the focus on the page. I imagine that a purely client-side solution exists, and I'm hopeful that someone in the community can share.

Answer:
One solution is to build some javascript in you RowDataBound method to constantly update those totals when the textboxes change.
So during the RowDataBound, start building a javascript string in memory that will add up the textboxes you need added. What's nice in RowDataBound is you can get the Client Side id's of these textboxes by calling TextBox.ClientId.
Add this javascript to the page, then also add an onkeyup event to each textbox you require to call this script.
So something like (this is a row bound event from a gridview)
```
```
private string _jscript;
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      //Get your textbox
      Textbox tb = e.Row.FindControl("tbAddUp");
      //Add the event that you're going to call to this textbox's attributes
      tb.Attributes.Add("onkeyup", "MyAddUpJavaScriptMethod();");
      //Build the javascript for the MyAddUpJavaScriptMethod
      jscript += "document.getElementById('" + tb.ClientId + '").value + ";
   }
}
```
```
Then once you've built that whole script, use your Page.ClientScript class to add a method to you page which will be called by your onkeyup in your textboxes "MyAddUpJavaScriptMethod"
Hope that makes sense and helps


Question:
So, one commonly heard comment when talking about performance is that you write your code with whatever language gets the job done fastest. If performance in specific areas is a problem, then rewrite those bits in C/C++.

But, what if you're starting with a native C++ app? What options do you have if you want to write the easy bits, or refactor the old bits, in a language like Python, Ruby, C#, or whatever? Keep in mind that transferring data between the native and other sides is a must. Being able to simply call a function written in an "easier" language, while passing C++ classes as data, would be beautiful.

We've got a crusty Win32 app that would benefit greatly if we could crank out new code, or refactor old code, in C# or something. Very little of it requires the complexity of C++, and dealing with the little fiddly bits is dragging down the programming process.

Answer:
If you want to work between C++ and Python, than
Boost Python
is what you're looking for.  You can write C Python bindings by hand for Cython, but that limits in many ways how you're going to write your code.  This is the easiest way, as seen in some snippets from
this tutorial
:
A simple function that performs a hello world:
```
```
char const* greet()
{
   return "hello, world";
}
```
```
The Boost python code needed to expose it to python:
```
```
#include <boost/python.hpp>

BOOST_PYTHON_MODULE(hello_ext)
{
    using namespace boost::python;
    def("greet", greet);
}
```
```
How to use this code from python:
```
```
>>> import hello_ext
>>> print hello.greet()
hello, world
```
```
Going in the opposite direction is  bit tougher, since python doesn't compile to native code.  You have to embed the python interpreter into your C++ application, but the work necessary to do that is documented
here
.  This is an example of calling the python interpreter and extracting the result (the python interpreter defines the object class for use in C++):
```
```
object result = eval("5 ** 2");
int five_squared = extract<int>(result);
```
```


Question:
In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:

For Each item As Host In hostCollection1
    hostCollection2.Add(item)
Next

My collections are generic collections, inherited from the base class -- Collection(Of )

Answer:
I know you're asking for VB, but in C# you can just use the constructor of the collection to initialize it with any IEnumerable.  For example:
```
```
List<string> list1 = new List<string>();
list1.Add("Hello");
List<string> list2 = new List<string>(list1);
```
```
Perhaps the same kind of thing exists in VB.


Question:
I have a self built JSP webapp and at the moment I'm using tomcats built in admin pannel to manage user accounts (that are stored in tomcats config xml files) but this is limited because i can not create new accounts from within the web-app (eg. I can not have a sign up website) and need to manually create the accounts.

What is the most straight forward way of implementing accounts in a tomcat environment?

dennis

Answer:
Set up a
database realm in Tomcat
, either a simple JDBC realm or a DataSource realm that will allow for connection pooling. Then adding users is a very simple CRUD web application, possibly combined with some confirmation emails.


Question:
It is much more convenient and cleaner to use a single statement like

import java.awt.*;

than to import a bunch of individual classes

import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...

What is wrong with using a wildcard in the import statement?

Answer:
The only problem with it is that it clutters your local namespace.  For example, let's say that you're writing a Swing app, and so need
```
java.awt.Event
```
, and are also interfacing with the company's calendaring system, which has
```
com.mycompany.calendar.Event
```
.  If you import both using the wildcard method, one of these three things happens:
You have an outright naming conflict between
```
java.awt.Event
```
and
```
com.mycompany.calendar.Event
```
, and so you can't even compile.
You actually manage only to import one (only one of your two imports does
```
.*
```
), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
When you compile your code there is no
```
com.mycompany.calendar.Event
```
, but when they later add one your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly
wrong
, but future maintainers will thank you for your clarity otherwise.


Question:
I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous.

Now, the documentation says that the 5th parameter (see below) controls this.  Specifically, when you pass 'false' it's supposed to be a non-asynchronous call.  However, regardless if it's true or false, it still processes the call asynchronously.

Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);

Is there a work-around for this or perhaps I'm doing something wrong?

Answer:
ASPX Page
```
```
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="How-to-use-GetCallbackEventReference.aspx.vb" Inherits="How_to_use_Callback" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>How to use GetCallbackEventReference</title>

    <form id="form1" runat="server">

        <input id="Button1" type="button" value="Get Random Number" onclick="GetNumber()" />

        <asp:TextBox ID="txtGetNumber" runat="server"></asp:TextBox>

    </form>

```
```
Code Behind
```
```
Partial Class How_to_use_Callback
    Inherits System.Web.UI.Page
    Implements System.Web.UI.ICallbackEventHandler
    Dim CallbackResult As String = Nothing
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "GetRandomNumberFromServer", "context")
        Dim cbScript As String = "function UseCallback(arg,context)" & "{" & cbReference & " ; " & "}"
        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "UseCallback", cbScript, True)
    End Sub

    Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
        Return CallbackResult
    End Function

    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
        CallbackResult = Rnd().ToString()
    End Sub
End Class
```
```


Question:
I've developed a Visual C#.NET 2008 Express Edition solution containing three projects. I am cleaning it up to commit it into a CVS repository.

There are several files that are created during the build process that are not necessary to be placed in the repository since they will be regenerated automatically.

The question: Can anyone suggest a list of patterns to be placed into a .cvsignore file so that these generated files and folders are ignored?

Answer:
Typically these are the only things that you
have
to commit:
.sln files
.cs files
.csproj files
.config files
External DLLs and corresponding XML/config files that you are referencing
other non-generated files that your application uses
All the rest are to be ignored, including:
.suo files
.csproj.user files
/bin folder and contents
/obj folder and contents
practically everything else


Question:
Given the following XML structure

<html>
  <body>
    <div>
      <span>Test: Text2</span>
    </div>
    <div>
      <span>Test: Text3</span>
    </div>
    <div>
      <span>Test: Text5</span>
    </div>
  </body>
</html>

What is the best XPath query to locate any span with text that starts with Test?

Answer:
```
```
//span[starts-with(.,'Test')]
```
```
References:
http://www.w3.org/TR/xpath/#function-starts-with
https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/starts-with


Question: Is it possible to include one CSS file in another?

Answer:
Yes:
```
```
@import url("base.css");
```
```
Note:
The
```
@import
```
rule
must precede
all other rules (except
```
@charset
```
).
Additional
```
@import
```
statements require additional server requests. As an alternative, concatenate all CSS into one file to avoid multiple HTTP requests. For example, copy the contents of
```
base.css
```
and
```
special.css
```
into
```
base-special.css
```
and reference only
```
base-special.css
```
.


Question:
Given a string with a module name, how do you import everything in the module as if you had called:

from module import *

i.e. given string S="module", how does one get the equivalent of the following:

__import__(S, fromlist="*")

This doesn't seem to perform as expected (as it doesn't import anything).

Answer:
Please reconsider. The only thing worse than
```
import *
```
is
magic
```
import *
```
.
If you really want to:
```
```
m = __import__ (S)
try:
    attrlist = m.__all__
except AttributeError:
    attrlist = dir (m)
for attr in attrlist:
    globals()[attr] = getattr (m, attr)
```
```


Question:
How do you calculate the least common multiple of multiple numbers?

So far I've only been able to calculate it between two numbers. But have no idea how to expand it to calculate 3 or more numbers.

So far this is how I did it

LCM = num1 * num2 /  gcd ( num1 , num2 )

With gcd is the function to calculate the greatest common divisor for the numbers. Using euclidean algorithm

But I can't figure out how to calculate it for 3 or more numbers.

Answer:
You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.
```
```
lcm(a,b,c) = lcm(a,lcm(b,c))
```
```


Question:
Are there any IDE's for developing HLSL code?  The three key features I want are:

1) syntax highlighting

2) auto-complete

3) interaction debugging

Visual Studio doesn't do any of these things, and it doesn't seem that RenderMonkey or FX Composer do either.

Is there some IDE that I'm not aware of, or does one of these three IDE's actually support these features and I'm too clueless to figure out how to use them properly?

Answer:
Have you actually tried ATI's RenderMoney or NVidia's FX Composer?
Both actually provide syntax highlighting. Futher more, NVidia's Cg toolkits actually allows you to enable syntaxhightling in Visual Studio with some custom setting.
As for auto-completion, I don't think it's much needed as compare to our normal programming. It's because you won't be writing a very long code for your shader programming. Shader is quite critical in that it is run on every frame generated, and every instruction require 1 to a few clock cycle to execute, thus there's always a physical limit to how long you can afford to write.
Interactive debugging is currently the limitation of GPU hardware. To actually do that, the GPU has to be emulated with our CPU, which is quite impossible considering that the REF (software rendering) device can never cop up with even obsolete GPU, what more to say about emulating shader.


Question:
class someclass {};

class base
{
    int a;
    int *pint;
    someclass objsomeclass;
    someclass* psomeclass;
public:
    base()
    {
        objsomeclass = someclass();
        psomeclass = new someclass();
        pint = new int();
        throw "constructor failed";
        a = 43;
    }
}

int main()
{
    base temp();
}

In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?

int main()
{
    base *temp = new base();
}

How about in the above code? How can the memory leaks be avoided after the constructor throws?

Answer:
Everything you "new" needs to be deleted, or you'll cause a memory leak. So these two lines:
```
```
psomeclass = new someclass();
pint = new int();
```
```
Will cause memory leaks, because you need to do:
```
```
delete pint;
delete psomeclass;
```
```
In a finally block to avoid them being leaked.
Also, this line:
```
```
base temp = base();
```
```
Is unnecessary. You just need to do:
```
```
base temp;
```
```
Adding the "= base()" is unnecessary.


Question:
in Javascript, the following:

var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/".*?"/g);
alert(result);

yields "the quick","brown fox","jumps over","the lazy dog"

I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog

what regexp will do this?

Answer:
You can use the
Javascript replace() method
to strip them out.
```
```
var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';

var result = test.replace(/"/, '');
```
```
Is there more to it than just getting rid of the double-quotes?


Question:
What is the best way to detect if a user leaves a web page?

The onunload JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser).

Creating one will probably be blocked by current browsers.

Answer:
One (slightly hacky) way to do it is replace and links that lead away from your site with an AJAX call to the server-side, indicating the user is leaving, then use that same javascript block to take the user to the external site they've requested.
Of course this won't work if the user simply closes the browser window or types in a new URL.
To get around that, you'd potentially need to use Javascript's setTimeout() on the page, making an AJAX call every few seconds (depending on how quickly you want to know if the user has left).


Question:
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading.

What is the best way to achieve this?

Answer:
There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than).
However; if you just want it to work, then in .NET 3.5 there are some options...
I have put together a library
here
that allows efficient and simple access to operators with generics - such as:
```
```
T result = Operator.Add(first, second); // implicit <T>; here
```
```
It can be downloaded as part of
MiscUtil
Additionally, in C# 4.0, this becomes possible via
```
dynamic
```
:
```
```
static T Add<T>(T x, T y) {
    dynamic dx = x, dy = y;
    return dx + dy;
}
```
```
I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as
```
```
interface ICalc<T>
{
    T Add(T,T)()
    T Subtract(T,T)()
}
```
```
etc, but then you need to pass an
```
ICalc<T>;
```
through all the methods, which gets messy.


Question: I have Eclipse setup with PyDev and love being able to debug my scripts/apps.  I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?

Answer:
Create a new launch configuration (Python Run)
Main tab
Use paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory)
Don't forget to add the root folder of your application in the PYTHONPATH zone
Arguments
Set the base directory to the root folder also.
As Program Arguments use "serve development.ini" (or whatever you use to debug your app")
Common Tab
Check allocate console and launch in background


Question: How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET.

Answer:
Execute:
```
SELECT name FROM master.sys.databases
```
This the preferred approach now, rather than
```
dbo.sysdatabases
```
, which has been deprecated for some time.
Execute this query:
```
```
SELECT name FROM master.dbo.sysdatabases
```
```
or if you prefer
```
```
EXEC sp_databases
```
```


Question: How can I extract the list of available SQL servers in an SQL server group? I'm planning to put that list in a combo box in VB.NET.

Answer:
The only way I knew to do it was using the command line:
```
```
osql -L
```
```
But I found the below article which seems to solve your specific goal filling a combobox:
http://www.sqldbatips.com/showarticle.asp?ID=45


Question:
I'm looking at ways to deploy a Ruby on Rails app (running on JRuby) to a Tomcat instance for testing.

The tomcat instance is running on a Solaris server that I can SSH to. I've looked at using Capistrano, but there doesn't seem to be a lot out there about using it to deploy to Tomcat, or even about running it under JRuby, and I keep hitting bugs in Capistrano due to the Windows/JRuby environment my PC is running (yeah, it's corporate - not my choice, but I've got to live with it).

I'm using warble to build the .war file, and the app deploys and runs fine once I manually copy it up and deploy it. I'm wanting something easier and more automated to actually get it there.

Anyone done this before? Documentation on the web seems pretty thin.

Answer:
I don't have much experience on this, so I don't know if I can give you the BEST way, but if Capistrano doesn't work, and you can't have a separate MRI install just to run it, you have just a few alternatives left:
Try running plain Rake and write your own deployment target:
http://www.gra2.com/article.php/deploy-ruby-on-rails-applications-rake
Or use Ant or Maven.
Or if it just ONE server you have to deploy to, you could just hack together two Ruby scripts - one that listens on the server for shutdown/startup requests, and one local that you run to: Send shutdown, scp over the file, send startup.
By the way, have you submitted any integration bugs you find with Capistrano to the JRuby team? I'm sure they'd be happy to have any contribution.
:)


Question: How do you calculate the length of the string that would be returned by Array::pack?  Is there something like Python's calcsize?

Answer:
By making an interpreter complying to the specifications found in
Array::pack
.
Or, reusing the existing implementation to count the number of characters instead of appending them to a string.


Question:
In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so:

unsigned long value = 0xdeadbeef;
value &= ~(1<<10);

How do I do that in Python ?

Answer:
```
```
value = 0xdeadbeef
value &= ~(1<<10)
```
```


Question: Is there a Delphi equivalent of the C# #if(DEBUG) compiler directive?

Answer:
Use this:
```
```
{$IFDEF DEBUG}
...
{$ENDIF}
```
```


Question:
In a text file, there is a string "I don't like this".

However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use

f1 = open (file1, "r")
text = f1.read()

command to do the reading.

Now, is it possible to read the string in such a way that when it is read into the string, it is "I don't like this", instead of "I don\xe2\x80\x98t like this like this"?

Second edit: I have seen some people use mapping to solve this problem, but really, is there no built-in conversion that does this kind of ANSI to unicode ( and vice versa) conversion?

Answer:
Actually, U+2018 is the Unicode representation of the special character ‘ . If you want, you can convert instances of that character to U+0027 with this code:
```
```
text = text.replace (u"\u2018", "'")
```
```
In addition, what are you using to write the file?
```
f1.read()
```
should return a string that looks like this:
```
```
'I don\xe2\x80\x98t like this'
```
```
If it's returning
this
string, the file is being written incorrectly:
```
```
'I don\u2018t like this'
```
```


Question:
In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:

APPROVAL_CHOICES = (
    ('yes', 'Yes'),
    ('no', 'No'),
    ('cancelled', 'Cancelled'),
)

client_approved = models.CharField(choices=APPROVAL_CHOICES)

to create a drop down box in your form and force the user to choose one of those options.

I'm just wondering if there is a way to define a set of choices where multiple can be chosen using checkboxes? (Would also be nice to be able to say that the user can select a maximum number of them.) It seems like it's a feature that is probably implemented, it's just I can't seem to find it in the documentation.

Answer:
In terms of the forms library, you would use the
MultipleChoiceField
field with a
CheckboxSelectMultiple
widget to do that. You could validate the number of choices which were made by writing a validation method for the field:
```
```
class MyForm(forms.Form):
    my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())

    def clean_my_field(self):
        if len(self.cleaned_data['my_field']) > 3:
            raise forms.ValidationError('Select no more than 3.')
        return self.cleaned_data['my_field']
```
```
To get this in the admin application, you'd need to customise a ModelForm and
override the form used in the appropriate ModelAdmin
.


Question:
We are setting up a Selenium test campaign on a big web application.
The first thing we've done was to build a framework which initialize SQL data in database before the test, launch the test, archive results and then clear data.

We've integrate that in a Maven 2 process, run every day by TeamCity on a dedicated database.

We've set up several Selenium tests now but It's not as used as planned.

Reasons are that tests are sometimes broken for other reasons than regressions (data may have changed, stored procedure may have been recompiled and so on).

I would like to know if there are big success in user interface testing and if so, reasons to that. Commons errors may also interest me.

Answer:
I use http-unit which has the added benefit of working before any styling has been added to the page.
http://httpunit.sourceforge.net/
You can attach the tests to run in the integration test phase for maven2.
From the site
Written in Java, HttpUnit emulates the
  relevant portions of browser behavior,
  including form submission, JavaScript,
  basic http authentication, cookies and
  automatic page redirection, and allows
  Java test code to examine returned
  pages either as text, an XML DOM, or
  containers of forms, tables, and
  links.


Question: With the recent buzz on multicore programming is anyone exploring the possibilities of using MPI ?

Answer:
No, in my opinion it is unsuitable for most processing you would do on a multicore system.  The overhead is too high, the objects you pass around must be deeply cloned, and passing large objects graphs around to then run a very small computation is very inefficient. It is really meant for sharing data between separate processes, most often running in separate memory spaces, and most often running long computations.
A multicore processor is a shared memory machine, so there are much more efficient ways to do parallel processing, that do not involve copying objects and where most of the threads run for a very small time. For example, think of a multithreaded Quicksort. The overhead of allocating memory and copying the data to a thread before it can be partioned will be much slower with MPI and an
unlimited
number of processors than Quicksort running on a single processor.
As an example, in Java, I would use a BlockingQueue (a shared memory construct), to pass object
references
between threads, with very little overhead.
Not that it does not have its place, see for example the Google search cluster that uses message passing. But it's probably not the problem you are trying to solve.


Question:
I'm creating an installation script for an application that I'm developing and need to create databases dynamically from within PHP. I've got it to create the database but now I need to load in several .sql files. I had planned to open the file and mysql_query it a line at a time - until I looked at the schema files and realised they aren't just one query per line.

So, how do I load an sql file from within PHP (as phpMyAdmin does with its import command)?

Answer:
```
```
mysql_query("LOAD DATA LOCAL INFILE '/path/to/file' INTO TABLE mytable");
```
```


Question:
To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII.
Anyone has a clue?

Answer:
Why not let the window resize itself based on the runtime height/width?
Run something like this in your pop-up:
```
```
window.resizeTo(document.body.clientWidth, document.body.clientHeight);
```
```


Question:
I am already excited about document databases and especially about CouchDB's simplicity. But I have a hard time understanding if such databases are a viable option for multi user systems. Since those systems require some kind of relations between records which document databases do not provide.

Is it completely the wrong tool for such cases? Or some tagging and temporary views are the way to accomplish this? Or else...

UPDATE:

I understand the answers so far. But let me rephrase the question a bit. Lets say I have a load of semi-structured data which is normally a fit for CouchDB. I can tag them like "type=post" and "year=2008". My question is how far can I go with this type of tagging? Say can I create an array field with 10.000 names in it? Or is there a better way of doing this? It is a matter of understanding how to think in this document based sense.

Answer:
Multi-user systems do not
require
relational databases, though RDBMSs are a staple technology for data storage/retrieval for a vast number of (especially CRUD) applications.
If you want to read-up on document/object -oriented, distributed database solutions of yore, search on "Lotus Notes/Domino" (it's a mature technology/product in this area that's good background knowledge in how applications are designed in a document-based paradigm. Classically, it's really good at workflow type applications).
On CouchDB specifically, check out:
http://wiki.apache.org/couchdb/
(this shouldn't be a surprise)
http://seanoc.wordpress.com/2007/10/12/more-on-couchdb/
(easy reading description overview)
http://twit.tv/floss36
(Podcast interview all about CouchDB)