q:
What is the best way to find if an object is in an array?

This is the best way I know:

function include(arr, obj) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == obj) return true;
  }
}

console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined

[A]
As of ECMAScript 2016 you can use
```
includes()
```
```
```
arr.includes(obj);
```
```
If you want to support IE or other older browsers:
```
```
function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}
```
```
EDIT:
This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:
Mozilla's
(ECMA-262) version:
```
```
if (!Array.prototype.indexOf)
   {

        Array.prototype.indexOf = function(searchElement /*, fromIndex */)

     {

     "use strict";

     if (this === void 0 || this === null)
       throw new TypeError();

     var t = Object(this);
     var len = t.length >>> 0;
     if (len === 0)
       return -1;

     var n = 0;
     if (arguments.length > 0)
     {
       n = Number(arguments[1]);
       if (n !== n)
         n = 0;
       else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
         n = (n > 0 || -1) * Math.floor(Math.abs(n));
     }

     if (n >= len)
       return -1;

     var k = n >= 0
           ? n
           : Math.max(len - Math.abs(n), 0);

     for (; k < len; k++)
     {
       if (k in t && t[k] === searchElement)
         return k;
     }
     return -1;
   };

 }
```
```
Daniel James
's version:
```
```
if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function (obj, fromIndex) {
     if (fromIndex == null) {
         fromIndex = 0;
     } else if (fromIndex < 0) {
         fromIndex = Math.max(0, this.length + fromIndex);
     }
     for (var i = fromIndex, j = this.length; i < j; i++) {
         if (this[i] === obj)
             return i;
     }
     return -1;
   };
 }
```
```
roosteronacid
's version:
```
```
Array.prototype.hasObject = (
   !Array.indexOf ? function (o)
   {
     var l = this.length + 1;
     while (l -= 1)
     {
         if (this[l - 1] === o)
         {
             return true;
         }
     }
     return false;
   } : function (o)
   {
     return (this.indexOf(o) !== -1);
   }
 );
```
```


q:
let's say we have a c++ class like:

class MyClass
{
   void processArray( <an array of 255 integers> )
   {
     int i ;
     for (i=0;i<255;i++)
     {
        // do something with values in the array
     }
   }
}

and one instance of the class like:

MyClass myInstance ;

and 2 threads which call the processArray method of that instance (depending on how system executes threads, probably in a completely irregular order). There is no mutex lock used in that scope so both threads can enter.

My question is what happens to the i ? Does each thread scope has it's own "i" or would each entering thread modify i in the for loop, causing i to be changing weirdly all the time.

[A]
```
i
```
is allocated on the stack.  Since each thread has its own separate stack, each thread gets its own copy of
```
i
```
.

s: huggingface

c: devops

d: intermediate


q:
I want to be able to run a single spec file's tests — for the one file I'm editing, for example.  rake spec executes all the specs.  My project is not a Rails project, so rake spec:doc doesn't work.

Don't know if this matters, but here is my directory structure.

./Rakefile
./lib
./lib/cushion.rb
./lib/cushion
./lib/cushion/doc.rb
./lib/cushion/db.rb
./spec
./spec/spec.opts
./spec/spec_helper.rb
./spec/db_spec.rb

[A]
The raw invocation:
```
rake spec SPEC=spec/controllers/sessions_controller_spec.rb \
          SPEC_OPTS="-e \"should log in with cookie\""
```
Now figure out how to embed this into your editor.


q:
My side question is there really any difference between tinyblob & tinytext?

Buy my real question is what reason, if any, would I choose varchar(255) over tinyblob or tinytext?

[A]
Primarily
storage requirements
and memory handling/speed:
In the following table,
```
M
```
represents the declared column length in characters for nonbinary string types and bytes for binary string types.
```
L
```
represents the actual length in bytes of a given string value.
VARCHAR(
```
M
```
), VARBINARY(
```
M
```
):
```
L
```
+ 1
  bytes if column values require 0 – 255
  bytes,
```
L
```
+ 2 bytes if values may
  require more than 255 bytes
TINYBLOB, TINYTEXT:
```
L
```
+ 1 bytes, where
```
L
```
< 2
8
Additionally, see
this
post:
For each table in use, MySQL allocates
  memory for 4 rows. For each of these
  rows CHAR(X)/VARCHAR(X) column takes
  up the X characters.
A TEXT/BLOB on the other hand is
  represented by a 8 byte pointer + a
  1-4 byte length (depending on the
  BLOB/TEXT type). The BLOB/TEXT is
  allocated dynamicly on use. This will
  use less memory, but in some cases it
  may fragment your memory in the long
  run.
Edit
: As an aside, blobs store binary data and text stores ASCII, thats the only difference between TINYBLOB and TINYTEXT.


q: I think title should be good enough.

[A]
Tags should be used when you want to mark a milestone.  The milestone could be as small as a daily build.
Branches should be used when you want to make changes independently from another branch/trunk.


q: When would you use a bigtabe/simpledb database vs a Relational database?

[A]
Size, redundancy and performance are all key words that pop up in my head.
It's fairly easy to create a little database that does its job but when you need to do significant scaling and redundancy, while keeping it performing at the speed of light, it's cheaper for lots of people to ship the job off to Amazon who've been doing it for a lot longer than most of us.


q:
I'm playing with ASP.NET MVC for the last few days and was able to build a small site. Everything works great.

Now, I need to pass the page's META tags (title, description, keywords, etc.) via the ViewData. (i'm using a master page).

How you're dealing with this? Thank you in advance.

[A]
Here is how I am currently doing it...
In the masterpage, I have a content place holder with a default title, description and keywords:
```
```
<head>
<asp:ContentPlaceHolder ID="cphHead" runat="server">
    <title>Default Title</title>
    <meta name="description" content="Default Description" />
    <meta name="keywords" content="Default Keywords" />
</asp:ContentPlaceHolder>
</head>
```
```
And then in the page, you can override all this content:
```
```
<asp:Content ID="headContent" ContentPlaceHolderID="cphHead" runat="server">
    <title>Page Specific Title</title>
    <meta name="description" content="Page Specific Description" />
    <meta name="keywords" content="Page Specific Keywords" />
</asp:Content>
```
```
This should give you an idea on how to set it up. Now you can put this information in your ViewData (ViewData["PageTitle"]) or include it in your model (ViewData.Model.MetaDescription - would make sense for blog posts, etc) and make it data driven.


q: Wondering if there is any Text to Speech software available as a plug in for IE or Firefox.

[A]
WebAnywhere
is a university project aimed at creating a site that allows you to use text to speech from any browser at any location, without installing anything or using any plugins.
You can
try it out
and see for yourself. I was pretty impressed with it when I first heard of it.


q:
I have a sparse array in Jscript, with non-null elements occuring at both negative and positive indices. When I try to use a for in loop, it doesn't traverse the array from the lowest (negative) index to the highest positive index. Instead it returns the array in the order that I added the elements. Enumeration doesn't work either. Is there any method that will allow me to do that?

Example

arrName = new Array();
arrName[-10] = "A";
arrName[20] = "B";
arrName[10] = "C";

When looping through, it should give me A then C the B.

[A]
Technically, "A" isn't in the Array at all since you can't have a negative index. It is just a member of the arrName object. If you check the arrName.length you will see that it is 21 (0,1,2,...,20) Why don't you use a plain object instead (as a hashtable). Something like this should work:
```
```
<script type="text/javascript">
//define and initialize your object/hastable
var obj = {};
obj[20] = 'C';
obj[10] = 'B';
obj[-10] = 'A';

// get the indexes and sort them
var indexes = [];
for(var i in obj){
    indexes.push(i);
}
indexes.sort(function(a,b){
    return a-b;
});

// write the values to the page in index order (increasing)
for(var i=0,l=indexes.length; i<l; i++){
    document.write(obj[indexes[i]] + ' ');
}
// Should print out as "A B C" to the page
</script>
```
```


q: Why does a user needs privileges over his own schema to create packages and triggers?

[A]
I can't give you the "official" answer, but I can take a stab at the reasoning behind how it works.  On the project I work on, Oracle Developers are the ones that deploy the triggers and packages into the database schema.  But we have other teams of Java developers and testers, etc.  Once the schema are migrated into the Test and then Production environments, we don't want the testers or the end user applications to be able to arbitrarily modify the triggers and packages associated with that schema, as that could invalidate the integrity of any testing they are doing (or cause even worse issues on the production system).
So within the test/production environments, you want the testers, the Java developers, and the end-user application to be able to read and write data to the schema, but not modify the triggers and packages which encompass the baselined code.


q:
I am a AS3 novice learning PureMVC and want to write code following best practices so that any other AS3 developer can pick up my code and easily understand what I did, I am tempted to do stuff as I would in JavaScript or Asp.Net/C#, but I have a feeling that might not be the best approach.

Thoughts? Links?

[A]
I found that reading through the docs helped me get a clear definition of each of the parts to
PureMVC
.  On top of that I downloaded the source for the demos and added them in Flex Builder so I could look through them easily and see how they were constructed to get an idea of how I should construct my project.
One thing you have to remember is that you can do things any way you want, but to make using the framework worthwhile you should stick to the structure and way of doing things that it suggests.  For example you could give your view a reference to the facade and have it get information from Proxies etc.  But you should keep the view decoupled from the framework and just have it dispatch events and have a Mediator deal with the facade.


q: Is there any C#/F# performance comparison available on web to show proper usage of new F# language?

[A]
See these questions that I asked recently:
Is a program F# any more efficient (execution-wise) than C#?
How can I use functional programming in the real world?
Is it possible that F# will be optimized more than other .Net languages in the future?


q: I am writing an iPhone application and need to essentially implement something equivalent to the 'eyedropper' tool in photoshop, where you can touch a point on the image and capture the RGB values for the pixel in question to determine and match its color.  Getting the UIImage is the easy part, but is there a way to convert the UIImage data into a bitmap representation in which I could extract this information for a given pixel?  A working code sample would be most appreciated, and note that I am not concerned with the alpha value.

[A]
You can't access the bitmap data of a UIImage directly.
You need to get the CGImage representation of the UIImage. Then get the CGImage's data provider, from that a CFData representation of the bitmap. Make sure to release the CFData when done.
```
```
CGImageRef cgImage = [image CGImage];
CGDataProviderRef provider = CGImageGetDataProvider(cgImage);
CFDataRef bitmapData = CGDataProviderCopyData(provider);
```
```
You will probably want to look at the bitmap info of the CGImage to get pixel order, image dimensions, etc.


q:
Does Apple's Xcode development environment provide any tools for memory leak detection?

I am especially interested in tools that apply to the iPhone SDK. Currently my favourite platform for hobby programming projects

Documentations/tutorials for said tools would be very helpful.

[A]
ObjectAlloc and MallocDebug should both be of help to you. If you installed the entire SDK, they will be found in Developer->Applications->Performance Tools.
Their names give you a pretty good clue as to their functions, OA, tracks the objects create and MA is a general memory leak tool.
I haven't tried them with iPhone development yet, but I have to believe that they would work there as well.
Assuming you have registered for ADC iPhone developer site, here the link to follow:
```
Instruments User Guide
```


q:
I am searching for a good system for PHP, which does UnitTesting, Subversion, Coding Standards.

I would love to hear your suggestions and which one is the best and why.
I will be running it on a debian server so anything which runs on mac or windows servers would be out of the question.

[A]
We have played with Xinc, but we stuck with phpUnderControl for now. It seemed a bit more mature, when we evaluated the different solutions.
phpug came with the obvious support for phpUnit, also generates docs (phpDocumentor) uses xdebug code coverage and project mess detection and even checks on CS (through phpcs). As for phpUnit, you can now even run
phpt
-style tests with it which makes it for some people easier to write tests.
And even though phpug adds CruiseControl and Java to the game it hasn't been much of a hassle for us. Not as much as I assumed anyway. :) I mean, that's the advantage with a Java-based service. (Assuming you have the JDK) You just download and run it. That easy. I am not familiar with Java on Debian, but last time I checked it wasn't an issue.
As for commercial solutions I know a bunch of PHP shops that use
Bamboo
(along with the complete Atlassian suite).


q: I have to implement MPI system in a cluster. If anyone here has any experience with MPI (MPICH/OpenMPI), I'd like to know which is better and how the performance can be boosted on  a cluster of x86_64 boxes.

[A]
MPICH has been around a lot longer.  It's extremely portable and you'll find years worth of tips and tricks online.  It's a safe bet and it's probably compatible with more MPI programs out there.
OpenMPI is newer.  While it's not quite as portable, it supports the most common platforms really well.  Most people seem to think it's a lot better in several regards, especially for fault-tolerance - but to take advantage of this you may have to use some of its special features that aren't part of the MPI standard.
As for performance, it depends a lot on the application; it's hard to give general advice.  You should post a specific question about the type of calculation you want to run, the number of nodes, and the type of hardware - including what type of network hardware you're using.


q:
I'm processing a huge file with (GNU) awk, (other available tools are: Linux shell tools, some old (>5.0) version of Perl, but can't install modules).

My problem: if some field1, field2, field3 contain X, Y, Z I must search for a file in another directory which contains field4, and field5 on one line, and insert some data from the found file to the current output.

E.g.:

Actual file line:

f1 f2 f3 f4 f5
X  Y  Z  A  B

Now I need to search for another file (in another directory), which contains e.g.

f1 f2 f3 f4
A  U  B  W

And write to STDOUT $0 from the original file, and f2 and f3 from the found file, then process the next line of the original file.

Is it possible to do it with awk?

[A]
This seems to work for some test files I set up matching your examples.  Involving perl in this manner (interposed with grep) is probably going to hurt the performance a great deal, though...
```
```
## perl code to do some dirty work

for my $line (`grep 'X Y Z' myhugefile`) {
    chomp $line;
    my ($a, $b, $c, $d, $e) = split(/ /,$line);
    my $cmd = 'grep -P "' . $d . ' .+? ' . $e .'" otherfile';
    for my $from_otherfile (`$cmd`) {
        chomp $from_otherfile;
        my ($oa, $ob, $oc, $od) = split(/ /,$from_otherfile);
        print "$a $ob $oc\n";
    }
}
```
```
EDIT:
Use tsee's solution (above), it's much more well-thought-out.


q: Can somebody please provide me some important aspects I should be aware of while handling Unicode strings in C#?

[A] C# (and .Net in general) handle unicode strings transparently, and you won't have to do anything special unless your application needs to read/write files with specific encodings. In those cases, you can convert managed strings to byte arrays of the encoding of your choice by using the classes in the System.Text.Encodings namespace.


q:
If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path?

I know of
Path.Combine
 but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters.

e.g:

string folder1 = "foo";
string folder2 = "bar";

CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt")

Any ideas?
Does C# support unlimited args in methods?

[A]
Does C# support unlimited args in methods?
Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested):
```
```
string CombinePaths(params string[] parts) {
    string result = String.Empty;
    foreach (string s in parts) {
        result = Path.Combine(result, s);
    }
    return result;
}
```
```


q: I want to get a files these attributes as integer values.

[A]
Delphians tend to like the
```
FindFirst
```
approach (the
```
SearchRec
```
structure has some of those), but I'd suggest the Win32 API function
```
GetFileAttributesEx
```
.


q:
I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java:

Array (
        ["col_name_1"] => Array (
                               1 => ["col_value_1"],
                               2 => ["col_value_2"],
                               ... ,
                               n => ["col_value_n"]
                          ),
        ["col_name_n"] => Array (
                               1 => ["col_value_1"],
                               2 => ["col_value_2"],
                               ... ,
                               n => ["col_value_n"]
                          )
)

Is there a clean way (i.e. no dirty code) to save this thing in Java? Note; I would like to use Strings as array indexes (in the first dimension) and I don't know the definite size of the arrays..

[A]
You want a
Map
, which are keyed by just about anything.
HashMap
s work in most cases.
Something like this.
```
```
List<String> col1Vals = new java.util.ArrayList<String>();
col1Vals.add("col_value_1");
col1Vals.add("col_value_2");
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("col_name_1", col1Vals);
```
```
If you want something simpler, the
commons-lang
library has a
MultiMap
.


q:
I'm currently writing an interface to allow applications to send exception data to a central repository for support purposes. I'm at a quandary about how to pass extra contextual data:

public interface IExceptionNotifier
{
    void Notify(Exception ex, NameValueCollection context); //this
    void Notify(Exception ex, IDictionary<string, string> context); //or this
}

I've often found myself is a similar position when creating lookups. Ignoring whether or not the exception notifier concept is good, is it be best to use an IDictionary<string, string> or NameValueCollection? Why would you pick one over the other?

[A]
If the context is a throw-away value and (here comes the important part) will not be serialized, e.g. for sending the data to another system, I'd go with the IDictionary because it makes using your interface more flexible.
If, on the other hand, the context is kept all the time or the context will be serialized, use NameValueCollection because then you are under control of what you'll actually get from your caller.
Edit: mausch is right in that you should use a generic approach, but I still wouldn't use an interface if you want to serialize the data.


q:
I'm building Desktop Software for over 10 years now, mostly it's simple Data-Input Software. My problem is, it's always looking the same: A Treeview on the Left and a lot of Text/Data Fields to the right, depending on the type of data currently is worked on. Are there any fresh ideas how such software nowadays should look like?

For further clarification:
It's very hierarchical data, mostly for electronic devices. There are elements of data which provide static settings for the device and there are parts which describe some sort of 'Program' for the device. There are a lot (more than 30) of different input masks. Of course i use combo boxes and Up/Down Entry Fields.

[A]
Having all of your software look the same thing is a
good
thing.  One of the best ways to make it easy for people to use your software is to make it look exactly the same as other software your users already know how to use.
There are basically two common strategies for how to handle entry of a lot of data.  The first is to have lots of data entry fields on one page.  The next is to have only a few data entry fields but a lot of pages in a sort of wizard-style interface.  Expert users find the latter much slower to use, as do users who are entering data over and over again.  However, the wizard style interface is less confusing for newer users since it offers fewer elements at once and tends to provide more detail on them.
I do suggest replacing as many text fields as possible with auto-complete-based combo-boxes.  This allows users to enter data exactly the same as with text-boxes, but also allows users to save typing by hitting the down key to scroll through choices after typing part of the data in.
Providing more detail on what data is being entered would probably yield more specific answers.


q: Why use one over the other?

[A]
== is the identity test. It will return true if the two objects being tested are in fact the same object.
```
Equals()
```
performs an equality test, and will return true if the two objects consider themselves equal.
Identity testing is faster, so you can use it when there's no need for more expensive equality tests. For example, comparing against
```
null
```
or the empty string.
It's possible to overload either of these to provide different behavior -- like identity testing for
```
Equals()
```
--, but for the sake of anybody reading your code, please don't.
Pointed out below: some types like
```
String
```
or
```
DateTime
```
provide overloads for the
```
==
```
operator that give it equality semantics. So the exact behavior will depend on the types of the objects you are comparing.
See also:
http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx


q: We use a grid control from Infragistics at work. Are there others? Pay or free?

[A] I started out using the Infragistics control also which is great and is very powerful, but it's difficult to use because it's features are so extensive. I feel the same way about ComponentOne. I've switched over to the DataGrid CPT from Microsoft, and I've had a lot of success with it. Obviosly it's not as feature rich at this point as other 3rd part controls, but overall I'ts really good.


q:
Ruby is truly memory-hungry - but also worth every single bit.

What do you do to keep the memory usage low? Do you avoid big strings and use smaller arrays/hashes instead or is it no problem to concern about for you and let the garbage collector do the job?

Edit: I found a nice article about this topic here - old but still interesting.

[A]
I am not a ruby developer but I think some techniques and methods are true of any language:
Use the minimum size variable suitable for the job
Destroy and close variables and connections when not in use
However if you have an object you will need to use many times consider keeping it in scope
Any loops with manipulations of a big string dp the work on a smaller string and then append to bigger string
Use decent (try catch finally) error handling to make sure objects and connections are closed
When dealing with data sets only return the minimum necessary


q: I thought that there was some way in .net 3.0 to give an array list a type so that it didnt just return Object's but I'm having trouble doing so. Is it possible? If so, how?

[A]
You're probably looking for List
```
<T>
```
, available since .NET 2.0, or for any other of the generic types available from System.Collections.Generic or System.Collections.ComponentModel.


q:
What serial communication bus would you use in a automotive embedded system if your main selection criteria were:

Electrically robust

Slow speed (32 kb/s)

Easy to program

Easy to interface with microcontrollers

It won't be transferring much data, but it will need to be transferred periodically at high speed (100 - 500 Hz). I find that RS-232 is just not reliable enough if you have noise in your ground line. CAN-bus seems interesting, but I have no experience with it.

We are currently interested in a combination of AVR AT90CAN128 microcontrollers.

[A]
For all out reliability you can't go past CANbus (but then that was sort of implied by your choice of processor?)
Depending on what you want to interface to, this can be very simple - the base level protocol is quite straight forward. But if you want to talk to any other non-proprietary devices you'll have to implement the higher protocols (eg. CANopen).
But if CANbus isn't appropriate, then I would recommend RS485 or RS422 (depending on your topology). If all you're trying to achieve is point to point communications it's identical to RS232. (you'll have to put your own protocol layer on top if you're trying to support multidrop comms though.)


q:
By default (using the plain style) BibTeX orders citations alphabetically.

How to order the citations by order of appearance in the document?

[A]
The best I came up with is using the
```
unsrt
```
style, which seems to be a tweaked
```
plain
```
style. i.e.
```
```
\bibliographystyle{unsrt}
\bibliography{bibliography}
```
```
However what if my style is not the default?


q:
I require a tree / directed acyclic graph implementation something like this:

public class TreeNode<K, V> {
    private K key; // 'key' for this node, always present
    private V value; // 'value' for this node, doesn't have to be set

    private TreeNode<K, V> parent;
    private Set<TreeNode<K, V>> children;
}

There is no sorting of any kind.

The TreeNode is just a wrapper around the key and a possible value (nodes don't have to have values set).

I require links to both the parent and the children.

Is there anything out there in the standard APIs or Commons etc that will do this for me?

I don't mind writing it myself (and I'm certainly not asking you folks to) I just don't want to re-invent the wheel.

[A]
There doesn't seem to be anything of the kind. I asked
a similar question
last week and ended up implementing my own tree.  My implementation was very similar to what you're proposing:
```
```
public class TreeNode<T>
{
    private LinkedList<TreeNode<T>> children = new LinkedList<TreeNode<T>>();
    public T value { get; set; }

    public TreeNode(T value)
    {
        this.value = value;
    }
    public LinkedList<TreeNode<T>> GetChildren()
    {
        return children;
    }
}
```
```
You will have to add a link back to the parent(s).


q:
I've the following rewrite rule in .htaccess:

RewriteRule ^groups/([^/\.]+)/?$  groupdetail.php?gname=$1 [L,NC]

This takes something like www.example.com/groups/groupname and calls www.example/groupdetail.php?gname=groupname.  And it works just fine.

But all the relative links on groupdetail.php use groups/ as the relative path, and I don't want them to.  How do I avoid this?

For example, when a user clicks on a link <a href="link.php"> on groupdetail.php?gname=groupname, he's taken to www.example/groups/link.php.  I want to take the user to www.example.com/link.php.

Obviously, I want to URL to the user to look like "www.example.com/groups/groupname" so I  don't want to use [R]/redirect.

[A]
If you change the rewite rule to do a
force redirect
(add the [R] option), then the browser will be using the /groupdetail.php URL and the relative links will work fine.  However, that adds one redirect and makes the URLs less pretty.
```
```
RewriteRule ^groups/([^/.]+)/?$ groupdetail.php?gname=$1 [L,NC,R]
```
```


q:
I have a Java program that uses Hibernate and MySQL to store a lot of tracing data about the use of the Eclipse IDE. This data contains a lot of strings such as method names, directories, perspective name, etc.

For example, an event object (which is then reflected in a record) can specify the source file and the current method, the user name, etc. Obviously, string data can repeat itself.

As long as it's in memory, much of it is internalized so all repeated string instances point to the same object (I make sure of that). However, with @Basic (I use annotations), Hibernate maps it into a VARCHAR(255), which means a lot of wasted space.

If I was coding the SQL myself, I could have replaced the VARCHAR with an index to a manually-managed string lookup table and saved the space (at the cost of extra lookups).

Is there some way to get Hibernate to do this for me? I'm willing to pay the performance hit for the space.

[A]
I suspect you'll need a string holder object and then make sure all these objects refer to that.
```
```
class StringHolder {
  private Long id;
  private String string;

  public StringHolder() {/* Not sure if this is necessary */}

  public StringHolder(String string) {
    this.string = string;
  }

  public void getString() {
    return this.string;
  }
}
```
```


q:
I've removed a checked in file from the CVS branch, i.e.:

cvs remove -f file.txt
cvs commit

How do I restore the file?

[A]
I believe that:
```
```
cvs add file.txt
cvs commit file.txt
```
```
... will resurrect it from the attic.


q:
I am using Eclipse 3.4 (ganymede official, not the service pack).

I have an update site that organizes features into categories; everything looks great in the editor and in the XML.

Once the site is online, accessing it in the usual manner tells me that all the features are "uncategorized". I've tried from multiple computers running 3.4 and the same problem persists.

What is curious is that I used Eclipse 3.3, and it saw the categories well, though of course it wasn't able to instlal the plugins which are made from 3.4.

Am I doing something wrong or is this a known problem?

[A]
It appears to be a known problem, due to the new
'p2' provisioning system
.
See
this discussion
, and
this bug
. What it seems to say is... "stay put until 3.5M3, and then try it again".


q:
I think I might be missing the point of having a logging framework for your application.  In all the small apps I've always written a small "Logging" class and just pass log messages to a method in it which is written to a file.

What is the purpose of a 3rd party logging framework like log4net?  Is it thread safety with logging write operations or am I missing something?

[A]
you might want to switch to log to a db for some message, or an alerting system that pages the poor person on support
More importantly though, most logging frameworks allow you to specify the loglevel of different classes so you dont need to cut a new binary each time you want more/less logging (that verbose logging for the bug you just spotted in production)
Log4Net's site
has more detail


q:
In general I think I can convey most programming related concepts quite well.

Yet, I still find it hard to summarise the relationship between Fields, Classes and Packages.

How do You summarise "Fields", "Classes" and "Packages" and "Their Relationship" ?

[A]
I've faced a similar problem since I taught C, C++, and Java.
Here is what I do:
First, I keep packages separately and explain them in the end.
Ideally, in my opinion, students should first learn about ADTs, preferably in C. They have the struct, they have the separate operations on it. Fields are then simply the "slots" in the struct and you can even show the memory layout to demonstrate it. Functions are separate entities that operate on those structs.
You then make the transition to classes, methods, and fields and show that in essence (barring inheritance and some anecdotes) they are in many ways syntactic sugar for ADTs.
If you need, you can then teach object layouts, inheritance, and virtual tables (in my experience it helps students understand inheritance better to see the memory layout).
Finally you get to the topic of how to organize classes together. If you teach C++, you don't really have packages but you can explain namespaces and discuss organization and separate compilation.
If you are in Java, then you just explain that these are collections of classes in the same namespace, that have special access rules and show them. The package system in Java is kind of broken anyway so I usually go through patterns (e.g., separating a UI package from the C).
So in summary: Classes form the basis for objects that are a memory arrangement of several fields and associated methods that operate on them. Packages are collections of classes that have one more access restriction mechanism.


q: I frequently start with a simple console application to try out an idea, then create a new GUI based project and copy the code in. Is there a better way? Can I convert my existing console application easily?

[A]
Just add a new Winform, add the following code to your
```
Main
```
:
```
```
Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
```
```
Also, be sure the
```
[STAThread]
```
attribute is declared above your
```
Main
```
function to indicate the COM threading model your Windows application will use (more about STAThread
here
).
Then right click your project and select properties and change the "Output type" to Windows application and you're done.
EDIT :
In VS2008 the property to change is Application type


q: I have an XML document with un-namespaced elements, and I want to use XSLT to add namespaces to them. Most elements will be in namespace A; a few will be in namespace B. How do I do this?

[A]
Here's what I have so far:
```
```
<xsl:template match="*">
    <xsl:element name="{local-name()}" namespace="A" >
        <xsl:apply-templates />
    </xsl:element>
</xsl:template>

<xsl:template match="a-special-element">
    <B:a-special-element xmlns:B="B">
      <xsl:apply-templates />
    </B:a-special-element>
</xsl:template>
```
```
This almost works; the problem is that it's not copying attributes. From what I've read thusfar, xsl:element doesn't have a way to copy all of the attributes from the element as-is (use-attribute-sets doesn't appear to cut it).


q: Is it possible to install/register another local server instance in any SqlServer version, besides the default local instance, where only one SqlServer version is installed?

[A]
Yes, it's possible. I have several combinations in my servers. I have one server that has both SQL Server 2000 and 2005 installed side by side. My desktop at work is a Windows 2003 Server, and I have SQL Server 2005 and 2008 installed side by side.
What you want is called a named instance. There will be a screen during the install, where you will be able to give it a name.


q:
The prompt says that if I install the software into a directory with spaces:

the rebuild build tool used by the D Shared Source System will fail to build

and that I will be

forced to reinstall in a different location

However, I don't like random things in my C:\ drive. D, IMO, belongs in Program Files with PHP and MinGW and so on. How can I get it here?

If it matters, I'm using the Easy D installer package.

[A]
You could install it into C:\Program Files, and then use the
```
subst
```
command to make it appear as a new drive letter:
```
```
subst x: "c:\program files\d"
```
```


q:
Recently I have started playing with jQuery, and have been following a couple of tutorials. Now I feel slightly competent with using it (it's pretty easy), and I thought it would be cool if I were able to make a 'console' on my webpage (as in, you press the ` key like you do in FPS games, etc.), and then have it Ajax itself back to the server in-order to do stuff.

I originally thought the best way would be to just get the text inside the textarea, and then split it, or should I use the keyup event, convert the keycode returned to an ASCII character, append the character to a string and send the string to the server (then empty the string).

I couldn't find any information on getting text from a textarea, all I got was keyup information. Also, how can I convert the keycode returned to an ASCII character?

[A]
Normally, it's the value property
```
```
testArea.value
```
```
Or is there something I'm missing in what you need?


q:
I know that attributes are extremely useful. There are some predefined ones such as [Browsable(false)] which allows you to hide properties in the properties tab. Here is a good question explaining attributes: What are attributes in .NET?

What are the predefined attributes (and their namespace) you actually use in your projects?

[A]
```
[Serializable]
```
is used all the time for serializing and deserializing objects to and from external data sources such as xml or from a remote server.
More about it here.


q:
I am in the process of writing a Bluetooth scanner that locates and identifies mobile devices in the local vicinity. Is this something that I can accomplish using C#, or do I need to drop down into the C/C++ APIs? My application is targeting Windows XP and Vista. Pointers are appreciated.

Thanks!

[A]
There is also Peter Foot's 32feet.net
http://inthehand.com/content/32feet.aspx
I've played around with this back when it was v1.5 and it worked well.


q: I'm using an XYPlot in JFreeChart. All the lines on it are XYSeries objects. Both axes are NumberAxis objects. The Y-Axis range is from 0-1, with ticks every .1. Along with displaying the numbers though, I'd like to display text on the Y-Axis, like High/Medium/Low. High would cover .7-1, etc. What is the best way to go about doing this?

[A]
I have some JFreeChart experience, and after a little research I don't have an answer for adding the three labels to the axis.
However, as an alternative approach, you should be able to delineate these three areas on the plot with colors by setting a
MarkerAxisBand
for the NumberAxis (using
this method
).
You could then add interval markers to the MarkerAxisBand to highlight the three areas.


q: What's the easiest way to centre a java.awt.Window, such as a JFrame or a JDialog?

[A]
From
this link
If you are using Java 1.4 or newer,
  you can use the simple method
  setLocationRelativeTo(null) on the
  dialog box, frame, or window to center
  it.


q:
Code below is not working as expected to detect if it is in design mode (VS.Net 2003 - Control Library):

if (this.Site != null && this.Site.DesignMode == true)

{

  // Design Mode

}

else

{

  // Run-time

}

It is used in a complex user control, deriving from another user control and including other user controls on it.

Is there another way to detect design time in a VS.NET 2003 or what is the problem with the code above?

[A]
I guess you could use HttpContext.Current == null as described at
http://west-wind.com/weblog/posts/189.aspx
In .Net 2.0 there's Control.DesignMode (
http://msdn.microsoft.com/en-us/library/system.web.ui.control.designmode.aspx
). I guess you have a good reasons to stay on VS 2003 though, so upgrading might not be an option for you.
Update
If you are doing Winforms, Component.DesignMode (
http://msdn.microsoft.com/en-us/library/system.componentmodel.component.designmode.aspx
) is the right way to check. Though, if this.Site.DesignMode doesn't work properly, Component.DesignMode might not work as well, as it does exactly the check you are doing (Site != null && Site.DesignMode).
This might be a long shot, but are you sure that your base control does not override the Site property?


q:
How have you used the Exception.Data property in C# projects that you've worked on?

I'd like answers that suggest a pattern, rather than those that are very specific to your app.

[A]
I have used it when I knew the exception I was creating was going to need to be serialized.  Using Reflector one day, I found that Excepion.Data gets stuck into and pulled from serialization streams.
So, basically, if I have properties on a custom exception class that are already serializable types, I implement them on the derived class and use the underlying data object as their storage mechanism rather than creating private fields to hold the data.  If properties of my custom exception object require more advanced serialization, I generally implement them using backing private fields and handle their serialization in the derived class.
Bottom line, Exception.Data gives you serialization for free just by sticking your properties into it -- but just remember those items need to be serializable!


q:
Can this be done? How?

I want to write my own extension. Can Get the current page sorcecode in my own extension?

[A]
Sure, just add view-source: in front of the URL.
```
```
view-source:http://stackoverflow.com/posts/edit/145419
```
```
Will show the source of this page for instance - try it in the address bar.


q: Every time I start Emacs I see a page of help text and a bunch of messages suggesting that I try the tutorial.  How do I stop this from happening?

[A]
Put the following in your
```
.emacs
```
:
```
(setq inhibit-startup-message t)
(setq inhibit-startup-echo-area-message t)
```


q:
I'm confused by the discussion and advancement both of a new version of HTML and a new version of XHTML. Are they competitors? If so, what is likeliest to be the adopted future of the web? If not, what is the differing non-competing purpose for each?

Are we due to have a BluRay/HDVD battle here? Is there ultimately any clear decision? I fear a future where browsers pick and choose among the easiest and/or flashiest features of each to implement, leaving web developers trying to sort out the lowest common denominator for any new web app.

[A]
In my opinion HTML5 will be the next dominant format. XHTML is just too unforgiving to be used in a web environment (you can't have the page fail on every small error...).
HTML5 is shaping up to be quite the treat for web developers - a formal spec for the CANVAS element, native drag-and-drop API, an offline storage API, server notifications API (push model), a formal content editing API and much more. If they can deliver even half of what they are proposing to, it will be a major advancement for web applications.


q:
Very simply put, I have the following code snippet:

FILE* test = fopen("C:\\core.u", "w");
printf("Filepointer at: %d\n", ftell(test));
fwrite(data, size, 1, test);
printf("Written: %d bytes.\n", size);
fseek(test, 0, SEEK_END);
printf("Filepointer is now at %d.\n", ftell(test));
fclose(test);

and it outputs:

Filepointer at: 0
Written: 73105 bytes.
Filepointer is now at 74160.

Why is that? Why does the number of bytes written not match the file pointer?

[A]
Since you're opening the file in text mode, it will convert end-of-line markers, such as LF, into CR/LF.
This is likely if you're running on Windows (and you probably are, given that your file name starts with
```
"c:\"
```
).
If you open the file in
```
"wb"
```
mode, I suspect you'll find the numbers are identical:
```
```
FILE* test = fopen("C:\\core.u", "wb");
```
```
The C99 standard has this to say in
```
7.19.5.3 The fopen function
```
:
The argument mode points to a string. If the string is one of the following, the file is
  open in the indicated mode. Otherwise, the behaviour is undefined.
```
r
```
open text file for reading
```
w
```
truncate to zero length or create text file for writing
```
a
```
append; open or create text file for writing at end-of-file
```
rb
```
open binary file for reading
```
wb
```
truncate to zero length or create binary file for writing
```
ab
```
append; open or create binary file for writing at end-of-file
```
r+
```
open text file for update (reading and writing)
```
w+
```
truncate to zero length or create text file for update
```
a+
```
append; open or create text file for update, writing at end-of-file
```
r+b
```
or
```
rb+
```
open binary file for update (reading and writing)
```
w+b
```
or
```
wb+
```
truncate to zero length or create binary file for update
```
a+b
```
or
```
ab+
```
append; open or create binary file for update, writing at end-of-file
You can see they distinguish between
```
w
```
and
```
wb
```
. I don't believe an implementation is
required
to treat the two differently but it's usually safer to use binary mode for binary data.


q:
I haven't been around Java development for 8 years, but am starting to build a NetBeans Web Application. When I walk through the Web Application wizard, it asks for the server I'm going to be using.

What would be the best and simplest server for me to start using with NetBeans?

[A]
Since the NetBeans IDE is a Sun product, I would assume that the Glassfish application server would be a natural fit.
That said, one of the pluses of developing a web application in Java is that the interface for working with the http is standardized (i.e. the Servlet specification), so that you can pick any servlet container you want: be it Glassfish, Tomcat, Jetty or Weblogic. Since it sounds to me that you're experimenting and you want to use something easy to administer, I might go with Glassfish. However, be open to revisit that decision when you need to actually deploy your web application in a production environment. Be sure to check out other options like Tomcat or Jetty.


q:
I have some accesses from 192.168.0.71 on my apache logs.  I looked up this IP (because my server almost exclusively takes requests from 127.0.0.1, and I saw that it's reserved for "special purposes."  What types of purposes might those be?

Edit:

I didn't tell you, typing 192.168.0.71 brings me straight to my site, just as 127.0.0.1 would.  I just wonder how this is different, then from 127.0.0.1.

[A] 192.168.0.71 (Well the entire range 192.168.0.0 – 192.168.255.255) are for private (read. not internet accessible) network IP addresses, so that is from something inside your private network.


q:
Can iPhone applications compiled against 2.1 be successfully installed via iTunes on a 2.0 device?

I know iPhone applications compiled with 2.1 can run on a 2.0 device (assuming they're not using anything new from 2.1). But am not sure if iTunes will let the install take place.

Does anyone have concrete information on this?

I have not seen any apps on the AppStore that are 2.1+ only.

[A]
Short answer, yes.
There have been some apps that dont work 100% in 2.1, but the two firmwares are pretty much backwards compatible


q: I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features.  However, some others have told me that this is not necessarily true.  Can anyone shed some light on this?

[A]
Overview:
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function).  C++ does change the definition of some terms in C such as structs, although still in a superset way.
Examples of why it is not a strict superset:
This Wikipedia article
has a couple good examples of such a differences:
One commonly encountered difference is
  that C allows implicit conversion from
  void* to other pointer types, but C++
  does not. So, the following is valid C
  code:
```
```
int *i = malloc(sizeof(int) * 5);
```
```
... but to make it work in both C and
  C++ one would need to use an explicit
  cast:
```
```
int *i = (int *) malloc(sizeof(int) * 5)
```
```
Another common portability issue is
  that C++ defines many new keywords,
  such as new and class, that may be
  used as identifiers (e.g. variable
  names) in a C program.
This wikipedia article
has further differences as well:
C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:
```
```
void fn(void)
 {
  goto flack;
  int i = 1;
 flack:
   ;
 }
```
```
What should you learn first?
You should learn C++ first, not because learning C first will hurt you, not because you will have to unlearn anything (you won't), but because there is no benefit in learning C first.  You will eventually learn just about everything about C anyway because it is more or less contained in C++.


q:
I need to do some performance benchmarks on .NET programs (C#) in Windows, but I haven't done benchmarking much in the Windows world.  I've looked into using the Windows 2000/XP Performance monitor with custom counters for this, but I don't think this is quite what I want.

Are there any good system facilities for this in Windows XP, or do I need to just use System.Diagnostics.Stopwatch [edit] and write text logs for manual interpretation, or is there something else?

Edit: is there anything beyond System.Diagnostics.Stopwatch?

[A]
```
```
using System.Diagnostics;
....

Stopwatch sw = new Stopwatch();

sw.Start();

// Code you want to time...

// Note: for averaged accuracy (without other OS effects),
//       run timed code multiple times in a loop
//       and then divide by the number of runs.

sw.Stop();

Console.WriteLine("Took " + sw.ElapsedTicks + " Ticks");
```
```


q:
My singleton accessor method is usually some variant of:

static MyClass *gInstance = NULL;

+ (MyClass *)instance
{
    @synchronized(self)
    {
        if (gInstance == NULL)
            gInstance = [[self alloc] init];
    }

    return(gInstance);
}

What could I be doing to improve this?

[A]
```
```
@interface MySingleton : NSObject
{
}

+ (MySingleton *)sharedSingleton;
@end

@implementation MySingleton

+ (MySingleton *)sharedSingleton
{
  static MySingleton *sharedSingleton;

  @synchronized(self)
  {
    if (!sharedSingleton)
      sharedSingleton = [[MySingleton alloc] init];

    return sharedSingleton;
  }
}

@end
```
```
[Source]


q: Right now I write expressions in the *scratch* buffer and test them by evaluating with C-x C-e. I would really appreciate having an interactive interpreter like SLIME or irb, in which I could test Emacs Lisp expressions.

[A]
In the
```
*scratch*
```
buffer, just type C-j to evaluate the expression before point.


q:
I guess the question is self-explanatory, but I'm wondering whether HTML qualifies as a programming language (obviously the "L" stands for language).

The reason for asking is more pragmatic—I'm putting together a resume and don't want to look like a fool for listing things like HTML and XML under languages, but can't figure out how to classify them.

[A]
YES, a declarative programming language.
You really want to list the most important things you know that are relative to the job you're applying for on your resume. If you list ASP.NET but don't list HTML, even though it's somewhat obvious, there are a lot of managers and/or HR types that will assume you don't know HTML since it's not listed. I've had it happen to me before.
Update - Some say no it isn't a programming language, and you may not agree with me on this, but regardless on a resume it IS a programming language. You get HR types looking at your resume before the hiring manager even sees it. If the manager says you need to know HTML, and it's not listed in the 'programming languages' section then the HR person may disregard you resume thinking you don't know it because it's not listed.
Update 6-8-2012: Any instruction that tells the computer to do something is a programming language. So even after all these years, I still stand by my answer. HTML is a programming language. Something that isn't a programming language would be XML.


q:
Is there a free software for creating windows help files for your program?

I would like something that allows an output of both CHM and HTML files.

[A]
If you're developing for .NET and you're looking to generate XML documentation help files you should look into Microsoft's shared-source
Sandcastle
project, and the front-end GUI for it "
Sandcastle Help File Builder
."
It's pretty nice and highly configurable. You can make some really good help documentation using it.
It was a little slow the last time I used it (over 6 months ago) but it may have been optimized since then...


q:
I have a home-spun 2000 lines VBScript script, that has become progressively slow with each additional code I add. It was created as a private debugging aid and now that it has become really useful. I want to polish it and ship it along with our product.

I thought I could speed it up by compiling it and making it an EXE. Furthermore I want to have a user interface for my tool, which might be possible once I use the extra libraries that the compiling platform might give me. I'm also considering extending the script by calling Win32 functions for whatever missing functionalities I require.

I have VB 6.0 or I can buy an external compiler. But I also need the created program (not the compiler itself) to run fine in Windows Vista. What are my best options?

[A]
I would recommend downloading Visual Basic Express Edition (
http://www.microsoft.com/express/vb/
) and port your tool to VB.Net. However, that approach has one drawback - your program will be dependent on .Net. For the most part that shouldn't be a big problem, as by now most machines should have .Net 2.0, still it's better to keep it in mind.
I would stay away from VB6.0; however, aside from VB.Net I don't know any other good Basic compilers you could use.


q: What application do you use to monitor HTTP communication on OS X?


q:
What would be the quickest way to construct a Python binding to a C or C++ library?

(I am using Windows if this matters.)

[A]
The quickest way to do this is using
SWIG
.
Example from SWIG
tutorial
:
```
```
/* File : example.c */
int fact(int n) {
    if (n <= 1) return 1;
    else return n*fact(n-1);
}
```
```
Interface file:
```
```
/* example.i */
%module example
%{
/* Put header files here or function declarations like below */
extern int fact(int n);
%}

extern int fact(int n);
```
```
Building a Python module on Unix:
```
```
swig -python example.i
gcc -fPIC -c example.c example_wrap.c -I/usr/local/include/python2.7
gcc -shared example.o example_wrap.o -o _example.so
```
```
Usage:
```
```
>>> import example
>>> example.fact(5)
120
```
```
Note that you have to have python-dev. Also in some systems python header files will be in /usr/include/python2.7 based on the way you have installed it.
From the tutorial:
SWIG is a fairly complete C++ compiler with support for nearly every language feature. This includes preprocessing, pointers, classes, inheritance, and even C++ templates. SWIG can also be used to package structures and classes into proxy classes in the target language — exposing the underlying functionality in a very natural manner.


q:
Can you have smart behavior for the home key in Emacs? By smart I mean that instead of going to the character number 0, it should go to the first non-blank character, and go to 0 on a second pressing, and back to the first non-blank in a third and so on.
Having smart end would be nice as well.

[A]
```
```
(defun smart-beginning-of-line ()
  "Move point to first non-whitespace character or beginning-of-line.

Move point to the first non-whitespace character on this line.
If point was already at that position, move point to beginning of line."
  (interactive "^") ; Use (interactive) in Emacs 22 or older
  (let ((oldpos (point)))
    (back-to-indentation)
    (and (= oldpos (point))
         (beginning-of-line))))

(global-set-key [home] 'smart-beginning-of-line)
```
```
I'm not quite sure what smart end would do.  Do you normally have a lot of trailing whitespace?
Note:
The major difference between this function and Robert Vuković's is that his always moves to the first non-blank character on the first keypress, even if the cursor was already there.  Mine would move to column 0 in that case.
Also, he used
```
(beginning-of-line-text)
```
where I used
```
(back-to-indentation)
```
.  Those are very similar, but there are some differences between them.
```
(back-to-indentation)
```
always moves to the first non-whitespace character on a line.
```
(beginning-of-line-text)
```
sometimes moves past non-whitespace characters that it considers insignificant.  For instance, on a comment-only line, it moves to the first character of the comment's text, not the comment marker.  But either function could be used in either of our answers, depending on which behavior you prefer.


q:
I have been trying to learn multi-threaded programming in C# and I am confused about when it is best to use a thread pool vs. create my own threads. One book recommends using a thread pool for small tasks only (whatever that means), but I can't seem to find any real guidelines.

What are some pros and cons of thread pools vs creating my own threads? And what are some example use cases for each?

[A]
Thread pools are great when you have more tasks to process than available threads.
You can add all the tasks to a thread pool and specify the maximum number of threads that can run at a certain time.
Check out
this
page on MSDN:
http://msdn.microsoft.com/en-us/library/3dasc8as(VS.80).aspx


q: What is the maximum number of threads you can create in a C# application?  And what happens when you reach this limit?  Is an exception of some kind thrown?

[A]
There is no inherent limit. The maximum number of threads is determined by the amount of physical resources available. See this
article by Raymond Chen
for specifics.
If you need to ask what the maximum number of threads is, you are probably doing something wrong.
[
Update
: Just out of interest: .NET Thread Pool default numbers of threads:
1023 in Framework 4.0 (32-bit environment)
32767 in Framework 4.0 (64-bit environment)
250 per core in Framework 3.5
25 per core in Framework 2.0
(These numbers may vary depending upon the hardware and OS)]


q:
What is a good free/open source alternative to WebFOCUS?

Is there an ASP.NET way of getting info from an OLAP cube?

Update: I chose Magnus Smith's answer as the correct one, but Alexmac's answer was also very good!

[A]
I am not aware of free analytical suite. But what is it you are trying to accomplish?
You can query an OLAP cube by using MDX queries with ADO.net.
http://msdn.microsoft.com/en-us/library/ms144785.aspx
You can then bind the results to a datagrid for example. MDX is a little like SQL but be careful as it has several syntax differences. I think Excel has a query tool you can use to graphically construct your queries which can be helpful.
On a related note look into SQL reporting services. With SQL express you can use a cut down version of sql reporting services that may accomplish what you are looking to do.


q:
What is the most efficient way to check if an array is a flat array
of primitive values or if it is a multidimensional array?

Is there any way to do this without actually looping through an
array and running is_array() on each of its elements?

[A]
You could look check
```
is_array()
```
on the first element, under the assumption that if the first element of an array is an array, then the rest of them are too.


q:
How do you debug your SharePoint 2007 code?  Since SharePoint runs on a remote server, and I'm developing on a windows xp machine (with the necessary .dll files copied into my GAC), I haven't had much luck with finding easy ways to debug.  Breakpoints don't work, etc.

The best way I've come up with is to enable page tracing in the web.config file, write trace messages throughout my code, and access trace.axd whenever I need to debug.

Does anyone have any better suggestions for debugging?  Am I missing something?

[A]
From
Andrew Connell's blog post
on the subject:
Attaching the debugger to GAC'd
  assemblies: "Why aren't my breakpoints
  being hit?!?!" Ever been there? Me
  too... what a PITA that is! What's
  going on? Well, the assemblies are in
  the GAC and the Visual Studio debugger
  can't see the debugging symbols (aka:
  *.pdb). Unless you've gone through the trouble of setting up a symbol store
  where all your PDBs are going, you'll
  need to put the debugging symbols in
  the same location as the assembly. The
  trick is finding the folder that
  contains your DLL in the GAC.
The c:\windows\assembly folder is not
  a real folder, it's a virtual folder.
  To get to the REAL folder, do the
  following:
Start » Run
%systemroot%\assembly\gac
  [ENTER]
This will open the GAC folder.
  Now, poke around until you find a
  folder that looks like this (you might
  need to jump up one folder and dive
  into the MSIL folder): [assembly file
  name -.DLL extention][assembly
  version in format of
> #.#.#.#]__[assembly public key token].
When you find that folder, open it up
  and you'll see your assembly. Copy the
  PDB file to that folder and then
  attach the debugger for some debugging
  joy!


q: I'd like to open the intelligence window without typing a character and then backspacing it. I can't seem to remember the shortcut for this. What is it?

[A]
Ctrl
+
Space
?
Also, go to
Tools -> Options -> Environment -> Keyboard
or
Default Keyboard Shortcuts in Visual Studio
, you can then search for commands and see what is assigned to that (and remap).


q:
Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical?

I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class.

[A]
The only problems i can think of are the gettype() and the is_array() functions.
Check your code for
```
```
gettype($FakeArray) == 'array'
is_array($FakeArray)
```
```
Because although you can use the object just like an array, it will still be identified as an object.


q:
How do I connect to an SQL Server remotely and administer my database objects? I need to connect to my database located on the web hosting company's server. I have the server name, IP address, my database username & password. I have an installation of SQL Server 2000 in my machine.

Can I use SQL Server Enterprise Manager for this? A step by step guide would be very helpful.

[A]
Yes, you can use Enterprise Manager (or SQL Server Management Studio, even if it's an Express version) to connect to any SQL Server (of the same or lower version as the tool you're using) you have TCP/IP connectivity to. Just launch it, enter the DNS host name or IP address in the 'Server Name' box and hit Connect.
Two things may prevent this from working:
Your SQL Server isn't set up for TCP/IP connectivity. This is the default setting from version 2005 onwards, and can be changed using the
SQL Server Configuration Manager
.
There is a firewall between you and your SQL Server blocking TCP/IP traffic. This is an entirely sensible construction: you do
NOT
want your database server to be available from the general Internet, as this is a huge security risk. In fact, if your hosting company allows this kind of access by default, I'd be looking for a different provider...
Anyway, what seems to be needed in your scenario is: a) the hosting company enabling TCP/IP on your SQL Server instance, b) them providing you with
secure
access to the IP address that instance is running on.
This will involve some kind of VPN or SSH port-forwarding soluition, or at least an IP filter, where only 'trusted' IP addresses can access the SQL Server (which is not a great solution, but can be used if nothing else can be implemented). You'll have to discuss these requirements with your hosting company.


q:
As I am using for-loops on large multi-dim arrays, any saving on the for-loop mechanism itself is meaningful.

Accordingly, I am looking for any tips on how to reduce this overhead.

e.g. : counting down using uint instead of int and != 0 as stop instead of >0 allows the CPU to do less work (heard it once, not sure it is always true)

[A]
One important suggestion: move as much calculation to the outer loop as possible.  Not all compilers can do that automatically.  For eample, instead of:
```
```
for row = 0 to 999
    for col = 0 to 999
        cell[row*1000+col] = row * 7 + col
```
```
use:
```
```
for row = 0 to 999
    x = row * 1000
    y = row * 7
    for col = 0 to 999
        cell[x+col] = y + col
```
```


q: How do I dictate the destination folder of a clickOnce application?

[A]
This is not possible with ClickOnce. ClickOnce applications are always installed in the
```
Apps
```
subdirectory of local application data.


q:
I have an application written using VS2005 in C# targeting the Compact Framework 2.0 SP2. As part of the solution, I have CAB deploy project which deploys to the device without a problem. What I can't do is create a shortcut to my application on the devices desktop.

I have spent several hours reading various bits of documentation (why is the search at the MSDN site so bad?), followed the instructions but no joy.

What I've done is:

Add the "Windows Folder" node to the File System

Created a folder underneath that named "Desktop"

Created a shortcut to the Applications Primary Output and placed that in the "Desktop" folder

What am I missing?

[A]
I assume that you're working with a "Smart Device CAB Project"?  I don't think this project creates shortcuts in the correct manner for Windows CE 4.2.  I think you can download an SDK from Microsoft that after installation will show you something like "Windows CE CAB Project" as a project option.
I think you can do this manually, though.  A Windows CE shortcut is a file with a *.lnk extension, so if you want a shortcut labeled "My Application", create a text file on your PC named "My Application.lnk".  The file's contents should be:
46#\Program Files\My
  Application\MyApplication.exe (the # should be the full path length)
or whatever full path your application has on the Windows CE device.
In your CAB project, continue with adding the "Windows" folder and then the "Desktop" folder as you were.  In the Desktop folder, right-click and add the LNK file that you created.  You may have to soft-reset the device in order to have the shortcut show up after installation.


q:
If I use multiple repositories, all located under a single root folder, how can I set it up so that they will use a single master svnconf/passwd file for setup but still allow me to customize each if the need arises?

This is on Windows, but I guess the process would be similar on other systems.

Update: I am using svnserve as a service.

[A]
If you are using svnserve, then the
```
conf/svnserve.conf
```
file in each repository has a configuration item which names the password database file. This is the
```
password-db
```
item in the
```
[general]
```
section, just set them all to point to the same file.
If you're not using svnserve, then this probably doesn't apply.


q:
Notice in the bottom right hand corner of this page it has the SVN revision id? I'm assuming that's dynamic.

I'd love to add that to some of my sites, just as a comment in the source to make sure code pushes are going through.

NOTE: You can also assume that the working directory of the site in question is an svn checkout of the repo in question.

Edit: I'm looking for the global revision number, not the revision number of the file I'm looking at.

[A]
Read up on Keyword substitution.  See
http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html


q:
we need reports in our web application and there is the free ReportViewer Control from microsoft (normally used, to display reports from the reporting services). I like the fact, that the Report Format (.RDL-Format) from the ReportViewer is a documented XML-Format. But the functionality is somewhat limited, when the ReportViewer is used without the ReportingServices.

Is there a good replacement, which is based or compatible with the .RDL-Format?

The first Reports are build in the application, but later, the customer should make his reports by himself.

The Application is a ASP.NET Web-Application

[A]
This depend on your requirements. I am not clear what your requirements are.
Is your application a web application or a desktop application?
If your application is a
web application
then you can use any other reporting service. I like
i-net Clear Reports
. There is also a free and fully functional GUI
report designer
that is easy to use. Your customer can create your own reports.
If you have a
desktop application
then you are limit to the language of your application.
You should also think about the platforms. The reporting services are limited to windows and a SQL Server is needed. Does all your customer have a SQL Server?


q:
If you think it shouldn't, explain why.

If yes, how deep should the guidelines be in your opinion? For example, indentation of code should be included?

[A]
I believe having a consistent codebase is important. It increases the maintainability of ur code. If everyone expects the same kind of code, they can easily read and understand it.
Besides it is not much of a hassle given today's IDEs and their autoformatting capabilities.
P.S:
 I have this annoying habit of putting my braces on the next line :). No one else seems to like it


q: Title is the entire question. Can someone give me a reason why this happens?

[A]
This method compares the value parameter to the substring at the beginning of this string that is the same length as value, and returns a value that indicates whether they are equal.
To be equal, value must be an empty string (Empty), a reference to this same instance, or match the beginning of this instance.
.NET String.StartsWith
true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise.
Note also that true will be returned if the argument is an empty string
or is equal to this String object as determined by the equals(Object) method.
Java String.startsWith


q:
I basically want to do this:

grep 'example.com' www_log > example.com.YYYY-MM-DD-H:i:S.log

...with of course the filename being example.com.2008-09-27-11:21:30.log

I'd then put this in crontab to run daily.

[A]
The verbose method:
```
```
grep 'example.com' www_log > `date +example.com.%Y-%m-%d-%H:%M:%S.log`
```
```
The terse method:
```
```
grep 'example.com' www_log > `date +example.com.%F-%T.log`
```
```


q:
I have three related questions.

I want to create a word file with a name from C++. I want to be able to sent the printing command to this file, so that the file is being printed without the user having to open the document and do it manually and I want to be able to open the document. Opening the document should just open word which then opens the file.

[A]
I have no experience from integrating with Microsoft Office, but I guess there are some APIs around that you can use for this.
However, if what you want to accomplish is a rudimentary way of printing formatted output and exporting it to a file that can be handled in Word, you might want to look into the RTF format. The format is quite simple to learn, and is supported by the RtfTextBox (or is it RichTextBox?), which also has some printing capabilities. The rtf format is the same format as is used by Windows Wordpad (write.exe).
This also has the benefit of not depending on MS Office in order to work.


q: How can I use Cron on Google App Engine?

[A]
This page
lists how to achieve Cron-like functionality on Google Appengine.


q:
I need to compare large count of PDF files for it optical content. Because the PDF files was created on different platforms and with different versions of the software there are structural differences. For example:

the chunking of text can be different

the write order can be different

the position can be differ some pixels

It should compare the content like a human people and not the internal structure. I want test for regressions between different versions of the PDF generator that we used.

[A]
I think your best approach would be to convert the PDF to images at a decent resolution and than do an image compare.
To generate images from PDF you can use Adobe PDF Library or the solution suggested at
Best way to convert pdf files to tiff files
.
To compare the generated TIFF files I found GNU
tiffcmp
(for windows part of
GnuWin32 tiff
) and
tiffinfo
did a good job. Use tiffcmp -l and count the number of lines of output to find any differences. If you are happy to have a small amount of content change (e.g. anti-aliasing differences) then use tiffinfo to count the total number of pixels and you can then generate a percentage difference value.
By the way for anyone doing simple PDF comparison where the structure hasn't changed it is possible to use command line diff and ignore certain patterns, e.g. with GNU diff 2.7:
```
diff --brief -I xap: -I xapMM: -I /CreationDate -I /BaseFont -I /ID --binary --text
```
This still has the problem that it doesn't always catch changes in generated font names.


q:
You know that particular part of your code that is essential for the project but will probably take a lot of time to get it done? Do you ever get the feeling that you'd rather work on something else (probably less important) or not code at all instead of working on that part? That beast you try so hard to avoid and use every lazy trick you know to delay its inevitable implementation?

Now, I'm probably just being lazy, but I've always had to deal with code like that. Write something I don't feel like writing (and it's worse if you're doing it for fun and not getting paid!). A large system that will take a lot of time to get it into a stage where you get back any useful results or indication of it working. How do you start coding something like that? Most people would probably suggest divide and conquer and similar architectural techniques, but this isn't about how you do it; it's about how you get yourself started on doing it. What's the very first steps you'd take?

[A] I agree with you that many large, important parts of a software are not fun to write. I usually start my development day with some smaller things, like adding a feature here, or fixing a bug there. When it's time, I start with the large part, but when I just can't see the thing any more, I do something different. That's all fine if you still get everything done on time. And remember that it may make things easier if you talk with other people about that large beast before you're doing it, while you're doing and after you're done. This will not only free your mind, but you'll also get other people's opinion from a less subjective point of view. Planning such things together also helps.


q:
Design patterns are usually related to object oriented design.

Are there design patterns for creating and programming relational databases?

Many problems surely must have reusable solutions.

Examples would include patterns for table design, stored procedures, triggers, etc...

Is there an online repository of such patterns, similar to martinfowler.com?

Examples of problems that patterns could solve:

Storing hierarchical data (e.g. single table with type vs multiple tables with 1:1 key and differences...)

Storing data with variable structure (e.g. generic columns vs xml vs delimited column...)

Denormalize data (how to do it with minimal impact, etc...)

[A]
There's a book in Martin Fowler's Signature Series called
Refactoring Databases
. That provides a list of techniques for refactoring databases. I can't say I've heard a list of database patterns so much.
I would also highly recommend David C. Hay's
Data Model Patterns
and the follow up
A Metadata Map
which builds on the first and is far more ambitious and intriguing. The Preface alone is enlightening.
Also a great place to look for some pre-canned database models is Len Silverston's Data Model Resource Book Series
Volume 1
contains universally applicable data models (employees, accounts, shipping, purchases, etc),
Volume 2
contains industry specific data models (accounting, healthcare, etc),
Volume 3
provides data model patterns.
Finally, while this book is ostensibly about UML and Object Modelling, Peter Coad's
Modeling in Color With UML
provides an "archetype" driven process of entity modeling starting from the premise that there are 4 core archetypes of any object/data model


q:
At the moment I use PHP for almost everything I develop for the Web but its linguistic limitations are starting to annoy me. However, as I developed some practices and maintain some PHP libraries that help me a lot, I don't feel I'd be ready to just switch to LISP throwing away all my PHP output. It could even be impossible on the servers where all I have access to is a regular LAMP hosting account.

Ergo, my questions are:
Could LISP code be just combined with PHP one? Are there solutions for side-by-side LISP/PHP, interface for their interoperability or perphaps just an implementation of one for the other? Or is it a mutually exclusive choice?

[A]
It's not a mutually-exclusive choice, you can run both on one system, in the same way that perl and php (for example) are run side-by-side on many systems.
There's a
good post here
on a similar topic, which suggests using sockets to communicate between both languages -
If you want to go the PHP<->Lisp route the easyest thing to do would be to make PHP communicate with your Lisp-process using sockets.
http://php.net/manual/en/ref.sockets.php
http://www.sbcl.org/manual/Networking.html
This approach does still leave you with the potential added complexity and maintenance issues you get from having 2 languages in your project, but might be a fit for your particular use case.


q: Could anyone show me a sample about how to use these two commands in Windbg please? I read the document in debugger.chm, but confused. I did search in Google and MSDN, but not find an easy to learn sample.

[A]
Think in terms of function levels as per the following pseudo-code:
```
```
1  x = 0
 2  y = 0
 3  call 8
 4  x = 5
 5  y = 7
 6  call 8
 7  halt

 8  print x
 9  print y
10  call 12
11  return

12  print x + y
13  print x * y
14  return
```
```
The commands are basically "run until an event occurs".  The event causes the debugger to break (stop execution and await your command).
The "
```
gu
```
" command runs until it goes up to the next highest stack level.  If you're on lines 8, 9, 10 or 11, you'll end up at 4 or 7 depending on which "
```
call 8
```
" has called that code.  If you're on lines 12, 13 or 14, you'll break at 11.
Think of this as running until you've moved up the stack.  Note that if you first go down, you'll have to come up twice.
The "
```
pc
```
" command runs until the next call so, if you're on line 1, it will break at line 3.  This is sort of opposite to "
```
gu
```
" since it halts when you're trying to go
down
a stack level.


q:
Some years ago I was told about a study into code reuse. Apparently it was found that, on average, programmers have a 7 minute window when searching for code to reuse. If they don't find code that suits their needs within that window they'll write their own.

This was presented in the context of needing to carefully manage your code for reuse to ensure that you can find what you need within the window.

How do you (individuals and organisations) manage your source to make it easier to reuse?
Do you specifically maintain a reuse library? And if so, how do you index it to maximise your hit rate?

[A]
A complex question:
Some parts of the code can be generalized as libraries or APIs. We have a common library which is kept up to date with solutions to common problems. Typically: validation, caching, data access classes, logging, etc...
Some parts are application specific. They cannot be generalized easily. We convert them in HowTos and give internal presentations. Code is also recycled by use of an easily browsable SCM (in our case SVN).
We also have tools that generate code that one one hand cannot be recycled, on the other it's always similar (think calling a stored procedure).
Pair programming is also a useful way to spread knowledge of existing solutions. We use that when possible or appropriate.
The last technique is tuition. Each coder has a tutor to refer to. Since the tutors are few, there is a lot of sharing between them and this knowledge can be diffused in a top down manner.


q: 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?

[A]
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


q: 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.

[A]
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.


q:
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.

[A]
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);
```
```


q:
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.

[A]
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.


q:
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!

[A]
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).


q:
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?


q:
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.

[A]
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..."


q: 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?

[A]
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);
```
```


q:
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

[A]
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
.


q:
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.

[A]
```
```
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]);
    }
}
```
```


q: 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.

[A]
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
.


q:
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?

[A]
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
```
```


q:
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.

[A]
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.)


q:
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?

[A]
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.


q:
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?

[A]
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)))
```
```