Question:
I know that in JavaScript, creating a for loop like this: for(int i = 0; i < arr.length; i++) is costly as it computes the array length each time.
Is this behavior costly in c# for lists and arrays as well. Or at compile-time is it optimized?  Also what about other languages such as Java, how is this handled?

Answer:
It is
not
costly in C#. For one thing, there is no “calculation“: querying the length is basically an elementary operation thanks to inlining. And secondly, because (
according to its developers
), the compiler recognizes this pattern of access and will in fact optimize any (redundant) boundary checks for access on array elements.
And by the way, I believe that something similar is true for modern JavaScript virtual machines, and if it isn't already, it will be very soon since this is a trivial optimization.


Question:
I'm trying to convert my sites from CF8 to openBD.  I have a cfloop in a site that loops over a date range.

In essence, I want to insert a new record into the db for every 2 weeks (step) of a date range (from and to)

my loop looks like this...

<cfloop
  from  = "#form.startDate#"
  to    = "#form.endDate#"
  index = "i"
  step  = "#theStep#"
>

This works perfectly in CF8, in openBD, I get this error...
Data not supported: value [11/05/09] is not a number

Any ideas of a work around?

Thx

Answer:
I can't see your code, but here's my first suggestion:
```
```
<cfset current = [your begin date]>
<cfloop condition = "datecompare(enddate, current)">
  [do stuff]
  <cfset current = dateadd('d', 14, current)>
</cfloop>
```
```
HTH.


Question:
I have a RegEx that is working for me but I don't know WHY it is working for me. I'll explain.

RegEx: \s*<in.*="(<?.*?>)"\s*/>\s*

Text it finds (it finds the white-space before and after the input tag):

<td class="style9">
      <input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value="<?php echo $data[guarantor4]; ?>"  />    </td>
</tr>

The part I don't understand:

<in.*=" <--- As I understand it, this should only find up to the first =" as in it should only find <input name="

It actually finds: <input name="guarantor4" id="guarantor4" size="50" type="text" tabindex="10" value=" which happened to be what I was trying to do.

What am I not understanding about this RegEx?

Answer:
```
.*
```
is greedy. You want
```
.*?
```
to find up to only the first
```
=
```
.


Question:
I have a web server that runs my web application.

If I want to outsource my email to another provider, is it possible if they are on their on network/data center?

Answer:
Yes. To do this, you will need access to the DNS records for your domain. The MX record allows you to set up a mail server that's separate from the web server.
Google offers a service that will manage your domain's email through GMail, and the instructions on how to reconfigure your DNS for this service can be found
here
.


Question: I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a JProgressBar widget, which I would like to show the current progress of the download. For that I would need to know the size of the file. How do you get the size of the file prior to downloading the file.

Answer:
Any HTTP response is
supposed
to contain a Content-Length header, so you could query the URLConnection object for this value.
```
```
//once the connection has been opened
List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {

    // getHeaderFields() returns a Map with key=(String) header
    // name, value = List of String values for that header field.
    // just use the first value here.
    String sLength = (String) values.get(0);

    if (sLength != null) {
       //parse the length into an integer...
       ...
    }
```
```
It might not always be possible for a server to return an accurate Content-Length, so the value could be inaccurate, but at least you would get
some
usable value most of the time.
update:
Or, now that I look at the URLConnection javadoc more completely, you could just use the
getContentLength()
method.


Question:
I am looking for any and all suggestions of the best and effective resources that the StackOverflow community has used to better learn MSBuild with an emphasis on integrating unit tests and later static code analysis tools such as FxCop and StyleCop into the build process.

I have tried to find good clear documentation on adding unit tests into my build but I still am searching - even Google searches have come up empty or with just bits and pieces.  Ideally I want to add unit tests, report results, and eventually add code coverage statistics, etc into the build results.

I know it has to be in MSDN somewhere but I seem unable to find anything which explains and teaches well.  I am using Visual Studio Team System 2008.

Answer:
Continuous Integration From Theory to Practice
by Carel Lotz.  It covers the entire scope of your problem, and then some.  Well written, complete, and a full sample are all there.
Hands down best resource.  Use it as a tutorial first, then use it as a guide, then use it as a reference.
MSDN and others are good for clarifying (or confusing) the details.
Edit:
The guide by Carel Lotz uses MBUnit for unit tests (see his earlier document version for NUnit, though you can replace the MBUnit with NUnit pretty easily if you follow the NUnit help files).
Also, it is written to use Cruise Control.NET to run the MSBuild script in various configurations.
Personally, I run unit tests in a secondary MSBuild script, but have found that wrapping the NUnit calls in MSBuild gives more flexibility than running from CCNet directly.


Question:
I'm currently developing an html/ajax air app and am about to invest some effort into making animations using jQuery. I could do this quite a bit easier using the css animations if air had that recent a version of WebKit.

I know some people have alpha/beta versions of air 1.5. If you do, can you let me know?

Answer: I don't know offhand what AIR 1.5's CSS capabilities are, but it is a build with SquirrelFish, if that helps you track it down.


Question: Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes

Answer:
Java's answer to multiple inheritance is the ability to implement multiple interfaces.  Of course, this means you'll get the method declarations, but not the logic.
You could try emulating mixins by composition: your Java class could define member variables that represent other classes that perform some common business logic.
In designing Java classes, I have not found the lack of C++ style multiple inheritance to inhibit the design of my architecture.  You will find a way to achieve what you want to do.


Question:
I'm writing an image bank with Django, and I want to add a  button to get a hi-res version of an image (the low-res is shown in the details page).  If I put just an <a> link, the browser will open the image instead of downloading it.  Adding an HTTP header like:

Content-Disposition: attachment; filename="beach008.jpg"

works, but since it's an static file, I don't want to handle the request with Django.  Currently, I'm using NGINX to serve static files, and dynamic pages are redirected via FastCGI to the Django process.  I'm thinking about using NGINX add-header command, but could it set the filename="xx" part?.  Or maybe there's some way to handle the request in Django, but make NGINX serve the content?

Answer:
I wrote a simple decorator, for django.views.static.serve view
Which works for me perfectly.
```
```
def serve_download(view_func):
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        response['Content-Type'] = 'application/octet-stream';
        import os.path
        response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(kwargs['path'])
        return response
    return _wrapped_view_func
```
```
Also you can play with nginx mime-types
http://wiki.codemongers.com/NginxHttpCoreModule#types
This solution didn't work for me, because I wanted to have both direct link for the file (so user can view images, for example), and download link.


Question: You used to be able to get the package a Delphi component was installed under from the palette. That functionality doesn't seem to be in the lastest versions, though.  How can I find which package a component belongs to under D2007 or D2009?

Answer: I don't know of any way to do this through the Delphi IDE. However, you can do a search in your registry for the component name. For instance, to find the package that TBitBtn belongs to, open RegEdit and do a search (on Keys only) for TBitBtn. The entry for TBitBtn has a value called "Package Name". This is the internal name of the package, which is probably still not quite what you are looking for. Copy the "Package Name" value (dclstd100.bpl in my case), and do a search from the top (on Values this time) for that value. Once this entry is found you will see the "friendly" package name in the "Data" column.


Question:
I am looking for a backend solution for an application written in Ruby on Rails or Merb to handle data with several billions of records. I have a feeling that I'm supposed to go with a distributed model and at the moment I looked at

HBase with Hadoop

Couchdb

Problems with HBase solution as I see it -- ruby support is not very strong, and  Couchdb did not reach 1.0 version yet.

Do you have suggestion what would you use for such a big amount of data?

Data will require rather fast imports sometimes of 30-40Mb at once, but imports will come in chunks. So ~95% of the time data will be read only.

Answer:
There's a number of different solutions people have used. In my experience it really depends more on your usage patterns related to that data and not the sheer number of rows per table.
For example, "How many inserts/updates per second are occurring." Questions like these will play into your decision of what back-end database solution you'll choose.
Take Google for example: There didn't really exist a storage/search solution that satisfied their needs, so they created their own based on a Map/Reduce model.


Question:
In a tightly looped test application that prints out the value of DateTime.UtcNow.Ticks, I notice that the value will jump a remarkable amount once every hour or so.  Look closely at the following sample data:

1:52:14.312 PM - 633614215343125000
1:52:14.359 PM - 633614215343593750
1:52:14.421 PM - 633614215344218750
1:52:14.468 PM - 633614215344687500
1:52:14.515 PM - 633614215998593750 <-- WAY different

The delta is 653906250 ticks (65.390 seconds).  The only reason I can come up with is that the Windows Time service is doing some synchronization from underneath my feet.

Are there any experts out there that can confirm this?

Drifting a minute or so in about an hour seems pretty bad to me, but is that the case here?

Answer:
Can you post code to show how you generated this data?  And provide details about the machine you are running this on?
Using the following, I'm not getting what you are getting.
```
```
for (int i = 0; i < 10; i++)
        {

            Console.WriteLine(DateTime.Now.ToLongTimeString().ToString() + " - " + DateTime.UtcNow.Ticks.ToString());

            Thread.Sleep(10);
        }
```
```


Question:
I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it.

I have the id of the element, and the CSS class that I'm looking for.  I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.

Answer:
Use the
```
hasClass
```
method:
```
```
jQueryCollection.hasClass(className);
```
```
or
```
```
$(selector).hasClass(className);
```
```
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
Note:
If you pass a
```
className
```
argument that contains whitespace, it will be matched literally against the collection's elements'
```
className
```
string. So if, for instance, you have an element,
```
```
<span class="foo bar" />
```
```
then this will return
```
true
```
:
```
```
$('span').hasClass('foo bar')
```
```
and these will return
```
false
```
:
```
```
$('span').hasClass('bar foo')
$('span').hasClass('foo  bar')
```
```


Question:
Is there a way, within the .net framework, to check to see if two different shared folders are actually pointing to the same physical directory?  Do directories in Windows have some sort of unique identifier?  Google-fu is failing me.

(I mean, aside from writing a temp file to one and seeing if it appears in the other)

Edit: I think I've discovered what I need,with thanks to Brody for getting me pointed in the right direction in the System.Management namespace.

Answer:
You can examine the share definition itself by using the System.Management namespace but it is not easy to use.
it starts something like
```
```
ManagementClass management = new ManagementClass("\\\\.\\root\\cimv2", "Win32_Share", null)
```
```
And it gets much worse after that.  I have used it to create a share.  Hopefully you can use it to the path for each share and compare.


Question:
I have a Ruby script that generates a UTF8 CSV file remotely in a Linux machine and then transfers the file to a Windows machine thru SFTP.

I then need to open this file with Excel, but Excel doesn't get UTF8, so I always need to open the file in a text editor that has the capability to convert UTF8 to ANSI.

I would love to do this programmatically using Ruby and avoid the manual conversion step. What's the easiest way to do it?

PS: I tried using iconv but had no success.

Answer:
```
```
ascii_str = yourUTF8text.unpack("U*").map{|c|c.chr}.join
```
```
assuming that your text really does fit in the ascii character set.


Question:
I'm writing a program in C# that runs in the background and allows users to use a hotkey to switch keyboard layouts in the active window.  (Windows only supports CTRL+SHIFT and ALT+SHIFT)

I'm using RegisterHotKey to catch the hotkey, and it's working fine.

The problem is that I can't find any API to change the keyboard layout for the focused window.

ActivateKeyboardLayout and LoadKeyboardLayout  can only change the keyboard layout for the calling thread.

Does anyone know how to change the keyboard layout for a different thread (the way the Language Bar does)?

Answer:
I think the trick is to get your code to execute in the context of the thread whose keyboard layout you wish to change. You'll need to do some win32 interop here and learn about DLL Injection to get your code to execute in the remote thread.
A
keyboard hook handler
looks like a good option for you here.
Take a look at
http://www.codeproject.com/KB/threads/winspy.aspx


Question:
I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions.

Example:  "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc.

The current approach I'm thinking of consists of a state machine that eats one character at a time from the string and evaluates the expression after reaching '}'. Any hints or other suggestions?

Note: boost:: is most welcome! :-)

Update Thanks for the first three suggestions! Unfortunately I made the example too simple! I need to be able examine the contents within ${} so it's not a simple search and replace. Maybe it will say ${uppercase:foo} and then I have to use "foo" as a key in a hashmap and then convert it to uppercase, but I tried to avoid the inner details of ${} when writing the original question above... :-)

Answer:
How many evaluation expressions do intend to have?  If it's small enough, you might just want to use brute force.
For instance, if you have a
```
std::map<string, string>
```
that goes from your
```
key
```
to its
```
value
```
, for instance
```
user
```
to
```
Matt Cruikshank
```
, you might just want to iterate over your entire map and do a simple replace on your string of every
```
"${" + key + "}"
```
to its
```
value
```
.


Question: I'm reading The C++ Programming Language and in it Stroustrup states that the int value of a char can range from 0 to 255 or -127 to 127, depending on implementation. Is this correct? It seems like it should be from -128 to 127.  If not, why are their only 255 possible values in the second implementation possibility, not 256.

Answer:
You're stuck in
two's complement
thinking - The C++ standard does not define the representation used for negative numbers!
If your computer (god forbid) uses
ones's complement
to represent negative numbers, you have a range of -127 to + 127 in an 8-bit byte. On the upside, you have two different possible representations for zero...
However, in the real world,
you're unlikely to meet a one's complement computer
.


Question: Right now I'm not sure...

Answer:
I'd say yes.  I'm using it.  I know for a fact that Universal are using it on some of their (thousands of) sites.  I will add some caveats, however:
There are serious problems with setting it up, especially if you want to debug into the libraries.
The helper functions favour prototype, as opposed to the more modern jQuery.  This is changing rapidly, however.
The documentation is a bit chaotic, again the Castle Team are working on that.
I'm not guaranteeing every last "out-there" feature works, but the point of the system is actually to keep it simple.
Compared to vanilla ASP.NET, it's an absolute joy.  I assure you that you won't miss viewstate.


Question:
In .NET, the GetHashCode method is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when determining equality.

Is there a standard algorithm or best practice on how to implement GetHashCode for my custom classes so I don't degrade performance?

Answer:
I usually go with something like the implementation given in Josh Bloch's
fabulous
Effective Java
. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:
```
```
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + field1.GetHashCode();
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}
```
```
As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-
FNV
example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant
is
prime though. I don't know quite how important that is.)
This is better than the common practice of
```
XOR
```
ing hashcodes for two main reasons. Suppose we have a type with two
```
int
```
fields:
```
```
XorHash(x, x) == XorHash(y, y) == 0 for all x, y
XorHash(x, y) == XorHash(y, x) for all x, y
```
```
By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.
This page
gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The
FNV
alternative is similarly simple, but uses different constants and
```
XOR
```
instead of
```
ADD
```
as a combining operation. It looks
something
like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.
```
```
// Note: Not quite FNV!
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = (int) 2166136261;
        // Suitable nullity checks etc, of course :)
        hash = (hash * 16777619) ^ field1.GetHashCode();
        hash = (hash * 16777619) ^ field2.GetHashCode();
        hash = (hash * 16777619) ^ field3.GetHashCode();
        return hash;
    }
}
```
```
Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.
As per the
documentation
:
You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:
You can compute the hash code from fields that are not mutable; or
You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.
The link to the
FNV
article is broken but here is a copy in the Internet Archive:
Eternally Confuzzled - The Art of Hashing


Question:
Imagine the following REBOL code:

foo: context [bar: 3]

I now have a context foo in which 'bar is defined. How can I dynamically inject a new word into this context? Is it possible?

I've tried:

set/any in foo 'baz 3

But that doesn't work because the expression in foo 'baz fails because there is no word 'baz defined in the foo context.

I should add that I realize one way to do this is as follows:

foo-prototype: [bar: 3]
foo: context foo-prototype
foo: context head append foo-prototype [baz: 3]

But what if you don't have access to foo's prototype block?

Answer:
You can achieve the same by using the existing object as a prototype to create a new object.
```
```
>> foo: make object! [bar: 3]
>> foo: make foo [baz: 3]
>> probe foo
make object! [
    bar: 3
    baz: 3
]
```
```


Question:
I have a Java server that accepts SSL connections using JSSE and uses a simple XML message format inside the stream.  I would like the server to read a complete message and then send a reply.  This turns out to be quite difficult because org.xml.sax.XMLReader wants to read the entire stream and then call close().  I know it seems strange, but in Java 6 with the Sun JSSE provider this really does close both ends of the SSLSocket so no message can go back.  I tried using the shutdownOutput() method of Socket on the client side, but this is unsupported with JSSE.

My solution was to pass an InputStream wrapped in a custom class that silently ignores close requests and indicates that the stream is closed when it encounters the first blank line.  This constrains the XML beyond what is normally valid, but the client can easily filter out blank lines in the input if necessary.  Is there a better solution?

Answer:
I'm guessing that you are already doing dynamic assembly resolution and loading? If so, then you could try substituting a fake assembly name in place of the real assembly name i n the Xaml - you can then use that in your assembly resolution code to load up and return the right assembly. e.g. if your original source Xaml is:
```
```
xmlns:myassembly="clr-namespace:MyApp.MyAssembly;assembly=MyAssembly"
```
```
and you know that Xaml wants v2 of MyAssembly, replace the assembly ref in the Xaml string before parsing it to:
```
```
xmlns:myassembly="clr-namespace:MyApp.MyAssembly;assembly=MyAssembly.v2"
```
```
.. then in your assembly resolution / load code, when you see the ".v2" bit on the end you look for and load that assembly instead.
Please let me know if I've misunderstood the question, or you aren't current doing any custom assembly resolution - that would certainly be the key in this situation I think.


Question:
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.

Example - I have the following list:

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I want to have

result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]

So far what I've come up with is:

def add_list(array):
    number_items = len(array[0])
    result = [0] * number_items
    for index in range(number_items):
        for line in array:
            result[index] += line[index]
    return result

But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?

Answer:
```
```
[sum(a) for a in zip(*array)]
```
```


Question:
I have a C# .NET web project that I'm currently working on.  What I'm trying to do is read some files that I dropped into a dir which is at the same level as fileReader.cs which is attempting to read them.  On a normal desktop app the following would work:

DirectoryInfo di = new DirectoryInfo(./myDir);

However because it's a web project the execution context is different, and I don't know how to access these files?

Eventually fileReader will be called in an installation routine.  I intend to override one of the Installer.cs' abstract methods so will this affect the execution context?

Answer:
Use
```
Server.MapPath
```
to get the local path for the currently executing page.


Question:
I wish to dynamically change the scroll position of a Silverlight ListBox from C#, and I need to know how to access the ScrollViewer element of a ListBox control from C#?

Thanks guys,
Jeff

Answer:
Good question. I didn't find a way to do it directly, but came fairly close by looking at the Silverlight Controls project (they use the scrollviewer on the items control in some of the classes). Here is how you can get it, but it requires a custom listbox:
```
```
public class TestBox : ListBox
{
    private ScrollViewer _scrollHost;

    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        var itemsHost = VisualTreeHelper.GetParent(element) as Panel;

        for (DependencyObject obj = itemsHost; obj != item && obj != null; obj = VisualTreeHelper.GetParent(obj))
        {
            ScrollViewer viewer = obj as ScrollViewer;
            if (viewer != null)
            {
                _scrollHost = viewer;
                break;
            }
         }

        base.PrepareContainerForItemOverride(element, item);
    }
}
```
```
There might be another way to hook into that event (or another way to get that panel), If you look at the template for the ListBox you will see the scroll viewer is actually named "ScrollViewer", however the GetTemplateChild method is protected so you would still need to create a custom class.


Question:
In a forms model, I used to get the current logged-in user by:

Page.CurrentUser

How do I get the current user inside a controller class in ASP.NET MVC?

Answer:
I use:
```
```
Membership.GetUser().UserName
```
```
I am not sure this will work in ASP.NET MVC, but it's worth a shot :)


Question:
I am using the following code to determine free space on a volume.
The folder was provided using NSOpenPanel.  The item selected was a mounted volume and the path returned is \Volumes\Name

NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder];

unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue];

Is there a better method to determine the free space on a mounted volume using Cocoa?

Update: This is in fact the best way to determine the free space on a volume.  It appeared it wasn't working but that was due to the fact that folder was actually /Volumes rather  than /Volume/VolumeName

Answer:
statfs is consistent with results from df. In theory NSFileSystemFreeSize comes from statfs, so your problem should not exist.
You may want to run statfs as below as a replacement for NSFileSystemFreeSize:
```
```
#include <sys/param.h>
#include <sys/mount.h>

int main()
{
    struct statfs buf;

    int retval = statfs("/Volumes/KINGSTON", &buf);

    printf("KINGSTON Retval: %d, fundamental file system block size %ld, total data blocks %d, total in 512 blocks: %ld\n",
            retval, buf.f_bsize, buf.f_blocks, (buf.f_bsize / 512) * buf.f_blocks);
    printf("Free 512 blocks: %ld\n",  (buf.f_bsize / 512) * buf.f_bfree);
    exit(0);
}
```
```


Question:
We just switched from TFS to SVN, and so far we're loving it.

However, it did introduce a few new issues.

One is the way project files (.vbproj specifically) are handled. The .vbproj file is of course always changing as files and references are changed, and if a few people are collaberating there will be conflicts.

Oddly, in TFS we never had to deal with managing those conflicts, that particular piece was automagically handled. Now in SVN, we're mucking through XML in the merge tool and there have already been some mistakes.

How do you handle this? Any tips?

EDIT: by the way, we're using VisualSVN.

Answer:
This particular issue occurs if multiple developers add files to the same project.
To resolve a conflict when multiple developers have added files to the same project, you can usually make it work by resolving using "mine before theirs" option. It'll add both your changes together.
This issue and other merge issues are alleviated by committing and updating often. Commit once a day or more if possible. The longer you go without updating and committing, the more pain you and your team will feel.


Question:
I'm trying to use SubSonic for a new project with an existing database but when I try to build the project after generating the SubSonic files I'm getting these same two exceptions on different classes:

Partial declarations of 'MyData.UserCollection' must not specify different base classes

Type 'MyData.UserCollection' already defines a member called 'UserCollection' with the same parameter types

I'm able to successfully build a new project using the Northwind DB so I believe the error has something to do with the way the tables are setup but I'm not sure where to go from there.  Any help is appreciated.

Answer:
Search for UserCollection in your project. SubSonic generated a partial class for this in the User.cs generated file. You either have a UserCollection of your own in which case you should probably rename it or put it in another namespace. Either that, or you tried to add functionality to the UserCollection and you derive it from another type.
Last possibility is that you have a User table and a Users table. SubSonic will change Users to User. I'm not sure, but it might cause generation errors. I haven't tried it though.


Question:
In the following table structure:

Fruits
(
    fruit_id,
    fruitName
)

Vegetables
(
    vegetable_id,
    vegetableName
)

favoriteFoods
(
     food_id,
     foodName,
     type_id (References either a fruit or a vegetable)
)

I realize that I could forgo using a foreign key constraint on the favoriteFoods table and then simply add a type field to the favoriteFoods table to differentiate between fruits and vegetables.  But how would you structure the tables so that you could actually create the necessary foreign key constraints?

Answer:
I would only use 2 tables instead.  Instead of having a separate Fruits and Vegetables table, why not have a table of Foods.  Then have a foreign key constraint on fkfood_id to food_id.  Then if for some reason you ever have to add meat, it would be much easier to maintain the application that uses this.
```
```
Food
    (
    food_id,
    foodName,
    foodType
    )

favoriteFoods
    (
    favoritefood_id,
    fkfood_id
    )
```
```


Question:
I am evaluating VintaSoft .net control and Atalasoft DotTwain Image Capture. And I am very but very lost with the most of the definitions and keywords.

So I am asking this because I think I am in Lala land. Is it possible to listen or have the scanner tell my app that there is a scanned image and I can process it?

The idea is to have a winservice that is waiting for the scanner to scan something and when that happens process the image.

Answer:
[edit - if it was me, I'd look at adzm's answer ;-p]
As I understand it, regular TWAIN is a "pull", not a "push" from the scanner. I could well be wrong...
I expect such interfaces do exist for high end, high volume scanners (you know, the ones the size of a billiard table) - but not (AFAIK) for regular consumer scanners.
For use with .NET (and before that, COM), I've always managed with
ImageMan
.


Question:
I'm wondering how slow it's going to be switching between 2 databases on every call of every page of a site. The site has many different databases for different clients, along with a "global" database that is used for some general settings. I'm wondering if there would be much time added for the execution of each script if it has to connect to the database, select a DB, do a query or 2, switch to another DB and then complete the page generation. I could also have the data repeated in each DB, I just need to mantain it (will only change when upgrading).

So, in the end, how fast is mysql_select_db()?

Edit: Yes, I could connect to each DB separately, but as this is often the slowest part of any PHP script, I'd like to avoid this, especially since it's on every page. (It's slow because PHP has to do some kind of address resolution (be it an IP or host name) and then MySQL has to check the login parameters both times.)

Answer:
Assuming that both databases are on the same machine, you don't need to do the mysql_select_db. You can just specify the database in the queries. For example;
```
```
SELECT * FROM db1.table1;
```
```
You could also open two connections and use the DB object that is returned from the connect call and use those two objects to select the databases and pass into all of the calls. The database connection is an optional parameter on all of the mysql db calls, just check the docs.


Question:
A Java version of this question was just answered, and, well, I don't know how to do this in .net.

So how do you calculate the display width of a string in C# / .net?

Answer:
You've got the same problem in this question as was present in the Java question - not enough information! It will differ between WinForms and WPF.
For WinForms:
Graphics.MeasureString
For WPF I'm not sure, but I suspect it will depend on the exact way you're drawing the text...


Question:
Is there any Ruby equivalent for Python's builtin zip function? If not, what is a concise way of doing the same thing?

A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had zip, I could have written something like:

zip(a, b).all? {|pair| pair[0] === pair[1]}

I'd also accept a clean way of doing this without anything resembling zip (where "clean" means "without an explicit loop").

Answer:
Ruby has a zip function:
```
```
[1,2].zip([3,4]) => [[1,3],[2,4]]
```
```
so your code example is actually:
```
```
a.zip(b).all? {|pair| pair[0] === pair[1]}
```
```
or perhaps more succinctly:
```
```
a.zip(b).all? {|a,b| a === b }
```
```


Question:
I've inherited a ASP/VB6 code base (not my forte... yet) and I'm trying tease it apart to figure out the cause on an error message I'm receiving when running the app.

I've traced it back through an event that is being raised in on of my classes. Is there away in windows I can search the bulk of the code base for where it is being consumed?
Ctrl-F (and selecting Current Project) has not sufficed.

The linux geek in me is saying dump it to a insert distro box and just grep for the sucker. But there's got to be some way in the IDE to do it... right?

Answer:
But there's got to be some way in the IDE to do it... right?
No. There are some plugins for the IDE, such as the
MZ Tools
that
might
help. Otherwise, just use the
```
find
```
tool from the Windows command line. Not nearly as comfortable as using
```
grep
```
, of course.


Question: I've been having performance issues with a high traffic ASP.NET 2.0 site running on Windows 2000.  While editing the web.config file I noticed that the authentication mode was set to 'Windows'.  I changed it to 'None'.  The only users this site has are anonymous and it gets 25,000+ page views at day.  Could this have been a caused performance issues?

Answer:
But there's got to be some way in the IDE to do it... right?
No. There are some plugins for the IDE, such as the
MZ Tools
that
might
help. Otherwise, just use the
```
find
```
tool from the Windows command line. Not nearly as comfortable as using
```
grep
```
, of course.


Question:
I have a multidimensional array. I need to search it for a specific range of values, edit those values and return the edited data.

Example array:

array(3) {
  ["first"]=>
  array(1) {
    [0]=>
    string(4) "baz1"
  }
  ["second"]=>
  array(1) {
    [0]=>
    string(4) "foo1"
  }
  ["third"]=>
  array(1) {
    [0]=>
    string(4) "foo2"
  }

Now I want to find any values that match foo (foo1 and foo2 in the example array), insert "-bar" into them (foo-bar1, foo-bar2) and return that value. What are the best ways to approach this?

EDIT I should have mentioned that foo could actually be anythingfoo (ex. examplefoo1, somethingelsefoo2, blahblahfoo3). I think this rules out str_replace.

Answer:
How about something like this:
```
```
function addDashBar($arr)
{
    foreach ($arr as $key => $value)
    {
       if (is_array($value))
           $arr[$key] = addDashBar($value)
       else
       {
           $arr[$key] = str_replace($value, "foo", "foo-bar");
       }
    }

    return $arr;
}
```
```


Question:
In eclipse, I have a javaproject (not a web project), though it does provide reusable tag files.

layout

+src

+++META-INF

----my.tld

+++++++++++tags

---------------include.jsp

I keep on getting Fragment "/META-INF/tags/include.jsp" was not be found at expected path /Project/META-INF/tags/taginclude.jsp

How can I modify the path eclipse is looking for? I need to tell it to include "src" in the lookup

Answer:
Josh, if you're working with .jsp and .tld files, then you really shouldn't be doing this as a "Java Project", but instead a "Dynamic Web Project" in Eclipse.  Nonetheless, I'll try to answer your question.
Based on the diagram of your file system, your files are laid out incorrectly.  If you're trying to create a web app (a .war file), then you need a WEB-INF directory.  Under the WEB-INF directory you'll need a web.xml file (google for web.xml to see what needs to be in there), a tags directory, and a classes and lib directory.
Compiled class files must go in the WEB-INF/classes directory.
Jar files that you depend on must go in the WEB-INF/lib directory.
Tablibs must go in the WEB-INF/tags directory.
Finally, your .jsp files must go in src directory (the parent dir of WEB-INF).
So, your layout should look like this:
```
myproject/
`-- src
    |-- WEB-INF
    |   |-- classes
    |   |   `-- MyClass.class
    |   |-- lib
    |   |   `-- my.jar
    |   |-- tags
    |   |   `-- my.tld
    |   `-- web.xml
    `-- include.jsp
```
Hope this helps.
-Bryan


Question:
There's a requirement that we will need to support querying a local SQL Server database for new data when the database is updated.  Since these are external SQL Server databases, we may not be able to use SQL Server Notification Services nor can we make any changes to the database.

My basic idea is to watch for data being written to the database to trigger a query (instead of polling at set intervals).  However, I'm having a tough time trying to figure out how I could get the WriteFile call from the SqlServr.exe process (as can be monitored in tools such as Sysinternals' Process Monitor).  Can anyone direct me to which Win32 functions may be able to help me with this?

Answer:
I don't think going through the file system would be the best option. Even if you could get access to file system activity, I would think it would be difficult to discern what file operation added data vs any other type of file activity like maintenance, index defrags, etc.
A possible alternative would be to look into the
Microsoft.SqlServer.Management.Trace Namespace
as a mechanism to hook into SQL Server and look for the specific events that you want to respond to. I would be cautions however of the performance impact this may cause.


Question: Currently I have subversion set up so that when I make changes in Eclipse PDT, I can commit the changes and they will be saved in /home/administrator/Project File.  This file has the /branches /tags and /trunk directories recommended by subversion.  I have no problem properly uploading files to the repository, but do I have to "mv" the files in Linux to /var/www in order to make them live on the server?  Is there an automatic process to do this that I am missing?  I'm assuming we don't want to make the /var/www directory (which is live on the machine) the repository, but I don't know.

Answer:
You can do an
```
svn export
```
into your www directory. That will give you a "clean" version of your repo, without the .svn directories.
```
```
cd /var/www
svn export /home/administrator/MyProject/trunk MyProject
```
```
Edit: adding in some good ideas from the comments...
Some options for when you want to update your exported copy:
run
```
svn export --force /home/...../ MyProject
```
this will stop it complaining about overwriting the existing files. This method will mean that if you delete a file from your repository, it'll still remain in your www folder.
change your SVN command to export into a new directory each time:
```
svn export /home/..../ MyProject_20081105
```
and then create a symlink to that folder:
```
ln -s MyProject_20081105 MyProject
```
Just delete and recreate the symlink each time you "release". In this case, the export directory doesn't need to be in the
```
www
```
folder at all.


Question:
I have 15 stored procedures that return data from a common table and then join that table with a specific table to retrieve inventory.

Example:

Common: tblCommon
Specific: tblSpecific

Is there way I can pass the name "tblSpecific" into a single stored procedure as a variable, like the following?

SELECT ....
FROM tblCommon c
INNER JOIN @TABLE s on c.primaryKey = s.foreignKey

Answer:
Yep, you can generate an SQL statement dynamically and then execute it.
For example,
```
```
DECLARE @specificTableName nvarchar(50)
DECLARE @specificColumnName nvarchar(50)

SET @specificTableName = 'tblSpecific'
SET @specificColumnName = 'colSpecific'

DECLARE @sql nvarchar(4000)

set @sql = 'SELECT ... FROM tblCommon c INNER JOIN ' +
@specificTableName + ' s ON c.PrimaryKey = s.' + @specificColumnName

exec (@sql)
```
```


Question:
Alright. I have a query that looks like this:

SELECT
    SUM(`order_items`.`quantity`) as `count`,
    `menu_items`.`name`
FROM
    `orders`,
    `menu_items`,
    `order_items`
WHERE
    `orders`.`id` = `order_items`.`order_id` AND
    `menu_items`.`id` = `order_items`.`menu_item_id` AND
    `orders`.`date` >= '2008-11-01' AND
    `orders`.`date` <= '2008-11-30'
GROUP BY
    `menu_items`.`id`

The purpose of this query is to show the amount of items sold in a given date range. Although this works, I now need it to show a count of 0 if a particular item has no sales in the date range. I tried using COALESCE around the SUM but that didn't do the trick, and I didn't really expect it to. Anyhow, does anyone know how I would go about accomplishing this? I'm having one of those moments where I feel like I should know this but I can't think of it.

Cheers

Answer:
Randy's answer is close, but the where statement removes any mention of those items not part of any orders in that date range.
Note that "left join" is different to linking tables in the where clause in the manner you have done (i.e. inner joins). I suggest you read up on the different types of SQL joins (inner, outer, cross).
In essense, you need to join the data you get from Randy's query against your source list of items. Using a subselect will do this:
```
```
SELECT
    name
    , nvl(count, 0) as count
FROM
    menu_items items
    LEFT JOIN (
        SELECT
            menu_items.id
            , SUM(order_items.quantity) as count
        FROM
            menu_items
            LEFT JOIN order_items ON menu_items.id = order_items.menu_item_id
            LEFT JOIN orders ON orders.id = order_items.order_id
        WHERE
            "date" between to_date('2008-11-01','YYYY-MM-DD') and to_date('2008-11-30','YYYY-MM-DD')
        GROUP BY
            menu_items.id
    ) counts on items.id = counts.id;
```
```
This is in Oracle 10g BTW. I doubt you're using Oracle, so you'll need to convert to your own database.
Running a test shows the following:
```
```
SQL> create table menu_items ( id number, name varchar2(10));
create table order_items (order_id number, menu_item_id number, quantity number);
create table orders (id number, "date" date);

Table created.

SQL>
Table created.

SQL>
Table created.

SQL>
insert into menu_items values (1, 'bread');
insert into menu_items values (2, 'milk');
insert into menu_items values (3, 'honey');
insert into menu_items values (4, 'cheese');
SQL>
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL>
insert into orders values (1, to_date('2008-11-02', 'YYYY-MM-DD'));
insert into orders values (2, to_date('2008-11-03', 'YYYY-MM-DD'));
insert into orders values (3, to_date('2008-10-29', 'YYYY-MM-DD'));SQL>
1 row created.

SQL>
1 row created.

SQL>
insert into order_items values (1, 1, 1);
insert into order_items values (1, 3, 1);
1 row created.

SQL>
1 row created.

SQL>
insert into order_items values (2, 1, 1);
insert into order_items values (2, 2, 1);
insert into order_items values (2, 3, 1);

insert into order_items values (3, 4, 10);
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL>
1 row created.

SQL> SQL>

1 row created.

SQL>
SELECT
    name
    , nvl(count, 0) as count
FROM
    menu_items items
    LEFT JOIN (
        SELECT
            menu_items.id
            , SUM(order_items.quantity) as count
        FROM
            menu_items
            LEFT JOIN order_items ON menu_items.id = order_items.menu_item_id
            LEFT JOIN orders ON orders.id = order_items.order_id
        WHERE
            "date" between to_date('2008-11-01','YYYY-MM-DD') and to_date('2008-11-30','YYYY-MM-DD')
        GROUP BY
            menu_iteSQL>   2    3    4    5    6    7  ms.id
    ) counts on items.id = counts.id;  8    9   10   11   12   13   14   15   16   17   18

NAME            COUNT
---------- ----------
bread               2
milk                1
honey               2
cheese              0

SQL>
drop table menu_items;
drop table order_items;
drop table orders;SQL>
Table dropped.

SQL>
Table dropped.

SQL>

Table dropped.

SQL>
```
```
PS: It's bad practice to use 'date' as a column name as it is (in most cases) a type name and can cause problems to queries and parses.


Question:
The first batch file launches a command prompt, i need the second command to be in the ccontext of the first.  how can I do this in python?

As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes devenv without the necessary context.

os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')

think of it as in i'm in bash, and i need to execute a command in a perl context, so i type perl -c 'asdf'.  executing perl and asdf back to back won't work, i need to get the devenv inside of the perl context.

Answer:
You could append the devenv command onto the end of the original batch file like so:
```
```
'%comspec% /k "...vcvarsall.bat" x86 && devenv asdf.sln /rebuild ...'
```
```
(obviously I have shortened the commands for simplicity's sake)


Question: Is there a way to create a Distinct query in HQL.  Either by using the "distinct" keyword or some other method.  I am not sure if distinct is a valid keywork for HQL, but I am looking for the HQL equivalent of the SQL keyword "distinct".

Answer:
Here's a snippet of hql that we use. (Names have been changed to protect identities)
```
```
String queryString = "select distinct f from Foo f inner join foo.bars as b" +
                " where f.creationDate >= ? and f.creationDate < ? and b.bar = ?";
        return getHibernateTemplate().find(queryString, new Object[] {startDate, endDate, bar});
```
```


Question:
I have been searching for a way to allow one element of my FileHelpers mapping class to be an array of specific length.

For instance, I have a class like this:

[DelimitedRecord(",")]
public class Example
{
    public string code;
    public int month;
    public int day;
    public double h1;
    public double h2;
    public double h3;
    public double h4;
}

The values h1-h4 would really make more sense as an array simply called 'h'.  It would make processing the file a little easier as well.
I also know that the file I am reading will always have these, and only these, fields in it.

Has anyone figured out a way to include arrays in your FileHelper mapping classes?

Answer:
I don't know anything about the tool in question, but (assuming it isn't a limitation of the tool) I
really
doubt the wisdom of public fields. Properties would also give you the opportunity to shim the values:
```
```
[DelimitedRecord(",")]
public class Example
{
    public string Code {get;set;}
    public int Month {get;set;}
    public int Day {get;set;}

    private readonly double[] h = new double[4];

    public double H1 {get {return h[0];} set {h[0] = value;}}
    public double H2 {get {return h[1];} set {h[1] = value;}}
    public double H3 {get {return h[2];} set {h[2] = value;}}
    public double H4 {get {return h[3];} set {h[3] = value;}}
}
```
```
Again - I have no idea if the tool would support this, but it would be a viable way of implementing it. Of course, the "h" values would do just as well (actually, slightly more efficient - no array on the heap and no de-reference) as direct members:
```
```
public double H1 {get;set;}
    public double H2 {get;set;}
    public double H3 {get;set;}
    public double H4 {get;set;}
```
```


Question:
AlertEvent::AlertEvent(const std::string& text) :
    IMEvent(kIMEventAlert, alertText.c_str()),
    alertText(text)
{
    //inspection at time of crash shows alertText is a valid string
}

IMEvent::IMEvent(long eventID, const char* details)
{
    //during construction, details==0xcccccccc
}

on a related note, the monospace font looks really terrible in chrome, whats up with that?

Answer:
The IMEvent constructor is called before alertText's constructor is called. In particular therefore its argument
```
alertText.c_str()
```
is evaluated before alertText's constructor is called. This ain't good.
Initializer expressions are called in the order that the things being initialized are declared (not necessarily the order the initializers are listed). So parent classes first, then members. Compilers sometime helpfully warn you if you don't list the initializers in the order they will actually be executed. So provided you get that right, the rule is "don't use anything you haven't initialized". This code uses alertText before it is initialized.


Question: I am trying to get the DataGridView to render the "insert new row" row as the first row in the grid instead of the last row. How do I go about doing that, is it even possible in the control?

Answer:
I don't think there is any way to move the "new row" row to the top of the data grid.
But, what if you left the top row empty and as the data filled in move the row down as appropriate?  In other words, make your own "new row" row, which is just first row in the grid and add new blank rows above when editing is over.
```
```
Dim myrow = existingDataTable.NewRow

    existingDataTable.Rows.Add(myrow)

    adp.Fill(existingDataTable)
    With DataGridView1
        .DataSource =existingDataTable
    End With
```
```


Question:
I have N items of 2D image data that will be rectangular and I want to pack them into a single power of 2 texture as efficiently as possible.

A simple non-efficient and naive implementation of an algorithm to pack these rects would be easy to whip up, but I'm sure people have come up with algorithms to do this as space efficiently as possible.  I've found various references to lightmap packing which is similar to what I'm looking for, but the algorithms for lightmapping tend to take non-rectangular images into account which actually complicates things more than I need them to be.

Does anyone have hints? Names of algorithms or paper authors I should google?

Thanks.

Answer:
Your problem in 1D is called Bin Packing. Perhaps that's a good start for your search.
Note that the problem you want to solve is really hard (it is NP-hard). So you should not search for the optimal solution, but some clever heuristical algorithm.
I think bottom-up dynamic programming is possible for 1D bin packing, but not for the 2D case.
You could think of simplifying your problem by only solving the 1D problem, making restrictions like cutting the textures into several (variable sized) slices in 1 dimension.
Another possiblity is running meta-heuristic optimization on it, like Evolutionary Algorithms or Particle Swarm Optimization.


Question:
For my small wiki application, I mostly need to have the textarea used to edit the contents to use soft (or virtual) wrapping. However, in some cases, not wrapping the content would be preferable. I thought I would do this by simply having a button to turn off wrapping. Here is the simplified code:

  <form name="wikiedit" action="[[script_name]]" method="post">
    <textarea name="content" rows="25" cols="90" wrap="virtual">[[content]]</textarea>
    <input type="button" onclick="document.wikiedit.content.wrap='off';" value="No Wrap"> &nbsp;
    <input type="submit" value="Save">
  </form>

It works with IE, but not with Firefox or Opera. How should I do this?

Answer:
According to
the HTML 4.01 spec
,
```
wrap
```
isn't a valid attribute for
```
<textarea>
```
s which would explain why it's so difficult and strange. It looks as though Firefox actually does use the
```
wrap
```
attribute, but it won't let you change it.
I do have a solution though! It's pretty awful, but here it is. Completely replace the textarea with a new one.
```
```
// this is the onclick handler for your button
document.getElementById("nowrapButton").onclick = function() {
  var oldOne = this.form.content;  // the old textarea
  var newOne = document.createElement('textarea'); // the new textarea
  var attrs = ['name', 'rows', 'cols']; // these are the attributes to keep
  for (var i = 0; i < attrs.length; ++i) {
    // copy the attributes to the new one
    newOne.setAttribute(attrs[i], oldOne.getAttribute(attrs[i]));
  }

  // toggle the wrapping on and off
  if (oldOne.getAttribute('wrap') != 'off') {
    newOne.setAttribute('wrap', 'off');
  }

  // copy the text over
  newOne.value = oldOne.value;

  // add the new one
  oldOne.parentNode.insertBefore(newOne, oldOne);
  // get rid of the old one
  oldOne.parentNode.removeChild(oldOne);
  return false;
};
```
```
Here's a working version of this you can play with:
http://jsbin.com/ugepa
As usual, this'd be much nicer in jQuery. :)


Question:
In the following code I loop through a map and test if an element needs to be erased.  Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?

map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;
for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++)
{
    if (pm_it->second == delete_this_id) {
        port_map.erase(pm_it->first);
    }
}

UPDATE: Of course, I then read this question which I didn't think would be related but answers my question.

Answer:
C++11
This has been fixed in C++11 (or erase has been improved/made consistent across all container types).
The erase method now returns the next iterator.
```
```
auto pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        pm_it = port_map.erase(pm_it);
    }
    else
    {
        ++pm_it;
    }
}
```
```
C++03
Erasing elements in a map does not invalidate any iterators.
(apart from iterators on the element that was deleted)
Actually inserting or deleting does not invalidate any of the iterators:
Also see this answer:
Mark Ransom Technique
But you do need to update your code:
In your code you increment pm_it after calling erase. At this point it is too late and is already invalidated.
```
```
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        port_map.erase(pm_it++);  // Use iterator.
                                  // Note the post increment.
                                  // Increments the iterator but returns the
                                  // original value for use by erase
    }
    else
    {
        ++pm_it;           // Can use pre-increment in this case
                           // To make sure you have the efficient version
    }
}
```
```


Question:
Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better way to accomplish this?

Answer:
Do:
```
```
var isTrueSet = (myValue === 'true');
```
```
using the identity operator (
```
===
```
), which doesn't make any implicit type conversions when the compared variables have different types.
This will set
```
isTrueSet
```
to a boolean
```
true
```
if the string is "true" and boolean
```
false
```
if it is string "false" or not set at all.
Don't:
You should probably
be cautious about using these two methods
for your specific needs:
```
```
var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true
```
```
Any string which isn't the empty string will evaluate to
```
true
```
by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.


Question:
What's the best way to convert NetBeans (Matisse) .form files into .java files, without using the NetBeans IDE itself? Ideally I'd like to package the .form files along with my source code, and generate the .java files at build time. This will prevent developers from "accidentally" adding code to the generated .java file using some other IDE, which could then get overwritten by NetBeans the next time the form itself is edited in the GUI designer.

I've searched Google and all I can find is people saying, "Use the NetBeans IDE to generate the .java file," which is kind of difficult to do at build-time.

Answer:
Well, actually having to fight with "accidental" addition of codes is more a problem of process rather than a problem with technology. My steps would be:
Prevent committing the generated .java files in the CVS/SVN repository
Embed matisse form generation in a continuous integration project.
For step 1:
Use a sensible naming convention and stick with the standard for all the gui object, e.g.: put all the forms inside a common package and use the .svnignore directive on java files in it.
For step 2:
Fabrizio Giudici has a nice tutorial on how to build a netbeans project (yes using matisse) inside a continuous integration environment.
http://weblogs.java.net/blog/fabriziogiudici/archive/2006/11/setting_up_netb.html
Note that he talks about installing netbeans first on a machine with a gui then moving the jar files in an headless machine. IIRC it was possible to install Netbeans version 4.x in an headless environment without using the gui (since it is a java application, the only steps to do were to unzip the files and create a sensible shell file launching the application with the correct jvm/classpath combo).
Anyway, if you can't enforce both rules, or you can't find how to generate the matisse artifacts in the CI server, consider the possibility to scrap the use of matisse entirely.


Question:
Yeah, I know the title is a mouthful...

What I mean is to say is how do you communicate with a subject matter expert who needs a theory coded and tested?

For example, weather simulation is a collaboration between meteorologists, computer scientists, and software engineers.  The computer scientists and software engineers generally speak the same language, but he meteorologist is in a completely different world.

How do you increase the level of communication and understanding between disciplines?  And not necessarily just for weather, other sciences too.

Answer:
The shortest possible answer is Continuous customer involvement.
All the pretty UML diagrams, crayola UI mockups, explanations-to-four-year-olds and other techniques will never give the full experience of using a working application. Keeping the consumer in the loop allows for a feedback cycle both to the client, and from the client to you.  This symbiotic relationship has the greatest likelyhood of producing a product that will be useful to them.
If you go into a box and come out with a product that you think they need it will likely be a whole lot of what they don't want.  By regularly demoing your product you limit the impact of any misunderstanding, so that you don't spend too much time going down the wrong path.
It can be compared to dead reckoning. If you blindfold yourself and try to navigate through an area you know, the error between where you are and where you think you are will accumulate with time.  If, however, you take off the blindfold periodically you can update your mental location.  There will still be an error factor, but you are eliminating the accumulating error factor.
Even if you think your communication/explanatory skills are top notch, you still have to account for error in the way they communicate.


Question:
I have a Delphi 5 executable that calls into a .NET assembly via the free Delphi .NET code, and for the most part, this works great.  However, one of the requirements of my application is that our clients be able to use this from a networked share as well as local.  On my test machine, I can't get this to work, I just get an error message.  The .NET code has it's permissions set to full, but some error comes back that Delphi can't seem to get or interpret.  On a local drive, the application and assembly communicate flawlessly.

Can anyone tell me how to at least get the error messages back from this?  Or if possible, can anyone tell me why I would get errors this way?  Thanks.

Answer:
You say that you have given the code full permissions, but have you assigned FullTrust to the network share? In .NET, network shares are part of the local intranet domain, so you lose some trust. Run something like;
```
```
CasPol.exe -m -ag 1.2 -url file://\\ShawnFa-Srv/Tools/* FullTrust
```
```
For more info see this post about the topic,
Using CasPol to Fully Trust a Share


Question:
I don't want to include relations in my edmx entity framework, I want to have the foreign key field as a normal property in my entity.

How can I do that?

Answer:
http://www.thedatafarm.com/blog/2007/09/11/EntityDataModelAssociationsWheresMyForeignKey.aspx
I found the article describing the error in our ways...
basically we never supposed to be querying tables via foreign keys instead
take a bit more relational approach
```
```
(From o In nw.Orders
 Where o.OrderID = 10281
 Select o.Customers
).First
```
```


Question:
I find it much easier to write MXML classes with embedded Script than trying to make an actionscript file.

I was wondering however what kind of overhead there is of using an MXML file - in terms of file size. I'm not especially concerned about performance, but if that is relevant would be interested in any findings.

Obviously I'm talking about UI components that have layout. MXML is MUCH easier to visualize and modify but I'm unclear exactly what it compiles down too. I'm hoping there is a negligible difference.

Answer:
If you're going for the same functionality, MXML is not going to make your swf any bigger.
The thing that's affecting size is using the Flex SDK and its components. Whether you declare them with MXML or AS3, you're using them and their code is being built into the swf. By the same token, if you're referencing the Flex RSL, and thus avoiding building the Flex stuff directly into your swf, it will be the same size either way. Data Binding does create a lot of events and listeners, so that might cause some bloat, but not any more than if you declared the data binding mechanism with the AS3 utility functions.
Since MXML does generate intermediate AS3 code, it might be more verbose than you would care to write on your own, so you could see some additional size from that. To peek at it (which is good for understanding in general) you can look at with the compiler directive to keep the generated code.
From:
http://www.flashguru.co.uk/flex-2-compilation-hidden-goodies
Right-click a Flex Project in the Navigator Panel.
Select Properties from the Context Menu.
Select Flex Compiler in the Properties Window.
Enter -keep-generated-actionscript into the ‘Additional compiler
  arguments’ field.
Click ‘OK’ to apply the changes.
Build your Flex Project by clicking the Run button.
Right-click your Flex Project again in the Navigator Panel.
Choose Refresh from the Context-Menu.
A new folder should appear under your Flex Project in the Navigator
  Panel, named ‘generated’
This is a good thing to do once you get into debugging and profiling your project, since you can really see where the compiler is doing the right (or wrong) thing.


Question:
For example:

First, say I have a Silverlight app with Windowless=true so that I can place ASP.NET controls on top of it.  Then I place an ASP.NET button on the page.  How can I have say the text of a control in the Silverlight app change when the user presses the ASP.NET button?  How would I send the Silverlight app an update message from the C# code that catches the Click of the ASP.NET button?

Thanks,
Jeff

Answer:
Splitting the content of your file into multiple files - one file per class may help.
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=283434
Up-to-date link:
https://developercommunity.visualstudio.com/content/problem/389773/vs-2017-keeps-removing-and-re-adding-aspxcodebehin.html


Question:
What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g.

3.5 would return 4 for power of 2 and 1 for power of 10

123 would return 128 for power of 2 and 100 for power of 10

0.24 would return 0.25 for power of 2 and 0.1 for power of 10

I'm just looking for the algorithm and don't mind the language.

Answer:
```
```
n^round(log_n(x))
```
```
where log_n is the logarithm to base n. You may have to modify the round() depending on how you define "closest".
Note that
```
log_n(x)
```
can be implemented as:
```
```
log_n(x) = log(x) / log(n)
```
```
where
```
log
```
is a logarithm to any convenient base.


Question:
How can I make:

DELETE FROM foo WHERE id=1 AND bar not contains id==1

To elaborate, how can I remove a row with id = 1, from table foo, only if there is not a row in table bar with id = 1.

Answer:
```
```
DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1)
```
```
I'm assuming you mean that foo and bar are tables, and you want to remove a record from foo if it doesn't exist in bar.


Question:
I have a program that when it starts, opens a winform (it is the one specified in Application.Run(new ...). From this form I open another form:

OtherForm newForm=new OtherForm();
newForm.Show();

How can i communicate from the new winform with the form that opened it? So that I can add some items in it.

Answer:
The simplest way is to override the constructor, eg,
```
OtherForm newForm=new OtherForm(string title, int data);
```
. This also works for reference types (which would be a simple way to send the data back).


Question:
We've got an application we'd like our users to download.  Currently they click a link and download the EXE.  What we'd like to do is have a launchpad/downloader application that would be small and fast to download, which would then download and install the main application.

In a perfect world the downloader would be a MSI (so we could modify some MSI databases).

I'm a seriosu MSi newbie, so I've got no real ideas on where ot even start looking.  Any help or pointers woudl be much appreciated!

Thanks

Andy

Answer:
You'll need to write a bootstrap EXE, there's a little bit of documentation in
Windows Installer SDK
or if you're wanting to take the lazy route, it looks like
MSI Factory
includes WiX compatibility and a customizable bootstrap EXE including HTTP download options.
Alternatively if you're sticking to Open-Source, checkout ClickThrough in WiX. Doesn't seem to be much info on the WiX site, so I'm guessing it's part of WiX 3. But the description sounds similar to what you need.


Question: How can I fetch more than 1000 record from data store and put all in one single list to pass to django?

Answer:
You can't.
Part of the FAQ states that there is no way you can access beyond row 1000 of a query, increasing the "OFFSET" will just result in a shorter result set,
ie: OFFSET 999 --> 1 result comes back.
From Wikipedia:
App Engine limits the maximum rows
  returned from an entity get to 1000
  rows per Datastore call. Most web
  database applications use paging and
  caching, and hence do not require this
  much data at once, so this is a
  non-issue in most scenarios.[citation
  needed] If an application needs more
  than 1,000 records per operation, it
  can use its own client-side software
  or an Ajax page to perform an
  operation on an unlimited number of
  rows.
From
http://code.google.com/appengine/docs/whatisgoogleappengine.html
Another example of a service limit is
  the number of results returned by a
  query. A query can return at most
  1,000 results. Queries that would
  return more results only return the
  maximum. In this case, a request that
  performs such a query isn't likely to
  return a request before the timeout,
  but the limit is in place to conserve
  resources on the datastore.
From
http://code.google.com/appengine/docs/datastore/gqlreference.html
Note: A LIMIT clause has a maximum of
  1000. If a limit larger than the maximum is specified, the maximum is
  used. This same maximum applies to the
  fetch() method of the GqlQuery class.
Note: Like the offset parameter for
  the fetch() method, an OFFSET in a GQL
  query string does not reduce the
  number of entities fetched from the
  datastore. It only affects which
  results are returned by the fetch()
  method. A query with an offset has
  performance characteristics that
  correspond linearly with the offset
  size.
From
http://code.google.com/appengine/docs/datastore/queryclass.html
The limit and offset arguments control
  how many results are fetched from the
  datastore, and how many are returned
  by the fetch() method:
The datastore fetches offset + limit results to the application. The first offset results are
not
skipped by the datastore itself.
The fetch() method skips the first offset results, then returns the rest (limit results).
The query has performance characteristics that correspond
  linearly with the offset amount plus the limit.
What this means is
If you have a singular query, there is no way to request anything outside the range 0-1000.
Increasing offset will just raise the 0, so
```
```
LIMIT 1000  OFFSET 0
```
```
Will return 1000 rows,
and
```
```
LIMIT 1000 OFFSET 1000
```
```
Will return
0 rows
, thus, making it impossible to, with a single query syntax, fetch 2000 results either manually or using the API.
The only plausible exception
Is to create a numeric index on the table, ie:
```
```
SELECT * FROM Foo  WHERE ID > 0 AND ID < 1000

 SELECT * FROM Foo WHERE ID >= 1000 AND ID < 2000
```
```
If your data or query can't have this 'ID' hardcoded identifier, then you are
out of luck


Question:
I've been reading on the blogosphere for the past week that Linq to SQL is dead [and long live EF and Linq to Entities].  But when I read the overview on MSDN, it appeared to me Linq to Entities generates eSQL just the way Linq to SQL generates SQL queries.

Now, since the underlying implementation (and since SQL Server is not yet an ODBMS) is still a Relational store, at some point the Entity framework has to make the translation into SQL queries.  Why not fix the Linq to SQL issues (m:m relationships, only SQL server support etc.) and use Linq to SQL in as the layer that generates these queries?

Is this because of performance or EF uses a different way of transforming the eSQL statement into SQL?

It seemed to me - at least for my unlearned mind - a natural fit to dogfood Linq to SQL in EF.

Comments?

Answer:
It is worth noting that Entity Framework has (at least) three ways of being consumed:
LINQ to Entities over Object Services over Entity Client
Entity SQL over Object Services over Entity Client
Entity SQL using Entity Client command objects (most similar to classic ADO.NET)
Entity Client ultimately spits out a representation of the ESQL command (in a canonical, database agnostic form) which the ADO.NET Provider for the specific RDBMS is responsible for converting into store specific SQL. This is the right model IMHO as over the years a lot of time has been invested (and will continue to be invested) in producing great ADO.NET Providers for each store.
As Entity Framework needs to work with many stores and therefore many ADO.NET Providers there is less scope for them to easily optimise what the Entity Client generates on a per store basis (at least - thats where we are with v1). The LINQ to SQL team had a much smaller problem to solve - "works only with SQL Server" and hence could do store specific stuff more easily. I know the EF team are aware that there are cases where EF to SQL Server is producing TSQL less efficiently than L2S and are working on improving this for V2.
Interestingly this model allows new capabilities to be added between the Entity Client and the ADO.NET Provider for a store. These "wrapping providers" can add services such as logging, auditing, security, caching. This is discussed as a V2 feature over at
http://blogs.msdn.com/efdesign/archive/2008/07/09/transparent-caching-support-in-the-entity-framework.aspx
If you look therefor at the bigger picture you can see that it would be horribly difficult and indeed restrictive to try and somehow retrofit L2S TSQL generation into the archiecture of the Entity Framework.


Question:
I am looking to use quartz to schedule emails, but I'm not sure which approach to take:

Create a new job and trigger whenever an email is scheduled OR

Create a single job, and create a new trigger each time an email is scheduled

I need to pass the message/recipient etc either way, and I'm not sure whether creating heaps of jobs will start adding considerable memory overheads, as there will quite possibly be thousands of emails scheduled.

Update: These emails will be scheduled by users, not by me - so I will be adding these programmatically at runtime, they aren't scheduled to go out at any particular time.

Answer:
You might consider queuing or otherwise grouping a set of emails and have a single, or maybe a few, periodic (or scheduled) job(s) that then takes care of the 'batch'.
You could even have the Quartz job queue the emails for a collection of workers to consume and send.
I would not recommend thousands of Quartz jobs/triggers - it just isn't the intended use of the tool (IMHO).
EDIT: In response to the comment below:
I would not recommend thousands of Quartz jobs/triggers when used as part of a framework executing an application in the same JVM, The jobs/triggers will be competing for resources with the rest of the application.


Question: How do you determine what to put in .rhosts file in an VAX openvms system when trying to remotely access the server using a remote shell from Cygwin on windows XP ? .rlogin and rsh are the only methods that can be used to access the VAX server and it must be using Cygwin to remote in to the VAX server. SSH is not an option. When the VAX server is accessed from a Sun server it works fine. I have tried many combination's of possible things that Cygwin could be sending the VAX as far as a user name an address of origin.

Answer:
In lib/gzip.py, we find the method that builds the header, including the part that does indeed contain a timestamp. In Python 2.5, this begins on line 143:
```
```
def _write_gzip_header(self):
    self.fileobj.write('\037\213')             # magic header
    self.fileobj.write('\010')                 # compression method
    fname = self.filename[:-3]
    flags = 0
    if fname:
        flags = FNAME
    self.fileobj.write(chr(flags))
    write32u(self.fileobj, long(time.time())) # The current time!
    self.fileobj.write('\002')
    self.fileobj.write('\377')
    if fname:
        self.fileobj.write(fname + '\000')
```
```
As you can see, it uses time.time() to fetch the current time. According to the online module docs, time.time will "return the time as a floating point number expressed in seconds since the epoch, in UTC." So, if you change this to a floating-point constant of your choosing, you can always have the same headers written out. I can't see a better way to do this unless you want to hack the library some more to accept an optional time param that you use while defaulting to time.time() when it's not specified, in which case, I'm sure they'd love it if you submitted a patch!


Question:
I'm looking into integrating jBPM with my current project, so far so good just including the  jpdl jar in my ear and using the spring modules 0.8 jbpm module, however I've got to have a reasonable way of going from my changes to to the process definition in the designer to deployment in production.

The path has to be repeatable in a number of environments (dev, many test, staging and then prod) and ideally should be done while the system itself is not running.

I'd Ideally package the entire definition as an SQL script, however I haven't seen any tool to translate from processdefinition.xml to sql and assembling it all manually seems too fiddly and error prone.

Has anyone else out there had any experiences here?

The system is running on websphere 6.1 and it's my preference to avoid executing java code at migration time (running java code to generate artifacts that can then be used during migration is ok though)

Answer:
Why not use the ant task extensions provided by JBPM specifically
```
DeployProcessTask
```
. You can deploy to different environments having just a single
```
.par
```
file and the corresponding
```
jbpm-cfg.xml
```
for the various dev/test/staging/prod environments. The only change you might have to do is to configure your hibernate config to directly connect to the database instead of using the datasource.


Question:
I've come across the problem where Excel will not play nice with UTF-8 encoded CSV files. See this related question on Stack Overflow.

I've followed the solution of exporting as UTF-16, however it seems that with UTF-16, the comma character doesn't work as a delimiter, only the tab character.

However I can't find anywhere what the correct filename and mime-type should be for tab-delimited files. I found somewhere stating that it was application/vnd.ms-excel and xls. This works ok for Excel 2003 but 2007 does not approve.

So what should it be?

Answer:
For tab-delimited files,
http://www.rfc-editor.org/rfc/rfc4180.txt
mentions 'text/tab-separated-values'.
That format is (sparsely) described at
http://www.iana.org/assignments/media-types/text/tab-separated-values
.
More info can be found at :
http://www.cs.tut.fi/~jkorpela/TSV.html
I hope this helps?


Question:
I figure this problem is easier than just a regular spell checker since the list of U.S cities is small compared to all known English words.

Anyhow, here's the problem:
I have text files with full of city names; some of which are spelled correctly and some which aren't.

What kind of algorithm can I use to correct all the misspellings of city names?

Answer:
Do you actually need to correct the misspellings or just flag them as with a normal spell checker?  If the latter, you just need to obtain a list of correct spellings and make sure each name is the same as one in your list.
If you want to actually correct them, you probably want to use the concept of
edit distance
to compare the similarity of misspelled strings to those in your reference list.  Then you can replace the misspelled word with the closest match.  You may also want to handle the possibility that the intended city is not in your list.
The
Levenshtein distance
Wikipedia article is another good resource.


Question:
Is there a way (in C#) to access the systray?
I am not talking about making a notify icon.
I want to iterate through the items in the tray (I would guess through the processes but I don't know how to determine what is actually in the tray and what is just a process) and also represent the items with their icons in my own ui.

Answer:
Mathias Rauen's madCollection (for Delphi not c#) can list
Tray Icons
.
And there is a commandline tool:
Windows System Tray Scan Utility
I have also written (not released) my own program in Delphi (not Delphi.NET), not using madCollection, which shows tray icons, process names, tooltips and other info but it's not perfect. There are a few icons it can't display (even though it lists other info), and it can't display any icons under windows 9x. I haven't tested it at all under Vista.


Question:
Sometimes I need to access some servers running Linux (or maybe another Unix-like SO), but I don't know how to verify which distribution is in use on the server (there are times that even the "responsible" person for the server doesn't know).

Is there an easy and reliable way to discover that, one that is uniform and consistent across all of them?

Answer:
Try
```
uname -a
```


Question:
I am calling an unmanaged C++ dll that expects a char* as one of its parameters and I want to push a byte[] into it.  The project is written in VB.NET.

What type of marshalling will work for this?

Answer:
I'm not a .net expert, but I've needed to do something similar recently.
It is not just a matter of serialization, you also have to stop the garbage collector from cleaning up your byte array while it is being used in C++ land...
The below snippet of C# should help.
```
// pin the byte[] (byteArray)
GCHandle handle = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();
// Do your C++ stuff, using the address pointer.

// Cleanup
handle.Free();
```


Question: Is there a way to delete a folder, lets call it FolderX from an SVN trunk recursively? A quick search on google only tells me how to recursively delete all .svn folders and this is not what I want to do

Answer:
Try something like the following on a posix system:
```
```
find ./ -name "FolderX" | xargs svn delete --force
```
```
This will find all matching files/folders starting in the current directory and perform the action on them i.e. svn delete. I'm not sure how to do this in windows though without cygwin.
For win32, the commenter below suggests a similar solution (cmd):
```
```
for /R . %1 in (*.EXT) do svn delete %1
```
```


Question:
I'm not sure how to describe this problem, so I think an example is the best way to ask my question:

I have two tables with a manyToMany relationship:

DriversLicence <-> LicenceClass

LicenceClass is things like "Car", "Motorbike", and "Medium Rigid".

Using Hibernate Criteria, how can I find all licences that have both "Car" and "Motorbike" LicenceClasses?

UPDATE 12/11/2008
I have discovered that this can easily be achieved by using a custom ResultTransformer. However the problem is that a result transformer only gets applied AFTER the query returns its results, it does not actually become part of the SQL. So I guess my question is now "Can you do what I initially described in SQL - and is there a Hibernate Criteria analog?"

Answer:
You can still use dot notation to work across the relations.  For example, assuming you have a DriversLicence.licenceClass property and LicenceClass.type property, then:
```
```
session.createCriteria(DriversLicence.class)
   .add(Expression.or(
     Expression.eq("licenceClass.type", "Car"),
     Expression.eq("licenceClass.type", "Motorbike")
   )
).list();
```
```
Personally though, I'd simply avoid using criteria in this case because it's not a dynamic query, but instead use:
```
```
session.createQuery("from DriversLicence where licenceClass.type in (:types)")
  .setParameterList("types", myListOfTypes)
  .list();
```
```


Question:
let us have a situation in which the following program prints some 10 lines of #

for(i=0;i<10;i++)
prinf("\n#");

now how to go back to 5 th line and edit that # and change the color of it without clearing the screen or clearing the below 5 lines?

I have tried

window(5,0,20,20);
textcolor(GREEN);
cprintf("#");

but it is not editing that one but it is printing on the side of the original one.why?

is there any other way of doing it and changing the color of the already printed text dynamically?
please help me..my environment is turbo c on windows

Answer:
maybe-
```
```
cprintf("\b#");
```
```
'b' is for backspace


Question: Is there a reason to sort MultiMap in Java and how to do that?

Answer:
Assuming you're talking about
```
org.apache.commons.collections.MultiMap
```
, then you can't; since it returns a
```
Collection
```
and not a
```
List
```
, it doesn't support the concept of order.
If you are talking about
```
org.apache.commons.collections.MultiHashMap
```
, then all you need to do is iterate over the keys, take the
```
ArrayList
```
returned and sort it using
```
Collections.sort()
```
.
That's assuming you are using
that implementation though
.
There is nothing stopping you from implementing your own
```
MultiMap
```
fairly easily though, that supports sorting lists. It may be as easy as
```
HashMap<K, Collection<V>>
```
, I'm not familiar with how MultiMaps work.


Question:
I'm doing some searching of tags, and some users like "cat" while others like "Cat"  Go figure...

Anyways, is there a way to force a particular find to be case sensitive?  Such as:

Tag.find(:some-special-option-here)

Any ideas?

Answer:
In the mysql database, set your text's data type to utf_collate_bin. For example:
```
```
ALTER TABLE `sets` CHANGE `set_name` `set_name` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL
```
```
Where 'sets' is the table, 'set_name' is the column of type VARCHAR(64). You can also do this in PhpMyAdmin..
Any binary collate will do the job; but utf8 is preferable.
If you were wondering what the _ci at the end of your current collate is, it means "Case Insensitive" :p


Question:
I'm building my app in vc2008 and testing it on a network of machines.

Is there any way, other than installing Visual Studio 2008, to run a debug build of a C++ program on another machine? (i.e. that doesn't have vc2008 installed)

Installing the redist package only installs the release mode support DLL's for vc2008 programs. Currently it complains that "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.", which I assume is code for "I'm missing DLL's".

Answer:
You can't, because there's no installer redist for the debug runtime (and in fact the software license forbids distributing it, so you'd be breaking the EULA even if you did get something put together). However, a "debug build" generally involves 4 separate options, and the other 3 don't affect distributing the app.
Generating a .pdb file (cl /Zi and link /DEBUG), which allows symbolic debugging. You probably want to add /OPT:ref to the linker options; the linker drops unreferenced functions when not making a .pdb file, but with /DEBUG mode it keeps them all (since the debug symbols reference them) unless you add this expicitly.
I generally do this with all my builds, even production ones. As long as you turn the linker optimizations back on with /OPT:ref it doesn't really cost anything, and having the symbols can be handy if you end up wanting to read a crash dump.
Using a debug version of the C runtime library (probably MSVCR*D.dll, but it depends on what runtime you're using). This boils down to /MT or /MTd (or something else if not using the dll runtime).
This is the one that means you can't redistribute things anymore. It also has a huge impact in the performance of some libraty functions, particularly memory allocation. The debug runtime versions are careful to "poison" the memory they touch with values to make uninitialized data bugs clear, the release ones generally leave the old data round to save the time touching it. I believe with the MSVCP* STL implementations the debug verions also omit all the allocation pooling that is usually done, so that a leak checker can show exactly the block you'd think and not some larger chunk of memory that it's been sub-allocating, but that means it makes more calls to malloc on top of them being much slower. If you have pointer or iterator handling bugs, this could affect what sort of misbehavior you get.
Turning off the compiler optimizations (/Od).
This one does lots of things (
this question
has some good discussion of the subject), but basically it hurts performance. A lot. Unfortunately, it's needed if you want single-stepping to work smoothly.
setting the preprocessor #defines DEBUG or NDEBUG.
This affects lots of libraries in various ways, but most notable it compiles in or eliminates assert() and friends.
So you might consider making a build with some lesser combination of these selections. I make a lot of use of builds that use have symbols (/Zi and link /DEBUG) and asserts (/DDEBUG), but are still optimized (/O1 or /O2 or whatever flags you use) but with stack frame pointers kept for clear backtraces (/Oy-) and using the normal runtime library (/MT). This performs close to my release build and is semi-debuggable (backtraces are fine, single-stepping is a bit wacky at the source level; assembly level works fine of course). You can have however many configurations you want; just clone your release one and turn on whatever parts of the debugging seem useful.
The only one that should impact trying to redistribute the app is 2.
If you're trying to debug on another machine, you might also be interested in
msvsmon
.


Question:
I've found the "open" command in Mac OS X very handy in the command line. From "man open":

The open command opens a file (or a directory or URL), just as if you had
      double-clicked the file's icon. If no application name is specified, the
      default application as determined via LaunchServices is used to open the
      specified files.

That is, if I want to open a PDF file with the default PDF viewer (happens to be Preview), I only need to do:

open my.pdf

In Linux, however, to open a PDF file from the command line, I had to dig around to find the default PDF viewer is, for instance, "evince" (who'd have guessed??), and then

evince my.pdf

So, is there a simple equivalent of the 'open' command in the Linux command line?

Thanks!

Answer:
You could try
```
xdg-open
```
, most Linux distros have it. It will open default associated app for your file.
FYI
https://portland.freedesktop.org/doc/xdg-open.html


Question:
I have used this in my HTML:

<q> Hai How r u </q>

Which shows the text in quotes, like "Hai How r u", for example.

This is working fine in FF but not in IE 6.0.

Please let me know why this happens, and any solutions you might know of.

I don't want to use the quote (") character in my HTML or a separate css file for this.

Answer:
Why don't you just use the
```
"
```
characters? Unlike
```
<b>
```
and
```
<i>
```
which should be replaced by strong and emphasis respectively, as appropriate, the quote tag has a direct match in meaning to the quote character. There should be no need to use
```
<q>
```
.
Edit
: Thanks for clarifying the question Yan.
OP: Is there a specific reason you don't want to use the quotes? The stuff I said earlier still holds, but perhaps we can help with the problem preventing you from using quotes.
Edit 2
: :|


Question: I am using BSD style pty/tty pairs to implement running a sub shell.  When the user exits the sub shell, how do I detect in the master process that this has occurred?  I am using select(nfds, &read_fds, NULL, NULL, &timeout); with the master pty file descriptor set in the read_fds on the master side.

Answer:
The subshell is typically created by a
```
fork()
```
of some sort.  The PID of the child is returned to the master, which can check (with
```
waitpid()
```
, perhaps) if it's still running.


Question:
I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur.

For what it is worth, these objects are usually retrieved from the server as JSON and typically are no more than a handful of layers deep (i.e. it may be an array of objects that themselves have data and then arrays with other data objects).

I want to not only see the changes to basic properties, but differences in the number of members of an array, etc. etc.

If I don't get an answer, I will probably end up writing this myself, but hope someone has already done this work or know of someone who has.

EDIT: These objects will typically be very close in structure to one another, so we are not talking about objects that are utterly different from one another, but may have 3 or 4 deltas.

Answer:
Here is a partial, naïve solution to my problem - I will update this as I further develop it.
```
```
function findDifferences(objectA, objectB) {
   var propertyChanges = [];
   var objectGraphPath = ["this"];
   (function(a, b) {
      if(a.constructor == Array) {
         // BIG assumptions here: That both arrays are same length, that
         // the members of those arrays are _essentially_ the same, and
         // that those array members are in the same order...
         for(var i = 0; i < a.length; i++) {
            objectGraphPath.push("[" + i.toString() + "]");
            arguments.callee(a[i], b[i]);
            objectGraphPath.pop();
         }
      } else if(a.constructor == Object || (a.constructor != Number &&
                a.constructor != String && a.constructor != Date &&
                a.constructor != RegExp && a.constructor != Function &&
                a.constructor != Boolean)) {
         // we can safely assume that the objects have the
         // same property lists, else why compare them?
         for(var property in a) {
            objectGraphPath.push(("." + property));
            if(a[property].constructor != Function) {
               arguments.callee(a[property], b[property]);
            }
            objectGraphPath.pop();
         }
      } else if(a.constructor != Function) { // filter out functions
         if(a != b) {
            propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b });
         }
      }
   })(objectA, objectB);
   return propertyChanges;
}
```
```
And here is a sample of how it would be used and the data it would provide (please excuse the long example, but I want to use something relatively non-trivial):
```
```
var person1 = {
   FirstName : "John",
   LastName : "Doh",
   Age : 30,
   EMailAddresses : [
      "john.doe@gmail.com",
      "jd@initials.com"
   ],
   Children : [
      {
         FirstName : "Sara",
         LastName : "Doe",
         Age : 2
      }, {
         FirstName : "Beth",
         LastName : "Doe",
         Age : 5
      }
   ]
};

var person2 = {
   FirstName : "John",
   LastName : "Doe",
   Age : 33,
   EMailAddresses : [
      "john.doe@gmail.com",
      "jdoe@hotmail.com"
   ],
   Children : [
      {
         FirstName : "Sara",
         LastName : "Doe",
         Age : 3
      }, {
         FirstName : "Bethany",
         LastName : "Doe",
         Age : 5
      }
   ]
};

var differences = findDifferences(person1, person2);
```
```
At this point, here is what the
```
differences
```
array would look like if you serialized it to JSON:
```
```
[
   {
      "Property":"this.LastName",
      "ObjectA":"Doh",
      "ObjectB":"Doe"
   }, {
      "Property":"this.Age",
      "ObjectA":30,
      "ObjectB":33
   }, {
      "Property":"this.EMailAddresses[1]",
      "ObjectA":"jd@initials.com",
      "ObjectB":"jdoe@hotmail.com"
   }, {
      "Property":"this.Children[0].Age",
      "ObjectA":2,
      "ObjectB":3
   }, {
      "Property":"this.Children[1].FirstName",
      "ObjectA":"Beth",
      "ObjectB":"Bethany"
   }
]
```
```
The
```
this
```
in the
```
Property
```
value refers to the root of the object that was compared. So, this solution is not yet
exactly
what I need, but it is pretty darn close.
Hope this is useful to someone out there, and if you have any suggestions for improvement, I am all-ears; I wrote this very late last night (i.e. early this morning) and there may be things I am completely overlooking.
Thanks.