q:
I have a Flash application that is hosted from within a Drupal page.  Some parts of the Flash application should be available to all users, but some should only be available to a logged-in user.  (The specific role doesn't matter, just that they are any authorized user of the site).

From within Flash, I can detect whether the user is logged on by screen-scraping the "?q=user" page, but this is very brittle.  What is the "right" way to do this?  I can install additional Modules if necessary, but they need to be compatible with Drupal 6, not 5.

Similarly, if there is no user currently logged in, how can I take a username and password that they provide to me and log them in (or determine that the password is bad)?

[A]
The "right" solution
you probably want to look at something like the
services module
. basically, you want to expose user services to your flash app, so you can send requests (via XML-RPC or whatever implementation you choose) to get information like "what access does the current logged in user have", or "login this user with username x and password y" etc...
The do it yourself quickly solution
if you're familiar with module development, you can create your own module quickly to just get the functionality you need, without having to go through a "real" web services layer. here's a quick example, creating a module called "myservices":
```
```
<?php
// myservices.info
   name = My Services
   description = Expose basic services
   core = 6.x

<?php
// myservices.module

   function myservices_menu() {
       $items['myservices/user'] = array(
         'title' => 'Get auth',
         'page callback' => 'myservices_get_user',
         'access arguments' => array('access content'),
       );
       return $items;
   }

   function myservices_get_user() {
       global $user;
       if (in_array('authenticated user', $user->roles) ) {
           print 'yes';
       } else {
           print 'no';
       }
   }
```
```
put those two files in a directory "myservices" in your modules directory, activate it, and then go to
```
http://yourdomain.com/myservices/user
```
if you're authenticated, it'll just return
```
yes
```
, and if not
```
no
```
, etc... which you can pick up in your flash app.


q: What happens if the browser receives a redirect response to an ajax request?

[A]
The
```
ajax-request
```
will follow that redirect afaik. The actual content (
```
.responseText
```
,
```
.responseXML
```
) will be the content from the page you are redirected to.
You might be able to intercept the redirect (
```
status-code
```
,
```
location-header
```
) on
```
readyState
```
2 or 3, but not sure about it.

s: huggingface

c: devops

d: intermediate


q: Is there any software to help in learning / understanding / experimenting with the rules of harmony and counterpoint?

[A]
While very carefully coded applications could give you some hints, I find that the most important lesson is when to break the rules. And a computer program could never help with that.
I suggest you buy a book instead. Good ones include
The style of Palestrina and the dissonance
Twentieth century harmony
I haven't read any English books on baroque, wiener or romantic style.


q:
Is it possible to detect, on the client side, whether the user is using an encrypted page or not?

Put another way -- I want to know if the URL of the current page starts with http or https.

[A]
Use
```
window.location.protocol
```
to check if it is
```
https:
```
```
```
function isSecure()
{
   return window.location.protocol == 'https:';
}
```
```
Alternatively you can omit specifying "window" if you don't have a locally scoped location.
```
```
function isSecure()
{
   return location.protocol == 'https:';
}
```
```


q:
I am working on a small project to take a CSV file and then insert its data into a HTML table (I would use datagrid and dataset or datatable, but the system I will be talking to does not support ASP.NET uploads for sending newsletters).

Anyway, I will use the file.readalllines method to return the contents of the csv file into a string array.

But for each string member of the array, I will be using the string.split function to split up the string into the char array. Problem is (and the csv file is generated by the system I talk to btw - I get data from this system and feed data into it), the csv contents are makes of cars. This means that I could have:

Nissan Almera

Nissan Almera 1.4 TDi

VW Golf 1.9 SE

And so forth...

Is there a robust way I could ensure that where I have Almera 1.4 TDi, for example, it is one member in the char array I split each string into, rather than seperate members.

[A]
The Split() method takes a char parameter which can be used to specify the delimiter. So you can do something like:
```
```
String.Split(Convert.ToChar(","));
```
```
Judging by your question all the car makes should be delimited by commas so this should work.


q: I know of is and as for instanceof, but what about the reflective isInstance() method?

[A]
The equivalent of Java’s
```
obj.getClass().isInstance(otherObj)
```
in C# is as follows:
```
```
bool result = obj.GetType().IsAssignableFrom(otherObj.GetType());
```
```
Note that while both Java and C# work on the runtime type object (Java
```
java.lang.Class
```
≣ C#
```
System.Type
```
) of an
```
obj
```
(via
```
.getClass()
```
vs
```
.getType()
```
), Java’s
```
isInstance
```
takes an object as its argument, whereas C#’s
```
IsAssignableFrom
```
expects another
```
System.Type
```
object.


q:
How can I determine current version of my repository to see if I need to upgrade it (svnadmin upgrade)?

In reality I'm hosting SVN with 3rd party and I want to find out if I need to ask them to upgrade my repos or not.

I'm asking since 1.5 server will keep repo version at 1.4, unless I miss something?

[A]
Have a look at
```
<REPO>/db/format
```
. After upgrading to 1.5 format, my
```
format
```
file shows:
```
```
3
layout sharded 1000
```
```
Before it used to be:
```
```
2
```
```


q:
Does this pattern:

setTimeout(function(){
             // do stuff
}, 0);

Actually return control to the UI from within a loop? When are you supposed to use it? Does it work equally well in all browsers?

[A]
http://blog.thinkature.com/index.php/2006/11/26/escaping-the-javascript-call-stack-with-settimeout/
Some good info in there. Basically, you are correct and it works on pretty much all browsers. Cool trick.
You would want to use this in the example that the author of the post gave, as well as instances where you need to return execution back to the calling function before your code is executed. Javascript is, apparently, not multi-threaded, but this comes close.
Hope this helps :)


q: I've heard a lot about profiling. What is this all about? As far as I understand this is some kind of performance measurement but can someone elaborate this on more clearly so that a newbie can grasp the idea. Also, I use Eclipse IDE for my Java program. Can I profile my program using Eclipse IDE? What are the factors to be considered while profiling (I mean the best practices)?

[A]
Profiling basically shows you how often a given line of code is executed and how much time was spent in it (compared to other lines). This makes it easy to pinpoint the location where your code spends most of the time.
It also makes it possible to find places where your code spends much time without doing anything: this is the typical sign of a
cache miss
and this is where you should get active.
Usually, programs spend very much time (say, 90%) in one place. Unfortunately, finding this place without profiling isn't possible. Guesswork often goes awry. So if you optimize in the wrong place, this won't help at all: if the overall time spent in that line is only 10%, your code will only get 10% faster (at best!). If, however, you succeed in removing the call that takes 90% of the time, your programm will get
ten times faster
.
This, in a nutshell, is profiling.
Eclipse offers builtin profiling capabilies and I've been told that they're pretty good but since I don't know them, let someone else answer that.


q:
How does one choose the size of a buffer (bytes I read from or write to socket) for the maximum throughput when implementing a low-level HTTP and FTP transfer? My application should transfer data with HTTP or FTP on connections varying from 130 Kbps to 3 Mbps (I know the expected speed beforehand). Sometimes it's a one way transfer, sometimes it goes in both directions. Should I stick with some average buffer size or I must vary it depending on the connection speed?

Thanks.

[A]
Choose a buffer size over 8KB.  9000 is typically the largest MTU (maximum transmission unit) size used in even the fastest networks.
When you use a buffer larger than the MTU of the connection, the operating system will break it down in to MTU sized pieces as needed, and thus anything you use over the MTU will have little effect on network performance.
However, using a large buffer will likely have other effect on performance, if you're transferring files, then using large buffers may increase the read performance, thus improving the speed of your application.
So, Usually picking a nice round number like 16KB is a good idea.  Definitely don't go under 1500, as this can negatively effect network performance (causing the operating system to sometimes send small packets, which decrease performance on the network).


q:
In Ant is there any way to do something like this:

<arguments id="arg-list">
    <arg value="arg1" />
    <arg value="arg2" />
</arguments>

<property name="prop1" refid="arg-list" />

I'm trying to write a macro for psexec and I'm looking for a nice way to pass in the argument list.

I know that you can do something similar with classpaths...

Thanks!

[A]
I don't know of an answer to your specific question. The documentation is clear that refid 'Only yields reasonable results for references to PATH like structures or properties.'
Without a bit more information on what you're trying to do, it's hard to comment. At the risk of changing your design, rather than answering your question, I suggest:
1) You can pass the argument list to exec as a line:
```
```
<macrodef name="example">
  <attribute name="args"/>
  <sequential>
    <exec executable="example.exe">
      <arg value="somearg" />
      <arg line="@{args}"/>
    </exec>
  </sequential>
</macrodef>

<example args="somearg arg1 arg2"/>
```
```
Which will run example.exe:
```
```
example.exe arg1 arg2
```
```
2) I pass in arguments to macros that call external apps like this:
```
```
<macrodef name="example">
  <element name="params" optional="yes" implicit="yes"/>
  <sequential>
    <exec taskname="eg" executable="example.exe">
      <arg value="somearg" />
      <params />
    </exec>
  </sequential>
</macrodef>

<example>
  <arg value="arg1"/>
  <arg value="arg2"/>
</example>
```
```
This will run example.exe:
```
```
example.exe somearg arg1 arg2
```
```
I hope I haven't been teaching my grandmother to suck eggs here.


q:
I've noticed, using visual studio 2003, that I can "comment out" my comments to make them no longer be comments. This one needs an example:

If I have:

/*
int commented_out = 0;
*/

I can comment out the /* and */ with // and code within the /* and */ is no longer "commented out" (the text changes to non-comment color and the compiler treats it as code once again). Like so:

///*
int commented_out = 0;
//*/

I've found this is true for msvc 2003, is this normal C++ behavior or is it just a fluke that works with this compiler?

[A]
It should work in any compiler as the
```
//
```
is encountered first in the input stream.
I tend to use
```
#if 0
```
for this sort of stuff and change it to
```
#if 1
```
to uncomment, shown here:
```
```
#if 0
    int commented_out = 0;
#endif
```
```
Then I don't have to worry about comment markers at all.


q:
I was wondering if there is a way to implement an action listener for a Jbutton without a name. For example, I have the following for loop that creates a button for each letter of the alphabet.

for (int i = 65; i < 91; i++){
     alphabetPanel.add(new JButton("<html><center>" + (char)i));
}

Is there a way that I can add an action listener for each of those buttons without getting rid of my for loop and hard coding each JButton and then creating an action listener for each?

Thanks in advance,

Tomek

[A]
Your question is a little vague.  it would be trivial to modify the loop to add a listener inside the loop:
```
```
ActionListener listener = something;

for (int i = 65; i < 91; i++){
     JButton button = new JButton("<html><center>" + (char)i);
     button.addActionListener( listener );
     alphabetPanel.add(button);
}
```
```
if you can't modify the loop you could iterate over all of the panel's children, and add listeners to any of the children that are jbuttons.
also why are you using html to center the text?  isn't that overkill? doesn't jbutton already center text?
you could use setHorizontalAlignement(SwingConstants.CENTER) to do it too.


q:
I'm trying to design a homepage for an MVC site that has two different views, based on if the user is logged in or not.

So image the default (not logged in) view is showing general, nonspecific info. If i'm logged in, the view is showing mostly personal stuff instead.

What's the best practice to handling this? Don't forget, we also need to unit test this.

Thanks heaps!

[A]
This should be a simple case of returning the appropriate view from your controller.
```
```
public ActionResult Index()

    If (User.IsLoggedOn)
    {
        // Do user-specific controller stuff here...

        return View("LoggedOnIndex");
    }
    else
    {
        // Do anon controller stuff here...

        return View("AnonymousIndex");
    }
```
```


q: How does one do namespaced controllers in Merb, for instance to create an admin section to the site? In Rails one would use Admin::CategoriesController, is this similar in Merb or is this another recommended way of doing it?

[A]
The namespace method seems to do it.
This is placed in the routes file (router.rb):
```
```
namespace :admin do
  resources :categories
end
```
```
This generates routes like:
```
edit_admin_category - /admin/categories/:id/edit(.:format)
delete_admin_category - /admin/categories/:id/delete(.:format)
admin_categories - /admin/categories(/index)(.:format)
new_admin_category - /admin/categories/new(.:format)
admin_category - /admin/categories/:id(.:format)
```
I then put my controller in a module like this:
```
```
module Admin
  class Categories < Application
    def index
      ...
    end

    .
    .
    .
  end
end
```
```
I am not sure if this is the recommended way, any suggestions to this would be great.


q:
I'm using a logging module that can have reporting enabled/disabled at runtime. Calls generally go something like:

WARN(
     "Danger Will Robinson! There are "
     + boost::lexical_cast<string>(minutes)
     + " minutes of oxygen left!"
);

I'm using an inline function for WARN, but I'm curious as to how much optimization is going on behind the scenes -- evaluation of the arguments throughout the entire program would be costly. The WARN function goes something like this:

bool WARNINGS_ENABLED = false;
inline void WARN(const string &message) {
    if (!WARNINGS_ENABLED) {
       return;
    }
    // ...
}

Given that constructing the string argument has no side-effects, will the compiler optimize it out? Is a certain level of optimization required (-Ox in g++ for some x)?

[A]
I'd guess that it only has a chance to optimize it out if it can prove that there are no side effects (which might be difficult for the compiler to do for an expensive function call).
I'm not a boost expert, but I'm guessing there's a way to construct a lambda that will only be evaluated to generate the string if WARNINGS_ENABLED is true.  Something like...
```
```
inline void warnFunc(some_boost_lambda &message_generator) {
  if (WARNINGS_ENABLED) {
    cerr << message_generator() << endl;
  }
}

#define WARN(msg) warnFunc(...insert boost magic here to turn msg into a lambda...)
```
```


q:
I'm attempting to utilize VBScript to connect pull the physicalDeliveryOfficeName attribute in Active Directory by providing the email address.

I know how to do it with a common name like the following:

Set MyUser = GetObject ("LDAP://cn=" & uname & ",ou=" & strname & ",DC=bobdom,DC=net")

However only the email address is available.  How to do this? I've even tried

Set MyUser = GetObject ("LDAP://mail=" & uname & ",ou=" & strname & ",DC=bobdom,DC=net")

and that doesn't work.

[A]
If using an
LDAP
query (not sure if you need the server name in there in your case):
```
```
<LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(objectClass=user)(mail=mike.spencer@kenblanchard.com));
```
```
Trying it out in my own environment, it looks like this (with a couple things genericized):
```
```
<LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(mail=email@company.com));name,mail,member,description,memberOf,userParameters,userAccountControl,whenCreated,CN;subTreeCount=1
```
```
And the whole batch looks like this (in ASP; if done in a .vbs file you'll need to change the
```
Server.CreateObject
```
to just
```
CreateObject
```
... I think).
```
```
Set oCon        = Server.CreateObject("ADODB.Connection")
oCon.Provider   = "ADsDSOObject"
oCon.Open "ADProvider", "ADUsername", "ADPassword"

Set oCmd        = Server.CreateObject("ADODB.Command")
Set oCmd.ActiveConnection = oCon

sQuery = "<LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(mail=email@company.com));name,distinguishedName,physicalDeliveryOfficeName;subTreeCount=1>"

oCmd.CommandText = sQuery
Set ADRecordSet = oCmd.Execute
```
```
You may need to fiddle with
```
subTreeCount
```
.


q:
What is the correct way to convert ASP.NET SOAP-based web services to JSON-based responses?
...And then call these from jQuery?

What are "best practices" when integrating jQuery based AJAX and ASP.NET?
Articles? Books?

[A]
JSON conversion to .NET classes can be done with
System.Runtime.Serialization
and
System.Runtime.Serialization.JSON
. I suspect you're more interested in setting up function calls from client to server. I think it is worth trying
this tutorial
.
In this tutorial, you'll need to add a webservice '.asmx' file.  In the asmx file you will be able to create functions callable from client script.  Your ASP.NET pages can also reference client script generated to make calling the .asmx functions.
If you actually want to do JSON serialization though, you could also use the following:
```
```
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JsonSerializer
{
    // To make a type serializeable, mark it with DataContractAttribute
    // To make a member of such types serializeable, mark them with DataMemberAttribute
    // All types marked for serialization then need to be passed to JsonSerialize as
    // parameter 'types'

    static public string JsonSerialize(object objectToSerialize, params Type[] types)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(
            types[0], types.Skip(1));

        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, objectToSerialize);
        ms.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(ms);
        return sr.ReadToEnd();
    }
}
```
```


q:
In PHP, I can write:

$vname = 'phone';
$$vname = '555-1234';
print $phone;

... And the script will output "555-1234".

Is there any equivalent in Perl?

Is there any way to constrain $phone to the scope of the local block, as if I'd written my $phone? Using my $$vname gives me "Can't declare scalar dereference in my at ..." errors.

[A]
You can do it in a very similar way:
```
```
$vname = "phone";
$$vname = "555-1234";
print $phone;
```
```
But that you can doesn't mean that you should. The best way to manage this is,
as Michael Carman says
,
USE A HASH!


q:
Something that confuses me, but has never caused any problems... the recommended way to dispatch an event is as follows:

public event EventHandler SomeEvent;
...
{
    ....
    if(SomeEvent!=null)SomeEvent();
}

In a multi-threaded environment, how does this code guarantee that another thread will not alter the invocation list of SomeEvent between the check for null and the invocation of the event?

[A]
The recommended way is a little different and uses a temporary as follows:
```
```
EventHandler tmpEvent = SomeEvent;
if (tmpEvent != null)
{
    tmpEvent();
}
```
```


q:
I am confused by J2ee webservers !! I downloaded a free Glassfish server from sun, then as I am an Oracle developer downloaded the latest JDeveloper, which comes with a Weblogic server from BEa/Oracle.  One is free the other costs $1000s.  What is the real difference.

I want to write a SOAP interface to my Oracle database 10g, can I get away with the Glassfish server, why should I used a Weblogic server, and how does this differ from the Oracle Application server for J2EE apps.

As you can see I am confused to say the least, and would appreciate any enlightenment.  I am an experience SQL PL/SQL developer, but new to Java so have a certain lack of knowledge in this area.

[A]
Personally, if you are looking for an open source J2EE app server, I'd tend to go with JBoss if only because it has a much larger market share, making it a lot more likely that you are going to be able to find people that can answer questions or that have done some particular task and have posted instructions.
For the most part, if you are writing a pure J2EE application, it is relatively transparent to the developer what application server you deploy to.  If you decide to take advantage of application-server specific extensions, then the choice of app server may matter to developers, but most Java shops are using a rather vanilla setup that can move reasonably easily between application servers.  If you want to embrace one particular application server's extensions, there may be some performance/ productivity gains available in exchange for a loss of productivity.
The people that are more likely to care about what application server you are using are the admins.  Different application servers have very different administrative interfaces (and different levels of administrative complexity and configurability).  The bigger the site and the more critical the application, the more this sort of thing comes in to play.  Different application servers also have different JVM implementations which has different performance characteristics.  You also have the cost of support.  Even if you use a free application server like JBoss, you probably want to purchase a support contract if you are deploying a mission critical application there.  If you're deploying something smaller scale where you're comfortable relying on free sources of assistance (i.e. Google, Stackoverflow, etc.) one of the open source app servers is probably a no-brainer.


q:
If I have a list like this:

<ul id="mylist">
    <li id="list-item1">text 1</li>
    <li id="list-item2">text 2</li>
    <li id="list-item3">text 3</li>
    <li id="list-item4">text 4</li>
</ul>

What's the easiest way to re-arrange the DOM nodes to my preference? (This needs to happen automatically when the page loads, the list-order preference is gained from a cookie)

E.g.

<ul id="mylist">
    <li id="list-item3">text 3</li>
    <li id="list-item4">text 4</li>
    <li id="list-item2">text 2</li>
    <li id="list-item1">text 1</li>
</ul>

[A]
Though there's probably an easier way to do this using a JS Library, here's a working solution using vanilla js.
```
```
var list = document.getElementById('mylist');

var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
    if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
        itemsArr.push(items[i]);
    }
}

itemsArr.sort(function(a, b) {
  return a.innerHTML == b.innerHTML
          ? 0
          : (a.innerHTML > b.innerHTML ? 1 : -1);
});

for (i = 0; i < itemsArr.length; ++i) {
  list.appendChild(itemsArr[i]);
}
```
```


q:
I have some shapefile (demographic/heat map data in the USA, such as crime in New York) data imported into a sql server 2008 database, field data type: Geography.

How can i get this data, from a select query, in a format which i can then display on google maps or microsoft virtual earth?

thanks!

Edit 1: So far, the best solution has been to use a (free) 3rd Party dll (SharpMap). I'm hoping someone might suggest some sql tricks in sql2008 to return it in a compatible format ...

[A]
The easiest way to do this is to select to XML and then transform the data into GeoRSS or KML.  Virtual Earth and Google Maps both have support for KML so that would probably be the easiest way to do it.
There are considerations though.  If you have many many vertices in your data you probably want to implement some sort of AJAX method to retrieve only the data in the map view.  You can generalize data in SQL 2008 to make a fewer amount of vertices depending on your zoom level.  If you are zoomed out to a country level you don't need nearly as much detail as zoomed into a town.
MapDotNet
has a lot of features for getting your data in a Virtual Earth map more easily.  It is relatively easy to perfrom a select query and display the data as you desire.  I'm sure there are other similar products for Google maps but I haven't personally used them.  It has support for polygons as well as heat maps and gives you a lot more functionality than just using Virtual Earth.  Virtual Earth is powerful but there are a lot of GIS tools someone from a mapping background would expect that you have to program in yoursef.


q:
How can you express X of Y are true, in boolean logic?  a rule like 2 of the following must be true (A, B, C, D, E, F)
is it a form of multiplcation or set operations?

the end result is all the permutations like AB OR AC OR AD, if you said 3 of following it is like ABC, ABD, ABE, etc.. so it is like (A,B,C)^2?

thanks!

[A]
You've got the idea there.  To express "k of n holds" you're going to need to enumerate all cases for which k holds.  So, if we have variables A B C D E, and you want 3 of 5, you'll need
```
```
(A  &  B &  C & ~D & ~E) |
(A  &  B & ~C &  D & ~E) |
(A  &  B & ~C & ~D &  E) | ...
(~A & ~B &  C &  D &  E)
```
```
where & is "and", | is "or" and ~ is "not".


q:
I have a website cgi-bin program that is written in c++.

Unfortunately the website provider for my friend's site only allows Perl or PHP cgi-bin scripts.

Is there an easy way to simply have a very small Perl or PHP wrapper that just calls the c++ compiled binary?

Would the c++ program still be able to read from stdin for POST commands or would it have to be read by the Perl or PHP and then forwarded.

[A]
You can use PHP's system() function to execute a shell command, which you could use to launch another program.  The STDOUT of that program would then go to the same place as php's stdout (to the HTTP connection).  You might have to do some messing around to get stdin to read from get/post/etc.
But most likely the website provider has disabled the ability of you to execute programs in this way.  It can be a security risk, and if they specifically only allow php and perl, then they would probably specifically disable as many methods of running non-php/perl as they could. So, short answer is you're probably out of luck.


q:
I'm quite confused about the basic concepts of a Hash table. If I were to code a hash how would I even begin? What is the difference between a Hash table and just a normal array?

Basically if someone answered this question I think all my questions would be answered:
If I had 100 randomly generated numbers (as keys), how would I implement a hash table and why would that be advantageous over an array?

Psuedo-code or Java would be appreciated as a learning tool...

[A]
Hashtables are
associative
.  This is a huge difference from arrays, which are just linear data structures.  With an array, you might do something like this:
```
```
int[] arr = ...
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i] + 1);
}
```
```
Notice how you are getting an element out of the array by specifying an exact memory offset (
```
i
```
).  This contrasts with hashtables, which allow you to store key/value pairs, later retrieving the value based on the key:
```
```
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
table.put("Daniel", 20);
table.put("Chris", 18);
table.put("Joseph", 16);
```
```
With the above table, we can make the following call:
```
```
int n = table.get("Chris");
```
```
...and be assured that
```
n
```
will be valued at
```
18
```
.
I think this will probably answer most of your questions.  The implementation of a hashtable is a fairly interesting topic, one
which Wikipedia addresses passably well
.


q:
I was wondering if someone would be able to help me write a CQL query for NDepend that will show me all the methods in my form class that handle the form events.  So I would like to be able to find all the methods that look like this:

Private Sub AddFolderButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFolderButton.Click

I have had a look through some of the options but I can't really find anything that does what I need.

I have only just started using NDepend, so I haven't really got used to it yet, but I do know one thing how the hell did I live without it all this time.

[A]
I have sort of got something that works but its not really 100% correct, because all the form generated event handlers have an underscores in there name, I used the underscore as a filter,  I also filter where the name has "EventArgs" in it.  The query looks like this:
```
```
SELECT METHODS WHERE NameLike "_" OR NameLike "EventArgs" AND !IsSpecialName AND IsPrivate
```
```
That query pretty much returns all the methods that handle events but I would still like to find a more correct way.


q:
Currently we have a DLL that checks whether a username/password is a valid Windows user using the Windows API LogonUser method. We need to enhance it so it checks whether the user belongs to a specified group as well. Is there a Windows method that does that?

Given a Windows username and password, find out whether the user belongs to a specified group.

[A]
The closest single API is
CheckTokenMembership
, which just leaves the problem of obtaining the user's SID and handle for the group.
If you can use ATL check out the methods on the
CAccessToken
class ... and even if you can't use it check out the implementation in atlsecurity.h for examples.


q:
I'm working on deploying a small community site. User registration requires nothing more than a username, email address, and password. I'm not even asking for a name, and certainly not storing any sensitive data.

Should I still invest in an SSL certificate? Would it be considered terrible practice to transmit a user's password without one?

This is just a personal project, so I'd like to avoid the extra cost if I could, but I can't help but feel I'd be irresponsible if I didn't secure everything properly.

[A]
I wouldn't bother with SSL for something like that.
Think about it... there are a million messageboards on the Internet
and none of them use SSL.
Unless you are storing Credit Card numbers or other sensitive
financial/personal information, I just don't think it's worth the
cost.
EDIT: This response is totally outdated. Yes, EVERYONE needs SSL.  Most hosting companies include support for Let's Encrypt (free SSL) so you don't have any reason not to use it anymore.


q:
I was wondering if there was some kind of J tool in the java swing library that opens up a file browser window and allows a user to choose a file. Then the ouput of the file would be the absolute path of the chosen file.

Thanks in advance,

[A]
You can use the
JFileChooser
class, check
this example
.


q:
How do I utilize a ?: operator in the SELECT clause of a LINQ query?  If this can't be done, how can I emulate one?  The goal is to get a CASE block in my select clause. As you might suspect, I'm getting an error: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

Is this the proper way, or a sufficient way, to say "from a inner join i on a.ipid=i.id inner join u on i.uid=u.id"?  If not, please provide one.  Thanks.

var query =
    from a in db.tblActivities
    from i in db.tblIPs
    from u in db.tblUsers
    select new {
        u.UserName == null
            ? i.Address
            : u.UserName,
        a.Request,
        a.DateTime };

[A]
I'm fairly new to Linq to SQL but I'm pretty sure it would go like this:
```
```
var query =
    from a in db.tblActivities
    from i in a.tblIPs
    from u in i.tblUsers
    select new
    {
        userName = (u.UserName == null)
            ? i.Address
            : u.UserName,
        a.Request,
        a.DateTime
    };
```
```
The if statement needs to be in parentheses and the results outside of them.  As for the joins, you follow the chain down from one->many.


q: In visual studio 2008, when we press Ctrl+F5, the ASP.NET Development Server is launched to simulate a Web Server. I'm wondering what server does it simulate? IIS6 or IIS7? Is it possible to customize what server it simulate?

[A]
Sorry, a question, not an answer:
What are the server differences between IIS6 and II7 that matter to your code?
For ASP.NET development, the web server itself is somewhat ASP.NET neutral.   It forwards the request to the .NET framework, so THAT's the part that matters.
More info here:
http://msdn.microsoft.com/en-us/library/58wxa9w5.aspx
Adding Morgan Cheng's comment into the answer:
There is some difference between IIS6 and IIS7 on how to explain web.config. For example, to customize UrlRouteHandler, according to MSDN. IIS6 and IIS7 are different. Details in
http://msdn.microsoft.com/en-us/library/system.web.routing.urlroutinghandler.aspx


q: I am trying to see what are the gotchas in using XmlHttpWebRequest such that it works for Safari, Firefox and IE?

[A]
Here's somebody who got his hands dirty with that question:
http://www.webmasterworld.com/javascript/3195000.htm
One general way to research these questions is to peek at the source code of a javascript library, like jQuery, since one of the functions of the library is to handle the differences.   Here's a snippet of jQuery that deals with XMLHttpRequest.  Note the comments about browser differences.
```
```
// Create the request object; Microsoft failed to properly
    // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
    var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

    // Open the socket
    // Passing null username, generates a login popup on Opera (#2865)
    if( s.username )
        xhr.open(type, s.url, s.async, s.username, s.password);
    else
        xhr.open(type, s.url, s.async);

    // Need an extra try/catch for cross domain requests in Firefox 3
    try {
```
```


q:
I am trying to do something like this

public void GetData(ref Dictionary<T,V> dataDictionary)
{

}

Where T can be GUID, string, or int and V is custom user or item object.

[A]
Does this help?  Any additional info would be helpful.
```
```
public void GetData<T, V>(ref Dictionary<T, V> dataDictionary) {
    if (typeof(T) == typeof(string) || typeof(T) == typeof(int) || typeof(T) == typeof(Guid)) {
       ...
    } else {
        throw new ArgumentException();
    }
}
```
```


q: I remember from way back at university using a switch with 'binary search' or 'binary switch'. Something like that, My google foo is broken today. Anyway it goes down like this: You define an array of possible options (Strings usually), some magic happens, and those options in the array become the cases in the switch happens. I do remember that they had to be in alphabetical order for this to work. Can you help me remember the magic? Even a name of what I should be looking at would be fantastic.

[A]
I think what you are looking for is an
Enum
.
From the link above...
```
```
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

public class EnumTest {

    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
         switch (day) {
            case MONDAY:
                 System.out.println("Mondays are bad.");
                 break;

            case FRIDAY:
                 System.out.println("Fridays are better.");
                 break;

            case SATURDAY:
            case SUNDAY:
                 System.out.println("Weekends are best.");
                 break;

            default:
                 System.out.println("Midweek days are so-so.");
                 break;
        }
    }

    ....
}
```
```


q:
Is there a way to have a function return a editable reference to some internal data. Here's an example I hope helps show what I mean.

class foo
{
    public int value;
}

class bar
{
    bar()
    {
       m_foo = new foo();
       m_foo.value = 42;
    }
    private m_foo;
    foo getFoo(){return m_foo;}
}

class main
{
    int main()
    {
        bar b = new bar();
        b.getFoo().value = 37;
    }
}

The return of getFoo() according to "==" is the same as the internal m_foo until I try to edit it. In c/c++ I'd return a reference or pointer.

[A]
You're already returning the reference of
```
foo
```
in
```
getFoo
```
(this happens by default). So any changes that you make to the return value of
```
getFoo
```
will be reflected in the internal
```
foo
```
data structure in
```
bar
```
.


q:
I have a client-server architecture where client communicates with the server using .NET Remoting. Server handles all business logic and database interaction. I need to add an operation which may take a while to execute and the dataset it returns might be quite large. I'm thinking of employing asynchronous call for that. Now the problem arises: assume, the client made this async call, operation started SQL query, and user either closes the client or clicks Cancel -- what will happen to the operation? Is there any way to cancel the pending async call, which is busy talking to SQL server?

Thanks.

[A]
You could design your client/server interaction so that the server let a worker thread do the SQL stuff so that it was ready to receive another call from the client.   So, the client makes call 1 and says do SQL work.   The server gives that work to the worker thread and is ready for new incoming.   Then the client makes call 2 and says, "never mind".  The server would do some bookkeeping to make sure it doesn't call back to the client when the worker thread is done.
Can the server safely interrupt the worker thread.  I'm not sure.   Would that have any affect on what SQL Server is doing.   Not sure.


q:
If you have a particular line of C code in mind to examine in the machine output, how would you locate it in objdump output.  Here is an example

if (cond)
   foo;
   bar();

and I want to see if bar was inlined as I'd like.
Or would you use some alternative tool instead of objdump?

[A]
You can start objdump using the
```
-S
```
option (like
```
"objdump -Sd a.out"
```
). It will display the sourcecode intermixxed with the assembler code, if the source-files the code was compiled from are available.
Alternatively, you can use the following way:
```
```
int main(void) {
    int a = 0;
    asm("#");
    return a;
}
```
```
becomes
```
```
.file   "a.c"
        .text
.globl main
        .type   main, @function
main:
        leal    4(%esp), %ecx
        andl    $-16, %esp
        pushl   -4(%ecx)
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ecx
        subl    $16, %esp
        movl    $0, -8(%ebp)
#APP
# 3 "a.c" 1
        #
# 0 "" 2
#NO_APP
        movl    -8(%ebp), %eax
        addl    $16, %esp
        popl    %ecx
        popl    %ebp
        leal    -4(%ecx), %esp
        ret
        .size   main, .-main
        .ident  "GCC: (GNU) 4.3.2"
        .section        .note.GNU-stack,"",@progbits
```
```


q: I am extremely new at php and I was wondering if someone could help me use either a for() or while() loop to create an array of 10 elements.

[A]
```
```
$array = array();
$array2 = array();

// for example
for ($i = 0; $i < 10; ++$i) {
    $array[] = 'new element';
}

// while example
while (count($array2) < 10 ) {
    $array2[] = 'new element';
}

print "For: ".count($array)."
";
print "While: ".count($array2)."
";
```
```


q:
What is the time complexity of dynamic memory allocation using new, malloc, etc.?  I know very little about how memory allocators are implemented, but I assume the answer is that it depends on the implementation.   Therefore, please answer for some of the more common cases/implementations.

Edit:
I vaguely remember hearing that heap allocation is unbounded in the worst case, but I'm really interested in the average/typical case.

[A]
I would think it would generally be O(n) where n is the number of available memory blocks (since you have to scan the available memory blocks to find a suitable one).
Having said that, I've seen optimizations that can make it faster, specifically maintaining multiple lists of available blocks depending on their size ranges (so blocks less than 1k are in one list, blocks from 1k to 10k are in another list and so on).
This is still O(n) however, just with a smaller n.
I'd be interested in seeing your source that there's a heap allocation that's unbounded (if, by that, you mean it could take forever).


q:
What is the best way to give the user feedback for a color selection?

I have a dialog with a "Select Color" push button which pops a QColorDialog. After the selection is made I want to show the user the color selected.

Usually I do this using a QLabel and changing it's background color in the palette. This method is cumbersome and I think not very portable.

Is there a standard way of doing this?

[A]
The way I'm doing it is the following :
I actually change the color of the button, to reflect the user choice. To do this, I'm using the Qt style sheet, which ensure it is portable :
```
```
const QString COLOR_STYLE("QPushButton { background-color : %1; color : %2; }");

QColor ChosenColor; // Color chosen by the user with QColorDialog
QColor IdealTextColor = getIdealTextColor(ChosenColor);
btnChooseColor->setStyleSheet(COLOR_STYLE.arg(ChosenColor.name()).arg(IdealTextColor.name()));
```
```
To make sure the label of the button is always readable, I'm calling the method getIdealTextColor(), which is a method I've found from a codeproject article :
```
```
//==============================================================================
//  Nom : getIdealTextColor
//! @return an ideal label color, based on the given background color.
//! Based on http://www.codeproject.com/cs/media/IdealTextColor.asp
//==============================================================================
QColor JSPreferencesDlg::getIdealTextColor(const QColor& rBackgroundColor) const
{
    const int THRESHOLD = 105;
    int BackgroundDelta = (rBackgroundColor.red() * 0.299) + (rBackgroundColor.green() * 0.587) + (rBackgroundColor.blue() * 0.114);
    return QColor((255- BackgroundDelta < THRESHOLD) ? Qt::black : Qt::white);
}
```
```


q:
Suppose that I have a Java class with a static method, like so:

class A
{
    static void foo()
    {
        // Which class invoked me?
    }
}

And suppose further that class A has an arbitrary number of subclasses:

class B extends A { }
class C extends A { }
class D extends A { }
...

Now consider the following method invocations:

A.foo();
B.foo();
C.foo();
D.foo();
...

My question is, how can method foo() tell which class is invoking it?

[A]
It can't, and that's part of the problem with static methods.  As far as the compiler is concerned
```
A.foo()
```
and
```
B.foo()
```
are exactly the same thing.  In fact, they compile down to the same bytecode.  You can't get more similar than that.
If you really need this sort of information, use a singleton and turn
```
foo()
```
into an instance method.  If you still like the static syntax, you can build a facade
```
A.foo()
```
.


q:
Of course, the immediate answer for most situations is "yes", and I am a firm believer that a process should correctly cleanup any resources it has allocated, but what I have in my situation is a long-running system daemon that opens a fixed number of file descriptors at the startup, and closes them all before exiting.

This is an embedded platform, and I'm trying to make the code as compact as possible, while not introducing any bad style. But since file descriptors are closed before exit anyway, does this file descriptor cleanup code serve any purpose?  Do you always close all your file descriptors?

[A]
man 3 exit:
```
```
....
All open stdio(3) streams are flushed and closed.  Files created by tmpfile(3) are removed.
```
```
So i believe leaving main effectively calls the exit function with main's return value. Though I would argue that it is bad style. Personally, I
always
explicitly free/close any acquired resources.


q:
I'd like to give customers a choice of the database engine, but also want to minimize my troubles of such a decision.

The engines in question are MySQL (5 or later) and SQL Server (2005 or later).

[A]
Google for the differences in datatypes.
But the schema is just a part of the picture.
The SQL dialects are different too.  Google for those differences.   Then, either stick to a subset of SQL that's common to both, or build in a scheme to use somewhat different SQL in each.
Don't wait until the end to test on the "other" db.  Test on both from the start so that you don't invest too much in a dead end design direction.
Here's a starting place:
http://www.microsoft.com/technet/prodtechnol/sql/2000/deploy/mysql.mspx#EZD
and:
http://troels.arvin.dk/db/rdbms/#insert


q:
I'm trying to process a credit card transaction in .net and it works perfectly in Safari, Opera, and IE. When I try the same transaction in Firefox it sends two requests and I end up with a double charged card. From a quick search on Google it seems that this is an issue with Firebug but I am unable to find a way to stop this double post.

Does anyone have any idea on how to prevent Firefox (and Firebug) from doing this?

[A]
Use a
nonce
, a unique key which is only used once.
Send a unique number along with the form fields to the browser (this is often done with a hidden input field), and store a copy on the server with the transaction. Within the form, change the number on submit.  Validate that the keys match when processing your requests.
There may also be a clear explanation of what's happening on the front end, and that issue could be eliminated client-side.  It's best to solve the double-submit problem on the server, simply because there are so many ways in which a double submit could occur.


q: Is it possible to free memory allocated by C's alloca() explicitly, before the current function exits?  If so,how?

[A]
No, because it's allocated on the stack along with the local variables.  If you want memory that you can explicitly free, use one of the dynamic memory allocation functions.
There's no hybrid that allows you to explicitly free
AND
have it automatically free on function exit as well, at least not in the standard.


q:
I am using UIActivityIndicatorView to showing user that there is something going on, let them wait. But UIActivityIndicatorView looks small, do not have background color, and not very obvious to the user. While in iPhone SDK's UIImagePickerController, it uses the similar mechanism, but with the black background as well as some text besides the indicator.

I am wondering whether there is any existing component to do that task, or I have to implement my own class to perform that task.

Any suggestion are highly welcome, thanks in advance.

[A]
If you just want a different background color of your UIActivityIndictatorView, you could just send the setBackgroundColor message to the object, i.e.:
```
```
[activityIndicator setBackgroundColor:[UIColor blackColor]];
```
```
By the way, you can change the size of the indicator as well. just do setFrame or initWithFrame with a bigger rect. Remember UIActivityIndicatorView inherits from UIView so you get all the customization of UIView.


q:
My installation of APEX has come pear shaped on a Oracle 9.2.0.5.0 instance, all the packages are invalid.

I've tried recompiling everything with DBMS_UTILITY.compile_schema, but still all the packages are invalid. So, tried recompiling individual packages,

SQL> ALTER PACKAGE FLOWS_020000.WWV_FLOW_QUERY COMPILE BODY;

Warning: Package Body altered with compilation errors.

SQL> show err
No errors.
SQL>
SQL> ALTER PACKAGE FLOWS_020000.WWV_FLOW_QUERY COMPILE;

Warning: Package altered with compilation errors.

SQL> show err
No errors.
SQL>

nothing in the alter log for it..

How can I find what the error is? shouldn't "show err" give it to me?

[A]
try
```
```
SHOW ERRORS PACKAGE BODY FLOWS_020000.WWV_FLOW_QUERY
```
```


q:
Given the following simple example:

    List<string> list = new List<string>() { "One", "Two", "Three", "three", "Four", "Five" };

    CaseInsensitiveComparer ignoreCaseComparer = new CaseInsensitiveComparer();

    var distinctList = list.Distinct(ignoreCaseComparer as IEqualityComparer<string>).ToList();

It appears the CaseInsensitiveComparer is not actually being used to do a case-insensitive comparison.

In other words distinctList  contains the same number of items as list.   Instead I would expect, for example, "Three" and "three" be considered equal.

Am I missing something or is this an issue with the Distinct operator?

[A]
```
StringComparer
```
does what you need:
```
```
List<string> list = new List<string>() {
    "One", "Two", "Three", "three", "Four", "Five" };

var distinctList = list.Distinct(
    StringComparer.CurrentCultureIgnoreCase).ToList();
```
```
(or invariant / ordinal / etc depending on the data you are comparing)


q:
I'd like to popup a simple dialog with an editor box, to let user enter some value then just return. I am wondering whether iPhone SDK has that kind of support.

Thanks.

[A] You need to create your popup (UIAlertView) and add a UITextField (or whatever component you'd like to use) to it as a sub-view.  The UIAlertView won't auto-resize for the component you add so you have to hack that part of it together by adding text to it.  The text will increase the height of your popup and provided you don't add too much be hidden by your component.


q:
I want to assign default values to a column in my select sql query so that if the value of that column is null I get that default value in my recordset.  Is there anyway to do this?

Example:

select col1 (some default value) from tblname;

[A]
```
```
select
  isnull(col1, defaultvalue)
from
  tblname;
```
```


q: Can anyone help me to put a vertical scroll bar for an <asp:CheckBoxList>?

[A]
Try actually sending the Key Combination Ctrl+C, instead of directly terminating the process:
```
```
[DllImport("user32.dll")]
        public static extern int SendMessage(
              int hWnd,      // handle to destination window
              uint Msg,       // message
              long wParam,  // first message parameter
              long lParam   // second message parameter
              );
```
```
Look it up on the MSDN, you should find what you need there in order to send the Ctrl+Key combination...
I know that the message you need for sending Alt+Key is WM_SYSTEMKEYDOWN and WM_SYSTEMKEYUP, can't tell you about Ctrl...


q:
I have a solution in Visual Studio 2008 which has multiple projects. One of the projects is a WCF project. Sometimes I just want to debug other projects, but when I press F5, Visual Studio has wcfsvchost.exe launched to host the WCF project even it is not "StartUp Project".

Currently, every time I debugging other projects, I Have to Unload the WCF project to prevent the annoying WcfSvcHost.exe host pop up. However, it is not convenient. Anybody know better idea to prevent WCF project to be hosted in debugging mode?

[A]
You could try to unload the WCF project in the solution, then debug.
Sorry it was late I misread the last part to fast, then the only other way, that I know of, is to comment out the web parts in the Property Group of the project.  This prevented the pop-up for me
Unload the project, Comment out the mentioned part, reload.
```
```
<!--<PublishUrl>http://localhost/WindowsFormsApplication1/</PublishUrl>
<Install>true</Install>
<InstallFrom>Web</InstallFrom>
<UpdateEnabled>true</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>true</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>-->
```
```


q:
So my program needs to go through a plain text file line by line essentially:

Read line 1:
Do commands
loop
Read line2:
Do Commands
loop

etc until its done with the entire file does anyone know any good coding examples for this, all the tutorials seem to show open and writing/reading textfiles but nothing on how to do it line by line.

[A]
You could do it like this:
```
```
Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt")
    Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
        While Not s.EndOfStream
            Dim line As String = s.ReadLine

            'put you line processing code here

        End While
    End Using
End Using
```
```


q:
Suppose I have some code:

let listB = [ 1; 2; 3 ]

Using Lisp notation, how do I do a car and cadr against this list? I know cons is ::.

Or in Scheme, first and rest?

[A]
List.head
: Returns the first element of a nonempty list
(The head of the list)
.
List.tail
: Returns all the elements of a
nonempty list except the first
(The tail or rest of the list)
.
Example (
using F# Interactive Console
):
```
```
> let sample = [1;2;3;4];;

val sample : int list

> List.head sample;;

val it : int = 1

> List.tail sample;;

val it : int list = [2; 3; 4]
```
```


q:
I've got a lot of pages in my site, I'm trying to think of a nice way to separate these into areas that are a little more isolated than just simple directories under my base web project.  Is there a way to put my web forms into a separate class library?  If so, how is it done?

Thanks in advance.

[A]
At first thought, I don't think this is possible, due to the way ASPX is non-precompiled..
However, you can create classes that inherit from
```
Page
```
and place them into a DLL to re-use code-behind functionality. This can of course include control instantiate logic if required, but there is no designer to work with (if you need it).


q: Is it possible to retrieve the CPUID and MAC address of a client machine from a Ruby on Rails application?. Are there any plugins available for this?

[A]
I'm pretty sure it is not possible to parse the /proc filesystem of a client computer through a Rails applications (and thank God for that).
What you could do is make use of Javascript to some extent. There are quite some sites on the internet (mainly privacy scanners) which make use of Javascript to show extensive information about a client system. This might even work for the type of CPU of the client uses (assuming that is what you mean by 'CPUID').
What neither Javascript nor Rails can do for you though, is show you the MAC address of a client (assuming with 'macid' you mean a MAC address). If you take a deeper look into the way TCP/IP networking is done, you'll notice that this is by design. A computer in another network segment (say, the internet) is never intended to know your MAC address, nor does it need to.
If you really want to know someone's MAC, you'll need to use something like a Java applet or an ActiveX control (though that limits you to a certain platform). Those things should prompt your user for confirmation / permission before sending out privacy sensitive information like MAC addresses, which is a Good Thing.


q:
I have a list of email address which I want to distribute evenly by domain.

For example:

let the list be,

a@a.com
b@a.com
c@a.com
a@b.com
b@b.com
c@c.com

The output should be

a@a.com
a@b.com
c@c.com
b@a.com
b@b.com
c@a.com

The source list is not sorted by domain as in example, but can be sorted by domain, if that can help. What would be an efficient (single/two pass?) algorithm of doing this?

raj

[A]
My starting attempt would be a hash map of linked lists, so that once all the domain collisions were grouped, you could iterate though the linked lists one at a time.
If that makes any sense.
The following code is completely
UNTESTED
, and I know there is a bunch of stuff not right in the second loop, but it was faster than trying to explain further.
```
```
$sortedList = array();
$tempList
$emailList = array('a@a.com', 'b@a.com', 'c@b.com', 'd@b.com', 'e@c.com', 'f@a.com');

$emailCount = 0;
foreach ( $emailList as $email ) {
    list($username, $domain) = explode('@', $email);
    $tempList[$domain][] = $user;
    $emailCount++;
}

for ( $i = 0; $i < $emailCount; $i++ ) {
    $listIndex = $i % count($tempList);
    if ( !empty($tempList[$listIndex]) ) {
        $sortedList[] = $tempList[$listIndex][0];
        unset($tempList[$listIndex][0]);
    } else {
        unset$tempList[$listIndex]);
    }
}
```
```


q: we are writing tests for a COM library written in VB 6.0.The problem we are facing is that, we are unable to access events declared in VB( withevents). We get exception, "object does not support set of events". How can we overcome this problem?

[A]
For example, we have a class in VB 6.0 called DatabaseCommand.
```
```
Option Explicit

Public Event SavedSuccessfully()

Public Sub Execute(ByVal vAge As Integer, ByVal vName As String, ByVal vAddress As String)

    RaiseEvent SavedSuccessfully

End Sub
```
```
Now, personclass
```
```
Private WithEvents dbCommand As DatabaseCommand

Public Sub Init(ByVal vDBCommand As DatabaseCommand)

    Set dbCommand = vDBCommand

End Sub

Private Sub dbCommand_SavedSuccessfully()
    'not implemented
End Sub
```
```
Now, when try to test this ( after compiling the vb project)
```
```
MockRepository repository = new MockRepository();

PersonLib.DatabaseCommand db = repository.DynamicMock<PersonLib.DatabaseCommand>();

PersonLib.PersonClass person = new PersonLib.PersonClass();

person.Init(db);  --- this line throws error - Object or class does not support the set of events
```
```


q: I am an intermediate C programmer. If you have made any coding mistake that you came to know later that it was the most hazardous / harmful to the total application please share that code or description. I want to know this because in future I may come across such situations and I want to have your advice to avoid such mistakes.


q: My application communicates with another system via IBM Websphere MQ. Sometimes no message comes into my queue but the other system said They already sent to me. So I want to know how to keep a history for all messages that arriving on my queue.

[A]
Keep in mind that it may still be coming across the network as the MQ architecture may have many middle-ware queues.  Similarly, there's no requirement for a message to immediately get transmitted across a channel - the sender may batch up the messages and send them with a trigger.
The best way to ensure you log everything that arrives is to do this is with an interceptor queue.
This is the queue (let's call it A) that the channel writes to and, until this change, your application read from.  You then have a transfer process the reads from A, logs the message then writes it to the second queue (B).  This second queue is what your application now reads from.


q:
Is there an application , which can parse a given set of stored procedures (SQL Server 2000) and  gets all tables and associated columns that are being used in it.
The stored procedure can have tables from different databases.

Output should be like
TableA
   columnA
   columnC
   columnD

TableB
   columnE
   columnF
   columnG

I have written an small application using Database Edition GDR Any one interested can refer to http://tsqlparsergdr.codeplex.com

[A]
UPDATE - 20 Jan 2009
*
Visual Studio DB Professional Edition shipped with a full T-SQL script DOM parser
http://blogs.msdn.com/gertd/archive/2008/08/21/getting-to-the-crown-jewels.aspx
Not a concrete solution - but a line of thought.
Considered sysdepends as a potential solution - but it is notoriously unreliable at containing
all
the dependent object information.
but how about something Lex/Yacc derived?  There are a few commercial parsers e.g.
http://www.sqlparser.com/download.php
Not looked for open-source implementation but I think I would look for that route.  Here's how I started my search:
http://www.google.com/search?hl=en&q=sql+lex+yacc+parse
BNF syntax for ANSI SQL can be found here:
http://savage.net.au/SQL/
With a lex implementation of choice, this seems a relatively straight forward engineering problem from here.  (albeit with some heavylifting if you want to support MS SQL extensions)


q:
A lot of programmers who are used Visual Studio have a hard time adjusting to the fact that in other source control systems, files do not need to be locked/checked out to one developer at any given time.

Proponents of merging say that allowing two people to work on the same file speeds up productivity since it eliminates queuing up for the same source file. It also avoids cases where code needs to be written but the source is checked out to a guy who just left on a two-week vacation.

Locking advocates say that a lot of risk is introduced when more than one person works on the same file simultaneously. Communication and coordination between team members becomes much more necessary when using the merge model, according to them. Plus, a lot of people seem to mistrust automated merges.

What is the most compelling reason for you to use one method over the other?

[A]
Locking files may not scale very well to larger team. With version control systems that utilizes a lot of branching and merging, it simply may not be practical to let any one person give such control over the repository (thus, not scale to larger team).
With Subversion, for example, branching is a pointer copy, so you can easily create a TRY branch to avoid corrupting the trunk if you are experimenting with something, but want to commit.
With distributed version control systems like Git, every check out essentially is a branch.


q:
What's the best way to take some plain text (not PHP code) which contains PHP-style variables, and then substitute in the value of the variable. This is kinda hard to describe, so here's an example.

// -- myFile.txt --
Mary had a little $pet.

// -- parser.php --
$pet = "lamb";
// open myFile.txt and transform it such that...
$newContents = "Mary had a little lamb.";

I've been considering using a regex or perhaps eval(), though I'm not sure which would be easiest. This script is only going to be running locally, so any worries regarding security issues and eval() do not apply (i think?).

I'll also just add that I can get all the necessary variables into an array by using get_defined_vars():

$allVars = get_defined_vars();
echo $pet;             // "lamb"
echo $allVars['pet'];  // "lamb"

[A]
Here's what I've just come up with, but I'd still be interested to know if there's a better way. Cheers.
```
```
$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

foreach ($allVars as $var => $val) {
    $file = preg_replace("@\\$" . $var . "([^a-zA-Z_0-9\x7f-\xff]|$)@", $val . "\\1", $file);
}
```
```


q:
In my models, there are lots of attributes and methods that perform some calculation based on the model instance's attributes.  I've been having the methods return nil if the attributes that the calculations depend on are nil.  As a consequence of this design decision, I'm doing a lot of nil checks before displaying these values in my views.

I thought about having these methods return zero instead of nil when they don't have enough information, but I chose nil because zero is a valid computation result and nil implies that there was not enough information.

Should I return 0 instead of nil?  Is there any other pattern that I could use to avoid doing a bunch of nil checks in my views?

[A]
I tend to think you are doing things right if your problem is choosing whether to display, or not display, the results of a calculation.  If it would make no sense to display any value, then nil is perfectly reasonable.
If, however, your business logic is resulting in you getting into a state where much of the view will be habitually blank, then you probably should refactor such that your program loses its leaky abstractions.
Consider, for example, an application which starts by tracking recipes for
```
Food
```
.  Then, as requirements morph, we get the notion of pies needing to display different information than burgers.  Rather than having a
```
calculate_deliciousness_of_pie_or_nil_for_burger
```
method, and then checking for nil in the view, I'd break that into a pie view for pies and a burger view for burgers.  This might (probably would) require rethinking my object abstractions.


q: I need to read account number from Maestro/Mastercard with smart card reader. I am using Java 1.6 and its javax.smartcardio package. I need to send APDU command which will ask EMV application stored on card's chip for PAN number. Problem is, I cannot find regular byte array to construct APDU command which will return needed data anywhere...

[A]
You need to do construct a CommandAPDU object and pass it to the transmit()-command.
You should be able to find the precise command in the documentation for your smartcard, but here is one example:
```
```
byte[] readFile(CardChannel channel) throws CardException {
  CommandAPDU command = new CommandAPDU(0xB0, 0x60, 0x10, 0x00);
  ResponseAPDU response = channel.transmit(command);
  return response.getData();
}
```
```


q:
I'm putting a crontab job for updating with apt-get once a day (running Debian Lenny, there are updates almost daily). But almost all examples i've seen of this cron job invoke the -d flag.

This elicits 4 questions:

Why should I only download the
packages and not install them?

Doesn't this defeat the purpose of
running it automatically?

Don't I have to go in and actually
install the updates later?

Is it safe for me to run the cron
job without the -d flag?

[A]
You're operating on a faulty assumption--neither apt-get (nor aptitude) are meant to be run automatically, nor is the Debian packaging system really designed for it. That's why the tools make it difficult.
What happens when a software upgrade breaks because you forgot to update a configuration file? This has happened to me in the past (apache2), and some with severe consequences that prevented the machine from booting (mdadm). What happens when the software brings in dependencies you don't want (i.e. bringing in the entire X11 windowing system, on a server)? Etc, etc...
If you're worried about installing security upgrades automatically, you want to look at the
unattended-upgrades
package. It will download and install packages from the security archive for you.


q:
I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..

const char *GetString()
{
    std::stringstream ss;
    ss << "The random number is: " << rand();
    return ss.str().c_str();
}

could the c string be destroyed when ss falls off the stack? I'm  assuming so...

Another option may be to create a new string on the heap, but what is going to deallocate that?

const char *GetString()
{
    std::stringstream ss;
    ss << "The random number is: " << rand();
    char *out = new char[ss.str().size()];
    strcpy(ss.str().c_str(), out);
    return out;//is out ever deleted?
}

The same goes for pointers to other things as well as strings.

[A]
The first would actually not work because the stringstream deallocates it's space on destruction. So if you try to de-reference that pointer there is a good chance that your program would crash.
The second option you mention is how it's usually done and the user of the function is required to deallocate the space. IIf this is a C program which uses the function make sure you allocate with malloc() and free with free()
Another option is to return an address of a static char array. This is relevant if you know in advance a good upper bound to the length. More importantly this should be used ONLY if there is no chance that the function is going to be called from two different threads at the same time because using a static array essentially makes your function non-
reentrant
.


q: I am designing an Automatic text summarizer. One of the major modules in this project requires TRAINING CORPUS. Can someone please help me out by providing TRAINING CORPUS or referring some link to download it. Thanks in anticipation

[A]
See
How to Write a Spelling Corrector
by Norvig. He mentions
Project Gutenberg
,
Wiktionary
,
British National Corpus
,
Birkbeck spelling error corpus
. There's also
Brown Corpus
.


q: I'm having a problem where a jQuery setting against an .html() property on a selected element is returning the error 'nodeName' is null or not an object. This only occurs on IE6 and IE7, but not FF2, FF3, Opera (latest Nov 12,2008) or Safari (again, latest).

[A]
I resolved the problem. The example looks like this:
$('#section #detail .data').html(data);
...where data is HTML returned from an AJAX call, and this bug only occurs on IE6 and IE7 on the second attempt AJAX call, not the first. It's inexplicable. The error returned is:
```
```
'nodeName' is null or not an object
```
```
The fix is to simply clear the variable first before setting:
$('#section #detail .data').html('');
$('#section #detail .data').html(data);
And then IE6 and IE7 started working again with it.
BTW, I had to install Visual Web Developer 2008 Express Edition to get a debugger working in IE7. That info is
here
.


q:
In Erlang, every process has a group leader, and when a process wants to print something (i.e. it calls the io library or does something similar), it will send a message to its group leader.

My question is, where can I find the specification of these messages? Or in general, the specification of what a group leader should do?

I managed to find out with some experimenting that sometimes the process sends an {io_request, Sender, GroupLeader, Request} term, and the answer is an {io_reply, GroupLeader, ok} term, but there may be other cases.

[A]
The Erlang Rationale (video)
or
(slides)
;  is a good source of information, as is the source code for
user.erl
.
In short:
```
```
{io_request, From, ReplyAs, Request}
  %From is the process to send the reply to,
  %ReplyAs is any term the caller desires to
  %match up the request and the response. (returned verbatim in the reply)
  {io_reply, ReplyAs, Reply}
```
```
Some requests in user.erl:
```
```
{put_chars, IoList} % puts the iolist
 {put_chars, M,F,A} % puts the result of apply(M,F,A)
 {get_geometry, 'rows' | 'columns'} % returns the number of rows or columns of the console
 {get_line, Prompt} % calls io_lib:collect_line(Prompt)
 {get_chars, Prompt, Mod, Func, ExtraArgs}
 {get_until, Prompt, Mod, Func, Args}
 {setopts, Options} % only option supported by user is 'binary'
                    % (binary mode if present in Options, list mode otherwise)
```
```


q:
Let's say I'm running a simple server and have accept()ed a connection from a client.

What is the best way to tell when the client has disconnected? Normally, a client is supposed to send a close command, but what if it disconnects manually or loses network connection altogether? How can the server detect or handle this?

[A]
select (with the read mask set) will return with the handle signalled, but when you use ioctl* to check the number of bytes pending to be read, it will be zero. This is a sign that the socket has been disconnected.
This is a great discussion on the various methods of checking that the client has disconnected:
Stephen Cleary, Detection of Half-Open (Dropped) Connections
.
* for Windows use ioctlsocket.


q:
Consider the following signature in C#:

double Divide(int numerator, int denominator);

Is there a performance difference between the following implementations?

return (double)numerator / denominator;

return numerator / (double)denominator;

return (double)numerator / (double)denominator;

I'm assuming that both of the above return the same answer.

Have I missed any other equivalent solution?

[A]
Have you tried comparing the IL (for example, with
Reflector
)?
```
```
static double A(int numerator, int denominator)
{ return (double)numerator / denominator; }

static double B(int numerator, int denominator)
{ return numerator / (double)denominator; }

static double C(int numerator, int denominator)
{ return (double)numerator / (double)denominator; }
```
```
All three become (give or take the name):
```
```
.method private hidebysig static float64 A(int32 numerator, int32 denominator) cil managed
{
    .maxstack 8
    L_0000: ldarg.0 // pushes numerator onto the stack
    L_0001: conv.r8 // converts the value at the top of the stack to double
    L_0002: ldarg.1 // pushes denominator onto the stack
    L_0003: conv.r8 // converts the value at the top of the stack to double
    L_0004: div     // pops two values, divides, and pushes the result
    L_0005: ret     // pops the value from the top of the stack as the return value
}
```
```
So no: there is exactly zero difference.


q:
At the moment I have a set of divs, generated dynamically by php and all having their ids starting with 'itembox', with a count number appended. I have a droppable garbage bin area on the page so that the user can delete an individual itembox by fdragging and dropping on to the bin.

My problem is that the droppable won't seem to activate when I drag the original, while it will function (perfectly) when I have helper: 'clone' set. Unfortunately, though, when dragging, the cloning function takes its clone from the first iteration of the itembox, no matter which itembox is actually dragged.

So I'm looking for a solution to either make the droppable accept an original or force the cloning function to take its clone from the itembox actually dragged.

[A]
I guess the problem must lie in the accept option of your droppable initializer. Just try the following:
```
```
$('#mydroppable').droppable(
{
    accept: function() { return true; },
    drop: function () { alert("Dropped!"); }
});
```
```
Now this will accept everything, so you should probably implement some filtering in the accept function but none the less this should work.


q:
I understand the following elements :

there is some sort of crawling (configured in central administration)

when the crawling is done, there is a slight delay, after which you can have your search results displayed.

But, in a document library with publishing enabled, documents that are not published don't appear in search results. Is that normal ?

[A]
All contents are crawled using the default content access account. Most of the time, this is a dedicated account, and SharePoint give it "Full Read" permissions.
Unfortunately, non approved items are not visible for "read users". So it will index the latest published version.
However, you can't really give more permissions to this user. If you do so, it will always index unpublished item, without indexing the latest publish version. So user without approvers permissions won't be able to search those items.


q: What is the difference between atan and atan2 in C++?

[A]
```
std::atan2
```
allows calculating the arctangent of all four quadrants.
```
std::atan
```
only allows calculating from quadrants 1 and 4.


q:
My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it.

However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the

'foo.py' is not recognized as an internal or external command, operable
  program or batch file.

I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of.

[A]
From the error message, it looks like you need to pass the full path of "foo.py" to your Popen call. Normally just having "foo.py" will search in your current working directory, but this can be a bit unpredictable on Windows, I have found. Yours seems to be jumping around with the open file dialog.
Secondly, just for good measure, it would seem like you would need to pass foo.py as an argument to python.exe executable, rather than executing foo.py itself. Again, I would specify this by path.
So to be safe, something like:
```
```
subprocess.Popen([r'C:\Python2.5\python.exe', r'C:\path\to\foo.py'])
```
```


q:
When my IronPython program gets to the line

import wx

I get this message:

A first chance exception of type
'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll

Additional information: No module named _core_

although I do have the file wx\_core_.pyd. Also, before attempting the import, I have the lines:

sys.path.append('c:\\Python24\\Lib\\site-packages')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons')

which I hoped would let IronPython find everything it needed.

[A]
No, this won't work. Wx bindings (like most other "python bindings") are actually compiled against CPython.
In this regards they are not just packages on sys.path to be found, as you have tried. They actually depend on CPython itself.
This rather dry document explains the process.
Note: There was a mission by some of the crew at Resolver Systems to allow you to use CPython bindings with IronPython (called
IronClad
) but this is in its early stages, and I think they will concentrate on getting things like Numpy working first, GUI toolkits will always be the last, and hardest.


q:
Anyone know a good and effective way to search/match for a byte pattern in an byte[] array and then return the positions.

For example

byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};

byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125}

[A]
You can put the byte array into
String
and run match by IndexOf. Or you can at least reuse
existing algorithms
on string matching.
```
```
[STAThread]
    static void Main(string[] args)
    {
        byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};
        byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125};
        string needle, haystack;

        unsafe
        {
            fixed(byte * p = pattern) {
                needle = new string((SByte *) p, 0, pattern.Length);
            } // fixed

            fixed (byte * p2 = toBeSearched)
            {
                haystack = new string((SByte *) p2, 0, toBeSearched.Length);
            } // fixed

            int i = haystack.IndexOf(needle, 0);
            System.Console.Out.WriteLine(i);
        }
    }
```
```


q:
While connecting .NET to sybase server I got this error message:

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

This has worked properly before. System DSN with same details worked and data connection through vs.net also worked.

I am using VS.NET 2005.

Any suggestions?

[A]
Perform the following steps:
Start the Registry Editor by typing
```
regedit
```
in the Run window.
Select the following key in the registry:
```
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC
```
.
In the Security menu, click Permissions.
Grant Full Permission to the account which is being used for making connections.
Quit the Registry Editor.


q:
Is there any such thing as a virtual Lineprinter.I mean a software emulation of a printer, that outputs to screen.

I have a project to change the output of print job. My past experience with a lineprinter was tedious rounds of

loop:
   print
   walk down two flights
   check the output
   walk back up two flights
   edit code
got loop:

Anyone who thinks a lineprinter can be installed in a programmers office has not used a LinePrinter!

Googles just turning up printer emulation, as in printers that emulate other printers or virtual printer ports!


q:
I've been looking at some Ruby dependency injection libraries.  In particularly, I checked out  Needle and Copland.  They've been around for quite awhile, yet not a lot of usages.

What are some of the pros and cons of using these two libraries? It sure seems like a lot of libraries / frameworks out there could make good use of these two libraries, e.g. Merb / Datamapper's Hook.

[A]
Jamis Buck, who wrote Copland and Needle,
posted here
about Needle, dependency injection and their usefulness in a Ruby world.
It's long but worth reading, but in case you want the single paragraph most relevant to your question, I'd suggest this one, from just before the end:
DI frameworks are unnecessary. In more
  rigid environments, they have value.
  In agile environments like Ruby, not
  so much. The patterns themselves may
  still be applicable, but beware of
  falling into the trap of thinking you
  need a special tool for everything.
  Ruby is Play-Doh, remember! Let’s keep
  it that way.
HTH


q:
In C# you can use verbatim strings like this:

@"\\server\share\file.txt"

Is there something similar in JavaScript?

[A]
No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.
I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method.
What I did to solve this was as follows:
```
```
public void Alert(string message)
{
    message = message.Replace("\\", "\\\\")
        .Replace("\r\n", "\n")
        .Replace("\n", "\\n")
        .Replace("\t", "\\t")
        .Replace("\"", "\\\"");

    // and now register my JavaScript with this safe string.
}
```
```


q:
I know you can do it file by file.

Is there any way to do this in one step for all files in a project?

[A]
Do you mean using statements? First, note that they generally do no harm other that take space.
Tools like
ReSharper
offer automated tricks to do this, however: there was a
link in the VS feed
a little while ago; it boils down to:
go to Tools -> Macros -> Macros IDE...
in the Project Explorer, Add -> Add Module... (put in a name - I've used OrganiseUsings)
paste over with the code below
File -> Save MyMacros, exit
Now if you right-click on the toolbar and Customize... - you should be able to find MyMacros.OrganiseUsings.RemoveAndSortAll - drag this somewhere handy (maybe the Tools menu; you might also want to change the name after placing it).
You can now use this option to run the Remove and Sort command for an entire solution. A big time-saver.
==== code ====
```
```
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module OrganiseUsings

    Public Sub RemoveAndSortAll()
        On Error Resume Next
        Dim sol As Solution = DTE.Solution

        For i As Integer = 1 To sol.Projects.Count
            Dim proj As Project = sol.Projects.Item(i)
            For j As Integer = 1 To proj.ProjectItems.Count
                RemoveAndSortSome(proj.ProjectItems.Item(j))
            Next
        Next
    End Sub

    Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)
        On Error Resume Next
        If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then
            If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then
                Dim window As Window = projectItem.Open(Constants.vsViewKindCode)

                window.Activate()

                projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort")

                window.Close(vsSaveChanges.vsSaveChangesYes)
            End If
        End If

        For i As Integer = 1 To projectItem.ProjectItems.Count
            RemoveAndSortSome(projectItem.ProjectItems.Item(i))
        Next
    End Sub

End Module
```
```


q:
Suppose I have the following directory layout in a Maven project:

src/
|-- main
|   |-- bin
|   |   |-- run.cmd
|   |   `-- run.sh
|   |-- etc
|   |   |-- common-spring.xml
|   |   |-- log4j.xml
|   |   `-- xml-spring.xml
|   `-- java
|       `-- com
...

I would like to build a zip file that, when unzipped, produces something like this:

assembly
|-- bin
|   |-- run.cmd
|   `-- run.sh
|-- etc
|   |-- common-spring.xml
|   |-- log4j.xml
|   `-- xml-spring.xml
`-- lib
    |-- dependency1.jar
    |-- dependency2.jar
...

where `run.xx' are executable shell scripts that will call my main application and put all dependencies on the classpath.

Is this possible with some of the `official' Maven plugins, e.g. maven-assembly-plugin?

[A]
I use the
AppAssembler plugin
to get something similar. Example:
```
```
...
<build>
<plugins>
  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>appassembler-maven-plugin</artifactId>
    <configuration>
      <programs>
        <program>
          <mainClass>com.acme.MainClass</mainClass>
          <name>app</name>
        </program>
      </programs>
    </configuration>
  </plugin>
</plugins>
```
```


q:
How can I build a native Mac OS X installer for my application, on a non-Mac platform?

For example, I have a windows pc and a Java application. I want the windows pc to build an installer (possibly inside a .dmg archive) that works with Apple installer.

[A]
So, a couple of quick questions.
First, why do you want an installer? Most Mac users prefer apps that are just drag installed. If you are not writing Mac OS X specific code it is hard to imagine you need to place bits in special places, like Application Support or LaunchDaemons. Assuming everything you have just goes in one folder why bother with an installer at all?
Second, why would it be a problem to build the Mac installer on a Mac? Surely you have a macintosh around to test the app (you are not just blindly shipping it for Mac without testing it on a Mac, right?).
Okay, having said that, assuming you still have a good reason to actually build this on a PC, there are some bits that are not going to be easy. Basically a .pkg is a bunch of text scripts, localizations, an archive file (Archive.pax.gz), and a bill of materials (Archive.bom).
Assuming not much changes between builds, you can make the installer on a Mac, and then just rebuild the bom and the pax.gz, replace them into the existing .pkg, and batch a few pieces of metadata. The pax should be easy enough to deal with (pax is a standard archive format), but the bom file may prove a bit trickier, since I do not believe it is publicly documented, and I doubt the tools for creating them (mkbom) are part of darwin (not opensource). So you are going to need to figure that out and write a custom tool to create the bom file.
In other words, this is likely to be a large amount of work.


q:
I just can't remember the terminology used for this and other related properties.

EDIT - Maybe such a concept doesn't exist but I remember reading something in Effective C++ (or More Effective C++) where he advocated using swaps to commit changes last in the function because the vector swap functions were guaranteed not to throw an exception.

[A]
I think you mean to say that the function is "exception-safe". See e.g.
http://en.wikipedia.org/wiki/Exception_safety
.
The Wikipedia article further divides the safety into various levels. This is the one that is relevant here:
2. Commit or rollback semantics, also known as strong exception safety or no-change guarantee: Operations can fail, but failed operations are guaranteed to have no side effects so all data retain original values.
There's a reference to an STL design document that introduces exception safety and commit-or-rollback semantics:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1077.asc


q: Should I use the change or textInput event to capture user input on a TextInput control? Why?

[A]
```
textInput
```
is dispatched only when the user has
input
text into the control.
```
change
```
, on the other hand, is dispatched on every change committed by the user. So for example, if the user deletes a part of the text, only the
```
change
```
event is dispatched.
Neither of these is dispatched when the text is modified via code:
```
flash.events.TextEvent.TEXT_INPUT
```
:
"Dispatched when
the user
types, deletes, or pastes text into the
  control."
(ignore the word "delete" there -- I just tried it and this event is
not
dispatched when text is deleted by the user)
```
flash.events.Event.CHANGE
```
:
"Dispatched when text in the TextInput control changes through user
  input.
This event does not occur if
  you use data binding or ActionScript
  code to change the text
."
You can also use the
```
valueCommit
```
event, which is dispatched when the user "commits" the changes (usually by moving the focus away from the text field), but remember that this event is also dispatched when the field value is changed programmatically.


q:
We just shifted from VB to C# and I am having some troubles..!

Why can't I create a private static const void??

why is it not working?

 private static const void MyVoid(void void)
 {
   try
   {
      this.void void = new void(void + void);
      return this.void;
   }
   catch (void)
   {
      Response.Write(void);
   }
 }

[A]
```
void
```
is the return type of
"there is no return type"
. It is not a type in itself (as in
```
int
```
,
```
bool
```
etc.), but rather specifies it returns nothing.


q:
This line:

strcat(query,*it);

(where *it is an iterator to a string)

Keeps giving me this error:

no matching function for call to ``strcat(char[200], const std::basic_string, std::allocator >&)`'

I guess it's because strcat takes in a char* while *it is a string.
How do I convert it from a string to a char* to make it work with strcat() ?

I've tried strcat(query,(*it).c_str()) but that just gives me a runtime error.

Edit: sorry, it should be converted to a const char*

[A]
```
strcat(query,(*it).c_str())
```
should work. What's the runtime error? Are you sure that
```
query
```
is null-terminated before you make the call?


q:
Given a method signature:

public bool AreTheSame<T>(Expression<Func<T, object>> exp1, Expression<Func<T, object>> exp2)

What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple MemberExpressions, eg c => c.ID.

An example call might be:

AreTheSame<User>(u1 => u1.ID, u2 => u2.ID); --> would return true

[A]
Hmmm... I guess you'd have to parse the tree, checking the node-type and member of each. I'll knock up an example...
```
```
using System;
using System.Linq.Expressions;
class Test {
    public string Foo { get; set; }
    public string Bar { get; set; }
    static void Main()
    {
        bool test1 = FuncTest<Test>.FuncEqual(x => x.Bar, y => y.Bar),
            test2 = FuncTest<Test>.FuncEqual(x => x.Foo, y => y.Bar);
    }

}
// this only exists to make it easier to call, i.e. so that I can use FuncTest<T> with
// generic-type-inference; if you use the doubly-generic method, you need to specify
// both arguments, which is a pain...
static class FuncTest<TSource>
{
    public static bool FuncEqual<TValue>(
        Expression<Func<TSource, TValue>> x,
        Expression<Func<TSource, TValue>> y)
    {
        return FuncTest.FuncEqual<TSource, TValue>(x, y);
    }
}
static class FuncTest {
    public static bool FuncEqual<TSource, TValue>(
        Expression<Func<TSource,TValue>> x,
        Expression<Func<TSource,TValue>> y)
    {
        return ExpressionEqual(x, y);
    }
    private static bool ExpressionEqual(Expression x, Expression y)
    {
        // deal with the simple cases first...
        if (ReferenceEquals(x, y)) return true;
        if (x == null || y == null) return false;
        if (   x.NodeType != y.NodeType
            || x.Type != y.Type ) return false;

        switch (x.NodeType)
        {
            case ExpressionType.Lambda:
                return ExpressionEqual(((LambdaExpression)x).Body, ((LambdaExpression)y).Body);
            case ExpressionType.MemberAccess:
                MemberExpression mex = (MemberExpression)x, mey = (MemberExpression)y;
                return mex.Member == mey.Member; // should really test down-stream expression
            default:
                throw new NotImplementedException(x.NodeType.ToString());
        }
    }
}
```
```


q:
I'm using the ReportViewer control to display a Report within a WebForm, i've also implemented the "Export to Excel" feature, by calling the Render method of the Server Report

eg

ReportViewerControl.ServerReport.Render("Excel",etc,etc,etc);

My problem is that the exported report contains Hyperlinks that link to other reports, I wish these to appear in the webform but not appear hence be disabled in the Exported Spreadsheet (generated by the Code above).

Does anyone have a way of achieving this?

Thanks

[A]
regarding your question about list traversal - you can start by writing a function that returns lists that represent the path - that's I think easier and it will be later easy to turn it into a function that returns a number.
This one takes a list as the first argument (path so far) and a tree and returns a list> type - that is all the possible paths from the current branch.
```
```
let rec visitor lst tree =
  match tree with
  | Branch(n, sub) -> List.collect (visitor (n::lst)) sub
  | Leaf(n) -> [List.rev (n::lst)]

// For example...
> let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);;
> visitor [] tr;;
val it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]]
```
```
In the 'Leaf' case, we simply add the current number to the list and return the result as a list containing single list (we have to reverse it first, because we were adding numbers to the beginning).
In the 'Branch' case, we add 'n' to the list and recursively call the visitor to process all the sub-nodes of the current branch. This returns a bunch of lists and we use 'map_concat' to turn them into a single list that contains all posble paths from the current branch.
Now, you can rewrite this to return a list of integers:
```
```
let rec visitor2 lst tree =
  match tree with
  | Branch(n, sub) -> List.collect (visitor2 (lst * 10 + n)) sub
  | Leaf(n) -> [lst * 10 + n]

// For example...
> visitor2 0 tr;;
val it : int list = [13; 124; 125]
```
```
Instead of concatenating lists, we now calculate the number.


q:
is there a way to change an oracle user's default schema?

I found it in the FAQ that I can alter it in the session, but it's not what I want. E.G. the user at log on always sees another schema as default.

Thanks in advance.

[A]
I believe a logon trigger should work:
```
```
CREATE OR REPLACE TRIGGER db_logon
AFTER logon ON DATABASE WHEN (USER = 'A')
BEGIN
    execute immediate 'ALTER SESSION SET CURRENT_SCHEMA = B';
END;
```
```


q:
I have an website. When the user is logged the session details will loaded.
When the user logged out the session details will abandoned. (Log out by clicking the logout menu)
when the user simply closes the browser then how to destroy the session.

In the next time its get logging with the same session data. I need to avoid this.

[A]
You could configure your sessions to time out quicker.
In web.config:
```
```
< sessionState ... timeout="5" />
```
```


q: Currently, my Objective C classes use C++ objects by doing a new when the owner is created, and calling delete when it is destroyed. But is there another way? I'd like to be able to declare, say, an auto_ptr whose scope lasts the duration of the Objective C class' lifetime.

[A]
Ok, let me assume you are using C++ and Objective-C on a Mac, if I'm right you are likely using X-code. So if you go to the properties (info) of your project. You can check the compile options (GCC's). In there, there is an option to enable C++ constructors/destructors (which is turned off by default in Cocoa projects).
Then you get default-like C++ scoping, however I haven't used it much and I've had problems with heavily template code (Boost).
Also I don't think anyone officially supports this besides some good souls working on GCC. So I'd recommend that you unit test anything like this, and keep note that anything could go wrong.
Nevertheless being able to use C++ in objective-C, for me as a C++ person, is a relief and the risks are worth the benefits :)


q:
I have quite a large list of words in a txt file and I'm trying to do a regex find and replace in Notepad++. I need to add a string before each line and after each line.. So that:

wordone
wordtwo
wordthree

become

able:"wordone"
able:"wordtwo"
able:"wordthree"

How can I do this?

[A]
Assuming alphanumeric words, you can use:
```
```
Search  = ^([A-Za-z0-9]+)$
Replace = able:"\1"
```
```
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
```
```
Search = ^(.+)$
```
```
```
^
```
points to the start of the line.
```
$
```
points to the end of the line.
```
\1
```
will be the source match within the parentheses.